engine-adapter.js 164 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084
  1. (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. "use strict";
  3. /****************************************************************************
  4. Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
  5. https://www.cocos.com/
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated engine source code (the "Software"), a limited,
  8. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  9. to use Cocos Creator solely to develop games on your target platforms. You shall
  10. not use Cocos Creator software for developing other software or tools that's
  11. used for developing games. You are not granted to publish, distribute,
  12. sublicense, and/or sell copies of Cocos Creator.
  13. The software or tools in this License Agreement are licensed, not sold.
  14. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. ****************************************************************************/
  23. require('./jsb-assets-manager.js');
  24. require('./jsb-game.js');
  25. require('./jsb-gfx.js');
  26. require('./jsb-loader.js');
  27. if (window.oh) {
  28. require('./jsb-videoplayer-openharmony.js');
  29. } else {
  30. require('./jsb-videoplayer.js');
  31. }
  32. require('./jsb-webview.js');
  33. require('./jsb-editbox.js');
  34. require('./jsb-editor-support.js');
  35. require('./jsb-spine-skeleton.js');
  36. require('./jsb-dragonbones.js');
  37. if (cc.physics && cc.physics.PhysicsSystem.PHYSICS_PHYSX) {
  38. require('./jsb-physics.js');
  39. }
  40. },{"./jsb-assets-manager.js":2,"./jsb-dragonbones.js":4,"./jsb-editbox.js":5,"./jsb-editor-support.js":6,"./jsb-game.js":8,"./jsb-gfx.js":9,"./jsb-loader.js":10,"./jsb-physics.js":11,"./jsb-spine-skeleton.js":12,"./jsb-videoplayer-openharmony.js":13,"./jsb-videoplayer.js":14,"./jsb-webview.js":15}],2:[function(require,module,exports){
  41. "use strict";
  42. /*
  43. * Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
  44. *
  45. * Permission is hereby granted, free of charge, to any person obtaining a copy
  46. * of this software and associated documentation files (the "Software"), to deal
  47. * in the Software without restriction, including without limitation the rights
  48. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  49. * copies of the Software, and to permit persons to whom the Software is
  50. * furnished to do so, subject to the following conditions:
  51. *
  52. * The above copyright notice and this permission notice shall be included in
  53. * all copies or substantial portions of the Software.
  54. *
  55. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  56. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  57. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  58. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  59. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  60. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  61. * THE SOFTWARE.
  62. */
  63. if (jsb.AssetsManager) {
  64. jsb.AssetsManager.State = {
  65. UNINITED: 0,
  66. UNCHECKED: 1,
  67. PREDOWNLOAD_VERSION: 2,
  68. DOWNLOADING_VERSION: 3,
  69. VERSION_LOADED: 4,
  70. PREDOWNLOAD_MANIFEST: 5,
  71. DOWNLOADING_MANIFEST: 6,
  72. MANIFEST_LOADED: 7,
  73. NEED_UPDATE: 8,
  74. READY_TO_UPDATE: 9,
  75. UPDATING: 10,
  76. UNZIPPING: 11,
  77. UP_TO_DATE: 12,
  78. FAIL_TO_UPDATE: 13
  79. };
  80. jsb.Manifest.DownloadState = {
  81. UNSTARTED: 0,
  82. DOWNLOADING: 1,
  83. SUCCESSED: 2,
  84. UNMARKED: 3
  85. };
  86. jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST = 0;
  87. jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST = 1;
  88. jsb.EventAssetsManager.ERROR_PARSE_MANIFEST = 2;
  89. jsb.EventAssetsManager.NEW_VERSION_FOUND = 3;
  90. jsb.EventAssetsManager.ALREADY_UP_TO_DATE = 4;
  91. jsb.EventAssetsManager.UPDATE_PROGRESSION = 5;
  92. jsb.EventAssetsManager.ASSET_UPDATED = 6;
  93. jsb.EventAssetsManager.ERROR_UPDATING = 7;
  94. jsb.EventAssetsManager.UPDATE_FINISHED = 8;
  95. jsb.EventAssetsManager.UPDATE_FAILED = 9;
  96. jsb.EventAssetsManager.ERROR_DECOMPRESS = 10;
  97. }
  98. },{}],3:[function(require,module,exports){
  99. "use strict";
  100. /****************************************************************************
  101. Copyright (c) 2020 Xiamen Yaji Software Co., Ltd.
  102. https://www.cocos.com/
  103. Permission is hereby granted, free of charge, to any person obtaining a copy
  104. of cache-manager software and associated engine source code (the "Software"), a limited,
  105. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  106. to use Cocos Creator solely to develop games on your target platforms. You shall
  107. not use Cocos Creator software for developing other software or tools that's
  108. used for developing games. You are not granted to publish, distribute,
  109. sublicense, and/or sell copies of Cocos Creator.
  110. The software or tools in cache-manager License Agreement are licensed, not sold.
  111. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  112. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  113. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  114. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  115. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  116. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  117. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  118. THE SOFTWARE.
  119. ****************************************************************************/
  120. const {
  121. getUserDataPath,
  122. readJsonSync,
  123. makeDirSync,
  124. writeFileSync,
  125. deleteFile,
  126. rmdirSync
  127. } = require('./jsb-fs-utils');
  128. let writeCacheFileList = null;
  129. let cleaning = false;
  130. const REGEX = /^\w+:\/\/.*/;
  131. const cacheManager = {
  132. cacheDir: 'gamecaches',
  133. cachedFileName: 'cacheList.json',
  134. deleteInterval: 500,
  135. writeFileInterval: 2000,
  136. cachedFiles: null,
  137. version: '1.1',
  138. getCache(url) {
  139. this.updateLastTime(url);
  140. return this.cachedFiles.has(url) ? `${this.cacheDir}/${this.cachedFiles.get(url).url}` : '';
  141. },
  142. // eslint-disable-next-line no-unused-vars
  143. getTemp(url) {
  144. return '';
  145. },
  146. init() {
  147. this.cacheDir = `${getUserDataPath()}/${this.cacheDir}`;
  148. const cacheFilePath = `${this.cacheDir}/${this.cachedFileName}`;
  149. const result = readJsonSync(cacheFilePath);
  150. if (result instanceof Error || !result.version || result.version !== this.version) {
  151. if (!(result instanceof Error)) rmdirSync(this.cacheDir, true);
  152. this.cachedFiles = new cc.AssetManager.Cache();
  153. makeDirSync(this.cacheDir, true);
  154. writeFileSync(cacheFilePath, JSON.stringify({
  155. files: this.cachedFiles._map,
  156. version: this.version
  157. }), 'utf8');
  158. } else {
  159. this.cachedFiles = new cc.AssetManager.Cache(result.files);
  160. }
  161. },
  162. updateLastTime(url) {
  163. if (this.cachedFiles.has(url)) {
  164. const cache = this.cachedFiles.get(url);
  165. cache.lastTime = Date.now();
  166. }
  167. },
  168. _write() {
  169. writeCacheFileList = null;
  170. writeFileSync(`${this.cacheDir}/${this.cachedFileName}`, JSON.stringify({
  171. files: this.cachedFiles._map,
  172. version: this.version
  173. }), 'utf8');
  174. },
  175. writeCacheFile() {
  176. if (!writeCacheFileList) {
  177. writeCacheFileList = setTimeout(this._write.bind(this), this.writeFileInterval);
  178. }
  179. },
  180. cacheFile(id, url, cacheBundleRoot) {
  181. this.cachedFiles.add(id, {
  182. bundle: cacheBundleRoot,
  183. url,
  184. lastTime: Date.now()
  185. });
  186. this.writeCacheFile();
  187. },
  188. clearCache() {
  189. rmdirSync(this.cacheDir, true);
  190. this.cachedFiles = new cc.AssetManager.Cache();
  191. makeDirSync(this.cacheDir, true);
  192. clearTimeout(writeCacheFileList);
  193. this._write();
  194. cc.assetManager.bundles.forEach(bundle => {
  195. if (REGEX.test(bundle.base)) this.makeBundleFolder(bundle.name);
  196. });
  197. },
  198. clearLRU() {
  199. if (cleaning) return;
  200. cleaning = true;
  201. const caches = [];
  202. const self = this;
  203. this.cachedFiles.forEach((val, key) => {
  204. if (val.bundle === 'internal') return;
  205. caches.push({
  206. originUrl: key,
  207. url: this.getCache(key),
  208. lastTime: val.lastTime
  209. });
  210. });
  211. caches.sort((a, b) => a.lastTime - b.lastTime);
  212. caches.length = Math.floor(caches.length / 3);
  213. if (caches.length === 0) {
  214. cleaning = false;
  215. return;
  216. }
  217. for (let i = 0, l = caches.length; i < l; i++) {
  218. this.cachedFiles.remove(caches[i].originUrl);
  219. }
  220. clearTimeout(writeCacheFileList);
  221. this._write();
  222. function deferredDelete() {
  223. const item = caches.pop();
  224. deleteFile(item.url);
  225. if (caches.length > 0) {
  226. setTimeout(deferredDelete, self.deleteInterval);
  227. } else {
  228. cleaning = false;
  229. }
  230. }
  231. setTimeout(deferredDelete, self.deleteInterval);
  232. },
  233. removeCache(url) {
  234. if (this.cachedFiles.has(url)) {
  235. const path = this.getCache(url);
  236. this.cachedFiles.remove(url);
  237. clearTimeout(writeCacheFileList);
  238. this._write();
  239. deleteFile(path);
  240. }
  241. },
  242. makeBundleFolder(bundleName) {
  243. makeDirSync(`${this.cacheDir}/${bundleName}`, true);
  244. }
  245. };
  246. cc.assetManager.cacheManager = module.exports = cacheManager;
  247. },{"./jsb-fs-utils":7}],4:[function(require,module,exports){
  248. "use strict";
  249. /****************************************************************************
  250. Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
  251. http://www.cocos.com
  252. Permission is hereby granted, free of charge, to any person obtaining a copy
  253. of this software and associated engine source code (the "Software"), a limited,
  254. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  255. to use Cocos Creator solely to develop games on your target platforms. You shall
  256. not use Cocos Creator software for developing other software or tools that's
  257. used for developing games. You are not granted to publish, distribute,
  258. sublicense, and/or sell copies of Cocos Creator.
  259. The software or tools in this License Agreement are licensed, not sold.
  260. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  261. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  262. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  263. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  264. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  265. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  266. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  267. THE SOFTWARE.
  268. ****************************************************************************/
  269. const cacheManager = require('./jsb-cache-manager');
  270. // @ts-expect-error jsb polyfills
  271. (function () {
  272. if (globalThis.dragonBones === undefined || globalThis.middleware === undefined) return;
  273. const ArmatureDisplayComponent = cc.internal.ArmatureDisplay;
  274. if (ArmatureDisplayComponent === undefined) return;
  275. const dragonBones = globalThis.dragonBones;
  276. const middleware = globalThis.middleware;
  277. // dragonbones global time scale.
  278. Object.defineProperty(dragonBones, 'timeScale', {
  279. get() {
  280. return this._timeScale;
  281. },
  282. set(value) {
  283. this._timeScale = value;
  284. const factory = this.CCFactory.getInstance();
  285. factory.setTimeScale(value);
  286. },
  287. configurable: true
  288. });
  289. middleware.generateGetSet(dragonBones);
  290. const _slotColor = cc.color(0, 0, 255, 255);
  291. const _boneColor = cc.color(255, 0, 0, 255);
  292. const _originColor = cc.color(0, 255, 0, 255);
  293. ////////////////////////////////////////////////////////////
  294. // override dragonBones library by native dragonBones
  295. ////////////////////////////////////////////////////////////
  296. //--------------------
  297. // adapt event name
  298. //--------------------
  299. dragonBones.EventObject.START = 'start';
  300. dragonBones.EventObject.LOOP_COMPLETE = 'loopComplete';
  301. dragonBones.EventObject.COMPLETE = 'complete';
  302. dragonBones.EventObject.FADE_IN = 'fadeIn';
  303. dragonBones.EventObject.FADE_IN_COMPLETE = 'fadeInComplete';
  304. dragonBones.EventObject.FADE_OUT = 'fadeOut';
  305. dragonBones.EventObject.FADE_OUT_COMPLETE = 'fadeOutComplete';
  306. dragonBones.EventObject.FRAME_EVENT = 'frameEvent';
  307. dragonBones.EventObject.SOUND_EVENT = 'soundEvent';
  308. dragonBones.DragonBones = {
  309. ANGLE_TO_RADIAN: Math.PI / 180,
  310. RADIAN_TO_ANGLE: 180 / Math.PI
  311. };
  312. //-------------------
  313. // native factory
  314. //-------------------
  315. const factoryProto = dragonBones.CCFactory.prototype;
  316. factoryProto.createArmatureNode = function (comp, armatureName, node) {
  317. node = node || new cc.Node();
  318. let display = node.getComponent(ArmatureDisplayComponent);
  319. if (!display) {
  320. display = node.addComponent(ArmatureDisplayComponent);
  321. }
  322. node.name = armatureName;
  323. display._armatureName = armatureName;
  324. display._dragonAsset = comp.dragonAsset;
  325. display._dragonAtlasAsset = comp.dragonAtlasAsset;
  326. display._init();
  327. return display;
  328. };
  329. const _replaceSkin = factoryProto.replaceSkin;
  330. factoryProto.replaceSkin = function (armatrue, skinData, isOverride, exclude) {
  331. if (isOverride === undefined) isOverride = false;
  332. exclude = exclude || [];
  333. _replaceSkin.call(this, armatrue, skinData, isOverride, exclude);
  334. };
  335. const _changeSkin = factoryProto.changeSkin;
  336. factoryProto.changeSkin = function (armatrue, skinData, exclude) {
  337. _changeSkin.call(this, armatrue, skinData, exclude);
  338. };
  339. dragonBones.CCFactory.getInstance = function () {
  340. return dragonBones.CCFactory.getFactory();
  341. };
  342. //-------------------
  343. // native animation state
  344. //-------------------
  345. const animationStateProto = dragonBones.AnimationState.prototype;
  346. const _isPlaying = animationStateProto.isPlaying;
  347. Object.defineProperty(animationStateProto, 'isPlaying', {
  348. get() {
  349. return _isPlaying.call(this);
  350. }
  351. });
  352. //-------------------
  353. // native armature
  354. //-------------------
  355. const armatureProto = dragonBones.Armature.prototype;
  356. armatureProto.addEventListener = function (eventType, listener, target) {
  357. this.__persistentDisplay__ = this.getDisplay();
  358. this.__persistentDisplay__.on(eventType, listener, target);
  359. };
  360. armatureProto.removeEventListener = function (eventType, listener, target) {
  361. this.__persistentDisplay__ = this.getDisplay();
  362. this.__persistentDisplay__.off(eventType, listener, target);
  363. };
  364. //--------------------------
  365. // native CCArmatureDisplay
  366. //--------------------------
  367. const nativeArmatureDisplayProto = dragonBones.CCArmatureDisplay.prototype;
  368. Object.defineProperty(nativeArmatureDisplayProto, 'node', {
  369. get() {
  370. return this;
  371. }
  372. });
  373. nativeArmatureDisplayProto.getRootNode = function () {
  374. const rootDisplay = this.getRootDisplay();
  375. return rootDisplay && rootDisplay._ccNode;
  376. };
  377. nativeArmatureDisplayProto.convertToWorldSpace = function (point) {
  378. let newPos = this.convertToRootSpace(point.x, point.y);
  379. newPos = cc.v3(newPos.x, newPos.y, 0);
  380. const ccNode = this.getRootNode();
  381. if (!ccNode) return newPos;
  382. const finalPos = ccNode._uiProps.uiTransformComp.convertToWorldSpaceAR(newPos);
  383. return finalPos;
  384. };
  385. nativeArmatureDisplayProto.initEvent = function () {
  386. if (this._eventTarget) {
  387. return;
  388. }
  389. this._eventTarget = new cc.EventTarget();
  390. this.setDBEventCallback(function (eventObject) {
  391. this._eventTarget.emit(eventObject.type, eventObject);
  392. });
  393. };
  394. nativeArmatureDisplayProto.on = function (type, listener, target) {
  395. this.initEvent();
  396. this._eventTarget.on(type, listener, target);
  397. this.addDBEventListener(type, listener);
  398. };
  399. nativeArmatureDisplayProto.off = function (type, listener, target) {
  400. this.initEvent();
  401. this._eventTarget.off(type, listener, target);
  402. this.removeDBEventListener(type, listener);
  403. };
  404. nativeArmatureDisplayProto.once = function (type, listener, target) {
  405. this.initEvent();
  406. this._eventTarget.once(type, listener, target);
  407. this.addDBEventListener(type, listener);
  408. };
  409. ////////////////////////////////////////////////////////////
  410. // override DragonBonesAtlasAsset
  411. ////////////////////////////////////////////////////////////
  412. const dbAtlas = cc.internal.DragonBonesAtlasAsset.prototype;
  413. let _gTextureIdx = 1;
  414. const _textureKeyMap = {};
  415. const _textureMap = new WeakMap();
  416. const _textureIdx2Name = {};
  417. dbAtlas.removeRecordTexture = function (texture) {
  418. if (!texture) return;
  419. delete _textureIdx2Name[texture.image.url];
  420. const index = texture.__textureIndex__;
  421. if (index) {
  422. const texKey = _textureKeyMap[index];
  423. if (texKey && _textureMap.has(texKey)) {
  424. _textureMap.delete(texKey);
  425. delete _textureKeyMap[index];
  426. }
  427. }
  428. };
  429. dbAtlas.recordTexture = function () {
  430. if (this._texture && this._oldTexture !== this._texture) {
  431. this.removeRecordTexture(this._oldTexture);
  432. const texKey = _textureKeyMap[_gTextureIdx] = {
  433. key: _gTextureIdx
  434. };
  435. _textureMap.set(texKey, this._texture);
  436. this._oldTexture = this._texture;
  437. this._texture.__textureIndex__ = _gTextureIdx;
  438. _gTextureIdx++;
  439. }
  440. };
  441. dbAtlas.getTextureByIndex = function (textureIdx) {
  442. const texKey = _textureKeyMap[textureIdx];
  443. if (!texKey) return null;
  444. return _textureMap.get(texKey);
  445. };
  446. dbAtlas.updateTextureAtlasData = function (factory) {
  447. const url = this._texture.image.url;
  448. const preAtlasInfo = _textureIdx2Name[url];
  449. let index;
  450. // If the texture has store the atlas info before,then get native atlas object,and
  451. // update script texture map.
  452. if (preAtlasInfo) {
  453. index = preAtlasInfo.index;
  454. this._textureAtlasData = factory.getTextureAtlasDataByIndex(preAtlasInfo.name, index);
  455. const texKey = _textureKeyMap[preAtlasInfo.index];
  456. _textureMap.set(texKey, this._texture);
  457. this._texture.__textureIndex__ = index;
  458. // If script has store the atlas info,but native has no atlas object,then
  459. // still new native texture2d object,but no call recordTexture to increase
  460. // textureIndex.
  461. if (this._textureAtlasData) {
  462. return;
  463. }
  464. } else {
  465. this.recordTexture();
  466. }
  467. index = this._texture.__textureIndex__;
  468. this.jsbTexture = new middleware.Texture2D();
  469. this.jsbTexture.setRealTextureIndex(index);
  470. this.jsbTexture.setPixelsWide(this._texture.width);
  471. this.jsbTexture.setPixelsHigh(this._texture.height);
  472. this.jsbTexture.setRealTexture(this._texture);
  473. this._textureAtlasData = factory.parseTextureAtlasData(this.atlasJson, this.jsbTexture, this._uuid);
  474. _textureIdx2Name[url] = {
  475. name: this._textureAtlasData.name,
  476. index
  477. };
  478. };
  479. dbAtlas.init = function (factory) {
  480. this._factory = factory;
  481. // If create by manual, uuid is empty.
  482. if (!this._uuid) {
  483. const atlasJsonObj = JSON.parse(this.atlasJson);
  484. this._uuid = atlasJsonObj.name;
  485. }
  486. if (this._textureAtlasData) {
  487. factory.addTextureAtlasData(this._textureAtlasData, this._uuid);
  488. } else {
  489. this.updateTextureAtlasData(factory);
  490. }
  491. };
  492. dbAtlas._clear = function (dontRecordTexture) {
  493. if (this._factory) {
  494. this._factory.removeTextureAtlasData(this._uuid, true);
  495. this._factory.removeDragonBonesDataByUUID(this._uuid, true);
  496. }
  497. this._textureAtlasData = null;
  498. if (!dontRecordTexture) {
  499. this.recordTexture();
  500. }
  501. };
  502. dbAtlas.destroy = function () {
  503. this.removeRecordTexture(this._texture);
  504. this._clear(true);
  505. cc.Asset.prototype.destroy.call(this);
  506. };
  507. ////////////////////////////////////////////////////////////
  508. // override DragonBonesAsset
  509. ////////////////////////////////////////////////////////////
  510. const dbAsset = cc.internal.DragonBonesAsset.prototype;
  511. dbAsset.init = function (factory, atlasUUID) {
  512. this._factory = factory || dragonBones.CCFactory.getInstance();
  513. // If create by manual, uuid is empty.
  514. // Only support json format, if remote load dbbin, must set uuid by manual.
  515. if (!this._uuid && this.dragonBonesJson) {
  516. const rawData = JSON.parse(this.dragonBonesJson);
  517. this._uuid = rawData.name;
  518. }
  519. const armatureKey = `${this._uuid}#${atlasUUID}`;
  520. const dragonBonesData = this._factory.getDragonBonesData(armatureKey);
  521. if (dragonBonesData) return armatureKey;
  522. let filePath = null;
  523. if (this.dragonBonesJson) {
  524. filePath = this.dragonBonesJson;
  525. } else {
  526. filePath = cacheManager.getCache(this.nativeUrl) || this.nativeUrl;
  527. }
  528. this._factory.parseDragonBonesDataByPath(filePath, armatureKey);
  529. return armatureKey;
  530. };
  531. const armatureCacheMgr = dragonBones.ArmatureCacheMgr.getInstance();
  532. dragonBones.armatureCacheMgr = armatureCacheMgr;
  533. dbAsset._clear = function () {
  534. if (this._factory) {
  535. this._factory.removeDragonBonesDataByUUID(this._uuid, true);
  536. }
  537. armatureCacheMgr.removeArmatureCache(this._uuid);
  538. };
  539. ////////////////////////////////////////////////////////////
  540. // override ArmatureDisplay
  541. ////////////////////////////////////////////////////////////
  542. const superProto = cc.internal.UIRenderer.prototype;
  543. const armatureDisplayProto = cc.internal.ArmatureDisplay.prototype;
  544. const AnimationCacheMode = cc.internal.ArmatureDisplay.AnimationCacheMode;
  545. const armatureSystem = cc.internal.ArmatureSystem;
  546. armatureDisplayProto.initFactory = function () {
  547. this._factory = dragonBones.CCFactory.getFactory();
  548. };
  549. Object.defineProperty(armatureDisplayProto, 'armatureName', {
  550. get() {
  551. return this._armatureName;
  552. },
  553. set(value) {
  554. this._armatureName = value;
  555. const animNames = this.getAnimationNames(this._armatureName);
  556. if (!this.animationName || animNames.indexOf(this.animationName) < 0) {
  557. this.animationName = '';
  558. }
  559. const oldArmature = this._armature;
  560. if (this._armature) {
  561. if (!this.isAnimationCached()) {
  562. this._factory.remove(this._armature);
  563. }
  564. this._armature = null;
  565. }
  566. this._nativeDisplay = null;
  567. this._refresh();
  568. if (oldArmature && oldArmature !== this._armature) {
  569. oldArmature.dispose();
  570. }
  571. if (this._armature && !this.isAnimationCached() && this.shouldSchedule) {
  572. this._factory.add(this._armature);
  573. }
  574. },
  575. visible: false
  576. });
  577. Object.defineProperty(armatureDisplayProto, 'premultipliedAlpha', {
  578. get() {
  579. if (this._premultipliedAlpha === undefined) {
  580. return false;
  581. }
  582. return this._premultipliedAlpha;
  583. },
  584. set(value) {
  585. this._premultipliedAlpha = value;
  586. if (this._nativeDisplay) {
  587. this._nativeDisplay.setOpacityModifyRGB(this._premultipliedAlpha);
  588. }
  589. }
  590. });
  591. const _initDebugDraw = armatureDisplayProto._initDebugDraw;
  592. armatureDisplayProto._initDebugDraw = function () {
  593. _initDebugDraw.call(this);
  594. if (this._armature && !this.isAnimationCached()) {
  595. this._nativeDisplay.setDebugBonesEnabled(this.debugBones);
  596. }
  597. };
  598. armatureDisplayProto._buildArmature = function () {
  599. if (!this.dragonAsset || !this.dragonAtlasAsset || !this.armatureName) {
  600. return;
  601. }
  602. if (this._nativeDisplay) {
  603. this._nativeDisplay.dispose();
  604. this._nativeDisplay._comp = null;
  605. this._nativeDisplay = null;
  606. }
  607. const atlasUUID = this.dragonAtlasAsset._uuid;
  608. this._armatureKey = this.dragonAsset.init(this._factory, atlasUUID);
  609. if (this.isAnimationCached()) {
  610. const isShare = this._cacheMode === AnimationCacheMode.SHARED_CACHE;
  611. this._nativeDisplay = new dragonBones.CCArmatureCacheDisplay(this.armatureName, this._armatureKey, atlasUUID, isShare);
  612. if (this.shouldSchedule) this._nativeDisplay.beginSchedule();
  613. this._armature = this._nativeDisplay.armature();
  614. } else {
  615. this._nativeDisplay = this._factory.buildArmatureDisplay(this.armatureName, this._armatureKey, '', atlasUUID);
  616. if (!this._nativeDisplay) {
  617. return;
  618. }
  619. this._nativeDisplay.setDebugBonesEnabled(this.debugBones);
  620. this._armature = this._nativeDisplay.armature();
  621. this._armature.animation.timeScale = this.timeScale;
  622. if (this.shouldSchedule) this._factory.add(this._armature);
  623. }
  624. // add all event into native display
  625. const callbackTable = this._eventTarget._callbackTable;
  626. // just use to adapt to native api
  627. const emptyHandle = function () {};
  628. for (const key in callbackTable) {
  629. const list = callbackTable[key];
  630. if (!list || !list.callbackInfos || !list.callbackInfos.length) continue;
  631. if (this.isAnimationCached()) {
  632. this._nativeDisplay.addDBEventListener(key);
  633. } else {
  634. this._nativeDisplay.addDBEventListener(key, emptyHandle);
  635. }
  636. }
  637. this._preCacheMode = this._cacheMode;
  638. this._nativeDisplay._ccNode = this.node;
  639. this._nativeDisplay._comp = this;
  640. this._nativeDisplay._eventTarget = this._eventTarget;
  641. this._sharedBufferOffset = this._nativeDisplay.getSharedBufferOffset();
  642. this._sharedBufferOffset[0] = 0;
  643. this._useAttach = false;
  644. this._nativeDisplay.setOpacityModifyRGB(this.premultipliedAlpha);
  645. const compColor = this.color;
  646. this._nativeDisplay.setColor(compColor.r, compColor.g, compColor.b, compColor.a);
  647. this._nativeDisplay.setDBEventCallback(function (eventObject) {
  648. this._eventTarget.emit(eventObject.type, eventObject);
  649. });
  650. const materialTemplate = this.getMaterialTemplate();
  651. this._nativeDisplay.setMaterial(materialTemplate);
  652. this._nativeDisplay.setRenderEntity(this._renderEntity.nativeObj);
  653. this.attachUtil.init(this);
  654. if (this._armature) {
  655. const armatureData = this._armature.armatureData;
  656. const aabb = armatureData.aABB;
  657. this.node._uiProps.uiTransformComp.setContentSize(aabb.width, aabb.height);
  658. }
  659. if (this.animationName) {
  660. this.playAnimation(this.animationName, this.playTimes);
  661. }
  662. this.markForUpdateRenderData();
  663. };
  664. armatureDisplayProto._updateColor = function () {
  665. if (this._nativeDisplay) {
  666. const compColor = this.color;
  667. this._nativeDisplay.setColor(compColor.r, compColor.g, compColor.b, compColor.a);
  668. }
  669. };
  670. armatureDisplayProto.playAnimation = function (animName, playTimes) {
  671. this.playTimes = playTimes === undefined ? -1 : playTimes;
  672. this.animationName = animName;
  673. if (this._nativeDisplay) {
  674. if (this.isAnimationCached()) {
  675. return this._nativeDisplay.playAnimation(animName, this.playTimes);
  676. } else if (this._armature) {
  677. return this._armature.animation.play(animName, this.playTimes);
  678. }
  679. }
  680. return null;
  681. };
  682. armatureDisplayProto.updateAnimationCache = function (animName) {
  683. if (!this.isAnimationCached()) return;
  684. if (this._nativeDisplay) {
  685. if (animName) {
  686. this._nativeDisplay.updateAnimationCache(animName);
  687. } else {
  688. this._nativeDisplay.updateAllAnimationCache();
  689. }
  690. }
  691. };
  692. armatureDisplayProto.invalidAnimationCache = function () {
  693. if (!this.isAnimationCached()) return;
  694. if (this._nativeDisplay) {
  695. this._nativeDisplay.updateAllAnimationCache();
  696. }
  697. };
  698. const _onEnable = superProto.onEnable;
  699. armatureDisplayProto.onEnable = function () {
  700. if (_onEnable) {
  701. _onEnable.call(this);
  702. }
  703. this.shouldSchedule = true;
  704. if (this._armature) {
  705. if (this.isAnimationCached()) {
  706. this._nativeDisplay.onEnable();
  707. } else {
  708. this._factory.add(this._armature);
  709. }
  710. }
  711. this._flushAssembler();
  712. armatureSystem.getInstance().add(this);
  713. middleware.retain();
  714. };
  715. const _onDisable = superProto.onDisable;
  716. armatureDisplayProto.onDisable = function () {
  717. if (_onDisable) {
  718. _onDisable.call(this);
  719. }
  720. if (this._armature && !this.isAnimationCached()) {
  721. this._factory.remove(this._armature);
  722. }
  723. armatureSystem.getInstance().remove(this);
  724. middleware.release();
  725. };
  726. const _updateMaterial = armatureDisplayProto.updateMaterial;
  727. armatureDisplayProto.updateMaterial = function () {
  728. _updateMaterial.call(this);
  729. if (this._nativeDisplay) {
  730. const mat = this.getMaterialTemplate();
  731. this._nativeDisplay.setMaterial(mat);
  732. }
  733. };
  734. armatureDisplayProto.once = function (eventType, listener, target) {
  735. if (this._nativeDisplay) {
  736. if (this.isAnimationCached()) {
  737. this._nativeDisplay.addDBEventListener(eventType);
  738. } else {
  739. this._nativeDisplay.addDBEventListener(eventType, listener);
  740. }
  741. }
  742. this._eventTarget.once(eventType, listener, target);
  743. };
  744. armatureDisplayProto.addEventListener = function (eventType, listener, target) {
  745. if (this._nativeDisplay) {
  746. if (this.isAnimationCached()) {
  747. this._nativeDisplay.addDBEventListener(eventType);
  748. } else {
  749. this._nativeDisplay.addDBEventListener(eventType, listener);
  750. }
  751. }
  752. this._eventTarget.on(eventType, listener, target);
  753. };
  754. armatureDisplayProto.removeEventListener = function (eventType, listener, target) {
  755. if (this._nativeDisplay) {
  756. if (this.isAnimationCached()) {
  757. this._nativeDisplay.removeDBEventListener(eventType);
  758. } else {
  759. this._nativeDisplay.removeDBEventListener(eventType, listener);
  760. }
  761. }
  762. this._eventTarget.off(eventType, listener, target);
  763. };
  764. const _onDestroy = armatureDisplayProto.onDestroy;
  765. armatureDisplayProto.onDestroy = function () {
  766. _onDestroy.call(this);
  767. if (this._nativeDisplay) {
  768. this._nativeDisplay.dispose();
  769. this._nativeDisplay._comp = null;
  770. this._nativeDisplay = null;
  771. }
  772. };
  773. armatureDisplayProto.setAnimationCacheMode = function (cacheMode) {
  774. if (this._preCacheMode !== cacheMode) {
  775. this._cacheMode = cacheMode;
  776. this._buildArmature();
  777. if (this._armature && !this.isAnimationCached() && this.shouldSchedule) {
  778. this._factory.add(this._armature);
  779. }
  780. this._updateSocketBindings();
  781. this.markForUpdateRenderData();
  782. }
  783. };
  784. armatureDisplayProto.updateAnimation = function () {
  785. const nativeDisplay = this._nativeDisplay;
  786. if (!nativeDisplay) return;
  787. const node = this.node;
  788. if (!node) return;
  789. if (this.__preColor__ === undefined || !this.color.equals(this.__preColor__)) {
  790. const compColor = this.color;
  791. nativeDisplay.setColor(compColor.r, compColor.g, compColor.b, compColor.a);
  792. this.__preColor__ = compColor;
  793. }
  794. const socketNodes = this.socketNodes;
  795. if (!this._useAttach && socketNodes.size > 0) {
  796. this._useAttach = true;
  797. nativeDisplay.setAttachEnabled(true);
  798. }
  799. this.markForUpdateRenderData();
  800. if (!this.isAnimationCached() && this._debugDraw && this.debugBones) {
  801. const nativeDisplay = this._nativeDisplay;
  802. this._debugData = this._debugData || nativeDisplay.getDebugData();
  803. if (!this._debugData) return;
  804. const graphics = this._debugDraw;
  805. graphics.clear();
  806. const debugData = this._debugData;
  807. let debugIdx = 0;
  808. graphics.lineWidth = 5;
  809. graphics.strokeColor = _boneColor;
  810. graphics.fillColor = _slotColor; // Root bone color is same as slot color.
  811. const debugBonesLen = debugData[debugIdx++];
  812. for (let i = 0; i < debugBonesLen; i += 4) {
  813. const bx = debugData[debugIdx++];
  814. const by = debugData[debugIdx++];
  815. const x = debugData[debugIdx++];
  816. const y = debugData[debugIdx++];
  817. // Bone lengths.
  818. graphics.moveTo(bx, by);
  819. graphics.lineTo(x, y);
  820. graphics.stroke();
  821. // Bone origins.
  822. graphics.circle(bx, by, Math.PI * 2);
  823. graphics.fill();
  824. if (i === 0) {
  825. graphics.fillColor = _originColor;
  826. }
  827. }
  828. }
  829. };
  830. const _tempAttachMat4 = cc.mat4();
  831. armatureDisplayProto._render = function () {};
  832. armatureDisplayProto._updateBatch = function () {
  833. if (this.nativeDisplay) {
  834. this.nativeDisplay.setBatchEnabled(this.enableBatch);
  835. this.markForUpdateRenderData();
  836. }
  837. };
  838. armatureDisplayProto.syncAttachedNode = function () {
  839. const nativeDisplay = this._nativeDisplay;
  840. if (!nativeDisplay) return;
  841. const sharedBufferOffset = this._sharedBufferOffset;
  842. if (!sharedBufferOffset) return;
  843. const sockets = this.sockets;
  844. if (sockets.length > 0) {
  845. const attachInfoMgr = middleware.attachInfoMgr;
  846. const attachInfo = attachInfoMgr.attachInfo;
  847. const attachInfoOffset = sharedBufferOffset[0];
  848. // reset attach info offset
  849. sharedBufferOffset[0] = 0;
  850. const socketNodes = this.socketNodes;
  851. for (let l = sockets.length - 1; l >= 0; l--) {
  852. const sock = sockets[l];
  853. const boneNode = sock.target;
  854. const boneIdx = sock.boneIndex;
  855. if (!boneNode) continue;
  856. // Node has been destroy
  857. if (!boneNode.isValid) {
  858. socketNodes.delete(sock.path);
  859. sockets.splice(l, 1);
  860. continue;
  861. }
  862. const tm = _tempAttachMat4;
  863. const matOffset = attachInfoOffset + boneIdx * 16;
  864. tm.m00 = attachInfo[matOffset];
  865. tm.m01 = attachInfo[matOffset + 1];
  866. tm.m04 = attachInfo[matOffset + 4];
  867. tm.m05 = attachInfo[matOffset + 5];
  868. tm.m12 = attachInfo[matOffset + 12];
  869. tm.m13 = attachInfo[matOffset + 13];
  870. boneNode.matrix = tm;
  871. }
  872. }
  873. };
  874. //////////////////////////////////////////
  875. // assembler
  876. const assembler = cc.internal.DragonBonesAssembler;
  877. // eslint-disable-next-line no-unused-vars
  878. assembler.createData = function (comp) {};
  879. assembler.updateRenderData = function (comp) {
  880. comp._render();
  881. };
  882. // eslint-disable-next-line no-unused-vars
  883. assembler.fillBuffers = function (comp, renderer) {};
  884. })();
  885. },{"./jsb-cache-manager":3}],5:[function(require,module,exports){
  886. "use strict";
  887. /****************************************************************************
  888. Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
  889. https://www.cocos.com/
  890. Permission is hereby granted, free of charge, to any person obtaining a copy
  891. of this software and associated engine source code (the "Software"), a limited,
  892. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  893. to use Cocos Creator solely to develop games on your target platforms. You shall
  894. not use Cocos Creator software for developing other software or tools that's
  895. used for developing games. You are not granted to publish, distribute,
  896. sublicense, and/or sell copies of Cocos Creator.
  897. The software or tools in this License Agreement are licensed, not sold.
  898. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  899. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  900. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  901. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  902. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  903. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  904. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  905. THE SOFTWARE.
  906. ****************************************************************************/
  907. (function () {
  908. if (!(cc && cc.internal && cc.internal.EditBox)) {
  909. return;
  910. }
  911. const EditBox = cc.internal.EditBox;
  912. const KeyboardReturnType = EditBox.KeyboardReturnType;
  913. const InputMode = EditBox.InputMode;
  914. const InputFlag = EditBox.InputFlag;
  915. const worldMat = cc.mat4();
  916. function getInputType(type) {
  917. switch (type) {
  918. case InputMode.EMAIL_ADDR:
  919. return 'email';
  920. case InputMode.NUMERIC:
  921. case InputMode.DECIMAL:
  922. return 'number';
  923. case InputMode.PHONE_NUMBER:
  924. return 'phone';
  925. case InputMode.URL:
  926. return 'url';
  927. case InputMode.SINGLE_LINE:
  928. case InputMode.ANY:
  929. default:
  930. return 'text';
  931. }
  932. }
  933. function getKeyboardReturnType(type) {
  934. switch (type) {
  935. case KeyboardReturnType.DEFAULT:
  936. case KeyboardReturnType.DONE:
  937. return 'done';
  938. case KeyboardReturnType.SEND:
  939. return 'send';
  940. case KeyboardReturnType.SEARCH:
  941. return 'search';
  942. case KeyboardReturnType.GO:
  943. return 'go';
  944. case KeyboardReturnType.NEXT:
  945. return 'next';
  946. }
  947. return 'done';
  948. }
  949. const BaseClass = EditBox._EditBoxImpl;
  950. class JsbEditBoxImpl extends BaseClass {
  951. init(delegate) {
  952. if (!delegate) {
  953. cc.error('EditBox init failed');
  954. return;
  955. }
  956. this._delegate = delegate;
  957. }
  958. beginEditing() {
  959. const self = this;
  960. const delegate = this._delegate;
  961. const multiline = delegate.inputMode === InputMode.ANY;
  962. const rect = this._getRect();
  963. this.setMaxLength(delegate.maxLength);
  964. let inputTypeString = getInputType(delegate.inputMode);
  965. if (delegate.inputFlag === InputFlag.PASSWORD) {
  966. inputTypeString = 'password';
  967. }
  968. function onConfirm(res) {
  969. delegate._editBoxEditingReturn();
  970. }
  971. function onInput(res) {
  972. if (res.value.length > self._maxLength) {
  973. res.value = res.value.slice(0, self._maxLength);
  974. }
  975. if (delegate.string !== res.value) {
  976. delegate._editBoxTextChanged(res.value);
  977. }
  978. }
  979. function onComplete(res) {
  980. self.endEditing();
  981. }
  982. jsb.inputBox.onInput(onInput);
  983. jsb.inputBox.onConfirm(onConfirm);
  984. jsb.inputBox.onComplete(onComplete);
  985. if (!cc.sys.isMobile) {
  986. delegate._hideLabels();
  987. }
  988. const editLabel = delegate.textLabel;
  989. jsb.inputBox.show({
  990. defaultValue: delegate.string,
  991. maxLength: self._maxLength,
  992. multiple: multiline,
  993. confirmHold: false,
  994. confirmType: getKeyboardReturnType(delegate.returnType),
  995. inputType: inputTypeString,
  996. originX: rect.x,
  997. originY: rect.y,
  998. width: rect.width,
  999. height: rect.height,
  1000. isBold: editLabel.isBold,
  1001. isItalic: editLabel.isItalic,
  1002. isUnderline: editLabel.isUnderline,
  1003. underlineColor: 0x00000000 /* Black */,
  1004. fontSize: /**number */editLabel.fontSize,
  1005. fontColor: /**number */editLabel.color.toRGBValue(),
  1006. backColor: 0x00ffffff /*White*/,
  1007. backgroundColor: delegate.placeholderLabel.color.toRGBValue(),
  1008. textAlignment: /*left = 0, center = 1, right = 2*/editLabel.horizontalAlign
  1009. });
  1010. this._editing = true;
  1011. delegate._editBoxEditingDidBegan();
  1012. }
  1013. endEditing() {
  1014. this._editing = false;
  1015. if (!cc.sys.isMobile) {
  1016. this._delegate._showLabels();
  1017. }
  1018. jsb.inputBox.offConfirm();
  1019. jsb.inputBox.offInput();
  1020. jsb.inputBox.offComplete();
  1021. jsb.inputBox.hide();
  1022. this._delegate._editBoxEditingDidEnded();
  1023. }
  1024. setMaxLength(maxLength) {
  1025. if (!isNaN(maxLength)) {
  1026. if (maxLength < 0) {
  1027. //we can't set Number.MAX_VALUE to input's maxLength property
  1028. //so we use a magic number here, it should works at most use cases.
  1029. maxLength = 65535;
  1030. }
  1031. this._maxLength = maxLength;
  1032. }
  1033. }
  1034. _getRect() {
  1035. const node = this._delegate.node;
  1036. let viewScaleX = cc.view.getScaleX();
  1037. let viewScaleY = cc.view.getScaleY();
  1038. const dpr = jsb.device.getDevicePixelRatio() || 1;
  1039. node.getWorldMatrix(worldMat);
  1040. const transform = node._uiProps.uiTransformComp;
  1041. const vec3 = cc.v3();
  1042. let width = 0;
  1043. let height = 0;
  1044. if (transform) {
  1045. const contentSize = transform.contentSize;
  1046. const anchorPoint = transform.anchorPoint;
  1047. width = contentSize.width;
  1048. height = contentSize.height;
  1049. vec3.x = -anchorPoint.x * width;
  1050. vec3.y = -anchorPoint.y * height;
  1051. }
  1052. const translate = new cc.Mat4();
  1053. cc.Mat4.fromTranslation(translate, vec3);
  1054. cc.Mat4.multiply(worldMat, translate, worldMat);
  1055. viewScaleX /= dpr;
  1056. viewScaleY /= dpr;
  1057. const finalScaleX = worldMat.m00 * viewScaleX;
  1058. const finaleScaleY = worldMat.m05 * viewScaleY;
  1059. const viewportRect = cc.view.getViewportRect();
  1060. const offsetX = viewportRect.x / dpr;
  1061. const offsetY = viewportRect.y / dpr;
  1062. return {
  1063. x: worldMat.m12 * viewScaleX + offsetX,
  1064. y: worldMat.m13 * viewScaleY + offsetY,
  1065. width: width * finalScaleX,
  1066. height: height * finaleScaleY
  1067. };
  1068. }
  1069. }
  1070. EditBox._EditBoxImpl = JsbEditBoxImpl;
  1071. })();
  1072. },{}],6:[function(require,module,exports){
  1073. "use strict";
  1074. /****************************************************************************
  1075. Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
  1076. http://www.cocos.com
  1077. Permission is hereby granted, free of charge, to any person obtaining a copy
  1078. of this software and associated engine source code (the "Software"), a limited,
  1079. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  1080. to use Cocos Creator solely to develop games on your target platforms. You shall
  1081. not use Cocos Creator software for developing other software or tools that's
  1082. used for developing games. You are not granted to publish, distribute,
  1083. sublicense, and/or sell copies of Cocos Creator.
  1084. The software or tools in this License Agreement are licensed, not sold.
  1085. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  1086. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1087. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1088. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  1089. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  1090. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  1091. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  1092. THE SOFTWARE.
  1093. ****************************************************************************/
  1094. // @ts-expect-error jsb polyfills
  1095. (function () {
  1096. if (!globalThis.middleware) return;
  1097. const middleware = globalThis.middleware;
  1098. const middlewareMgr = middleware.MiddlewareManager.getInstance();
  1099. let reference = 0;
  1100. const director = cc.director;
  1101. const game = cc.game;
  1102. middleware.reset = function () {
  1103. middleware.preRenderComponent = null;
  1104. middleware.preRenderBufferIndex = 0;
  1105. middleware.indicesStart = 0;
  1106. middleware.resetIndicesStart = false;
  1107. };
  1108. middleware.reset();
  1109. middleware.retain = function () {
  1110. reference++;
  1111. };
  1112. middleware.release = function () {
  1113. if (reference === 0) {
  1114. cc.warn('middleware reference error: reference count should be greater than 0');
  1115. return;
  1116. }
  1117. reference--;
  1118. };
  1119. director.on(cc.Director.EVENT_BEFORE_UPDATE, () => {
  1120. if (reference === 0) return;
  1121. middlewareMgr.update(game.deltaTime);
  1122. });
  1123. director.on(cc.Director.EVENT_BEFORE_DRAW, () => {
  1124. if (reference === 0) return;
  1125. middlewareMgr.render(game.deltaTime);
  1126. // reset render order
  1127. middleware.reset();
  1128. //const batcher2D = director.root.batcher2D;
  1129. if (globalThis.dragonBones) {
  1130. const armaSystem = cc.internal.ArmatureSystem.getInstance();
  1131. armaSystem.prepareRenderData();
  1132. }
  1133. if (globalThis.spine) {
  1134. const skeletonSystem = cc.internal.SpineSkeletonSystem.getInstance();
  1135. skeletonSystem.prepareRenderData();
  1136. }
  1137. });
  1138. const attachInfoMgr = middlewareMgr.getAttachInfoMgr();
  1139. attachInfoMgr.attachInfo = attachInfoMgr.getSharedBuffer();
  1140. attachInfoMgr.setResizeCallback(function () {
  1141. this.attachInfo = this.getSharedBuffer();
  1142. });
  1143. middleware.attachInfoMgr = attachInfoMgr;
  1144. // generate get set function
  1145. middleware.generateGetSet = function (moduleObj) {
  1146. for (const classKey in moduleObj) {
  1147. const classProto = moduleObj[classKey] && moduleObj[classKey].prototype;
  1148. if (!classProto) continue;
  1149. for (const getName in classProto) {
  1150. const getPos = getName.search(/^get/);
  1151. if (getPos === -1) continue;
  1152. let propName = getName.replace(/^get/, '');
  1153. const nameArr = propName.split('');
  1154. const lowerFirst = nameArr[0].toLowerCase();
  1155. const upperFirst = nameArr[0].toUpperCase();
  1156. nameArr.splice(0, 1);
  1157. const left = nameArr.join('');
  1158. propName = lowerFirst + left;
  1159. const setName = `set${upperFirst}${left}`;
  1160. // eslint-disable-next-line no-prototype-builtins
  1161. if (classProto.hasOwnProperty(propName)) continue;
  1162. const setFunc = classProto[setName];
  1163. const hasSetFunc = typeof setFunc === 'function';
  1164. if (hasSetFunc) {
  1165. Object.defineProperty(classProto, propName, {
  1166. get() {
  1167. return this[getName]();
  1168. },
  1169. set(val) {
  1170. this[setName](val);
  1171. },
  1172. configurable: true
  1173. });
  1174. } else {
  1175. Object.defineProperty(classProto, propName, {
  1176. get() {
  1177. return this[getName]();
  1178. },
  1179. configurable: true
  1180. });
  1181. }
  1182. }
  1183. }
  1184. };
  1185. })();
  1186. },{}],7:[function(require,module,exports){
  1187. "use strict";
  1188. /****************************************************************************
  1189. Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd.
  1190. https://www.cocos.com/
  1191. Permission is hereby granted, free of charge, to any person obtaining a copy
  1192. of fsUtils software and associated engine source code (the "Software"), a limited,
  1193. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  1194. to use Cocos Creator solely to develop games on your target platforms. You shall
  1195. not use Cocos Creator software for developing other software or tools that's
  1196. used for developing games. You are not granted to publish, distribute,
  1197. sublicense, and/or sell copies of Cocos Creator.
  1198. The software or tools in fsUtils License Agreement are licensed, not sold.
  1199. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  1200. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1201. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1202. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  1203. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  1204. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  1205. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  1206. THE SOFTWARE.
  1207. ****************************************************************************/
  1208. const fs = jsb.fileUtils;
  1209. let jsb_downloader = null;
  1210. const downloading = new cc.AssetManager.Cache();
  1211. let tempDir = '';
  1212. jsb.Downloader.prototype._ctor = function () {
  1213. this.__nativeRefs = {};
  1214. };
  1215. const fsUtils = {
  1216. fs,
  1217. initJsbDownloader(jsbDownloaderMaxTasks, jsbDownloaderTimeout) {
  1218. jsb_downloader = new jsb.Downloader({
  1219. countOfMaxProcessingTasks: jsbDownloaderMaxTasks || 32,
  1220. timeoutInSeconds: jsbDownloaderTimeout || 30,
  1221. tempFileNameSuffix: '.tmp'
  1222. });
  1223. tempDir = `${fsUtils.getUserDataPath()}/temp`;
  1224. !fs.isDirectoryExist(tempDir) && fs.createDirectory(tempDir);
  1225. jsb_downloader.onSuccess = task => {
  1226. if (!downloading.has(task.requestURL)) return;
  1227. const {
  1228. onComplete
  1229. } = downloading.remove(task.requestURL);
  1230. onComplete && onComplete(null, task.storagePath);
  1231. };
  1232. jsb_downloader.onError = (task, errorCode, errorCodeInternal, errorStr) => {
  1233. if (!downloading.has(task.requestURL)) return;
  1234. const {
  1235. onComplete
  1236. } = downloading.remove(task.requestURL);
  1237. cc.error(`Download file failed: path: ${task.requestURL} message: ${errorStr}, ${errorCode}`);
  1238. onComplete(new Error(errorStr), null);
  1239. };
  1240. jsb_downloader.onProgress = (task, bytesReceived, totalBytesReceived, totalBytesExpected) => {
  1241. if (!downloading.has(task.requestURL)) return;
  1242. const {
  1243. onProgress
  1244. } = downloading.get(task.requestURL);
  1245. onProgress && onProgress(totalBytesReceived, totalBytesExpected);
  1246. };
  1247. },
  1248. getUserDataPath() {
  1249. return fs.getWritablePath().replace(/[\/\\]*$/, '');
  1250. },
  1251. checkFsValid() {
  1252. if (!fs) {
  1253. cc.warn('can not get the file system!');
  1254. return false;
  1255. }
  1256. return true;
  1257. },
  1258. deleteFile(filePath, onComplete) {
  1259. const result = fs.removeFile(filePath);
  1260. if (result === true) {
  1261. onComplete && onComplete(null);
  1262. } else {
  1263. cc.warn(`Delete file failed: path: ${filePath}`);
  1264. onComplete && onComplete(new Error('delete file failed'));
  1265. }
  1266. },
  1267. downloadFile(remoteUrl, filePath, header, onProgress, onComplete) {
  1268. downloading.add(remoteUrl, {
  1269. onProgress,
  1270. onComplete
  1271. });
  1272. let storagePath = filePath;
  1273. if (!storagePath) storagePath = `${tempDir}/${performance.now()}${cc.path.extname(remoteUrl)}`;
  1274. jsb_downloader.createDownloadTask(remoteUrl, storagePath, header);
  1275. },
  1276. saveFile(srcPath, destPath, onComplete) {
  1277. let err = null;
  1278. const result = fs.writeDataToFile(fs.getDataFromFile(srcPath), destPath);
  1279. fs.removeFile(srcPath);
  1280. if (!result) {
  1281. err = new Error(`Save file failed: path: ${srcPath}`);
  1282. cc.warn(err.message);
  1283. }
  1284. onComplete && onComplete(err);
  1285. },
  1286. copyFile(srcPath, destPath, onComplete) {
  1287. let err = null;
  1288. const result = fs.writeDataToFile(fs.getDataFromFile(srcPath), destPath);
  1289. if (!result) {
  1290. err = new Error(`Copy file failed: path: ${srcPath}`);
  1291. cc.warn(err.message);
  1292. }
  1293. onComplete && onComplete(err);
  1294. },
  1295. writeFile(path, data, encoding, onComplete) {
  1296. let result = null;
  1297. let err = null;
  1298. if (encoding === 'utf-8' || encoding === 'utf8') {
  1299. result = fs.writeStringToFile(data, path);
  1300. } else {
  1301. result = fs.writeDataToFile(data, path);
  1302. }
  1303. if (!result) {
  1304. err = new Error(`Write file failed: path: ${path}`);
  1305. cc.warn(err.message);
  1306. }
  1307. onComplete && onComplete(err);
  1308. },
  1309. writeFileSync(path, data, encoding) {
  1310. let result = null;
  1311. if (encoding === 'utf-8' || encoding === 'utf8') {
  1312. result = fs.writeStringToFile(data, path);
  1313. } else {
  1314. result = fs.writeDataToFile(data, path);
  1315. }
  1316. if (!result) {
  1317. cc.warn(`Write file failed: path: ${path}`);
  1318. return new Error(`Write file failed: path: ${path}`);
  1319. }
  1320. return null;
  1321. },
  1322. readFile(filePath, encoding, onComplete) {
  1323. if (encoding === 'utf-8' || encoding === 'utf8') {
  1324. fs.readTextFile(filePath, (err, content) => {
  1325. if (err) err = new Error(err);
  1326. onComplete && onComplete(err, content);
  1327. });
  1328. } else {
  1329. fs.readDataFile(filePath, (err, content) => {
  1330. if (err) err = new Error(err);
  1331. onComplete && onComplete(err, content);
  1332. });
  1333. }
  1334. },
  1335. readDir(filePath, onComplete) {
  1336. let files = null;
  1337. let err = null;
  1338. try {
  1339. files = fs.listFiles(filePath);
  1340. } catch (e) {
  1341. cc.warn(`Read dir failed: path: ${filePath} message: ${e.message}`);
  1342. err = new Error(e.message);
  1343. }
  1344. onComplete && onComplete(err, files);
  1345. },
  1346. readText(filePath, onComplete) {
  1347. fsUtils.readFile(filePath, 'utf8', onComplete);
  1348. },
  1349. readArrayBuffer(filePath, onComplete) {
  1350. fsUtils.readFile(filePath, '', onComplete);
  1351. },
  1352. readJson(filePath, onComplete) {
  1353. if (window.oh && window.scriptEngineType === 'napi') {
  1354. fsUtils.readFile(filePath, 'utf8', (err, text) => {
  1355. let out = null;
  1356. if (!err) {
  1357. try {
  1358. out = JSON.parse(text);
  1359. } catch (e) {
  1360. cc.warn(`Read json failed: path: ${filePath} message: ${e.message}`);
  1361. err = new Error(e.message);
  1362. }
  1363. }
  1364. onComplete && onComplete(err, out);
  1365. });
  1366. } else {
  1367. fs.readJsonFile(filePath, (err, jsonObj) => {
  1368. if (err) {
  1369. cc.warn(`Read json failed: path: ${filePath} message: ${err}`);
  1370. err = new Error(err);
  1371. }
  1372. onComplete && onComplete(err, jsonObj);
  1373. });
  1374. }
  1375. },
  1376. readJsonSync(path) {
  1377. try {
  1378. const str = fs.getStringFromFile(path);
  1379. return JSON.parse(str);
  1380. } catch (e) {
  1381. cc.warn(`Read json failed: path: ${path} message: ${e.message}`);
  1382. return new Error(e.message);
  1383. }
  1384. },
  1385. makeDirSync(path, recursive) {
  1386. const result = fs.createDirectory(path);
  1387. if (!result) {
  1388. cc.warn(`Make directory failed: path: ${path}`);
  1389. return new Error(`Make directory failed: path: ${path}`);
  1390. }
  1391. return null;
  1392. },
  1393. rmdirSync(dirPath, recursive) {
  1394. const result = fs.removeDirectory(dirPath);
  1395. if (!result) {
  1396. cc.warn(`rm directory failed: path: ${dirPath}`);
  1397. return new Error(`rm directory failed: path: ${dirPath}`);
  1398. }
  1399. return null;
  1400. },
  1401. exists(filePath, onComplete) {
  1402. const result = fs.isFileExist(filePath);
  1403. onComplete && onComplete(result);
  1404. },
  1405. loadSubpackage(name, onProgress, onComplete) {
  1406. throw new Error('not implement');
  1407. }
  1408. };
  1409. globalThis.fsUtils = module.exports = fsUtils;
  1410. },{}],8:[function(require,module,exports){
  1411. "use strict";
  1412. /****************************************************************************
  1413. Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
  1414. https://www.cocos.com/
  1415. Permission is hereby granted, free of charge, to any person obtaining a copy
  1416. of this software and associated engine source code (the "Software"), a limited,
  1417. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  1418. to use Cocos Creator solely to develop games on your target platforms. You shall
  1419. not use Cocos Creator software for developing other software or tools that's
  1420. used for developing games. You are not granted to publish, distribute,
  1421. sublicense, and/or sell copies of Cocos Creator.
  1422. The software or tools in this License Agreement are licensed, not sold.
  1423. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  1424. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1425. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1426. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  1427. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  1428. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  1429. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  1430. THE SOFTWARE.
  1431. ****************************************************************************/
  1432. cc.game.restart = function () {
  1433. // Need to clear scene, or native object destructor won't be invoke.
  1434. cc.director.getScene().destroy();
  1435. cc.Object._deferredDestroy();
  1436. __restartVM();
  1437. };
  1438. jsb.onError(function (location, message, stack) {
  1439. console.error(location, message, stack);
  1440. });
  1441. jsb.onMemoryWarning = function () {
  1442. cc.game.emit(cc.Game.EVENT_LOW_MEMORY);
  1443. };
  1444. },{}],9:[function(require,module,exports){
  1445. "use strict";
  1446. /****************************************************************************
  1447. Copyright (c) 2020 Xiamen Yaji Software Co., Ltd.
  1448. https://www.cocos.com/
  1449. Permission is hereby granted, free of charge, to any person obtaining a copy
  1450. of this software and associated engine source code (the "Software"), a limited,
  1451. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  1452. to use Cocos Creator solely to develop games on your target platforms. You shall
  1453. not use Cocos Creator software for developing other software or tools that's
  1454. used for developing games. You are not granted to publish, distribute,
  1455. sublicense, and/or sell copies of Cocos Creator.
  1456. The software or tools in this License Agreement are licensed, not sold.
  1457. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  1458. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1459. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1460. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  1461. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  1462. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  1463. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  1464. THE SOFTWARE.
  1465. ****************************************************************************/
  1466. /* global gfx */
  1467. const deviceProto = gfx.Device.prototype;
  1468. const swapchainProto = gfx.Swapchain.prototype;
  1469. const bufferProto = gfx.Buffer.prototype;
  1470. const textureProto = gfx.Texture.prototype;
  1471. const descriptorSetProto = gfx.DescriptorSet.prototype;
  1472. const jsbWindow = require('../jsbWindow');
  1473. ///////////////////////////// handle different paradigms /////////////////////////////
  1474. const oldCopyTexImagesToTextureFunc = deviceProto.copyTexImagesToTexture;
  1475. deviceProto.copyTexImagesToTexture = function (texImages, texture, regions) {
  1476. const images = [];
  1477. if (texImages) {
  1478. for (let i = 0; i < texImages.length; ++i) {
  1479. const texImage = texImages[i];
  1480. if (texImage instanceof jsbWindow.HTMLCanvasElement) {
  1481. // Refer to HTMLCanvasElement and ImageData implementation
  1482. images.push(texImage._data.data);
  1483. } else if (texImage instanceof jsbWindow.HTMLImageElement) {
  1484. // Refer to HTMLImageElement implementation
  1485. images.push(texImage._data);
  1486. } else {
  1487. console.log('copyTexImagesToTexture: Convert texImages to data buffers failed');
  1488. return;
  1489. }
  1490. }
  1491. }
  1492. oldCopyTexImagesToTextureFunc.call(this, images, texture, regions);
  1493. };
  1494. const oldDeviceCreateSwapchainFunc = deviceProto.createSwapchain;
  1495. deviceProto.createSwapchain = function (info) {
  1496. info.windowHandle = jsbWindow.windowHandle;
  1497. return oldDeviceCreateSwapchainFunc.call(this, info);
  1498. };
  1499. const oldSwapchainInitializeFunc = swapchainProto.initialize;
  1500. swapchainProto.initialize = function (info) {
  1501. info.windowHandle = jsbWindow.windowHandler;
  1502. oldSwapchainInitializeFunc.call(this, info);
  1503. };
  1504. const oldUpdate = bufferProto.update;
  1505. bufferProto.update = function (buffer, size) {
  1506. if (buffer.byteLength === 0) return;
  1507. let buffSize;
  1508. if (this.cachedUsage & 0x40) {
  1509. // BufferUsageBit.INDIRECT
  1510. // It is a IIndirectBuffer object.
  1511. const {
  1512. drawInfos
  1513. } = buffer;
  1514. buffer = new Uint32Array(drawInfos.length * 7);
  1515. let baseIndex = 0;
  1516. let drawInfo;
  1517. for (let i = 0; i < drawInfos.length; ++i) {
  1518. baseIndex = i * 7;
  1519. drawInfo = drawInfos[i];
  1520. buffer[baseIndex] = drawInfo.vertexCount;
  1521. buffer[baseIndex + 1] = drawInfo.firstVertex;
  1522. buffer[baseIndex + 2] = drawInfo.indexCount;
  1523. buffer[baseIndex + 3] = drawInfo.firstIndex;
  1524. buffer[baseIndex + 4] = drawInfo.vertexOffset;
  1525. buffer[baseIndex + 5] = drawInfo.instanceCount;
  1526. buffer[baseIndex + 6] = drawInfo.firstInstance;
  1527. }
  1528. buffSize = buffer.byteLength;
  1529. } else if (size !== undefined) {
  1530. buffSize = size;
  1531. } else {
  1532. buffSize = buffer.byteLength;
  1533. }
  1534. oldUpdate.call(this, buffer, buffSize);
  1535. };
  1536. const oldDeviceCreateBufferFun = deviceProto.createBuffer;
  1537. deviceProto.createBuffer = function (info) {
  1538. let buffer;
  1539. if (info.buffer) {
  1540. buffer = oldDeviceCreateBufferFun.call(this, info, true);
  1541. } else {
  1542. buffer = oldDeviceCreateBufferFun.call(this, info, false);
  1543. }
  1544. buffer.cachedUsage = info.usage;
  1545. return buffer;
  1546. };
  1547. const oldBufferInitializeFunc = bufferProto.initialize;
  1548. bufferProto.initialize = function (info) {
  1549. if (info.buffer) {
  1550. oldBufferInitializeFunc.call(this, info, true);
  1551. } else {
  1552. oldBufferInitializeFunc.call(this, info, false);
  1553. }
  1554. };
  1555. const oldDeviceCreateTextureFun = deviceProto.createTexture;
  1556. deviceProto.createTexture = function (info) {
  1557. if (info.texture) {
  1558. return oldDeviceCreateTextureFun.call(this, info, true);
  1559. }
  1560. return oldDeviceCreateTextureFun.call(this, info, false);
  1561. };
  1562. const oldTextureInitializeFunc = textureProto.initialize;
  1563. textureProto.initialize = function (info) {
  1564. if (info.texture) {
  1565. oldTextureInitializeFunc.call(this, info, true);
  1566. } else {
  1567. oldTextureInitializeFunc.call(this, info, false);
  1568. }
  1569. };
  1570. ///////////////////////////// optimizations /////////////////////////////
  1571. // Cache dirty to avoid invoking gfx.DescriptorSet.update().
  1572. descriptorSetProto.bindBuffer = function (binding, buffer, index) {
  1573. this.dirtyJSB = descriptorSetProto.bindBufferJSB.call(this, binding, buffer, index || 0);
  1574. };
  1575. descriptorSetProto.bindSampler = function (binding, sampler, index) {
  1576. this.dirtyJSB = descriptorSetProto.bindSamplerJSB.call(this, binding, sampler, index || 0);
  1577. };
  1578. descriptorSetProto.bindTexture = function (bindding, texture, index, flags) {
  1579. this.dirtyJSB = descriptorSetProto.bindTextureJSB.call(this, bindding, texture, index || 0, flags || 0);
  1580. };
  1581. const oldDSUpdate = descriptorSetProto.update;
  1582. descriptorSetProto.update = function () {
  1583. if (!this.dirtyJSB) return;
  1584. oldDSUpdate.call(this);
  1585. this.dirtyJSB = false;
  1586. };
  1587. Object.defineProperty(deviceProto, 'uboOffsetAlignment', {
  1588. get() {
  1589. if (this.cachedUboOffsetAlignment === undefined) {
  1590. this.cachedUboOffsetAlignment = this.getUboOffsetAlignment();
  1591. }
  1592. return this.cachedUboOffsetAlignment;
  1593. }
  1594. });
  1595. },{"../jsbWindow":16}],10:[function(require,module,exports){
  1596. "use strict";
  1597. /****************************************************************************
  1598. Copyright (c) 2013-2016 Chukong Technologies Inc.
  1599. Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd.
  1600. https://www.cocos.com/
  1601. Permission is hereby granted, free of charge, to any person obtaining a copy
  1602. of this software and associated engine source code (the "Software"), a limited,
  1603. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  1604. to use Cocos Creator solely to develop games on your target platforms. You shall
  1605. not use Cocos Creator software for developing other software or tools that's
  1606. used for developing games. You are not granted to publish, distribute,
  1607. sublicense, and/or sell copies of Cocos Creator.
  1608. The software or tools in this License Agreement are licensed, not sold.
  1609. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  1610. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1611. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1612. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  1613. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  1614. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  1615. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  1616. THE SOFTWARE.
  1617. ****************************************************************************/
  1618. /* eslint-disable no-undef */
  1619. const jsbWindow = require('../jsbWindow');
  1620. const cacheManager = require('./jsb-cache-manager');
  1621. const {
  1622. downloadFile,
  1623. readText,
  1624. readArrayBuffer,
  1625. readJson,
  1626. getUserDataPath,
  1627. initJsbDownloader
  1628. } = require('./jsb-fs-utils');
  1629. const REGEX = /^\w+:\/\/.*/;
  1630. const downloader = cc.assetManager.downloader;
  1631. const parser = cc.assetManager.parser;
  1632. const presets = cc.assetManager.presets;
  1633. downloader.maxConcurrency = 30;
  1634. downloader.maxRequestsPerFrame = 60;
  1635. presets.preload.maxConcurrency = 15;
  1636. presets.preload.maxRequestsPerFrame = 30;
  1637. presets.scene.maxConcurrency = 32;
  1638. presets.scene.maxRequestsPerFrame = 64;
  1639. presets.bundle.maxConcurrency = 32;
  1640. presets.bundle.maxRequestsPerFrame = 64;
  1641. let suffix = 0;
  1642. const failureMap = {};
  1643. const maxRetryCountFromBreakpoint = 5;
  1644. const loadedScripts = {};
  1645. function downloadScript(url, options, onComplete) {
  1646. if (typeof options === 'function') {
  1647. onComplete = options;
  1648. options = null;
  1649. }
  1650. if (loadedScripts[url]) {
  1651. onComplete && onComplete();
  1652. return;
  1653. }
  1654. download(url, (src, options, onComplete) => {
  1655. if (window.oh && window.scriptEngineType === 'napi') {
  1656. // TODO(qgh):OpenHarmony does not currently support dynamic require expressions
  1657. window.oh.loadModule(src);
  1658. } else if (__EDITOR__) {
  1659. // in editor mode,require is from electron,__require is from engine
  1660. globalThis.__require(src);
  1661. } else {
  1662. globalThis.require(src);
  1663. }
  1664. loadedScripts[url] = true;
  1665. onComplete && onComplete(null);
  1666. }, options, options.onFileProgress, onComplete);
  1667. }
  1668. function download(url, func, options, onFileProgress, onComplete) {
  1669. const result = transformUrl(url, options);
  1670. if (result.inLocal) {
  1671. func(result.url, options, onComplete);
  1672. } else if (result.inCache) {
  1673. cacheManager.updateLastTime(url);
  1674. func(result.url, options, (err, data) => {
  1675. if (err) {
  1676. cacheManager.removeCache(url);
  1677. }
  1678. onComplete(err, data);
  1679. });
  1680. } else {
  1681. const time = Date.now();
  1682. let storagePath = '';
  1683. const failureRecord = failureMap[url];
  1684. if (failureRecord) {
  1685. storagePath = failureRecord.storagePath;
  1686. } else if (options.__cacheBundleRoot__) {
  1687. storagePath = `${options.__cacheBundleRoot__}/${time}${suffix++}${cc.path.extname(url)}`;
  1688. } else {
  1689. storagePath = `${time}${suffix++}${cc.path.extname(url)}`;
  1690. }
  1691. downloadFile(url, `${cacheManager.cacheDir}/${storagePath}`, options.header, onFileProgress, (err, path) => {
  1692. if (err) {
  1693. if (failureRecord) {
  1694. failureRecord.retryCount++;
  1695. if (failureRecord.retryCount >= maxRetryCountFromBreakpoint) {
  1696. delete failureMap[url];
  1697. }
  1698. } else {
  1699. failureMap[url] = {
  1700. retryCount: 0,
  1701. storagePath
  1702. };
  1703. }
  1704. onComplete(err, null);
  1705. return;
  1706. }
  1707. delete failureMap[url];
  1708. func(path, options, (err, data) => {
  1709. if (!err) {
  1710. cacheManager.cacheFile(url, storagePath, options.__cacheBundleRoot__);
  1711. }
  1712. onComplete(err, data);
  1713. });
  1714. });
  1715. }
  1716. }
  1717. function transformUrl(url, options) {
  1718. let inLocal = false;
  1719. let inCache = false;
  1720. if (REGEX.test(url) && !url.startsWith('file://')) {
  1721. if (options.reload) {
  1722. return {
  1723. url
  1724. };
  1725. } else {
  1726. const cache = cacheManager.getCache(url);
  1727. if (cache) {
  1728. inCache = true;
  1729. url = cache;
  1730. }
  1731. }
  1732. } else {
  1733. inLocal = true;
  1734. if (url.startsWith('file://')) {
  1735. url = url.replace(/^file:\/\//, '');
  1736. }
  1737. }
  1738. return {
  1739. url,
  1740. inLocal,
  1741. inCache
  1742. };
  1743. }
  1744. function doNothing(content, options, onComplete) {
  1745. onComplete(null, content);
  1746. }
  1747. function downloadAsset(url, options, onComplete) {
  1748. download(url, doNothing, options, options.onFileProgress, onComplete);
  1749. }
  1750. function _getFontFamily(fontHandle) {
  1751. const ttfIndex = fontHandle.lastIndexOf('.ttf');
  1752. if (ttfIndex === -1) return fontHandle;
  1753. const slashPos = fontHandle.lastIndexOf('/');
  1754. let fontFamilyName;
  1755. if (slashPos === -1) {
  1756. fontFamilyName = `${fontHandle.substring(0, ttfIndex)}_LABEL`;
  1757. } else {
  1758. fontFamilyName = `${fontHandle.substring(slashPos + 1, ttfIndex)}_LABEL`;
  1759. }
  1760. if (fontFamilyName.indexOf(' ') !== -1) {
  1761. fontFamilyName = `"${fontFamilyName}"`;
  1762. }
  1763. return fontFamilyName;
  1764. }
  1765. function parseText(url, options, onComplete) {
  1766. readText(url, onComplete);
  1767. }
  1768. function parseJson(url, options, onComplete) {
  1769. readJson(url, onComplete);
  1770. }
  1771. function downloadText(url, options, onComplete) {
  1772. download(url, parseText, options, options.onFileProgress, onComplete);
  1773. }
  1774. function parseArrayBuffer(url, options, onComplete) {
  1775. readArrayBuffer(url, onComplete);
  1776. }
  1777. function downloadJson(url, options, onComplete) {
  1778. download(url, parseJson, options, options.onFileProgress, onComplete);
  1779. }
  1780. function downloadBundle(nameOrUrl, options, onComplete) {
  1781. const bundleName = cc.path.basename(nameOrUrl);
  1782. const version = options.version || downloader.bundleVers[bundleName];
  1783. let url;
  1784. if (REGEX.test(nameOrUrl) || nameOrUrl.startsWith(getUserDataPath())) {
  1785. url = nameOrUrl;
  1786. cacheManager.makeBundleFolder(bundleName);
  1787. } else if (downloader.remoteBundles.indexOf(bundleName) !== -1) {
  1788. url = `${downloader.remoteServerAddress}remote/${bundleName}`;
  1789. cacheManager.makeBundleFolder(bundleName);
  1790. } else {
  1791. url = `assets/${bundleName}`;
  1792. }
  1793. const config = `${url}/cc.config.${version ? `${version}.` : ''}json`;
  1794. options.__cacheBundleRoot__ = bundleName;
  1795. downloadJson(config, options, (err, response) => {
  1796. if (err) {
  1797. onComplete(err, null);
  1798. return;
  1799. }
  1800. const out = response;
  1801. out && (out.base = `${url}/`);
  1802. if (out.hasPreloadScript) {
  1803. const js = `${url}/index.${version ? `${version}.` : ''}${out.encrypted ? 'jsc' : `js`}`;
  1804. downloadScript(js, options, err => {
  1805. if (err) {
  1806. onComplete(err, null);
  1807. return;
  1808. }
  1809. onComplete(null, out);
  1810. });
  1811. } else {
  1812. onComplete(null, out);
  1813. }
  1814. });
  1815. }
  1816. function downloadArrayBuffer(url, options, onComplete) {
  1817. download(url, parseArrayBuffer, options, options.onFileProgress, onComplete);
  1818. }
  1819. function loadFont(url, options, onComplete) {
  1820. const fontFamilyName = _getFontFamily(url);
  1821. const fontFace = new jsbWindow.FontFace(fontFamilyName, `url('${url}')`);
  1822. jsbWindow.document.fonts.add(fontFace);
  1823. fontFace.load();
  1824. fontFace.loaded.then(() => {
  1825. onComplete(null, fontFamilyName);
  1826. }, () => {
  1827. cc.warnID(4933, fontFamilyName);
  1828. onComplete(null, fontFamilyName);
  1829. });
  1830. }
  1831. const originParsePlist = parser.parsePlist;
  1832. const parsePlist = function (url, options, onComplete) {
  1833. readText(url, (err, file) => {
  1834. if (err) {
  1835. onComplete(err);
  1836. return;
  1837. }
  1838. originParsePlist(file, options, onComplete);
  1839. });
  1840. };
  1841. parser.parsePVRTex = downloader.downloadDomImage;
  1842. parser.parsePKMTex = downloader.downloadDomImage;
  1843. parser.parseASTCTex = downloader.downloadDomImage;
  1844. parser.parsePlist = parsePlist;
  1845. downloader.downloadScript = downloadScript;
  1846. downloader._downloadArrayBuffer = downloadArrayBuffer;
  1847. downloader._downloadJson = downloadJson;
  1848. function loadAudioPlayer(url, options, onComplete) {
  1849. cc.AudioPlayer.load(url).then(player => {
  1850. const audioMeta = {
  1851. player,
  1852. url,
  1853. duration: player.duration,
  1854. type: player.type
  1855. };
  1856. onComplete(null, audioMeta);
  1857. }).catch(err => {
  1858. onComplete(err);
  1859. });
  1860. }
  1861. downloader.register({
  1862. // JS
  1863. '.js': downloadScript,
  1864. '.jsc': downloadScript,
  1865. // Images
  1866. '.png': downloadAsset,
  1867. '.jpg': downloadAsset,
  1868. '.bmp': downloadAsset,
  1869. '.jpeg': downloadAsset,
  1870. '.gif': downloadAsset,
  1871. '.ico': downloadAsset,
  1872. '.tiff': downloadAsset,
  1873. '.webp': downloadAsset,
  1874. '.image': downloadAsset,
  1875. '.pvr': downloadAsset,
  1876. '.pkm': downloadAsset,
  1877. '.astc': downloadAsset,
  1878. // Audio
  1879. '.mp3': downloadAsset,
  1880. '.ogg': downloadAsset,
  1881. '.wav': downloadAsset,
  1882. '.m4a': downloadAsset,
  1883. // Video
  1884. '.mp4': downloadAsset,
  1885. '.avi': downloadAsset,
  1886. '.mov': downloadAsset,
  1887. '.mpg': downloadAsset,
  1888. '.mpeg': downloadAsset,
  1889. '.rm': downloadAsset,
  1890. '.rmvb': downloadAsset,
  1891. // Text
  1892. '.txt': downloadAsset,
  1893. '.xml': downloadAsset,
  1894. '.vsh': downloadAsset,
  1895. '.fsh': downloadAsset,
  1896. '.atlas': downloadAsset,
  1897. '.tmx': downloadAsset,
  1898. '.tsx': downloadAsset,
  1899. '.fnt': downloadAsset,
  1900. '.plist': downloadAsset,
  1901. '.json': downloadJson,
  1902. '.ExportJson': downloadAsset,
  1903. '.binary': downloadAsset,
  1904. '.bin': downloadAsset,
  1905. '.dbbin': downloadAsset,
  1906. '.skel': downloadAsset,
  1907. // Font
  1908. '.font': downloadAsset,
  1909. '.eot': downloadAsset,
  1910. '.ttf': downloadAsset,
  1911. '.woff': downloadAsset,
  1912. '.svg': downloadAsset,
  1913. '.ttc': downloadAsset,
  1914. bundle: downloadBundle,
  1915. default: downloadText
  1916. });
  1917. parser.register({
  1918. // Images
  1919. '.png': downloader.downloadDomImage,
  1920. '.jpg': downloader.downloadDomImage,
  1921. '.bmp': downloader.downloadDomImage,
  1922. '.jpeg': downloader.downloadDomImage,
  1923. '.gif': downloader.downloadDomImage,
  1924. '.ico': downloader.downloadDomImage,
  1925. '.tiff': downloader.downloadDomImage,
  1926. '.webp': downloader.downloadDomImage,
  1927. '.image': downloader.downloadDomImage,
  1928. // Audio
  1929. '.mp3': loadAudioPlayer,
  1930. '.ogg': loadAudioPlayer,
  1931. '.wav': loadAudioPlayer,
  1932. '.m4a': loadAudioPlayer,
  1933. // compressed texture
  1934. '.pvr': downloader.downloadDomImage,
  1935. '.pkm': downloader.downloadDomImage,
  1936. '.astc': downloader.downloadDomImage,
  1937. '.binary': parseArrayBuffer,
  1938. '.bin': parseArrayBuffer,
  1939. '.dbbin': parseArrayBuffer,
  1940. '.skel': parseArrayBuffer,
  1941. // Text
  1942. '.txt': parseText,
  1943. '.xml': parseText,
  1944. '.vsh': parseText,
  1945. '.fsh': parseText,
  1946. '.atlas': parseText,
  1947. '.tmx': parseText,
  1948. '.tsx': parseText,
  1949. '.fnt': parseText,
  1950. '.plist': parsePlist,
  1951. // Font
  1952. '.font': loadFont,
  1953. '.eot': loadFont,
  1954. '.ttf': loadFont,
  1955. '.woff': loadFont,
  1956. '.svg': loadFont,
  1957. '.ttc': loadFont,
  1958. '.ExportJson': parseJson
  1959. });
  1960. if (CC_BUILD) {
  1961. cc.assetManager.transformPipeline.append(task => {
  1962. const input = task.output = task.input;
  1963. for (let i = 0, l = input.length; i < l; i++) {
  1964. const item = input[i];
  1965. if (item.config) {
  1966. item.options.__cacheBundleRoot__ = item.config.name;
  1967. }
  1968. if (item.ext === '.cconb') {
  1969. item.url = item.url.replace(item.ext, '.bin');
  1970. } else if (item.ext === '.ccon') {
  1971. item.url = item.url.replace(item.ext, '.json');
  1972. }
  1973. }
  1974. });
  1975. }
  1976. const originInit = cc.assetManager.init;
  1977. cc.assetManager.init = function (options) {
  1978. originInit.call(cc.assetManager, options);
  1979. const jsbDownloaderMaxTasks = cc.settings.querySettings('assets', 'jsbDownloaderMaxTasks');
  1980. const jsbDownloaderTimeout = cc.settings.querySettings('assets', 'jsbDownloaderTimeout');
  1981. initJsbDownloader(jsbDownloaderMaxTasks, jsbDownloaderTimeout);
  1982. cacheManager.init();
  1983. };
  1984. },{"../jsbWindow":16,"./jsb-cache-manager":3,"./jsb-fs-utils":7}],11:[function(require,module,exports){
  1985. "use strict";
  1986. const jsbPhy = globalThis['jsb.physics'];
  1987. jsbPhy.CACHE = {
  1988. trimesh: {},
  1989. convex: {},
  1990. height: {},
  1991. material: {}
  1992. };
  1993. jsbPhy.OBJECT = {
  1994. books: [],
  1995. ptrToObj: {},
  1996. raycastOptions: {
  1997. origin: null,
  1998. unitDir: null,
  1999. distance: 0,
  2000. mask: 0,
  2001. queryTrigger: true
  2002. }
  2003. };
  2004. jsbPhy.CONFIG = {
  2005. heightScale: 1 / 512
  2006. };
  2007. const books = jsbPhy.OBJECT.books;
  2008. const ptrToObj = jsbPhy.OBJECT.ptrToObj;
  2009. const raycastOptions = jsbPhy.OBJECT.raycastOptions;
  2010. const TriggerEventObject = {
  2011. type: 'onTriggerEnter',
  2012. selfCollider: null,
  2013. otherCollider: null,
  2014. impl: null
  2015. };
  2016. const CollisionEventObject = {
  2017. type: 'onCollisionEnter',
  2018. selfCollider: null,
  2019. otherCollider: null,
  2020. contacts: [],
  2021. impl: null
  2022. };
  2023. const CCTShapeEventObject = {
  2024. type: 'onControllerColliderHit',
  2025. controller: null,
  2026. collider: null,
  2027. worldPosition: null,
  2028. worldNormal: null,
  2029. motionDirection: null,
  2030. motionLength: 0
  2031. };
  2032. const CharacterTriggerEventObject = {
  2033. type: 'onControllerTriggerEnter',
  2034. characterController: null,
  2035. collider: null,
  2036. impl: null
  2037. };
  2038. function emitTriggerEvent(t, c0, c1, impl) {
  2039. TriggerEventObject.type = t;
  2040. TriggerEventObject.impl = impl;
  2041. if (c0.needTriggerEvent) {
  2042. TriggerEventObject.selfCollider = c0;
  2043. TriggerEventObject.otherCollider = c1;
  2044. c0.emit(t, TriggerEventObject);
  2045. }
  2046. if (c1.needTriggerEvent) {
  2047. TriggerEventObject.selfCollider = c1;
  2048. TriggerEventObject.otherCollider = c0;
  2049. c1.emit(t, TriggerEventObject);
  2050. }
  2051. }
  2052. function emitCCTTriggerEvent(t, cct, collider, impl) {
  2053. CharacterTriggerEventObject.type = t;
  2054. CharacterTriggerEventObject.impl = impl;
  2055. CharacterTriggerEventObject.characterController = cct;
  2056. CharacterTriggerEventObject.collider = collider;
  2057. if (collider.needTriggerEvent) {
  2058. collider.emit(t, CharacterTriggerEventObject);
  2059. }
  2060. if (cct.needTriggerEvent) {
  2061. cct.emit(t, CharacterTriggerEventObject);
  2062. }
  2063. }
  2064. const quat = new cc.Quat();
  2065. const contactsPool = [];
  2066. const contactBufferElementLength = 12;
  2067. class ContactPoint {
  2068. constructor(e) {
  2069. this.event = e;
  2070. this.impl = null;
  2071. this.colliderA = null;
  2072. this.colliderB = null;
  2073. this.index = 0;
  2074. }
  2075. get isBodyA() {
  2076. return this.colliderA.uuid === this.event.selfCollider.uuid;
  2077. }
  2078. getLocalPointOnA(o) {
  2079. this.getWorldPointOnB(o);
  2080. cc.Vec3.subtract(o, o, this.colliderA.node.worldPosition);
  2081. }
  2082. getLocalPointOnB(o) {
  2083. this.getWorldPointOnB(o);
  2084. cc.Vec3.subtract(o, o, this.colliderB.node.worldPosition);
  2085. }
  2086. getWorldPointOnA(o) {
  2087. this.getWorldPointOnB(o);
  2088. }
  2089. getWorldPointOnB(o) {
  2090. const i = this.index * contactBufferElementLength;
  2091. o.x = this.impl[i];
  2092. o.y = this.impl[i + 1];
  2093. o.z = this.impl[i + 2];
  2094. }
  2095. getLocalNormalOnA(o) {
  2096. this.getWorldNormalOnA(o);
  2097. cc.Quat.conjugate(quat, this.colliderA.node.worldRotation);
  2098. cc.Vec3.transformQuat(o, o, quat);
  2099. }
  2100. getLocalNormalOnB(o) {
  2101. this.getWorldNormalOnB(o);
  2102. cc.Quat.conjugate(quat, this.colliderB.node.worldRotation);
  2103. cc.Vec3.transformQuat(out, out, quat);
  2104. }
  2105. getWorldNormalOnA(o) {
  2106. this.getWorldNormalOnB(o);
  2107. if (!this.isBodyA) cc.Vec3.negate(o, o);
  2108. }
  2109. getWorldNormalOnB(o) {
  2110. const i = this.index * contactBufferElementLength + 3;
  2111. o.x = this.impl[i];
  2112. o.y = this.impl[i + 1];
  2113. o.z = this.impl[i + 2];
  2114. }
  2115. }
  2116. function emitCollisionEvent(t, c0, c1, impl, b) {
  2117. CollisionEventObject.type = t;
  2118. CollisionEventObject.impl = impl;
  2119. const contacts = CollisionEventObject.contacts;
  2120. contactsPool.push.apply(contactsPool, contacts);
  2121. contacts.length = 0;
  2122. const contactCount = b.length / contactBufferElementLength;
  2123. for (let i = 0; i < contactCount; i++) {
  2124. const c = contactsPool.length > 0 ? contactsPool.pop() : new ContactPoint(CollisionEventObject);
  2125. c.colliderA = c0;
  2126. c.colliderB = c1;
  2127. c.impl = b;
  2128. c.index = i;
  2129. contacts.push(c);
  2130. }
  2131. if (c0.needCollisionEvent) {
  2132. CollisionEventObject.selfCollider = c0;
  2133. CollisionEventObject.otherCollider = c1;
  2134. c0.emit(t, CollisionEventObject);
  2135. }
  2136. if (c1.needCollisionEvent) {
  2137. CollisionEventObject.selfCollider = c1;
  2138. CollisionEventObject.otherCollider = c0;
  2139. c1.emit(t, CollisionEventObject);
  2140. }
  2141. }
  2142. function emitCCTCollisionEvent(t, cct, collider, b) {
  2143. CCTShapeEventObject.type = t;
  2144. const contactCount = b.length / 10;
  2145. CCTShapeEventObject.worldPosition = new cc.Vec3(b[0], b[1], b[2]);
  2146. CCTShapeEventObject.worldNormal = new cc.Vec3(b[3], b[4], b[5]);
  2147. CCTShapeEventObject.motionDirection = new cc.Vec3(b[6], b[7], b[8]);
  2148. CCTShapeEventObject.motionLength = b[9];
  2149. CCTShapeEventObject.controller = cct;
  2150. CCTShapeEventObject.collider = collider;
  2151. cct.emit(t, CCTShapeEventObject);
  2152. }
  2153. class PhysicsWorld {
  2154. get impl() {
  2155. return this._impl;
  2156. }
  2157. constructor() {
  2158. this._impl = new jsbPhy.World();
  2159. }
  2160. setGravity(v) {
  2161. this._impl.setGravity(v.x, v.y, v.z);
  2162. }
  2163. setAllowSleep(v) {
  2164. this._impl.setAllowSleep(v);
  2165. }
  2166. setDefaultMaterial(v) {}
  2167. step(f, t, m) {
  2168. // books.forEach((v) => { v.syncToNativeTransform(); });
  2169. this._impl.step(f);
  2170. }
  2171. set debugDrawFlags(v) {
  2172. this._impl.setDebugDrawFlags(v);
  2173. }
  2174. get debugDrawFlags() {
  2175. return this._impl.getDebugDrawFlags();
  2176. }
  2177. set debugDrawConstraintSize(v) {
  2178. this._impl.setDebugDrawConstraintSize(v);
  2179. }
  2180. get debugDrawConstraintSize() {
  2181. return this._impl.getDebugDrawConstraintSize();
  2182. }
  2183. raycast(r, o, p, rs) {
  2184. raycastOptions.origin = r.o;
  2185. raycastOptions.unitDir = r.d;
  2186. raycastOptions.mask = o.mask >>> 0;
  2187. raycastOptions.distance = o.maxDistance;
  2188. raycastOptions.queryTrigger = !!o.queryTrigger;
  2189. const isHit = this._impl.raycast(raycastOptions);
  2190. if (isHit) {
  2191. const hits = this._impl.raycastResult();
  2192. for (let i = 0; i < hits.length; i++) {
  2193. const hit = hits[i];
  2194. const out = p.add();
  2195. out._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal);
  2196. rs.push(out);
  2197. }
  2198. }
  2199. return isHit;
  2200. }
  2201. raycastClosest(r, o, out) {
  2202. raycastOptions.origin = r.o;
  2203. raycastOptions.unitDir = r.d;
  2204. raycastOptions.mask = o.mask >>> 0;
  2205. raycastOptions.distance = o.maxDistance;
  2206. raycastOptions.queryTrigger = !!o.queryTrigger;
  2207. const isHit = this._impl.raycastClosest(raycastOptions);
  2208. if (isHit) {
  2209. const hit = this._impl.raycastClosestResult();
  2210. out._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal);
  2211. }
  2212. return isHit;
  2213. }
  2214. sweepBox(worldRay, halfExtent, orientation, options, pool, results) {
  2215. raycastOptions.origin = worldRay.o;
  2216. raycastOptions.unitDir = worldRay.d;
  2217. raycastOptions.mask = options.mask >>> 0;
  2218. raycastOptions.distance = options.maxDistance;
  2219. raycastOptions.queryTrigger = !!options.queryTrigger;
  2220. const isHit = this._impl.sweepBox(raycastOptions, halfExtent.x, halfExtent.y, halfExtent.z, orientation.w, orientation.x, orientation.y, orientation.z);
  2221. if (isHit) {
  2222. const hits = this._impl.sweepResult();
  2223. for (let i = 0; i < hits.length; i++) {
  2224. const hit = hits[i];
  2225. const out = pool.add();
  2226. out._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal);
  2227. results.push(out);
  2228. }
  2229. }
  2230. return isHit;
  2231. }
  2232. sweepBoxClosest(worldRay, halfExtent, orientation, options, result) {
  2233. raycastOptions.origin = worldRay.o;
  2234. raycastOptions.unitDir = worldRay.d;
  2235. raycastOptions.mask = options.mask >>> 0;
  2236. raycastOptions.distance = options.maxDistance;
  2237. raycastOptions.queryTrigger = !!options.queryTrigger;
  2238. const isHit = this._impl.sweepBoxClosest(raycastOptions, halfExtent.x, halfExtent.y, halfExtent.z, orientation.w, orientation.x, orientation.y, orientation.z);
  2239. if (isHit) {
  2240. const hit = this._impl.sweepClosestResult();
  2241. result._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal);
  2242. }
  2243. return isHit;
  2244. }
  2245. sweepSphere(worldRay, radius, options, pool, results) {
  2246. raycastOptions.origin = worldRay.o;
  2247. raycastOptions.unitDir = worldRay.d;
  2248. raycastOptions.mask = options.mask >>> 0;
  2249. raycastOptions.distance = options.maxDistance;
  2250. raycastOptions.queryTrigger = !!options.queryTrigger;
  2251. const isHit = this._impl.sweepSphere(raycastOptions, radius);
  2252. if (isHit) {
  2253. const hits = this._impl.sweepResult();
  2254. for (let i = 0; i < hits.length; i++) {
  2255. const hit = hits[i];
  2256. const out = pool.add();
  2257. out._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal);
  2258. results.push(out);
  2259. }
  2260. }
  2261. return isHit;
  2262. }
  2263. sweepSphereClosest(worldRay, radius, options, result) {
  2264. raycastOptions.origin = worldRay.o;
  2265. raycastOptions.unitDir = worldRay.d;
  2266. raycastOptions.mask = options.mask >>> 0;
  2267. raycastOptions.distance = options.maxDistance;
  2268. raycastOptions.queryTrigger = !!options.queryTrigger;
  2269. const isHit = this._impl.sweepSphereClosest(raycastOptions, radius);
  2270. if (isHit) {
  2271. const hit = this._impl.sweepClosestResult();
  2272. result._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal);
  2273. }
  2274. return isHit;
  2275. }
  2276. sweepCapsule(worldRay, radius, height, orientation, options, pool, results) {
  2277. raycastOptions.origin = worldRay.o;
  2278. raycastOptions.unitDir = worldRay.d;
  2279. raycastOptions.mask = options.mask >>> 0;
  2280. raycastOptions.distance = options.maxDistance;
  2281. raycastOptions.queryTrigger = !!options.queryTrigger;
  2282. const isHit = this._impl.sweepCapsule(raycastOptions, radius, height, orientation.w, orientation.x, orientation.y, orientation.z);
  2283. if (isHit) {
  2284. const hits = this._impl.sweepResult();
  2285. for (let i = 0; i < hits.length; i++) {
  2286. const hit = hits[i];
  2287. const out = pool.add();
  2288. out._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal);
  2289. results.push(out);
  2290. }
  2291. }
  2292. return isHit;
  2293. }
  2294. sweepCapsuleClosest(worldRay, radius, height, orientation, options, result) {
  2295. raycastOptions.origin = worldRay.o;
  2296. raycastOptions.unitDir = worldRay.d;
  2297. raycastOptions.mask = options.mask >>> 0;
  2298. raycastOptions.distance = options.maxDistance;
  2299. raycastOptions.queryTrigger = !!options.queryTrigger;
  2300. const isHit = this._impl.sweepCapsuleClosest(raycastOptions, radius, height, orientation.w, orientation.x, orientation.y, orientation.z);
  2301. if (isHit) {
  2302. const hit = this._impl.sweepClosestResult();
  2303. result._assign(hit.hitPoint, hit.distance, ptrToObj[hit.shape].collider, hit.hitNormal);
  2304. }
  2305. return isHit;
  2306. }
  2307. emitEvents() {
  2308. this.emitTriggerEvent();
  2309. this.emitCollisionEvent();
  2310. this.emitCCTCollisionEvent();
  2311. this.emitCCTTriggerEvent();
  2312. this._impl.emitEvents();
  2313. }
  2314. syncSceneToPhysics() {
  2315. this._impl.syncSceneToPhysics();
  2316. }
  2317. syncAfterEvents() {
  2318. // this._impl.syncSceneToPhysics()
  2319. }
  2320. destroy() {
  2321. this._impl.destroy();
  2322. }
  2323. emitTriggerEvent() {
  2324. const teps = this._impl.getTriggerEventPairs();
  2325. const len = teps.length / 3;
  2326. for (let i = 0; i < len; i++) {
  2327. const t = i * 3;
  2328. const sa = ptrToObj[teps[t + 0]];
  2329. const sb = ptrToObj[teps[t + 1]];
  2330. if (!sa || !sb) continue;
  2331. const c0 = sa.collider;
  2332. const c1 = sb.collider;
  2333. if (!(c0 && c0.isValid && c1 && c1.isValid)) continue;
  2334. if (!c0.needTriggerEvent && !c1.needTriggerEvent) continue;
  2335. const state = teps[t + 2];
  2336. if (state === 1) {
  2337. emitTriggerEvent('onTriggerStay', c0, c1, teps);
  2338. } else if (state === 0) {
  2339. emitTriggerEvent('onTriggerEnter', c0, c1, teps);
  2340. } else {
  2341. emitTriggerEvent('onTriggerExit', c0, c1, teps);
  2342. }
  2343. }
  2344. }
  2345. emitCollisionEvent() {
  2346. const ceps = this._impl.getContactEventPairs();
  2347. const len2 = ceps.length / 4;
  2348. for (let i = 0; i < len2; i++) {
  2349. const t = i * 4;
  2350. const sa = ptrToObj[ceps[t + 0]];
  2351. const sb = ptrToObj[ceps[t + 1]];
  2352. if (!sa || !sb) continue;
  2353. const c0 = sa.collider;
  2354. const c1 = sb.collider;
  2355. if (!(c0 && c0.isValid && c1 && c1.isValid)) continue;
  2356. if (!c0.needCollisionEvent && !c1.needCollisionEvent) continue;
  2357. const state = ceps[t + 2];
  2358. if (state === 1) {
  2359. emitCollisionEvent('onCollisionStay', c0, c1, ceps, ceps[t + 3]);
  2360. } else if (state === 0) {
  2361. emitCollisionEvent('onCollisionEnter', c0, c1, ceps, ceps[t + 3]);
  2362. } else {
  2363. emitCollisionEvent('onCollisionExit', c0, c1, ceps, ceps[t + 3]);
  2364. }
  2365. }
  2366. }
  2367. emitCCTCollisionEvent() {
  2368. const events = this._impl.getCCTShapeEventPairs();
  2369. const len2 = events.length / 3;
  2370. for (let i = 0; i < len2; i++) {
  2371. const t = i * 3;
  2372. const cct = ptrToObj[events[t + 0]];
  2373. const shape = ptrToObj[events[t + 1]];
  2374. if (!cct || !shape) continue;
  2375. const c0 = cct.characterController;
  2376. const c1 = shape.collider;
  2377. if (!(c0 && c0.isValid && c1 && c1.isValid)) continue;
  2378. emitCCTCollisionEvent('onControllerColliderHit', c0, c1, events[t + 2]);
  2379. }
  2380. }
  2381. emitCCTTriggerEvent() {
  2382. const teps = this._impl.getCCTTriggerEventPairs();
  2383. const len = teps.length / 3;
  2384. for (let i = 0; i < len; i++) {
  2385. const t = i * 3;
  2386. const sa = ptrToObj[teps[t + 0]];
  2387. const sb = ptrToObj[teps[t + 1]];
  2388. if (!sa || !sb) continue;
  2389. const cct = sa.characterController;
  2390. const collider = sb.collider;
  2391. if (!(cct && cct.isValid && collider && collider.isValid)) continue;
  2392. if (!collider.needTriggerEvent) continue;
  2393. const state = teps[t + 2];
  2394. if (state === 1) {
  2395. emitCCTTriggerEvent('onControllerTriggerStay', cct, collider, teps);
  2396. } else if (state === 0) {
  2397. emitCCTTriggerEvent('onControllerTriggerEnter', cct, collider, teps);
  2398. } else {
  2399. emitCCTTriggerEvent('onControllerTriggerExit', cct, collider, teps);
  2400. }
  2401. }
  2402. }
  2403. }
  2404. function bookNode(v) {
  2405. if (v._physicsBookIndex === undefined) {
  2406. v._physicsBookIndex = books.length;
  2407. books.push(v);
  2408. }
  2409. }
  2410. function unBookNode(v) {
  2411. const index = v._physicsBookIndex;
  2412. if (index !== undefined) {
  2413. books[index] = books[books.length - 1];
  2414. books[index]._physicsBookIndex = index;
  2415. books.length -= 1;
  2416. v._physicsBookIndex = undefined;
  2417. }
  2418. }
  2419. function updateCollisionMatrix() {
  2420. const phy = cc.PhysicsSystem.instance;
  2421. const world = phy.physicsWorld.impl;
  2422. const cm = phy.collisionMatrix;
  2423. if (cm.updateArray && cm.updateArray.length > 0) {
  2424. cm.updateArray.forEach(e => {
  2425. const key = `${1 << e}`;
  2426. const mask = cm[key];
  2427. world.setCollisionMatrix(e, mask);
  2428. });
  2429. cm.updateArray.length = 0;
  2430. }
  2431. }
  2432. class RigidBody {
  2433. get impl() {
  2434. return this._impl;
  2435. }
  2436. get rigidBody() {
  2437. return this._com;
  2438. }
  2439. get isAwake() {
  2440. return this._impl.isAwake();
  2441. }
  2442. get isSleepy() {
  2443. return false;
  2444. }
  2445. get isSleeping() {
  2446. return this._impl.isSleeping();
  2447. }
  2448. constructor() {
  2449. updateCollisionMatrix();
  2450. this._impl = new jsbPhy.RigidBody();
  2451. this._isUsingCCD = false;
  2452. }
  2453. initialize(v) {
  2454. v.node.updateWorldTransform();
  2455. this._com = v;
  2456. this._impl.initialize(v.node, v.type, v._group);
  2457. bookNode(v.node);
  2458. this._impl.setSleepThreshold(cc.PhysicsSystem.instance.sleepThreshold);
  2459. }
  2460. onEnable() {
  2461. this.setType(this._com.type);
  2462. this.setMass(this._com.mass);
  2463. this.setAllowSleep(this._com.allowSleep);
  2464. this.setLinearDamping(this._com.linearDamping);
  2465. this.setAngularDamping(this._com.angularDamping);
  2466. this.setLinearFactor(this._com.linearFactor);
  2467. this.setAngularFactor(this._com.angularFactor);
  2468. this.useGravity(this._com.useGravity);
  2469. this._impl.onEnable();
  2470. }
  2471. onDisable() {
  2472. this._impl.onDisable();
  2473. }
  2474. onDestroy() {
  2475. unBookNode(this._com.node);
  2476. this._impl.onDestroy();
  2477. }
  2478. setGroup(v) {
  2479. this._impl.setGroup(v);
  2480. }
  2481. getGroup() {
  2482. return this._impl.getGroup();
  2483. }
  2484. addGroup(v) {
  2485. this.setGroup(this.getGroup() | v);
  2486. }
  2487. removeGroup(v) {
  2488. this.setGroup(this.getGroup() & ~v);
  2489. }
  2490. setMask(v) {
  2491. this._impl.setMask(v >>> 0);
  2492. }
  2493. getMask() {
  2494. return this._impl.getMask();
  2495. }
  2496. addMask(v) {
  2497. this.setMask(this.getMask() | v);
  2498. }
  2499. removeMask(v) {
  2500. this.setMask(this.getMask() & ~v);
  2501. }
  2502. setType(v) {
  2503. this._impl.setType(v);
  2504. }
  2505. setMass(v) {
  2506. this._impl.setMass(v);
  2507. }
  2508. setAllowSleep(v) {
  2509. this._impl.setAllowSleep(v);
  2510. }
  2511. setLinearDamping(v) {
  2512. const dt = cc.PhysicsSystem.instance.fixedTimeStep;
  2513. this._impl.setLinearDamping((1 - (1 - v) ** dt) / dt);
  2514. }
  2515. setAngularDamping(v) {
  2516. const dt = cc.PhysicsSystem.instance.fixedTimeStep;
  2517. this._impl.setAngularDamping((1 - (1 - v) ** dt) / dt);
  2518. }
  2519. isUsingCCD() {
  2520. return this._isUsingCCD;
  2521. }
  2522. useCCD(v) {
  2523. this._isUsingCCD = v;
  2524. return this._impl.useCCD(v);
  2525. }
  2526. useGravity(v) {
  2527. this._impl.useGravity(v);
  2528. }
  2529. setLinearFactor(v) {
  2530. this._impl.setLinearFactor(v.x, v.y, v.z);
  2531. }
  2532. setAngularFactor(v) {
  2533. this._impl.setAngularFactor(v.x, v.y, v.z);
  2534. }
  2535. wakeUp() {
  2536. this._impl.wakeUp();
  2537. }
  2538. sleep() {
  2539. this._impl.sleep();
  2540. }
  2541. clearState() {
  2542. this._impl.clearState();
  2543. }
  2544. clearForces() {
  2545. this._impl.clearForces();
  2546. }
  2547. clearVelocity() {
  2548. this._impl.clearVelocity();
  2549. }
  2550. setSleepThreshold(v) {
  2551. this._impl.setSleepThreshold(v);
  2552. }
  2553. getSleepThreshold() {
  2554. return this._impl.getSleepThreshold();
  2555. }
  2556. getLinearVelocity(o) {
  2557. o.set(this._impl.getLinearVelocity());
  2558. }
  2559. setLinearVelocity(v) {
  2560. this._impl.setLinearVelocity(v.x, v.y, v.z);
  2561. }
  2562. getAngularVelocity(o) {
  2563. o.set(this._impl.getAngularVelocity());
  2564. }
  2565. setAngularVelocity(v) {
  2566. this._impl.setAngularVelocity(v.x, v.y, v.z);
  2567. }
  2568. applyForce(f, p) {
  2569. if (p == null) {
  2570. p = cc.Vec3.ZERO;
  2571. }
  2572. this._impl.applyForce(f.x, f.y, f.z, p.x, p.y, p.z);
  2573. }
  2574. applyLocalForce(f, p) {
  2575. if (p == null) {
  2576. p = cc.Vec3.ZERO;
  2577. }
  2578. this._impl.applyLocalForce(f.x, f.y, f.z, p.x, p.y, p.z);
  2579. }
  2580. applyImpulse(f, p) {
  2581. if (p == null) {
  2582. p = cc.Vec3.ZERO;
  2583. }
  2584. this._impl.applyImpulse(f.x, f.y, f.z, p.x, p.y, p.z);
  2585. }
  2586. applyLocalImpulse(f, p) {
  2587. if (p == null) {
  2588. p = cc.Vec3.ZERO;
  2589. }
  2590. this._impl.applyLocalImpulse(f.x, f.y, f.z, p.x, p.y, p.z);
  2591. }
  2592. applyTorque(t) {
  2593. this._impl.applyTorque(t.x, t.y, t.z);
  2594. }
  2595. applyLocalTorque(t) {
  2596. this._impl.applyLocalTorque(t.x, t.y, t.z);
  2597. }
  2598. }
  2599. const ESHAPE_FLAG = {
  2600. NONE: 0,
  2601. QUERY_FILTER: 1 << 0,
  2602. QUERY_SINGLE_HIT: 1 << 2,
  2603. DETECT_TRIGGER_EVENT: 1 << 3,
  2604. DETECT_CONTACT_EVENT: 1 << 4,
  2605. DETECT_CONTACT_POINT: 1 << 5,
  2606. DETECT_CONTACT_CCD: 1 << 6
  2607. };
  2608. class Shape {
  2609. get impl() {
  2610. return this._impl;
  2611. }
  2612. get collider() {
  2613. return this._com;
  2614. }
  2615. get attachedRigidBody() {
  2616. return this._attachedRigidBody;
  2617. }
  2618. constructor() {
  2619. updateCollisionMatrix();
  2620. }
  2621. initialize(v) {
  2622. v.node.updateWorldTransform();
  2623. this._com = v;
  2624. this._impl.initialize(v.node);
  2625. ptrToObj[this._impl.getObjectID()] = this;
  2626. bookNode(v.node);
  2627. }
  2628. onLoad() {
  2629. this.setMaterial(this._com.sharedMaterial);
  2630. this.setCenter(this._com.center);
  2631. this.setAsTrigger(this._com.isTrigger);
  2632. }
  2633. onEnable() {
  2634. this._impl.onEnable();
  2635. }
  2636. onDisable() {
  2637. this._impl.onDisable();
  2638. }
  2639. onDestroy() {
  2640. unBookNode(this._com.node);
  2641. delete ptrToObj[this._impl.getObjectID()];
  2642. ptrToObj[this._impl.getObjectID()] = null;
  2643. this._impl.onDestroy();
  2644. }
  2645. setMaterial(v) {
  2646. const ins = cc.PhysicsSystem.instance;
  2647. if (!v) v = ins.defaultMaterial;
  2648. if (!jsbPhy.CACHE.material[v.id]) {
  2649. jsbPhy.CACHE.material[v.id] = ins.physicsWorld.impl.createMaterial(v.id, v.friction, v.friction, v.restitution, 2, 2);
  2650. }
  2651. this._impl.setMaterial(v.id, v.friction, v.friction, v.restitution, 2, 2);
  2652. }
  2653. setAsTrigger(v) {
  2654. this._impl.setAsTrigger(v);
  2655. }
  2656. setCenter(v) {
  2657. this._impl.setCenter(v.x, v.y, v.z);
  2658. }
  2659. getAABB(v) {
  2660. v.copy(this._impl.getAABB());
  2661. }
  2662. getBoundingSphere(v) {
  2663. v.copy(this._impl.getBoundingSphere());
  2664. }
  2665. updateEventListener() {
  2666. let flag = 0;
  2667. flag |= ESHAPE_FLAG.DETECT_CONTACT_CCD;
  2668. if (this._com.isTrigger) flag |= ESHAPE_FLAG.IS_TRIGGER;
  2669. if (this._com.needTriggerEvent || this._com.needCollisionEvent) flag |= ESHAPE_FLAG.NEED_EVENT;
  2670. this._impl.updateEventListener(flag);
  2671. }
  2672. setGroup(v) {
  2673. this._impl.setGroup(v);
  2674. }
  2675. getGroup() {
  2676. return this._impl.getGroup();
  2677. }
  2678. addGroup(v) {
  2679. this.setGroup(this.getGroup() | v);
  2680. }
  2681. removeGroup(v) {
  2682. this.setGroup(this.getGroup() & ~v);
  2683. }
  2684. setMask(v) {
  2685. this._impl.setMask(v >>> 0);
  2686. }
  2687. getMask() {
  2688. return this._impl.getMask();
  2689. }
  2690. addMask(v) {
  2691. this.setMask(this.getMask() | v);
  2692. }
  2693. removeMask(v) {
  2694. this.setMask(this.getMask() & ~v);
  2695. }
  2696. }
  2697. class SphereShape extends Shape {
  2698. constructor() {
  2699. super();
  2700. this._impl = new jsbPhy.SphereShape();
  2701. }
  2702. updateRadius() {
  2703. this._impl.setRadius(this.collider.radius);
  2704. }
  2705. onLoad() {
  2706. super.onLoad();
  2707. this.updateRadius();
  2708. }
  2709. }
  2710. class BoxShape extends Shape {
  2711. constructor() {
  2712. super();
  2713. this._impl = new jsbPhy.BoxShape();
  2714. }
  2715. updateSize() {
  2716. const v = this.collider.size;
  2717. this._impl.setSize(v.x, v.y, v.z);
  2718. }
  2719. onLoad() {
  2720. super.onLoad();
  2721. this.updateSize();
  2722. }
  2723. }
  2724. class CapsuleShape extends Shape {
  2725. constructor() {
  2726. super();
  2727. this._impl = new jsbPhy.CapsuleShape();
  2728. }
  2729. setRadius(v) {
  2730. this._impl.setRadius(v);
  2731. }
  2732. setDirection(v) {
  2733. this._impl.setDirection(v);
  2734. }
  2735. setCylinderHeight(v) {
  2736. this._impl.setCylinderHeight(v);
  2737. }
  2738. onLoad() {
  2739. super.onLoad();
  2740. this.setRadius(this._com.radius);
  2741. this.setDirection(this._com.direction);
  2742. this.setCylinderHeight(this._com.cylinderHeight);
  2743. }
  2744. }
  2745. class PlaneShape extends Shape {
  2746. constructor() {
  2747. super();
  2748. this._impl = new jsbPhy.PlaneShape();
  2749. }
  2750. setConstant(v) {
  2751. this._impl.setConstant(v);
  2752. }
  2753. setNormal(v) {
  2754. this._impl.setNormal(v.x, v.y, v.z);
  2755. }
  2756. onLoad() {
  2757. super.onLoad();
  2758. this.setNormal(this._com.normal);
  2759. this.setConstant(this._com.constant);
  2760. }
  2761. }
  2762. function getConvexMesh(v) {
  2763. if (!jsbPhy.CACHE.convex[v._uuid]) {
  2764. const posArr = cc.physics.utils.shrinkPositions(v.renderingSubMeshes[0].geometricInfo.positions);
  2765. const world = cc.PhysicsSystem.instance.physicsWorld.impl;
  2766. const convex = {
  2767. positions: new Float32Array(posArr),
  2768. positionLength: posArr.length / 3
  2769. };
  2770. jsbPhy.CACHE.convex[v._uuid] = world.createConvex(convex);
  2771. }
  2772. return jsbPhy.CACHE.convex[v._uuid];
  2773. }
  2774. function getTriangleMesh(v) {
  2775. if (!jsbPhy.CACHE.trimesh[v._uuid]) {
  2776. const posArr = v.renderingSubMeshes[0].geometricInfo.positions;
  2777. const indArr = v.renderingSubMeshes[0].geometricInfo.indices;
  2778. const world = cc.PhysicsSystem.instance.physicsWorld.impl;
  2779. const trimesh = {
  2780. positions: new Float32Array(posArr),
  2781. positionLength: posArr.length / 3,
  2782. triangles: new Uint16Array(indArr),
  2783. triangleLength: indArr.length / 3,
  2784. isU16: true
  2785. };
  2786. jsbPhy.CACHE.trimesh[v._uuid] = world.createTrimesh(trimesh);
  2787. }
  2788. return jsbPhy.CACHE.trimesh[v._uuid];
  2789. }
  2790. function getHeightField(v) {
  2791. if (!jsbPhy.CACHE.height[v._uuid]) {
  2792. const rows = v.getVertexCountI();
  2793. const columns = v.getVertexCountJ();
  2794. const samples = new Int16Array(rows * columns);
  2795. const heightScale = jsbPhy.CONFIG.heightScale;
  2796. for (let i = 0; i < rows; i++) {
  2797. for (let j = 0; j < columns; j++) {
  2798. samples[j + i * columns] = v.getHeight(i, j) / heightScale;
  2799. }
  2800. }
  2801. const height = {
  2802. rows,
  2803. columns,
  2804. samples
  2805. };
  2806. const world = cc.PhysicsSystem.instance.physicsWorld.impl;
  2807. jsbPhy.CACHE.height[v._uuid] = world.createHeightField(height);
  2808. }
  2809. return jsbPhy.CACHE.height[v._uuid];
  2810. }
  2811. class CylinderShape extends Shape {
  2812. constructor() {
  2813. super();
  2814. this._impl = new jsbPhy.CylinderShape();
  2815. }
  2816. setRadius(v) {
  2817. this.updateGeometry();
  2818. }
  2819. setDirection(v) {
  2820. this.updateGeometry();
  2821. }
  2822. setHeight(v) {
  2823. this.updateGeometry();
  2824. }
  2825. updateGeometry() {
  2826. this._impl.setCylinder(this._com.radius, this._com.height, this._com.direction);
  2827. }
  2828. initialize(v) {
  2829. if (!jsbPhy.CACHE.convex.CYLINDER) {
  2830. const primitive = cc.physics.utils.cylinder(0.5, 0.5, 2, {
  2831. radialSegments: 32,
  2832. heightSegments: 1
  2833. });
  2834. const posArr = cc.physics.utils.shrinkPositions(primitive.positions);
  2835. const convex = {
  2836. positions: new Float32Array(posArr),
  2837. positionLength: posArr.length / 3
  2838. };
  2839. const pxObjectID = cc.PhysicsSystem.instance.physicsWorld.impl.createConvex(convex);
  2840. jsbPhy.CACHE.convex.CYLINDER = pxObjectID;
  2841. }
  2842. this._com = v;
  2843. this._impl.setCylinder(v.radius, v.height, v.direction);
  2844. this._impl.setConvex(jsbPhy.CACHE.convex.CYLINDER);
  2845. super.initialize(v);
  2846. }
  2847. }
  2848. class ConeShape extends Shape {
  2849. constructor() {
  2850. super();
  2851. this._impl = new jsbPhy.ConeShape();
  2852. }
  2853. setRadius(v) {
  2854. this.updateGeometry();
  2855. }
  2856. setDirection(v) {
  2857. this.updateGeometry();
  2858. }
  2859. setHeight(v) {
  2860. this.updateGeometry();
  2861. }
  2862. updateGeometry() {
  2863. this._impl.setCone(this._com.radius, this._com.height, this._com.direction);
  2864. }
  2865. initialize(v) {
  2866. if (!jsbPhy.CACHE.convex.CONE) {
  2867. const primitive = cc.physics.utils.cylinder(0, 0.5, 1, {
  2868. radialSegments: 32,
  2869. heightSegments: 1
  2870. });
  2871. const posArr = cc.physics.utils.shrinkPositions(primitive.positions);
  2872. const convex = {
  2873. positions: new Float32Array(posArr),
  2874. positionLength: posArr.length / 3
  2875. };
  2876. const pxObjectID = cc.PhysicsSystem.instance.physicsWorld.impl.createConvex(convex);
  2877. jsbPhy.CACHE.convex.CONE = pxObjectID;
  2878. }
  2879. this._com = v;
  2880. this._impl.setCone(v.radius, v.height, v.direction);
  2881. this._impl.setConvex(jsbPhy.CACHE.convex.CONE);
  2882. super.initialize(v);
  2883. }
  2884. }
  2885. class TrimeshShape extends Shape {
  2886. constructor() {
  2887. super();
  2888. this._impl = new jsbPhy.TrimeshShape();
  2889. }
  2890. setConvex(v) {
  2891. this._impl.useConvex(v);
  2892. }
  2893. setMesh(v) {
  2894. if (!v) return;
  2895. const isConvex = this._com.convex;
  2896. this._impl.useConvex(isConvex);
  2897. const pxObjectID = isConvex ? getConvexMesh(v) : getTriangleMesh(v);
  2898. this._impl.setMesh(pxObjectID);
  2899. }
  2900. initialize(v) {
  2901. this._com = v;
  2902. this.setConvex(v.convex);
  2903. this.setMesh(v.mesh);
  2904. super.initialize(v);
  2905. }
  2906. }
  2907. class TerrainShape extends Shape {
  2908. constructor() {
  2909. super();
  2910. this._impl = new jsbPhy.TerrainShape();
  2911. }
  2912. setTerrain(v) {
  2913. if (!v) return;
  2914. const pxObjectID = getHeightField(v);
  2915. this._impl.setTerrain(pxObjectID, v.tileSize, v.tileSize, jsbPhy.CONFIG.heightScale);
  2916. }
  2917. initialize(v) {
  2918. this._com = v;
  2919. this.setTerrain(v.terrain);
  2920. super.initialize(v);
  2921. }
  2922. }
  2923. class Joint {
  2924. get impl() {
  2925. return this._impl;
  2926. }
  2927. get joint() {
  2928. return this._com;
  2929. }
  2930. setEnableCollision(v) {
  2931. this._impl.setEnableCollision(v);
  2932. }
  2933. setConnectedBody(v) {
  2934. this._impl.setConnectedBody(v ? v.body.impl.getObjectID() : 0);
  2935. }
  2936. initialize(v) {
  2937. this._com = v;
  2938. this._impl.initialize(v.node);
  2939. ptrToObj[this._impl.getObjectID()] = this;
  2940. this.onLoad();
  2941. }
  2942. onLoad() {
  2943. this.setConnectedBody(this._com.connectedBody);
  2944. this.setEnableCollision(this._com.enableCollision);
  2945. }
  2946. onEnable() {
  2947. this._impl.onEnable();
  2948. }
  2949. onDisable() {
  2950. this._impl.onDisable();
  2951. }
  2952. onDestroy() {
  2953. delete ptrToObj[this._impl.getObjectID()];
  2954. ptrToObj[this._impl.getObjectID()] = null;
  2955. this._impl.onDestroy();
  2956. }
  2957. }
  2958. class SphericalJoint extends Joint {
  2959. constructor() {
  2960. super();
  2961. this._impl = new jsbPhy.SphericalJoint();
  2962. }
  2963. setPivotA(v) {
  2964. this._impl.setPivotA(v.x, v.y, v.z);
  2965. }
  2966. setPivotB(v) {
  2967. this._impl.setPivotB(v.x, v.y, v.z);
  2968. }
  2969. onLoad() {
  2970. super.onLoad();
  2971. this.setPivotA(this._com.pivotA);
  2972. this.setPivotB(this._com.pivotB);
  2973. }
  2974. }
  2975. class RevoluteJoint extends Joint {
  2976. constructor() {
  2977. super();
  2978. this._impl = new jsbPhy.RevoluteJoint();
  2979. }
  2980. setAxis(v) {
  2981. this._impl.setAxis(v.x, v.y, v.z);
  2982. }
  2983. setPivotA(v) {
  2984. this._impl.setPivotA(v.x, v.y, v.z);
  2985. }
  2986. setPivotB(v) {
  2987. this._impl.setPivotB(v.x, v.y, v.z);
  2988. }
  2989. setLimitEnabled(v) {
  2990. this._impl.setLimitEnabled(v);
  2991. }
  2992. setLowerLimit(v) {
  2993. this._impl.setLowerLimit(v);
  2994. }
  2995. setUpperLimit(v) {
  2996. this._impl.setUpperLimit(v);
  2997. }
  2998. setMotorEnabled(v) {
  2999. this._impl.setMotorEnabled(v);
  3000. }
  3001. setMotorVelocity(v) {
  3002. this._impl.setMotorVelocity(v);
  3003. }
  3004. setMotorForceLimit(v) {
  3005. this._impl.setMotorForceLimit(v);
  3006. }
  3007. onLoad() {
  3008. super.onLoad();
  3009. this.setAxis(this._com.axis);
  3010. this.setPivotA(this._com.pivotA);
  3011. this.setPivotB(this._com.pivotB);
  3012. this.setLimitEnabled(this._com.limitEnabled);
  3013. this.setLowerLimit(this._com.lowerLimit);
  3014. this.setUpperLimit(this._com.upperLimit);
  3015. this.setMotorEnabled(this._com.motorEnabled);
  3016. this.setMotorVelocity(this._com.motorVelocity);
  3017. this.setMotorForceLimit(this._com.motorForceLimit);
  3018. }
  3019. }
  3020. class FixedJoint extends Joint {
  3021. constructor() {
  3022. super();
  3023. this._impl = new jsbPhy.FixedJoint();
  3024. }
  3025. setBreakForce(v) {
  3026. this._impl.setBreakForce(v);
  3027. }
  3028. setBreakTorque(v) {
  3029. this._impl.setBreakTorque(v);
  3030. }
  3031. onLoad() {
  3032. super.onLoad();
  3033. this.setBreakForce(this._com.breakForce);
  3034. this.setBreakTorque(this._com.breakTorque);
  3035. }
  3036. }
  3037. class ConfigurableJoint extends Joint {
  3038. constructor() {
  3039. super();
  3040. this._impl = new jsbPhy.GenericJoint();
  3041. }
  3042. setConstraintMode(idx, v) {
  3043. this._impl.setConstraintMode(idx, v);
  3044. }
  3045. setLinearLimit(idx, upper, lower) {
  3046. this._impl.setLinearLimit(idx, upper, lower);
  3047. }
  3048. setAngularExtent(twist, swing1, swing2) {
  3049. this._impl.setAngularExtent(twist, swing1, swing2);
  3050. }
  3051. setLinearSoftConstraint(v) {
  3052. this._impl.setLinearSoftConstraint(v);
  3053. }
  3054. setLinearStiffness(v) {
  3055. this._impl.setLinearStiffness(v);
  3056. }
  3057. setLinearDamping(v) {
  3058. this._impl.setLinearDamping(v);
  3059. }
  3060. setLinearRestitution(v) {
  3061. this._impl.setLinearRestitution(v);
  3062. }
  3063. setSwingSoftConstraint(v) {
  3064. this._impl.setSwingSoftConstraint(v);
  3065. }
  3066. setTwistSoftConstraint(v) {
  3067. this._impl.setTwistSoftConstraint(v);
  3068. }
  3069. setSwingStiffness(v) {
  3070. this._impl.setSwingStiffness(v);
  3071. }
  3072. setSwingDamping(v) {
  3073. this._impl.setSwingDamping(v);
  3074. }
  3075. setSwingRestitution(v) {
  3076. this._impl.setSwingRestitution(v);
  3077. }
  3078. setTwistStiffness(v) {
  3079. this._impl.setTwistStiffness(v);
  3080. }
  3081. setTwistDamping(v) {
  3082. this._impl.setTwistDamping(v);
  3083. }
  3084. setTwistRestitution(v) {
  3085. this._impl.setTwistRestitution(v);
  3086. }
  3087. // motor
  3088. setDriverMode(idx, v) {
  3089. this._impl.setDriverMode(idx, v);
  3090. }
  3091. setLinearMotorTarget(v) {
  3092. this._impl.setLinearMotorTarget(v.x, v.y, v.z);
  3093. }
  3094. setLinearMotorVelocity(v) {
  3095. this._impl.setLinearMotorVelocity(v.x, v.y, v.z);
  3096. }
  3097. setLinearMotorForceLimit(v) {
  3098. this._impl.setLinearMotorForceLimit(v);
  3099. }
  3100. setAngularMotorTarget(v) {
  3101. this._impl.setAngularMotorTarget(v.x, v.y, v.z);
  3102. }
  3103. setAngularMotorVelocity(v) {
  3104. this._impl.setAngularMotorVelocity(v.x, v.y, v.z);
  3105. }
  3106. setAngularMotorForceLimit(v) {
  3107. this._impl.setAngularMotorForceLimit(v);
  3108. }
  3109. setPivotA(v) {
  3110. this._impl.setPivotA(v.x, v.y, v.z);
  3111. }
  3112. setPivotB(v) {
  3113. this._impl.setPivotB(v.x, v.y, v.z);
  3114. }
  3115. setAutoPivotB(v) {
  3116. this._impl.setAutoPivotB(v);
  3117. }
  3118. setAxis(v) {
  3119. this._impl.setAxis(v.x, v.y, v.z);
  3120. }
  3121. setSecondaryAxis(v) {
  3122. this._impl.setSecondaryAxis(v.x, v.y, v.z);
  3123. }
  3124. setBreakForce(v) {
  3125. this._impl.setBreakForce(v);
  3126. }
  3127. setBreakTorque(v) {
  3128. this._impl.setBreakTorque(v);
  3129. }
  3130. onLoad() {
  3131. super.onLoad();
  3132. this.setBreakForce(this._com.breakForce);
  3133. this.setBreakTorque(this._com.breakTorque);
  3134. const com = this._com;
  3135. const linearLimit = com.linearLimitSettings;
  3136. const angularLimit = com.angularLimitSettings;
  3137. this.setConstraintMode(0, linearLimit.xMotion);
  3138. this.setConstraintMode(1, linearLimit.yMotion);
  3139. this.setConstraintMode(2, linearLimit.zMotion);
  3140. this.setConstraintMode(3, angularLimit.twistMotion);
  3141. this.setConstraintMode(4, angularLimit.swingMotion1);
  3142. this.setConstraintMode(5, angularLimit.swingMotion2);
  3143. this.setLinearLimit(0, linearLimit.lower.x, linearLimit.upper.x);
  3144. this.setLinearLimit(1, linearLimit.lower.y, linearLimit.upper.y);
  3145. this.setLinearLimit(2, linearLimit.lower.z, linearLimit.upper.z);
  3146. this.setAngularExtent(angularLimit.twistExtent, angularLimit.swingExtent1, angularLimit.swingExtent2);
  3147. this.setLinearSoftConstraint(linearLimit.enableSoftConstraint);
  3148. this.setLinearStiffness(linearLimit.stiffness);
  3149. this.setLinearDamping(linearLimit.damping);
  3150. this.setLinearRestitution(linearLimit.restitution);
  3151. this.setSwingSoftConstraint(angularLimit.enableSoftConstraintSwing);
  3152. this.setTwistSoftConstraint(angularLimit.enableSoftConstraintTwist);
  3153. this.setSwingStiffness(angularLimit.swingStiffness);
  3154. this.setSwingDamping(angularLimit.swingDamping);
  3155. this.setSwingRestitution(angularLimit.swingRestitution);
  3156. this.setTwistStiffness(angularLimit.twistStiffness);
  3157. this.setTwistDamping(angularLimit.twistDamping);
  3158. this.setTwistRestitution(angularLimit.twistRestitution);
  3159. const linearMotor = com.linearDriverSettings;
  3160. const angularMotor = com.angularDriverSettings;
  3161. this.setDriverMode(0, linearMotor.xDrive);
  3162. this.setDriverMode(1, linearMotor.yDrive);
  3163. this.setDriverMode(2, linearMotor.zDrive);
  3164. this.setDriverMode(3, angularMotor.twistDrive);
  3165. this.setDriverMode(4, angularMotor.swingDrive1);
  3166. this.setDriverMode(5, angularMotor.swingDrive2);
  3167. this.setLinearMotorTarget(linearMotor.targetPosition);
  3168. this.setLinearMotorVelocity(linearMotor.targetVelocity);
  3169. this.setLinearMotorForceLimit(linearMotor.strength);
  3170. this.setAngularMotorTarget(angularMotor.targetOrientation);
  3171. this.setAngularMotorVelocity(angularMotor.targetVelocity);
  3172. this.setAngularMotorForceLimit(angularMotor.strength);
  3173. this.setPivotA(com.pivotA);
  3174. this.setPivotB(com.pivotB);
  3175. this.setAutoPivotB(com.autoPivotB);
  3176. this.setAxis(com.axis);
  3177. this.setSecondaryAxis(com.secondaryAxis);
  3178. this.setBreakForce(com.breakForce);
  3179. this.setBreakTorque(com.breakTorque);
  3180. }
  3181. }
  3182. class CharacterController {
  3183. get impl() {
  3184. return this._impl;
  3185. }
  3186. get characterController() {
  3187. return this._com;
  3188. }
  3189. constructor() {
  3190. updateCollisionMatrix();
  3191. }
  3192. initialize(com) {
  3193. this._com = com;
  3194. const inited = this._impl.initialize(com.node);
  3195. ptrToObj[this._impl.getObjectID()] = this;
  3196. return inited;
  3197. }
  3198. onLoad() {
  3199. this.setGroup(this._com.group);
  3200. const cm = cc.PhysicsSystem.instance.collisionMatrix;
  3201. const mask = cm[this._com.group];
  3202. this.setMask(mask);
  3203. this.setCenter(this._com.center);
  3204. this.setStepOffset(this._com.stepOffset);
  3205. this.setSlopeLimit(this._com.slopeLimit);
  3206. this.setContactOffset(this._com.skinWidth);
  3207. this.setDetectCollisions(true); //this._com.detectCollisions);
  3208. this.setOverlapRecovery(true); //this._com.enableOverlapRecovery);
  3209. }
  3210. onEnable() {
  3211. this._impl.onEnable();
  3212. }
  3213. onDisable() {
  3214. this._impl.onDisable();
  3215. }
  3216. onDestroy() {
  3217. delete ptrToObj[this._impl.getObjectID()];
  3218. ptrToObj[this._impl.getObjectID()] = null;
  3219. this._impl.onDestroy();
  3220. }
  3221. onGround() {
  3222. return this._impl.onGround();
  3223. }
  3224. move(v, minDist, dt) {
  3225. return this._impl.move(v.x, v.y, v.z, minDist, dt);
  3226. }
  3227. syncPhysicsToScene() {
  3228. this._impl.syncPhysicsToScene();
  3229. }
  3230. setPosition(v) {
  3231. this._impl.setPosition(v.x, v.y, v.z);
  3232. }
  3233. getPosition() {
  3234. return this._impl.getPosition();
  3235. }
  3236. setStepOffset(v) {
  3237. this._impl.setStepOffset(v);
  3238. }
  3239. getStepOffset() {
  3240. return this._impl.getStepOffset();
  3241. }
  3242. setSlopeLimit(v) {
  3243. this._impl.setSlopeLimit(v);
  3244. }
  3245. getSlopeLimit() {
  3246. return this._impl.getSlopeLimit();
  3247. }
  3248. setContactOffset(v) {
  3249. this._impl.setContactOffset(v);
  3250. }
  3251. getContactOffset() {
  3252. return this._impl.getContactOffset();
  3253. }
  3254. setDetectCollisions(v) {
  3255. this._impl.setDetectCollisions(v);
  3256. }
  3257. setOverlapRecovery(v) {
  3258. this._impl.setOverlapRecovery(v);
  3259. }
  3260. setCenter(v) {
  3261. this._impl.setCenter(v.x, v.y, v.z);
  3262. }
  3263. updateEventListener() {
  3264. let flag = 0;
  3265. if (this._com.needTriggerEvent) flag |= ESHAPE_FLAG.DETECT_TRIGGER_EVENT;
  3266. this._impl.updateEventListener(flag);
  3267. }
  3268. setGroup(v) {
  3269. this._impl.setGroup(v);
  3270. }
  3271. getGroup() {
  3272. return this._impl.getGroup();
  3273. }
  3274. addGroup(v) {
  3275. this.setGroup(this.getGroup() | v);
  3276. }
  3277. removeGroup(v) {
  3278. this.setGroup(this.getGroup() & ~v);
  3279. }
  3280. setMask(v) {
  3281. this._impl.setMask(v >>> 0);
  3282. }
  3283. getMask() {
  3284. return this._impl.getMask();
  3285. }
  3286. addMask(v) {
  3287. this.setMask(this.getMask() | v);
  3288. }
  3289. removeMask(v) {
  3290. this.setMask(this.getMask() & ~v);
  3291. }
  3292. }
  3293. class CapsuleCharacterController extends CharacterController {
  3294. constructor() {
  3295. super();
  3296. this._impl = new jsbPhy.CapsuleCharacterController();
  3297. }
  3298. setRadius(v) {
  3299. this._impl.setRadius(v);
  3300. }
  3301. setHeight(v) {
  3302. this._impl.setHeight(v);
  3303. }
  3304. onLoad() {
  3305. super.onLoad();
  3306. this.setRadius(this._com.radius);
  3307. this.setHeight(this._com.height);
  3308. }
  3309. }
  3310. class BoxCharacterController extends CharacterController {
  3311. constructor() {
  3312. super();
  3313. this._impl = new jsbPhy.BoxCharacterController();
  3314. }
  3315. setHalfHeight(v) {
  3316. this._impl.setHalfHeight(v);
  3317. }
  3318. setHalfSideExtent(v) {
  3319. this._impl.setHalfSideExtent(v);
  3320. }
  3321. setHalfForwardExtent(v) {
  3322. this._impl.setHalfForwardExtent(v);
  3323. }
  3324. onLoad() {
  3325. super.onLoad();
  3326. this.setHalfHeight(this._com.halfHeight);
  3327. this.setHalfSideExtent(this._com.halfSideExtent);
  3328. this.setHalfForwardExtent(this._com.halfForwardExtent);
  3329. }
  3330. }
  3331. cc.physics.selector.register('physx', {
  3332. PhysicsWorld,
  3333. RigidBody,
  3334. SphereShape,
  3335. BoxShape,
  3336. PlaneShape,
  3337. CapsuleShape,
  3338. ConeShape,
  3339. CylinderShape,
  3340. TrimeshShape,
  3341. TerrainShape,
  3342. PointToPointConstraint: SphericalJoint,
  3343. HingeConstraint: RevoluteJoint,
  3344. FixedConstraint: FixedJoint,
  3345. ConfigurableConstraint: ConfigurableJoint,
  3346. CapsuleCharacterController,
  3347. BoxCharacterController
  3348. });
  3349. },{}],12:[function(require,module,exports){
  3350. "use strict";
  3351. /****************************************************************************
  3352. Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
  3353. http://www.cocos.com
  3354. Permission is hereby granted, free of charge, to any person obtaining a copy
  3355. of this software and associated engine source code (the "Software"), a limited,
  3356. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  3357. to use Cocos Creator solely to develop games on your target platforms. You shall
  3358. not use Cocos Creator software for developing other software or tools that's
  3359. used for developing games. You are not granted to publish, distribute,
  3360. sublicense, and/or sell copies of Cocos Creator.
  3361. The software or tools in this License Agreement are licensed, not sold.
  3362. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  3363. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  3364. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  3365. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  3366. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  3367. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  3368. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  3369. THE SOFTWARE.
  3370. ****************************************************************************/
  3371. const cacheManager = require('./jsb-cache-manager');
  3372. // @ts-expect-error jsb polyfills
  3373. (function () {
  3374. if (globalThis.spine === undefined || globalThis.middleware === undefined) return;
  3375. if (cc.internal.SpineSkeletonData === undefined) return;
  3376. const spine = globalThis.spine;
  3377. const middleware = globalThis.middleware;
  3378. middleware.generateGetSet(spine);
  3379. // spine global time scale
  3380. Object.defineProperty(spine, 'timeScale', {
  3381. get() {
  3382. return this._timeScale;
  3383. },
  3384. set(value) {
  3385. this._timeScale = value;
  3386. spine.SkeletonAnimation.setGlobalTimeScale(value);
  3387. },
  3388. configurable: true
  3389. });
  3390. const _slotColor = cc.color(0, 0, 255, 255);
  3391. const _boneColor = cc.color(255, 0, 0, 255);
  3392. const _meshColor = cc.color(255, 255, 0, 255);
  3393. const _originColor = cc.color(0, 255, 0, 255);
  3394. const skeletonDataProto = cc.internal.SpineSkeletonData.prototype;
  3395. let _gTextureIdx = 1;
  3396. const _textureKeyMap = {};
  3397. const _textureMap = new WeakMap();
  3398. const skeletonDataMgr = spine.SkeletonDataMgr.getInstance();
  3399. spine.skeletonDataMgr = skeletonDataMgr;
  3400. skeletonDataMgr.setDestroyCallback(textureIndex => {
  3401. if (!textureIndex) return;
  3402. const texKey = _textureKeyMap[textureIndex];
  3403. if (texKey && _textureMap.has(texKey)) {
  3404. _textureMap.delete(texKey);
  3405. delete _textureKeyMap[textureIndex];
  3406. }
  3407. });
  3408. const skeletonCacheMgr = spine.SkeletonCacheMgr.getInstance();
  3409. spine.skeletonCacheMgr = skeletonCacheMgr;
  3410. skeletonDataProto.destroy = function () {
  3411. this.reset();
  3412. skeletonCacheMgr.removeSkeletonCache(this.mergedUUID());
  3413. cc.Asset.prototype.destroy.call(this);
  3414. };
  3415. skeletonDataProto.reset = function () {
  3416. if (this._skeletonCache) {
  3417. spine.disposeSkeletonData(this.mergedUUID());
  3418. this._jsbTextures = null;
  3419. this._skeletonCache = null;
  3420. }
  3421. this._atlasCache = null;
  3422. };
  3423. skeletonDataProto.getRuntimeData = function () {
  3424. if (!this._skeletonCache) {
  3425. this.init();
  3426. }
  3427. return this._skeletonCache;
  3428. };
  3429. skeletonDataProto.init = function () {
  3430. if (this._skeletonCache) return;
  3431. const uuid = this.mergedUUID();
  3432. if (!uuid) {
  3433. cc.errorID(7504);
  3434. return;
  3435. }
  3436. const atlasText = this.atlasText;
  3437. if (!atlasText) {
  3438. cc.errorID(7508, this.name);
  3439. return;
  3440. }
  3441. const textures = this.textures;
  3442. const textureNames = this.textureNames;
  3443. if (!(textures && textures.length > 0 && textureNames && textureNames.length > 0)) {
  3444. cc.errorID(7507, this.name);
  3445. return;
  3446. }
  3447. const jsbTextures = {};
  3448. for (let i = 0; i < textures.length; ++i) {
  3449. const texture = textures[i];
  3450. const textureIdx = this.recordTexture(texture);
  3451. const spTex = new middleware.Texture2D();
  3452. spTex.setRealTextureIndex(textureIdx);
  3453. spTex.setPixelsWide(texture.width);
  3454. spTex.setPixelsHigh(texture.height);
  3455. spTex.setRealTexture(texture);
  3456. jsbTextures[textureNames[i]] = spTex;
  3457. }
  3458. this._jsbTextures = jsbTextures;
  3459. let filePath = this.skeletonJsonStr;
  3460. if (!filePath) {
  3461. filePath = cacheManager.getCache(this.nativeUrl) || this.nativeUrl;
  3462. }
  3463. this._skeletonCache = spine.initSkeletonData(uuid, filePath, atlasText, jsbTextures, this.scale);
  3464. if (this._skeletonCache) {
  3465. this.width = this._skeletonCache.width;
  3466. this.height = this._skeletonCache.height;
  3467. }
  3468. };
  3469. skeletonDataProto.recordTexture = function (texture) {
  3470. const index = _gTextureIdx;
  3471. const texKey = _textureKeyMap[index] = {
  3472. key: index
  3473. };
  3474. _textureMap.set(texKey, texture);
  3475. _gTextureIdx++;
  3476. return index;
  3477. };
  3478. skeletonDataProto.getTextureByIndex = function (textureIdx) {
  3479. const texKey = _textureKeyMap[textureIdx];
  3480. if (!texKey) return null;
  3481. return _textureMap.get(texKey);
  3482. };
  3483. const animation = spine.SkeletonAnimation.prototype;
  3484. // The methods are added to be compatibility with old versions.
  3485. animation.setCompleteListener = function (listener) {
  3486. this._compeleteListener = listener;
  3487. this.setCompleteListenerNative(function (trackEntry) {
  3488. const loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd);
  3489. this._compeleteListener && this._compeleteListener(trackEntry, loopCount);
  3490. });
  3491. };
  3492. // The methods are added to be compatibility with old versions.
  3493. animation.setTrackCompleteListener = function (trackEntry, listener) {
  3494. this._trackCompeleteListener = listener;
  3495. this.setTrackCompleteListenerNative(trackEntry, function (trackEntryNative) {
  3496. const loopCount = Math.floor(trackEntryNative.trackTime / trackEntryNative.animationEnd);
  3497. this._trackCompeleteListener && this._trackCompeleteListener(trackEntryNative, loopCount);
  3498. });
  3499. };
  3500. // Temporary solution before upgrade the Spine API
  3501. animation.setAnimationListener = function (target, callback) {
  3502. this._target = target;
  3503. this._callback = callback;
  3504. const AnimationEventType = cc.internal.SpineAnimationEventType;
  3505. this.setStartListener(function (trackEntry) {
  3506. if (this._target && this._callback) {
  3507. this._callback.call(this._target, this, trackEntry, AnimationEventType.START, null, 0);
  3508. }
  3509. });
  3510. this.setInterruptListener(function (trackEntry) {
  3511. if (this._target && this._callback) {
  3512. this._callback.call(this._target, this, trackEntry, AnimationEventType.INTERRUPT, null, 0);
  3513. }
  3514. });
  3515. this.setEndListener(function (trackEntry) {
  3516. if (this._target && this._callback) {
  3517. this._callback.call(this._target, this, trackEntry, AnimationEventType.END, null, 0);
  3518. }
  3519. });
  3520. this.setDisposeListener(function (trackEntry) {
  3521. if (this._target && this._callback) {
  3522. this._callback.call(this._target, this, trackEntry, AnimationEventType.DISPOSE, null, 0);
  3523. }
  3524. });
  3525. this.setCompleteListener(function (trackEntry, loopCount) {
  3526. if (this._target && this._callback) {
  3527. this._callback.call(this._target, this, trackEntry, AnimationEventType.COMPLETE, null, loopCount);
  3528. }
  3529. });
  3530. this.setEventListener(function (trackEntry, event) {
  3531. if (this._target && this._callback) {
  3532. this._callback.call(this._target, this, trackEntry, AnimationEventType.EVENT, event, 0);
  3533. }
  3534. });
  3535. };
  3536. const skeleton = cc.internal.SpineSkeleton.prototype;
  3537. const AnimationCacheMode = cc.internal.SpineSkeleton.AnimationCacheMode;
  3538. Object.defineProperty(skeleton, 'paused', {
  3539. get() {
  3540. return this._paused || false;
  3541. },
  3542. set(value) {
  3543. this._paused = value;
  3544. if (this._nativeSkeleton) {
  3545. this._nativeSkeleton.paused(value);
  3546. }
  3547. }
  3548. });
  3549. Object.defineProperty(skeleton, 'premultipliedAlpha', {
  3550. get() {
  3551. if (this._premultipliedAlpha === undefined) {
  3552. return true;
  3553. }
  3554. return this._premultipliedAlpha;
  3555. },
  3556. set(value) {
  3557. this._premultipliedAlpha = value;
  3558. if (this._nativeSkeleton) {
  3559. this._nativeSkeleton.setOpacityModifyRGB(this._premultipliedAlpha);
  3560. }
  3561. }
  3562. });
  3563. Object.defineProperty(skeleton, 'timeScale', {
  3564. get() {
  3565. if (this._timeScale === undefined) return 1.0;
  3566. return this._timeScale;
  3567. },
  3568. set(value) {
  3569. this._timeScale = value;
  3570. if (this._nativeSkeleton) {
  3571. this._nativeSkeleton.setTimeScale(this._timeScale);
  3572. }
  3573. }
  3574. });
  3575. const _updateMaterial = skeleton.updateMaterial;
  3576. skeleton.updateMaterial = function () {
  3577. _updateMaterial.call(this);
  3578. if (this._nativeSkeleton) {
  3579. const mat = this.getMaterialTemplate();
  3580. this._nativeSkeleton.setMaterial(mat);
  3581. }
  3582. };
  3583. const _updateDebugDraw = skeleton._updateDebugDraw;
  3584. skeleton._updateDebugDraw = function () {
  3585. _updateDebugDraw.call(this);
  3586. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3587. this._nativeSkeleton.setDebugMeshEnabled(this.debugMesh);
  3588. this._nativeSkeleton.setDebugSlotsEnabled(this.debugSlots);
  3589. this._nativeSkeleton.setDebugBonesEnabled(this.debugBones);
  3590. }
  3591. };
  3592. const _updateUseTint = skeleton._updateUseTint;
  3593. skeleton._updateUseTint = function () {
  3594. _updateUseTint.call(this);
  3595. if (this._nativeSkeleton) {
  3596. this._nativeSkeleton.setUseTint(this.useTint);
  3597. }
  3598. };
  3599. skeleton._updateBatch = function () {
  3600. if (this._nativeSkeleton) {
  3601. this._renderEntity.setUseLocal(!this.enableBatch);
  3602. this._nativeSkeleton.setBatchEnabled(this.enableBatch);
  3603. this.markForUpdateRenderData();
  3604. }
  3605. };
  3606. skeleton._updateUITransform = function () {
  3607. const skeletonData = this._skeletonData;
  3608. if (!skeletonData) return;
  3609. if (skeletonData.width != null && skeletonData.height != null) {
  3610. const uiTrans = this.node._uiProps.uiTransformComp;
  3611. uiTrans.setContentSize(skeletonData.width, skeletonData.height);
  3612. }
  3613. };
  3614. skeleton.setSkeletonData = function (skeletonData) {
  3615. const uuid = skeletonData.mergedUUID();
  3616. if (!uuid) {
  3617. cc.errorID(7504);
  3618. return;
  3619. }
  3620. const texValues = skeletonData.textures;
  3621. const texKeys = skeletonData.textureNames;
  3622. if (!(texValues && texValues.length > 0 && texKeys && texKeys.length > 0)) {
  3623. cc.errorID(7507, skeletonData.name);
  3624. return;
  3625. }
  3626. if (this._nativeSkeleton) {
  3627. this._nativeSkeleton.stopSchedule();
  3628. this._nativeSkeleton._comp = null;
  3629. this._nativeSkeleton = null;
  3630. }
  3631. let nativeSkeleton = null;
  3632. if (this.isAnimationCached()) {
  3633. nativeSkeleton = new spine.SkeletonCacheAnimation(uuid, this._cacheMode === AnimationCacheMode.SHARED_CACHE);
  3634. } else {
  3635. nativeSkeleton = new spine.SkeletonAnimation();
  3636. try {
  3637. spine.initSkeletonRenderer(nativeSkeleton, uuid);
  3638. } catch (e) {
  3639. cc._throw(e);
  3640. return;
  3641. }
  3642. nativeSkeleton.setDebugSlotsEnabled(this.debugSlots);
  3643. nativeSkeleton.setDebugMeshEnabled(this.debugMesh);
  3644. nativeSkeleton.setDebugBonesEnabled(this.debugBones);
  3645. }
  3646. this._nativeSkeleton = nativeSkeleton;
  3647. nativeSkeleton._comp = this;
  3648. if (this.shouldSchedule) nativeSkeleton.beginSchedule();
  3649. nativeSkeleton.setUseTint(this.useTint);
  3650. nativeSkeleton.setOpacityModifyRGB(this.premultipliedAlpha);
  3651. nativeSkeleton.setTimeScale(this.timeScale);
  3652. nativeSkeleton.setBatchEnabled(this.enableBatch);
  3653. const compColor = this.color;
  3654. nativeSkeleton.setColor(compColor.r, compColor.g, compColor.b, compColor.a);
  3655. const materialTemplate = this.getMaterialTemplate();
  3656. nativeSkeleton.setMaterial(materialTemplate);
  3657. this._renderEntity.setUseLocal(!this.enableBatch);
  3658. nativeSkeleton.setRenderEntity(this._renderEntity.nativeObj);
  3659. this._skeleton = nativeSkeleton.getSkeleton();
  3660. // init skeleton listener
  3661. this._startListener && this.setStartListener(this._startListener);
  3662. this._endListener && this.setEndListener(this._endListener);
  3663. this._completeListener && this.setCompleteListener(this._completeListener);
  3664. this._eventListener && this.setEventListener(this._eventListener);
  3665. this._interruptListener && this.setInterruptListener(this._interruptListener);
  3666. this._disposeListener && this.setDisposeListener(this._disposeListener);
  3667. this._sharedBufferOffset = nativeSkeleton.getSharedBufferOffset();
  3668. this._useAttach = false;
  3669. this.markForUpdateRenderData();
  3670. };
  3671. skeleton._updateColor = function () {
  3672. if (this._nativeSkeleton) {
  3673. const compColor = this._color;
  3674. this.setEntityColorDirty(true);
  3675. this.setEntityColor(compColor);
  3676. this.setEntityOpacity(this.node._uiProps.localOpacity);
  3677. this._nativeSkeleton.setColor(compColor.r, compColor.g, compColor.b, compColor.a);
  3678. this.markForUpdateRenderData();
  3679. }
  3680. };
  3681. skeleton.setAnimationStateData = function (stateData) {
  3682. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3683. this._stateData = stateData;
  3684. this._nativeSkeleton.setAnimationStateData(stateData);
  3685. }
  3686. };
  3687. const _onEnable = skeleton.onEnable;
  3688. skeleton.onEnable = function () {
  3689. if (_onEnable) {
  3690. _onEnable.call(this);
  3691. }
  3692. this.shouldSchedule = true;
  3693. if (this._nativeSkeleton) {
  3694. this._nativeSkeleton.onEnable();
  3695. }
  3696. middleware.retain();
  3697. };
  3698. const _onDisable = skeleton.onDisable;
  3699. skeleton.onDisable = function () {
  3700. if (_onDisable) {
  3701. _onDisable.call(this);
  3702. }
  3703. if (this._nativeSkeleton) {
  3704. this._nativeSkeleton.onDisable();
  3705. }
  3706. middleware.release();
  3707. };
  3708. skeleton.setVertexEffectDelegate = function (effectDelegate) {
  3709. if (cc.internal.SPINE_VERSION === '4.2') {
  3710. cc.warn('setVertexEffectDelegate is deprecated since spine 4.2');
  3711. return;
  3712. }
  3713. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3714. this._nativeSkeleton.setVertexEffectDelegate(effectDelegate);
  3715. }
  3716. };
  3717. // eslint-disable-next-line no-unused-vars
  3718. skeleton.updateAnimation = function (dt) {
  3719. const nativeSkeleton = this._nativeSkeleton;
  3720. if (!nativeSkeleton) return;
  3721. const node = this.node;
  3722. if (!node) return;
  3723. if (this.__preColor__ === undefined || !this.color.equals(this.__preColor__)) {
  3724. const compColor = this.color;
  3725. nativeSkeleton.setColor(compColor.r, compColor.g, compColor.b, compColor.a);
  3726. this.__preColor__ = compColor;
  3727. }
  3728. const socketNodes = this.socketNodes;
  3729. if (!this._useAttach && socketNodes.size > 0) {
  3730. this._useAttach = true;
  3731. nativeSkeleton.setAttachEnabled(true);
  3732. }
  3733. };
  3734. skeleton.updateWorldTransform = function () {
  3735. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3736. this._nativeSkeleton.updateWorldTransform();
  3737. }
  3738. };
  3739. skeleton.setToSetupPose = function () {
  3740. if (this._nativeSkeleton) {
  3741. this._nativeSkeleton.setToSetupPose();
  3742. }
  3743. };
  3744. skeleton.setBonesToSetupPose = function () {
  3745. if (this._nativeSkeleton) {
  3746. this._nativeSkeleton.setBonesToSetupPose();
  3747. }
  3748. };
  3749. skeleton.setSlotsToSetupPose = function () {
  3750. if (this._nativeSkeleton) {
  3751. this._nativeSkeleton.setSlotsToSetupPose();
  3752. }
  3753. };
  3754. skeleton.setSlotsRange = function (startSlotIndex, endSlotIndex) {
  3755. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3756. this._nativeSkeleton.setSlotsRange(startSlotIndex, endSlotIndex);
  3757. }
  3758. };
  3759. skeleton.updateAnimationCache = function (animName) {
  3760. if (!this.isAnimationCached()) return;
  3761. if (this._nativeSkeleton) {
  3762. if (animName) {
  3763. this._nativeSkeleton.updateAnimationCache(animName);
  3764. } else {
  3765. this._nativeSkeleton.updateAllAnimationCache();
  3766. }
  3767. }
  3768. };
  3769. skeleton.invalidAnimationCache = function () {
  3770. if (!this.isAnimationCached()) return;
  3771. if (this._nativeSkeleton) {
  3772. this._nativeSkeleton.updateAllAnimationCache();
  3773. }
  3774. };
  3775. skeleton.findBone = function (boneName) {
  3776. if (this._nativeSkeleton) return this._nativeSkeleton.findBone(boneName);
  3777. return null;
  3778. };
  3779. skeleton.findSlot = function (slotName) {
  3780. if (this._nativeSkeleton) return this._nativeSkeleton.findSlot(slotName);
  3781. return null;
  3782. };
  3783. skeleton.setSkin = function (skinName) {
  3784. this._skinName = skinName;
  3785. if (this._nativeSkeleton) return this._nativeSkeleton.setSkin(skinName);
  3786. return null;
  3787. };
  3788. skeleton.getAttachment = function (slotName, attachmentName) {
  3789. if (this._nativeSkeleton) return this._nativeSkeleton.getAttachment(slotName, attachmentName);
  3790. return null;
  3791. };
  3792. skeleton.setAttachment = function (slotName, attachmentName) {
  3793. this._nativeSkeleton && this._nativeSkeleton.setAttachment(slotName, attachmentName);
  3794. };
  3795. // eslint-disable-next-line no-unused-vars
  3796. skeleton.getTextureAtlas = function (regionAttachment) {
  3797. cc.warn('Spine Skeleton getTextureAtlas not support in native');
  3798. return null;
  3799. };
  3800. skeleton.setMix = function (fromAnimation, toAnimation, duration) {
  3801. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3802. this._nativeSkeleton.setMix(fromAnimation, toAnimation, duration);
  3803. }
  3804. };
  3805. skeleton.setAnimation = function (trackIndex, name, loop) {
  3806. const strName = name.toString();
  3807. this._playTimes = loop ? 0 : 1;
  3808. let res = null;
  3809. if (this._nativeSkeleton) {
  3810. if (!this._nativeSkeleton.findAnimation(strName)) return res;
  3811. this._animationName = strName;
  3812. if (this.isAnimationCached()) {
  3813. res = this._nativeSkeleton.setAnimation(strName, loop);
  3814. } else {
  3815. res = this._nativeSkeleton.setAnimation(trackIndex, strName, loop);
  3816. }
  3817. /**
  3818. * note: since native spine animation update called after Director.EVENT_BEFORE_UPDATE
  3819. * and before setAnimation. it's need to update native animation to first frame directly.
  3820. */
  3821. this._nativeSkeleton.update(0);
  3822. }
  3823. return res;
  3824. };
  3825. skeleton.addAnimation = function (trackIndex, name, loop, delay) {
  3826. if (this._nativeSkeleton) {
  3827. delay = delay || 0;
  3828. if (this.isAnimationCached()) {
  3829. return this._nativeSkeleton.addAnimation(name, loop, delay);
  3830. } else {
  3831. return this._nativeSkeleton.addAnimation(trackIndex, name, loop, delay);
  3832. }
  3833. }
  3834. return null;
  3835. };
  3836. skeleton.findAnimation = function (name) {
  3837. if (this._nativeSkeleton) return this._nativeSkeleton.findAnimation(name);
  3838. return null;
  3839. };
  3840. skeleton.getCurrent = function (trackIndex) {
  3841. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3842. return this._nativeSkeleton.getCurrent(trackIndex);
  3843. }
  3844. return null;
  3845. };
  3846. skeleton.clearTracks = function () {
  3847. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3848. this._nativeSkeleton.clearTracks();
  3849. }
  3850. };
  3851. skeleton.clearTrack = function (trackIndex) {
  3852. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3853. this._nativeSkeleton.clearTrack(trackIndex);
  3854. }
  3855. };
  3856. skeleton.setStartListener = function (listener) {
  3857. this._startListener = listener;
  3858. if (this._nativeSkeleton) {
  3859. if (this.isAnimationCached()) {
  3860. this._nativeSkeleton.setStartListener(function (animationName) {
  3861. const self = this._comp;
  3862. self._startEntry.animation.name = animationName;
  3863. self._startListener && self._startListener(self._startEntry);
  3864. });
  3865. } else {
  3866. this._nativeSkeleton.setStartListener(listener);
  3867. }
  3868. }
  3869. };
  3870. skeleton.setInterruptListener = function (listener) {
  3871. this._interruptListener = listener;
  3872. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3873. this._nativeSkeleton.setInterruptListener(listener);
  3874. }
  3875. };
  3876. skeleton.setEndListener = function (listener) {
  3877. this._endListener = listener;
  3878. if (this._nativeSkeleton) {
  3879. if (this.isAnimationCached()) {
  3880. this._nativeSkeleton.setEndListener(function (animationName) {
  3881. const self = this._comp;
  3882. self._endEntry.animation.name = animationName;
  3883. self._endListener && self._endListener(self._endEntry);
  3884. });
  3885. } else {
  3886. this._nativeSkeleton.setEndListener(listener);
  3887. }
  3888. }
  3889. };
  3890. skeleton.setDisposeListener = function (listener) {
  3891. this._disposeListener = listener;
  3892. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3893. this._nativeSkeleton.setDisposeListener(listener);
  3894. }
  3895. };
  3896. skeleton.setCompleteListener = function (listener) {
  3897. this._completeListener = listener;
  3898. if (this._nativeSkeleton) {
  3899. if (this.isAnimationCached()) {
  3900. this._nativeSkeleton.setCompleteListener(function (animationName) {
  3901. const self = this._comp;
  3902. self._endEntry.animation.name = animationName;
  3903. self._completeListener && self._completeListener(self._endEntry);
  3904. });
  3905. } else {
  3906. this._nativeSkeleton.setCompleteListener(listener);
  3907. }
  3908. }
  3909. };
  3910. skeleton.setEventListener = function (listener) {
  3911. this._eventListener = listener;
  3912. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3913. this._nativeSkeleton.setEventListener(listener);
  3914. }
  3915. };
  3916. skeleton.setTrackStartListener = function (entry, listener) {
  3917. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3918. this._nativeSkeleton.setTrackStartListener(entry, listener);
  3919. }
  3920. };
  3921. skeleton.setTrackInterruptListener = function (entry, listener) {
  3922. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3923. this._nativeSkeleton.setTrackInterruptListener(entry, listener);
  3924. }
  3925. };
  3926. skeleton.setTrackEndListener = function (entry, listener) {
  3927. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3928. this._nativeSkeleton.setTrackEndListener(entry, listener);
  3929. }
  3930. };
  3931. skeleton.setTrackDisposeListener = function (entry, listener) {
  3932. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3933. this._nativeSkeleton.setTrackDisposeListener(entry, listener);
  3934. }
  3935. };
  3936. skeleton.setTrackCompleteListener = function (entry, listener) {
  3937. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3938. this._nativeSkeleton.setTrackCompleteListener(entry, listener);
  3939. }
  3940. };
  3941. skeleton.setTrackEventListener = function (entry, listener) {
  3942. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3943. this._nativeSkeleton.setTrackEventListener(entry, listener);
  3944. }
  3945. };
  3946. skeleton.getState = function () {
  3947. if (this._nativeSkeleton && !this.isAnimationCached()) {
  3948. return this._nativeSkeleton.getState();
  3949. }
  3950. return null;
  3951. };
  3952. skeleton._ensureListener = function () {
  3953. cc.warn('Spine Skeleton _ensureListener not need in native');
  3954. };
  3955. skeleton._updateSkeletonData = function () {
  3956. if (this.skeletonData) {
  3957. this.skeletonData.init();
  3958. this.setSkeletonData(this.skeletonData);
  3959. this._indexBoneSockets();
  3960. this._updateSocketBindings();
  3961. this.attachUtil.init(this);
  3962. this._preCacheMode = this._cacheMode;
  3963. if (this.defaultSkin && this.defaultSkin !== '') {
  3964. this.setSkin(this.defaultSkin);
  3965. } else if (this._skinName && this._skinName !== '') {
  3966. this.setSkin(this._skinName);
  3967. }
  3968. if (this.defaultAnimation) {
  3969. this.animation = this.defaultAnimation;
  3970. } else if (this._animationName) {
  3971. this.animation = this._animationName;
  3972. } else {
  3973. this.animation = '';
  3974. }
  3975. } else if (this._nativeSkeleton) {
  3976. this._nativeSkeleton.stopSchedule();
  3977. this._nativeSkeleton._comp = null;
  3978. this._nativeSkeleton = null;
  3979. }
  3980. this._needUpdateSkeltonData = false;
  3981. };
  3982. const _onDestroy = skeleton.onDestroy;
  3983. skeleton.onDestroy = function () {
  3984. _onDestroy.call(this);
  3985. if (this._nativeSkeleton) {
  3986. this._nativeSkeleton.setRenderEntity(null);
  3987. this._nativeSkeleton.stopSchedule();
  3988. this._nativeSkeleton._comp = null;
  3989. this._nativeSkeleton = null;
  3990. }
  3991. this._stateData = null;
  3992. };
  3993. skeleton._render = function () {
  3994. const nativeSkeleton = this._nativeSkeleton;
  3995. if (!nativeSkeleton) return;
  3996. if (!this.isAnimationCached() && (this.debugBones || this.debugSlots || this.debugMesh) && this._debugRenderer) {
  3997. const graphics = this._debugRenderer;
  3998. graphics.clear();
  3999. graphics.lineWidth = 5;
  4000. const debugData = this._debugData || nativeSkeleton.getDebugData();
  4001. if (!debugData) return;
  4002. let debugIdx = 0;
  4003. let debugType = 0;
  4004. let debugLen = 0;
  4005. debugType = debugData[debugIdx++];
  4006. while (debugType !== 0) {
  4007. debugLen = debugData[debugIdx++];
  4008. switch (debugType) {
  4009. case 1:
  4010. // slots
  4011. graphics.strokeColor = _slotColor;
  4012. for (let i = 0; i < debugLen; i += 8) {
  4013. graphics.moveTo(debugData[debugIdx++], debugData[debugIdx++]);
  4014. graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]);
  4015. graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]);
  4016. graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]);
  4017. graphics.close();
  4018. graphics.stroke();
  4019. }
  4020. break;
  4021. case 2:
  4022. // mesh
  4023. graphics.strokeColor = _meshColor;
  4024. for (let i = 0; i < debugLen; i += 6) {
  4025. graphics.moveTo(debugData[debugIdx++], debugData[debugIdx++]);
  4026. graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]);
  4027. graphics.lineTo(debugData[debugIdx++], debugData[debugIdx++]);
  4028. graphics.close();
  4029. graphics.stroke();
  4030. }
  4031. break;
  4032. case 3:
  4033. // bones
  4034. graphics.strokeColor = _boneColor;
  4035. graphics.fillColor = _slotColor; // Root bone color is same as slot color.
  4036. for (let i = 0; i < debugLen; i += 4) {
  4037. const bx = debugData[debugIdx++];
  4038. const by = debugData[debugIdx++];
  4039. const x = debugData[debugIdx++];
  4040. const y = debugData[debugIdx++];
  4041. // Bone lengths.
  4042. graphics.moveTo(bx, by);
  4043. graphics.lineTo(x, y);
  4044. graphics.stroke();
  4045. // Bone origins.
  4046. graphics.circle(bx, by, Math.PI * 1.5);
  4047. graphics.fill();
  4048. if (i === 0) {
  4049. graphics.fillColor = _originColor;
  4050. }
  4051. }
  4052. break;
  4053. default:
  4054. return;
  4055. }
  4056. debugType = debugData[debugIdx++];
  4057. }
  4058. }
  4059. };
  4060. const _tempAttachMat4 = cc.mat4();
  4061. skeleton.syncAttachedNode = function () {
  4062. const nativeSkeleton = this._nativeSkeleton;
  4063. if (!nativeSkeleton) return;
  4064. const socketNodes = this.socketNodes;
  4065. if (socketNodes.size > 0 && this._useAttach) {
  4066. const sharedBufferOffset = this._sharedBufferOffset;
  4067. if (!sharedBufferOffset) return;
  4068. const attachInfoMgr = middleware.attachInfoMgr;
  4069. const attachInfo = attachInfoMgr.attachInfo;
  4070. const attachInfoOffset = sharedBufferOffset[0];
  4071. // reset attach info offset
  4072. sharedBufferOffset[0] = 0;
  4073. for (const boneIdx of socketNodes.keys()) {
  4074. const boneNode = socketNodes.get(boneIdx);
  4075. // Node has been destroy
  4076. if (!boneNode || !boneNode.isValid) {
  4077. socketNodes.delete(boneIdx);
  4078. continue;
  4079. }
  4080. const tm = _tempAttachMat4;
  4081. const matOffset = attachInfoOffset + boneIdx * 16;
  4082. tm.m00 = attachInfo[matOffset];
  4083. tm.m01 = attachInfo[matOffset + 1];
  4084. tm.m04 = attachInfo[matOffset + 4];
  4085. tm.m05 = attachInfo[matOffset + 5];
  4086. tm.m12 = attachInfo[matOffset + 12];
  4087. tm.m13 = attachInfo[matOffset + 13];
  4088. boneNode.matrix = tm;
  4089. }
  4090. }
  4091. };
  4092. skeleton.setSlotTexture = function (slotName, tex2d, createNew) {
  4093. if (this.isAnimationCached()) {
  4094. console.error(`Cached mode can't change texture of slot`);
  4095. return;
  4096. }
  4097. if (!this._nativeSkeleton) return;
  4098. const slot = this.findSlot(slotName);
  4099. if (!slot) {
  4100. console.error(`No slot named:${slotName}`);
  4101. return;
  4102. }
  4103. const createNewAttachment = createNew || false;
  4104. this._nativeSkeleton.setSlotTexture(slotName, tex2d, createNewAttachment);
  4105. };
  4106. //////////////////////////////////////////
  4107. // assembler
  4108. const assembler = cc.internal.SpineAssembler;
  4109. // eslint-disable-next-line no-unused-vars
  4110. assembler.createData = function (comp) {};
  4111. assembler.updateRenderData = function (comp) {
  4112. comp._render();
  4113. comp.syncAttachedNode();
  4114. };
  4115. // eslint-disable-next-line no-unused-vars
  4116. assembler.fillBuffers = function (comp, renderer) {};
  4117. })();
  4118. },{"./jsb-cache-manager":3}],13:[function(require,module,exports){
  4119. "use strict";
  4120. /****************************************************************************
  4121. Copyright (c) 2022 Xiamen Yaji Software Co., Ltd.
  4122. https://www.cocos.com/
  4123. Permission is hereby granted, free of charge, to any person obtaining a copy
  4124. of this software and associated engine source code (the "Software"), a limited,
  4125. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  4126. to use Cocos Creator solely to develop games on your target platforms. You shall
  4127. not use Cocos Creator software for developing other software or tools that's
  4128. used for developing games. You are not granted to publish, distribute,
  4129. sublicense, and/or sell copies of Cocos Creator.
  4130. The software or tools in this License Agreement are licensed, not sold.
  4131. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  4132. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4133. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4134. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4135. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4136. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  4137. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  4138. THE SOFTWARE.
  4139. ****************************************************************************/
  4140. if (cc.internal.VideoPlayer) {
  4141. const {
  4142. EventType
  4143. } = cc.internal.VideoPlayer;
  4144. const vec3 = cc.Vec3;
  4145. const mat4 = cc.Mat4;
  4146. const _mat4_temp = new mat4();
  4147. const _topLeft = new vec3();
  4148. const _bottomRight = new vec3();
  4149. let kVideoTag = 0;
  4150. const videoPlayers = [];
  4151. const VideoEvent = {
  4152. PLAYING: 0,
  4153. PAUSED: 1,
  4154. STOPPED: 2,
  4155. COMPLETED: 3,
  4156. META_LOADED: 4,
  4157. CLICKED: 5,
  4158. READY_TO_PLAY: 6,
  4159. UPDATE: 7,
  4160. QUIT_FULLSCREEN: 1000
  4161. };
  4162. cc.internal.VideoPlayerImplManager.getImpl = function (componenet) {
  4163. return new VideoPlayerImplOpenHarmony(componenet);
  4164. };
  4165. window.oh.onVideoEvent = args => {
  4166. const data = JSON.parse(args);
  4167. videoPlayers.forEach(player => {
  4168. if (player.index === data.videoTag) {
  4169. player.dispatchEvent(data.videoEvent, data.args);
  4170. }
  4171. });
  4172. };
  4173. class VideoPlayer {
  4174. constructor() {
  4175. this._events = {};
  4176. this._currentTime = 0;
  4177. this._duration = 0;
  4178. this._videoIndex = kVideoTag++;
  4179. this._matViewProj_temp = new mat4();
  4180. window.oh.postMessage('createVideo', this._videoIndex);
  4181. videoPlayers.push(this);
  4182. }
  4183. get index() {
  4184. return this._videoIndex;
  4185. }
  4186. play() {
  4187. window.oh.postMessage('startVideo', this._videoIndex);
  4188. }
  4189. // private function
  4190. _isURL(url) {
  4191. const regexp = /((http|https):\/\/([\w\-]+\.)+[\w\-]+(\/[\w\u4e00-\u9fa5\-\.\/?\@\%\!\&=\+\~\:\#\;\,]*)?)/ig;
  4192. if (regexp.test(url)) {
  4193. return true;
  4194. } else {
  4195. return false;
  4196. }
  4197. }
  4198. setURL(url) {
  4199. if (this._isURL(url)) {
  4200. window.oh.postMessage('setVideoUrl', {
  4201. tag: this._videoIndex,
  4202. resourceType: 0,
  4203. url
  4204. });
  4205. } else {
  4206. window.oh.postMessage('setVideoUrl', {
  4207. tag: this._videoIndex,
  4208. resourceType: 1,
  4209. url
  4210. });
  4211. }
  4212. }
  4213. pause() {
  4214. window.oh.postMessage('pauseVideo', this._videoIndex);
  4215. }
  4216. setVisible(visible) {
  4217. window.oh.postMessage('setVideoVisible', {
  4218. tag: this._videoIndex,
  4219. visible
  4220. });
  4221. }
  4222. resume() {
  4223. window.oh.postMessage('resumeVideo', this._videoIndex);
  4224. }
  4225. currentTime() {
  4226. window.oh.postSyncMessage('currentTime', this._videoIndex).then(result => {
  4227. this._currentTime = result;
  4228. });
  4229. return this._currentTime;
  4230. }
  4231. stop() {
  4232. window.oh.postMessage('stopVideo', this._videoIndex);
  4233. }
  4234. seekTo(val) {
  4235. window.oh.postMessage('seekVideoTo', {
  4236. tag: this._videoIndex,
  4237. time: val
  4238. });
  4239. }
  4240. duration() {
  4241. window.oh.postSyncMessage('getVideoDuration', this._videoIndex).then(result => {
  4242. this._duration = result;
  4243. });
  4244. return this._duration;
  4245. }
  4246. destroy() {
  4247. window.oh.postMessage('removeVideo', this._videoIndex);
  4248. }
  4249. setFullScreenEnabled(enable) {
  4250. window.oh.postMessage('setFullScreenEnabled', {
  4251. tag: this._videoIndex,
  4252. fullScreen: enable
  4253. });
  4254. }
  4255. setKeepAspectRatioEnabled(enable) {
  4256. cc.warn('The platform does not support');
  4257. }
  4258. setFrame(x, y, w, h) {
  4259. window.oh.postMessage('setVideoRect', {
  4260. tag: this._videoIndex,
  4261. x,
  4262. y,
  4263. w,
  4264. h
  4265. });
  4266. }
  4267. eventTypeToEventName(ev) {
  4268. let evString;
  4269. switch (ev) {
  4270. case VideoEvent.PLAYING:
  4271. evString = 'play';
  4272. break;
  4273. case VideoEvent.PAUSED:
  4274. evString = 'pause';
  4275. break;
  4276. case VideoEvent.STOPPED:
  4277. evString = 'stoped';
  4278. break;
  4279. case VideoEvent.COMPLETED:
  4280. evString = 'ended';
  4281. break;
  4282. case VideoEvent.META_LOADED:
  4283. evString = 'loadedmetadata';
  4284. break;
  4285. case VideoEvent.CLICKED:
  4286. evString = 'click';
  4287. break;
  4288. case VideoEvent.READY_TO_PLAY:
  4289. evString = 'suspend';
  4290. break;
  4291. case VideoEvent.UPDATE:
  4292. evString = 'update';
  4293. break;
  4294. case VideoEvent.QUIT_FULLSCREEN:
  4295. evString = 'suspend';
  4296. break;
  4297. default:
  4298. evString = 'none';
  4299. break;
  4300. }
  4301. return evString;
  4302. }
  4303. dispatchEvent(type, args) {
  4304. const eventName = this.eventTypeToEventName(type);
  4305. const listeners = this._events[eventName];
  4306. if (listeners) {
  4307. for (let i = 0; i < listeners.length; i++) {
  4308. listeners[i](args);
  4309. }
  4310. }
  4311. }
  4312. addEventListener(name, listener) {
  4313. if (!this._events[name]) {
  4314. this._events[name] = [];
  4315. }
  4316. this._events[name].push(listener);
  4317. }
  4318. removeEventListener(name, listener) {
  4319. const listeners = this._events[name];
  4320. if (listeners && listeners.length > 0) {
  4321. for (let i = listeners.length; i--; i > 0) {
  4322. if (listeners[i] === listener) {
  4323. listeners.splice(i, 1);
  4324. break;
  4325. }
  4326. }
  4327. }
  4328. }
  4329. }
  4330. class VideoPlayerImplOpenHarmony extends cc.internal.VideoPlayerImpl {
  4331. constructor(componenet) {
  4332. super(componenet);
  4333. this._matViewProj_temp = new mat4();
  4334. this._loaded = false;
  4335. }
  4336. syncClip(clip) {
  4337. this.removeVideoPlayer();
  4338. if (!clip) {
  4339. return;
  4340. }
  4341. this.createVideoPlayer(clip._nativeAsset);
  4342. }
  4343. syncURL(url) {
  4344. this.removeVideoPlayer();
  4345. if (!url) {
  4346. return;
  4347. }
  4348. this.createVideoPlayer(url);
  4349. }
  4350. onCanPlay(args = 0) {
  4351. if (this._loaded) {
  4352. return;
  4353. }
  4354. this._video._duration = args;
  4355. this._loaded = true;
  4356. this.video.setVisible(this._visible);
  4357. this.dispatchEvent(EventType.READY_TO_PLAY);
  4358. //this.delayedPlay();
  4359. }
  4360. onUpdate(args = 0) {
  4361. if (this.video) {
  4362. this.video._currentTime = args;
  4363. }
  4364. }
  4365. _bindEvent() {
  4366. this.video.addEventListener('loadedmetadata', this.onLoadedMetadata.bind(this));
  4367. this.video.addEventListener('suspend', this.onCanPlay.bind(this));
  4368. this.video.addEventListener('play', this.onPlay.bind(this));
  4369. this.video.addEventListener('pause', this.onPause.bind(this));
  4370. this.video.addEventListener('stoped', this.onStoped.bind(this));
  4371. this.video.addEventListener('click', this.onClick.bind(this));
  4372. this.video.addEventListener('ended', this.onEnded.bind(this));
  4373. this.video.addEventListener('update', this.onUpdate.bind(this));
  4374. }
  4375. _unBindEvent() {
  4376. this.video.removeEventListener('loadedmetadata', this.onLoadedMetadata.bind(this));
  4377. this.video.removeEventListener('suspend', this.onCanPlay.bind(this));
  4378. this.video.removeEventListener('play', this.onPlay.bind(this));
  4379. this.video.removeEventListener('pause', this.onPause.bind(this));
  4380. this.video.removeEventListener('stoped', this.onStoped.bind(this));
  4381. this.video.removeEventListener('click', this.onClick.bind(this));
  4382. this.video.removeEventListener('ended', this.onEnded.bind(this));
  4383. this.video.removeEventListener('update', this.onUpdate.bind(this));
  4384. }
  4385. onLoadedMetadata() {
  4386. this._loadedMeta = true;
  4387. this._forceUpdate = true;
  4388. if (this._visible) {
  4389. this.enable();
  4390. } else {
  4391. this.disable();
  4392. }
  4393. this.dispatchEvent(EventType.META_LOADED);
  4394. this.delayedFullScreen();
  4395. this.delayedPlay();
  4396. }
  4397. createVideoPlayer(url) {
  4398. this._video = new VideoPlayer();
  4399. this._bindEvent();
  4400. this._video.setVisible(this._visible);
  4401. this._video.setURL(url);
  4402. this._forceUpdate = true;
  4403. }
  4404. removeVideoPlayer() {
  4405. const video = this.video;
  4406. if (video) {
  4407. video.stop();
  4408. video.setVisible(false);
  4409. video.destroy();
  4410. this._unBindEvent();
  4411. this._playing = false;
  4412. this._loaded = false;
  4413. this._loadedMeta = false;
  4414. this._ignorePause = false;
  4415. this._cachedCurrentTime = 0;
  4416. this._video = null;
  4417. }
  4418. }
  4419. getDuration() {
  4420. if (!this.video) {
  4421. return -1;
  4422. }
  4423. return this.video.duration();
  4424. }
  4425. syncPlaybackRate() {
  4426. cc.warn('The platform does not support');
  4427. }
  4428. syncVolume() {
  4429. cc.warn('The platform does not support');
  4430. }
  4431. syncMute() {
  4432. cc.warn('The platform does not support');
  4433. }
  4434. syncLoop() {
  4435. cc.warn('The platform does not support');
  4436. }
  4437. syncStayOnBottom() {
  4438. cc.warn('The platform does not support');
  4439. }
  4440. getCurrentTime() {
  4441. if (this.video) {
  4442. this._cachedCurrentTime = this.video.currentTime();
  4443. return this._cachedCurrentTime;
  4444. }
  4445. return -1;
  4446. }
  4447. seekTo(val) {
  4448. const video = this._video;
  4449. if (!video) return;
  4450. video.seekTo(val);
  4451. this._cachedCurrentTime = val;
  4452. }
  4453. disable(noPause) {
  4454. if (this.video) {
  4455. if (!noPause) {
  4456. this.video.pause();
  4457. }
  4458. this.video.setVisible(false);
  4459. this._visible = false;
  4460. }
  4461. }
  4462. enable() {
  4463. if (this.video) {
  4464. this.video.setVisible(true);
  4465. this._visible = true;
  4466. }
  4467. }
  4468. canPlay() {
  4469. this.video.play();
  4470. this.syncCurrentTime();
  4471. }
  4472. resume() {
  4473. if (this.video) {
  4474. this.video.resume();
  4475. this.syncCurrentTime();
  4476. this._playing = true;
  4477. }
  4478. }
  4479. pause() {
  4480. if (this.video) {
  4481. this._cachedCurrentTime = this.video.currentTime();
  4482. this.video.pause();
  4483. }
  4484. }
  4485. stop() {
  4486. if (this.video) {
  4487. //this._ignorePause = true;
  4488. this.video.seekTo(0);
  4489. this._cachedCurrentTime = 0;
  4490. this.video.stop();
  4491. }
  4492. }
  4493. canFullScreen(enabled) {
  4494. if (this.video) {
  4495. this.video.setFullScreenEnabled(enabled);
  4496. }
  4497. }
  4498. syncKeepAspectRatio(enabled) {
  4499. if (this.video) {
  4500. this.video.setKeepAspectRatioEnabled(enabled);
  4501. }
  4502. }
  4503. syncMatrix() {
  4504. if (!this._video || !this._component || !this._uiTrans) return;
  4505. const camera = this.UICamera;
  4506. if (!camera) {
  4507. return;
  4508. }
  4509. this._component.node.getWorldMatrix(_mat4_temp);
  4510. const {
  4511. width,
  4512. height
  4513. } = this._uiTrans.contentSize;
  4514. if (!this._forceUpdate && camera.matViewProj.equals(this._matViewProj_temp) && this._m00 === _mat4_temp.m00 && this._m01 === _mat4_temp.m01 && this._m04 === _mat4_temp.m04 && this._m05 === _mat4_temp.m05 && this._m12 === _mat4_temp.m12 && this._m13 === _mat4_temp.m13 && this._w === width && this._h === height) {
  4515. return;
  4516. }
  4517. this._matViewProj_temp.set(camera.matViewProj);
  4518. // update matrix cache
  4519. this._m00 = _mat4_temp.m00;
  4520. this._m01 = _mat4_temp.m01;
  4521. this._m04 = _mat4_temp.m04;
  4522. this._m05 = _mat4_temp.m05;
  4523. this._m12 = _mat4_temp.m12;
  4524. this._m13 = _mat4_temp.m13;
  4525. this._w = width;
  4526. this._h = height;
  4527. const canvas_width = cc.game.canvas.width;
  4528. const canvas_height = cc.game.canvas.height;
  4529. const ap = this._uiTrans.anchorPoint;
  4530. // Vectors in node space
  4531. vec3.set(_topLeft, -ap.x * this._w, (1.0 - ap.y) * this._h, 0);
  4532. vec3.set(_bottomRight, (1 - ap.x) * this._w, -ap.y * this._h, 0);
  4533. // Convert to world space
  4534. vec3.transformMat4(_topLeft, _topLeft, _mat4_temp);
  4535. vec3.transformMat4(_bottomRight, _bottomRight, _mat4_temp);
  4536. // need update camera data
  4537. camera.update();
  4538. // Convert to Screen space
  4539. camera.worldToScreen(_topLeft, _topLeft);
  4540. camera.worldToScreen(_bottomRight, _bottomRight);
  4541. const finalWidth = _bottomRight.x - _topLeft.x;
  4542. const finalHeight = _topLeft.y - _bottomRight.y;
  4543. this._video.setFrame(_topLeft.x, canvas_height - _topLeft.y, finalWidth, finalHeight);
  4544. this._forceUpdate = false;
  4545. }
  4546. }
  4547. }
  4548. },{}],14:[function(require,module,exports){
  4549. /****************************************************************************
  4550. Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
  4551. https://www.cocos.com/
  4552. Permission is hereby granted, free of charge, to any person obtaining a copy
  4553. of this software and associated engine source code (the "Software"), a limited,
  4554. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  4555. to use Cocos Creator solely to develop games on your target platforms. You shall
  4556. not use Cocos Creator software for developing other software or tools that's
  4557. used for developing games. You are not granted to publish, distribute,
  4558. sublicense, and/or sell copies of Cocos Creator.
  4559. The software or tools in this License Agreement are licensed, not sold.
  4560. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  4561. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4562. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4563. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4564. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4565. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  4566. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  4567. THE SOFTWARE.
  4568. ****************************************************************************/
  4569. 'use strict';
  4570. if (cc.internal.VideoPlayer) {
  4571. const {
  4572. EventType
  4573. } = cc.internal.VideoPlayer;
  4574. let vec3 = cc.Vec3;
  4575. let mat4 = cc.Mat4;
  4576. let _mat4_temp = new mat4();
  4577. let _topLeft = new vec3();
  4578. let _bottomRight = new vec3();
  4579. cc.internal.VideoPlayerImplManager.getImpl = function (componenet) {
  4580. return new VideoPlayerImplJSB(componenet);
  4581. };
  4582. class VideoPlayerImplJSB extends cc.internal.VideoPlayerImpl {
  4583. constructor(componenet) {
  4584. super(componenet);
  4585. this._matViewProj_temp = new mat4();
  4586. }
  4587. syncClip(clip) {
  4588. this.removeVideoPlayer();
  4589. if (!clip) {
  4590. return;
  4591. }
  4592. this.createVideoPlayer(clip._nativeAsset);
  4593. }
  4594. syncURL(url) {
  4595. this.removeVideoPlayer();
  4596. if (!url) {
  4597. return;
  4598. }
  4599. this.createVideoPlayer(url);
  4600. }
  4601. onCanplay() {
  4602. if (this._loaded) {
  4603. return;
  4604. }
  4605. this._loaded = true;
  4606. this.video.setVisible(this._visible);
  4607. this.dispatchEvent(EventType.READY_TO_PLAY);
  4608. this.delayedPlay();
  4609. }
  4610. _bindEvent() {
  4611. this.video.addEventListener('loadedmetadata', this.onLoadedMetadata.bind(this));
  4612. this.video.addEventListener('suspend', this.onCanPlay.bind(this));
  4613. this.video.addEventListener('play', this.onPlay.bind(this));
  4614. this.video.addEventListener('pause', this.onPause.bind(this));
  4615. this.video.addEventListener('stoped', this.onStoped.bind(this));
  4616. this.video.addEventListener('click', this.onClick.bind(this));
  4617. this.video.addEventListener('ended', this.onEnded.bind(this));
  4618. }
  4619. onLoadedMetadata() {
  4620. this._loadedMeta = true;
  4621. this._forceUpdate = true;
  4622. if (this._visible) {
  4623. this.enable();
  4624. } else {
  4625. this.disable();
  4626. }
  4627. this.dispatchEvent(EventType.META_LOADED);
  4628. this.delayedFullScreen();
  4629. this.delayedPlay();
  4630. }
  4631. createVideoPlayer(url) {
  4632. this._video = new jsb.VideoPlayer();
  4633. this._bindEvent();
  4634. this._video.setVisible(this._visible);
  4635. this._video.setURL(url);
  4636. this._forceUpdate = true;
  4637. }
  4638. removeVideoPlayer() {
  4639. let video = this.video;
  4640. if (video) {
  4641. video.stop();
  4642. video.setVisible(false);
  4643. video.destroy();
  4644. this._playing = false;
  4645. this._loaded = false;
  4646. this._loadedMeta = false;
  4647. this._ignorePause = false;
  4648. this._cachedCurrentTime = 0;
  4649. this._video = null;
  4650. }
  4651. }
  4652. getDuration() {
  4653. if (!this.video) {
  4654. return -1;
  4655. }
  4656. return this.video.duration();
  4657. }
  4658. syncPlaybackRate(value) {
  4659. if (this.video) {
  4660. this.video.setPlaybackRate(value);
  4661. }
  4662. }
  4663. syncVolume() {
  4664. cc.warn('The platform does not support');
  4665. }
  4666. syncMute(enable) {
  4667. if (this.video && this.video.muted !== enable) {
  4668. this.video.setMute(enable);
  4669. }
  4670. }
  4671. syncLoop(enable) {
  4672. if (this.video && this.video.loop !== enable) {
  4673. this.video.setLoop(enable);
  4674. }
  4675. }
  4676. syncStayOnBottom() {
  4677. cc.warn('The platform does not support');
  4678. }
  4679. getCurrentTime() {
  4680. if (this.video) {
  4681. this._cachedCurrentTime = this.video.currentTime();
  4682. return this._cachedCurrentTime;
  4683. }
  4684. return -1;
  4685. }
  4686. seekTo(val) {
  4687. let video = this._video;
  4688. if (!video) return;
  4689. video.seekTo(val);
  4690. this._cachedCurrentTime = val;
  4691. }
  4692. disable(noPause) {
  4693. if (this.video) {
  4694. if (!noPause) {
  4695. this.video.pause();
  4696. }
  4697. this.video.setVisible(false);
  4698. this._visible = false;
  4699. }
  4700. }
  4701. enable() {
  4702. if (this.video) {
  4703. this.video.setVisible(true);
  4704. this._visible = true;
  4705. }
  4706. }
  4707. canPlay() {
  4708. this.video.play();
  4709. this.syncCurrentTime();
  4710. }
  4711. resume() {
  4712. if (this.video) {
  4713. this.video.resume();
  4714. this.syncCurrentTime();
  4715. this._playing = true;
  4716. }
  4717. }
  4718. pause() {
  4719. if (this.video) {
  4720. this._cachedCurrentTime = this.video.currentTime();
  4721. this.video.pause();
  4722. }
  4723. }
  4724. stop() {
  4725. if (this.video) {
  4726. this._ignorePause = true;
  4727. this.video.seekTo(0);
  4728. this._cachedCurrentTime = 0;
  4729. this.video.stop();
  4730. }
  4731. }
  4732. canFullScreen(enabled) {
  4733. if (this.video) {
  4734. this.video.setFullScreenEnabled(enabled);
  4735. }
  4736. }
  4737. syncKeepAspectRatio(enabled) {
  4738. if (this.video) {
  4739. this.video.setKeepAspectRatioEnabled(enabled);
  4740. }
  4741. }
  4742. syncMatrix() {
  4743. if (!this._video || !this._component || !this._uiTrans) return;
  4744. const camera = this.UICamera;
  4745. if (!camera) {
  4746. return;
  4747. }
  4748. this._component.node.getWorldMatrix(_mat4_temp);
  4749. const {
  4750. width,
  4751. height
  4752. } = this._uiTrans.contentSize;
  4753. if (!this._forceUpdate && camera.matViewProj.equals(this._matViewProj_temp) && this._m00 === _mat4_temp.m00 && this._m01 === _mat4_temp.m01 && this._m04 === _mat4_temp.m04 && this._m05 === _mat4_temp.m05 && this._m12 === _mat4_temp.m12 && this._m13 === _mat4_temp.m13 && this._w === width && this._h === height) {
  4754. return;
  4755. }
  4756. this._matViewProj_temp.set(camera.matViewProj);
  4757. // update matrix cache
  4758. this._m00 = _mat4_temp.m00;
  4759. this._m01 = _mat4_temp.m01;
  4760. this._m04 = _mat4_temp.m04;
  4761. this._m05 = _mat4_temp.m05;
  4762. this._m12 = _mat4_temp.m12;
  4763. this._m13 = _mat4_temp.m13;
  4764. this._w = width;
  4765. this._h = height;
  4766. let canvas_width = cc.game.canvas.width;
  4767. let canvas_height = cc.game.canvas.height;
  4768. let ap = this._uiTrans.anchorPoint;
  4769. // Vectors in node space
  4770. vec3.set(_topLeft, -ap.x * this._w, (1.0 - ap.y) * this._h, 0);
  4771. vec3.set(_bottomRight, (1 - ap.x) * this._w, -ap.y * this._h, 0);
  4772. // Convert to world space
  4773. vec3.transformMat4(_topLeft, _topLeft, _mat4_temp);
  4774. vec3.transformMat4(_bottomRight, _bottomRight, _mat4_temp);
  4775. // need update camera data
  4776. camera.update();
  4777. // Convert to Screen space
  4778. camera.worldToScreen(_topLeft, _topLeft);
  4779. camera.worldToScreen(_bottomRight, _bottomRight);
  4780. let finalWidth = _bottomRight.x - _topLeft.x;
  4781. let finalHeight = _topLeft.y - _bottomRight.y;
  4782. this._video.setFrame(_topLeft.x, canvas_height - _topLeft.y, finalWidth, finalHeight);
  4783. this._forceUpdate = false;
  4784. }
  4785. }
  4786. }
  4787. },{}],15:[function(require,module,exports){
  4788. "use strict";
  4789. /****************************************************************************
  4790. Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd.
  4791. https://www.cocos.com/
  4792. Permission is hereby granted, free of charge, to any person obtaining a copy
  4793. of this software and associated engine source code (the "Software"), a limited,
  4794. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  4795. to use Cocos Creator solely to develop games on your target platforms. You shall
  4796. not use Cocos Creator software for developing other software or tools that's
  4797. used for developing games. You are not granted to publish, distribute,
  4798. sublicense, and/or sell copies of Cocos Creator.
  4799. The software or tools in this License Agreement are licensed, not sold.
  4800. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  4801. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4802. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4803. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4804. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4805. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  4806. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  4807. THE SOFTWARE.
  4808. ****************************************************************************/
  4809. if (cc.internal.WebView) {
  4810. const {
  4811. EventType
  4812. } = cc.internal.WebView;
  4813. const Vec3 = cc.Vec3;
  4814. const Mat4 = cc.Mat4;
  4815. const _mat4_temp = new Mat4();
  4816. const _topLeft = new Vec3();
  4817. const _bottomRight = new Vec3();
  4818. cc.internal.WebViewImplManager.getImpl = function (componenet) {
  4819. return new WebViewImplJSB(componenet);
  4820. };
  4821. class WebViewImplJSB extends cc.internal.WebViewImpl {
  4822. constructor(componenet) {
  4823. super(componenet);
  4824. this.jsCallback = null;
  4825. this.interfaceSchema = null;
  4826. this._matViewProj_temp = new Mat4();
  4827. }
  4828. _bindEvent() {
  4829. const onLoaded = () => {
  4830. this._forceUpdate = true;
  4831. this.dispatchEvent(EventType.LOADED);
  4832. };
  4833. const onError = () => {
  4834. this.dispatchEvent(EventType.ERROR);
  4835. };
  4836. this.webview.setOnDidFinishLoading(onLoaded);
  4837. this.webview.setOnDidFailLoading(onError);
  4838. this.jsCallback && this.setOnJSCallback(this.jsCallback);
  4839. this.interfaceSchema && this.setJavascriptInterfaceScheme(this.interfaceSchema);
  4840. // remove obj
  4841. this.jsCallback = null;
  4842. this.interfaceSchema = null;
  4843. }
  4844. createWebView() {
  4845. // eslint-disable-next-line no-undef
  4846. if (!jsb.WebView) {
  4847. console.warn('jsb.WebView is null');
  4848. return;
  4849. }
  4850. // eslint-disable-next-line no-undef
  4851. this._webview = jsb.WebView.create();
  4852. this._bindEvent();
  4853. }
  4854. removeWebView() {
  4855. const webview = this.webview;
  4856. if (webview) {
  4857. this.webview.destroy();
  4858. this.reset();
  4859. }
  4860. }
  4861. disable() {
  4862. if (this.webview) {
  4863. this.webview.setVisible(false);
  4864. }
  4865. }
  4866. enable() {
  4867. if (this.webview) {
  4868. this.webview.setVisible(true);
  4869. }
  4870. }
  4871. setOnJSCallback(callback) {
  4872. const webview = this.webview;
  4873. if (webview) {
  4874. webview.setOnJSCallback(callback);
  4875. } else {
  4876. this.jsCallback = callback;
  4877. }
  4878. }
  4879. setJavascriptInterfaceScheme(scheme) {
  4880. const webview = this.webview;
  4881. if (webview) {
  4882. webview.setJavascriptInterfaceScheme(scheme);
  4883. } else {
  4884. this.interfaceSchema = scheme;
  4885. }
  4886. }
  4887. loadURL(url) {
  4888. const webview = this.webview;
  4889. if (webview) {
  4890. webview.src = url;
  4891. webview.loadURL(url);
  4892. this.dispatchEvent(EventType.LOADING);
  4893. }
  4894. }
  4895. evaluateJS(str) {
  4896. const webview = this.webview;
  4897. if (webview) {
  4898. return webview.evaluateJS(str);
  4899. }
  4900. return null;
  4901. }
  4902. syncMatrix() {
  4903. if (!this._webview || !this._component || !this._uiTrans) return;
  4904. const camera = this.UICamera;
  4905. if (!camera) {
  4906. return;
  4907. }
  4908. this._component.node.getWorldMatrix(_mat4_temp);
  4909. const {
  4910. width,
  4911. height
  4912. } = this._uiTrans.contentSize;
  4913. if (!this._forceUpdate && camera.matViewProj.equals(this._matViewProj_temp) && this._m00 === _mat4_temp.m00 && this._m01 === _mat4_temp.m01 && this._m04 === _mat4_temp.m04 && this._m05 === _mat4_temp.m05 && this._m12 === _mat4_temp.m12 && this._m13 === _mat4_temp.m13 && this._w === width && this._h === height) {
  4914. return;
  4915. }
  4916. this._matViewProj_temp.set(camera.matViewProj);
  4917. // update matrix cache
  4918. this._m00 = _mat4_temp.m00;
  4919. this._m01 = _mat4_temp.m01;
  4920. this._m04 = _mat4_temp.m04;
  4921. this._m05 = _mat4_temp.m05;
  4922. this._m12 = _mat4_temp.m12;
  4923. this._m13 = _mat4_temp.m13;
  4924. this._w = width;
  4925. this._h = height;
  4926. // const canvas_width = cc.game.canvas.width;
  4927. const canvasHeight = cc.game.canvas.height;
  4928. const ap = this._uiTrans.anchorPoint;
  4929. // Vectors in node space
  4930. Vec3.set(_topLeft, -ap.x * this._w, (1.0 - ap.y) * this._h, 0);
  4931. Vec3.set(_bottomRight, (1 - ap.x) * this._w, -ap.y * this._h, 0);
  4932. // Convert to world space
  4933. Vec3.transformMat4(_topLeft, _topLeft, _mat4_temp);
  4934. Vec3.transformMat4(_bottomRight, _bottomRight, _mat4_temp);
  4935. // need update camera data
  4936. camera.update();
  4937. // Convert to Screen space
  4938. camera.worldToScreen(_topLeft, _topLeft);
  4939. camera.worldToScreen(_bottomRight, _bottomRight);
  4940. const finalWidth = _bottomRight.x - _topLeft.x;
  4941. const finalHeight = _topLeft.y - _bottomRight.y;
  4942. this._webview.setFrame(_topLeft.x, canvasHeight - _topLeft.y, finalWidth, finalHeight);
  4943. this._forceUpdate = false;
  4944. }
  4945. }
  4946. }
  4947. },{}],16:[function(require,module,exports){
  4948. "use strict";
  4949. const jsbWindow = globalThis.jsb.window = globalThis.jsb.window || {}; //TODO(PatriceJiang):
  4950. module.exports = jsbWindow;
  4951. },{}]},{},[1]);