diff --git a/appmanifest.json b/appmanifest.json
new file mode 100644
index 0000000..e098713
--- /dev/null
+++ b/appmanifest.json
@@ -0,0 +1,41 @@
+{
+ "name": "chesssss",
+ "short_name": "chesssss",
+ "description": "",
+ "start_url": "index.html",
+ "display": "fullscreen",
+ "orientation": "any",
+ "background_color": "#ffffff",
+ "icons": [
+ {
+ "src": "icons/icon-16.png",
+ "sizes": "16x16",
+ "type": "image/png"
+ },
+ {
+ "src": "icons/icon-32.png",
+ "sizes": "32x32",
+ "type": "image/png"
+ },
+ {
+ "src": "icons/icon-64.png",
+ "sizes": "64x64",
+ "type": "image/png"
+ },
+ {
+ "src": "icons/icon-128.png",
+ "sizes": "128x128",
+ "type": "image/png"
+ },
+ {
+ "src": "icons/icon-256.png",
+ "sizes": "256x256",
+ "type": "image/png"
+ },
+ {
+ "src": "icons/icon-512.png",
+ "sizes": "512x512",
+ "type": "image/png"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/data.json b/data.json
new file mode 100644
index 0000000..55af5b1
--- /dev/null
+++ b/data.json
@@ -0,0 +1 @@
+{"project":["chesssss",null,[[0,false,true,true,true,true,true,true,true,false,false,false,false,true,true,true,true,false],[5,true,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false],[6,true,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false],[8,false,true,true,true,true,true,true,true,false,false,false,false,true,true,false,true,false],[9,true,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false]],[["Rook",0,false,[],1,0,null,[["Animation 1",5,false,1,0,false,112415129311788,[["images/shared-0-sheet1.webp",9786,1,65,32,52,false,1,0,0.5,[],[0.34375,-0.4807692307692308,0.6249999999999999,-0.4807692307692308,0.84375,-0.46153846153846156,0.9375,-0.4230769230769231,0.96875,-0.3846153846153846,0.96875,0.3846153846153846,0.9375,0.42307692307692313,0.75,0.4807692307692307,0.1875,0.4807692307692307,0.09375,0.4423076923076923,0.03125,0.40384615384615385,0.03125,-0.3846153846153846,0.15624999999999994,-0.46153846153846156],""]]]],[["Pin",1,658195939845592,0]],false,false,767353565061932,[],null,1,null],["Sprite",0,false,[],0,0,null,[["Animation 1",5,false,1,0,false,947617253610230,[["images/shared-0-sheet1.webp",9786,69,129,34,34,false,1,0,0,[],[0.4411764705882353,0.058823529411764705,0.5,0.058823529411764705,0.5588235294117647,0.08823529411764706,0.7058823529411765,0.3235294117647059,0.7352941176470589,0.38235294117647056,0.9117647058823529,0.8529411764705882,0.9117647058823529,0.9117647058823529,0.08823529411764706,0.9117647058823529,0.058823529411764705,0.8823529411764706,0.058823529411764705,0.8235294117647058,0.38235294117647056,0.11764705882352941],""]]]],[],false,false,240097099648693,[],null,2,null],["Object_Knight",0,false,[],2,0,null,[["knight",5,false,1,0,false,211201186399303,[["images/shared-0-sheet1.webp",9786,65,65,32,50,false,1,0,0.5,[],[0.8235294117647058,-0.42592592592592593,0.11764705882352941,0.35185185185185186,0.058823529411764705,-0.12962962962962965],""]]],["king",5,false,1,0,false,180385112038762,[["images/shared-0-sheet1.webp",9786,35,129,32,50,false,1,0,0.5,[],[0.625,-0.4375,0.875,-0.25,0.0625,0.375,0.125,-0.25],""]]]],[["Pin",1,341061351904539,0],["Tween",2,630022612882658,3]],false,false,393845821989548,[],null,4,null],["Object2",0,false,[],0,0,null,[["rook",5,false,1,0,false,684773524232524,[["images/shared-0-sheet1.webp",9786,89,1,32,52,false,1,0,0.5,[],[0.1875,-0.46153846153846156,0.9375,-0.34615384615384615,0.0625,0.34615384615384615],""]]],["king",5,false,1,0,false,458998235976794,[["images/shared-0-sheet1.webp",9786,55,1,32,52,false,1,0,0.5,[],[0.625,-0.4375,0.875,-0.25,0.0625,0.375,0.125,-0.25],""]]]],[],false,false,826704195567444,[],null,5,null],["Board",0,false,[],0,0,null,[["Animation 1",5,false,1,0,false,989051801526261,[["images/shared-0-sheet0.webp",68870,387,1,320,320,false,1,0,0,[],[],""]]]],[],false,false,999416709711246,[],null,6,null],["Player",0,false,[],2,0,null,[["Animation 1",5,false,1,0,false,563190961651921,[["images/shared-0-sheet1.webp",9786,69,193,32,32,false,1,0,0,[["center",0.5,0.5]],[],""]]]],[["TileMovement",3,687035352816978,7],["BoundToLayout",4,637249227096787,8]],false,false,483302433623773,[],null,9,null],["Keyboard",5,false,[],0,0,null,null,[],false,false,255147428442573,[],null,10,null,[]],["Audio",6,false,[],0,0,null,null,[],false,false,240839869984571,[],null,11,null,[0,0,false,0,true,1,1,600,600,10000,1]],["Wall_tile",0,false,[],1,0,null,[["Animation 1",5,false,1,0,false,582831939948205,[["images/shared-0-sheet1.webp",9786,1,193,32,32,false,1,0,0,[],[],""]]]],[["Solid",7,640132709161122,12]],false,false,732716697058176,[],null,13,null],["wall_yellow",0,false,[],0,0,null,[["Animation 1",5,false,1,0,false,498199456065876,[["images/shared-0-sheet1.webp",9786,1,129,32,32,false,1,0,0,[],[],""]]]],[],false,false,751104966153356,[],null,14,null],["Opning_sprite",0,false,[],0,0,null,[["Animation 1",5,false,1,0,false,783619442187473,[["images/shared-0-sheet1.webp",9786,1,1,52,52,false,1,0,0,[],[0.4423076923076923,0.038461538461538464,0.6153846153846154,0.038461538461538464,0.7307692307692307,0.11538461538461539,0.8461538461538461,0.23076923076923078,0.8846153846153846,0.6346153846153846,0.8846153846153846,0.9807692307692307,0.21153846153846154,0.9807692307692307,0.09615384615384616,0.5769230769230769,0.09615384615384616,0.5,0.11538461538461539,0.4423076923076923],""]]]],[],false,false,904566420681124,[],null,15,null],["Text",8,false,[],0,0,null,null,[],false,false,498871999190611,[],null,16,null],["moves",8,false,[],0,0,null,null,[],false,false,625395379037507,[],null,17,null],["wall_green",0,false,[],0,0,null,[["Animation 1",5,false,1,0,false,647504166799417,[["images/shared-0-sheet1.webp",9786,103,97,20,20,false,1,-0.3,-0.3,[],[],""]]]],[],false,false,646953883678696,[],null,18,null],["Sprite2",0,false,[],0,0,null,[["Animation 1",5,false,1,0,false,612130617462273,[["images/shared-0-sheet1.webp",9786,35,193,32,48,false,1,0,0.5,[],[0.625,-0.4583333333333333,0.8125,-0.33333333333333337,0.0625,0.33333333333333337,0.1875,-0.33333333333333337],""]]]],[],false,false,526141952293498,[],null,19,null],["opnning_sprite",0,false,[],0,0,null,[["Animation 1",5,false,1,0,false,592140473666826,[["images/shared-0-sheet0.webp",68870,769,1,302,239,true,1,0.5,0.5,[],[-0.4966887417218543,-0.49581589958158995,0.4966887417218543,-0.49581589958158995,0.4966887417218543,0.49581589958159,-0.4966887417218543,0.49581589958159],""]]]],[],false,false,481086356146160,[],null,20,null],["Sprite3",0,false,[],0,0,null,[["Animation 1",5,false,1,0,false,908946809784373,[["images/shared-0-sheet0.webp",68870,769,769,250,250,false,1,0.5,0.5,[],[],""]]]],[],false,false,550144207619805,[],null,21,null],["Text2",8,false,[],0,0,null,null,[],false,false,223319455946912,[],null,22,null],["Date",9,false,[],0,0,null,null,[],false,false,991266526674558,[],null,23,null,[]],["UICombatBG",0,false,[],0,0,null,[["Animation 1",0,false,1,0,false,947628073234988,[["images/shared-0-sheet0.webp",68870,1,1,576,384,true,1,0,0,[],[],""]]]],[],false,false,824273853202151,[],null,24,null],["UICombatBar",0,false,[],0,0,null,[["Animation 1",0,false,1,0,false,491134073403044,[["images/shared-0-sheet0.webp",68870,641,323,578,64,true,1,0.5,0.5,[],[-0.4982698961937716,-0.4864864864864865,0.4982698961937716,-0.4864864864864865,0.4982698961937716,0.4864864864864865,-0.4982698961937716,0.4864864864864865],""]]]],[],false,false,449669997374542,[],null,25,null],["Text3",8,false,[],0,0,null,null,[],false,false,640249096707132,[],null,26,null],["Text4",8,false,[],0,0,null,null,[],false,false,765687269570484,[],null,27,null],["wall_blue",0,false,[[669352951395624,0,"overlap",28]],0,0,null,[["Animation 1",5,false,1,0,false,797940510131740,[["images/shared-0-sheet1.webp",9786,103,65,20,20,false,1,-0.3,-0.3,[],[0.30396825396825394,0.30396825396825394,1.296031746031746,0.30396825396825394,1.296031746031746,1.296031746031746,0.30396825396825394,1.296031746031746],""]]]],[],false,false,232494804165684,[],null,29,null],["coin",0,false,[],0,0,null,[["Animation 1",8,true,1,0,false,198180019047046,[["images/coin-sheet0.webp",2430,50,129,45,48,false,1,0.5,0.5,[["for_grid",0,0]],[-0.16666666666666669,-0.5,0.16666666666666663,-0.5,0.30000000000000004,-0.4375,0.43333333333333335,-0.3125,0.5,-0.1875,0.5,0.1875,0.43333333333333335,0.3125,0.30000000000000004,0.4375,0.16666666666666663,0.5,-0.16666666666666669,0.5,-0.3,0.4375,-0.43333333333333335,0.3125,-0.5,0.1875,-0.5,-0.1875,-0.43333333333333335,-0.3125,-0.3,-0.4375],""],["images/coin-sheet0.webp",2430,65,65,45,48,false,1,0.5,0.5,[],[-0.16666666666666669,-0.5,0.16666666666666663,-0.5,0.30000000000000004,-0.4375,0.43333333333333335,-0.3125,0.5,-0.1875,0.5,0.1875,0.43333333333333335,0.3125,0.30000000000000004,0.4375,0.16666666666666663,0.5,-0.16666666666666669,0.5,-0.3,0.4375,-0.43333333333333335,0.3125,-0.5,0.1875,-0.5,-0.1875,-0.43333333333333335,-0.3125,-0.3,-0.4375],""],["images/coin-sheet0.webp",2430,42,193,39,48,false,1,0.5,0.5,[],[-0.1923076923076923,-0.5,0.1923076923076923,-0.5,0.42307692307692313,-0.3125,0.5,-0.1875,0.5,0.1875,0.42307692307692313,0.3125,0.1923076923076923,0.5,-0.1923076923076923,0.5,-0.4230769230769231,0.3125,-0.5,0.1875,-0.5,-0.1875,-0.4230769230769231,-0.3125],""],["images/coin-sheet0.webp",2430,1,193,33,48,false,1,0.5,0.5,[],[-0.2272727272727273,-0.5,0.2272727272727273,-0.5,0.40909090909090906,-0.375,0.5,-0.25,0.5,0.25,0.40909090909090906,0.375,0.2272727272727273,0.5,-0.2272727272727273,0.5,-0.40909090909090906,0.375,-0.5,0.25,-0.5,-0.25,-0.40909090909090906,-0.375],""],["images/coin-sheet0.webp",2430,97,129,15,48,false,1,0.5,0.5,[],[],""],["images/coin-sheet0.webp",2430,83,193,33,48,false,1,0.5,0.5,[],[-0.2272727272727273,-0.5,0.2272727272727273,-0.5,0.40909090909090906,-0.375,0.5,-0.25,0.5,0.25,0.40909090909090906,0.375,0.2272727272727273,0.5,-0.2272727272727273,0.5,-0.40909090909090906,0.375,-0.5,0.25,-0.5,-0.25,-0.40909090909090906,-0.375],""],["images/coin-sheet0.webp",2430,1,129,39,48,false,1,0.5,0.5,[],[-0.1923076923076923,-0.5,0.1923076923076923,-0.5,0.42307692307692313,-0.3125,0.5,-0.1875,0.5,0.1875,0.42307692307692313,0.3125,0.1923076923076923,0.5,-0.1923076923076923,0.5,-0.4230769230769231,0.3125,-0.5,0.1875,-0.5,-0.1875,-0.4230769230769231,-0.3125],""],["images/coin-sheet0.webp",2430,1,65,47,50,false,1,0.5,0.5,[["for_grid",0,0]],[-0.14539007092198586,-0.48,0.1879432624113474,-0.48,0.3212765957446809,-0.4175,0.45460992907801423,-0.2925,0.5,-0.16749999999999998,0.5,0.20750000000000002,0.45460992907801423,0.3325,0.3212765957446809,0.4575,0.1879432624113474,0.5,-0.14539007092198586,0.5,-0.27872340425531916,0.4575,-0.41205673758865247,0.3325,-0.4787234042553192,0.20750000000000002,-0.4787234042553192,-0.16749999999999998,-0.41205673758865247,-0.2925,-0.27872340425531916,-0.4175],""]]]],[],false,false,892493543962194,[],null,30,null]],[],[["opnning",576,384,false,false,0.5,0.5,"opnning_sheet",568771412717546,[["Layer 0",0,399937147528905,true,[0,0,0],false,1,1,1,false,false,1,0,true,[[[288,160,0,302,239,0,0,[1,1,1,1],0.5,0.5,0,0,[],null,null,null,["",""]],15,68,[],[],[true,"Animation 1",0,true]],[[160,288,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],10,69,[],[],[true,"Animation 1",0,true]],[[192,288,0,192,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],11,70,[],[],["Press any of key to start",true,"Arial",12,0,false,false,[1,1,1],1,1,0,0,-1,true,0,false]],[[384,288,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],10,71,[],[],[true,"Animation 1",0,true]],[[160,0,0,256,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],17,72,[],[],["Runaway Chess",true,"Arial",25,0,false,false,[0.9764705882352941,0.5019607843137255,0.5019607843137255],1,1,0,0,-1,true,0,false]]],[],0,true,false,false,[]]],[],[]],["Layout 1",576,384,false,false,0.5,0.5,"Event sheet 1",174958797768382,[["board",0,923175099032989,true,[94,94,94],false,1,1,1,false,false,1,0,true,[[[128,32,0,320,320,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],4,2,[],[],[true,"Animation 1",0,true]],[[288,256,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],5,4,[],[[32,32,128,32,200,200,true,false,false],[1]],[true,"Animation 1",0,true]],[[32,64,0,96,30,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],12,14,[],[],["Moves: 0",true,"Arial",10,0,false,false,[1,1,1],0,0,0,0,-1,true,0,false]],[[224,160,0,32,52,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],3,3,[],[],[true,"rook",0,true]],[[384,64,0,32,52,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],3,18,[],[],[true,"rook",0,true]],[[192,96,0,32,48,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],14,19,[],[],[true,"Animation 1",0,true]],[[224,96,0,32,48,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],14,20,[],[],[true,"Animation 1",0,true]],[[256,96,0,32,48,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],14,21,[],[],[true,"Animation 1",0,true]],[[352,96,0,32,48,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],14,22,[],[],[true,"Animation 1",0,true]],[[320,96,0,32,48,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],14,23,[],[],[true,"Animation 1",0,true]],[[288,96,0,32,48,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],14,24,[],[],[true,"Animation 1",0,true]],[[384,96,0,32,48,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],14,25,[],[],[true,"Animation 1",0,true]],[[288,256,0,32,50,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],2,17,[],[[false],[true]],[true,"knight",0,true]],[[256,192,0,20,20,0,0,[1,1,1,0.3],-0.3,-0.3,0,0,[],null,null,null,["",""]],23,66,[1],[],[true,"Animation 1",0,true]]],[],0,true,false,false,[]],["wall",1,613100942118163,true,[94,94,94],true,1,1,1,false,false,1,0,true,[[[128,32,0,288,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,7,[],[[true,""]],[false,"Animation 1",0,true]],[[416,32,0,32,288,0,0.000016257569729782873,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,8,[],[[true,""]],[false,"Animation 1",0,true]],[[128,64,0,32,288,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,9,[],[[true,""]],[false,"Animation 1",0,true]],[[160,320,0,288,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,10,[],[[true,""]],[false,"Animation 1",0,true]]],[],0,true,false,false,[]],["event_wall",2,765373491238833,false,[94,94,94],true,1,1,1,false,false,1,0,true,[[[352,64,0,20,20,0,0,[1,1,1,0.3],-0.3,-0.3,0,0,[],null,null,null,["",""]],13,15,[],[],[true,"Animation 1",0,true]],[[192,128,0,32,32,0,0,[1,1,1,0.3],0,0,0,0,[],null,null,null,["",""]],9,11,[],[],[true,"Animation 1",0,true]],[[288,96,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,49,[],[[true,""]],[false,"Animation 1",0,true]],[[192,96,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,46,[],[[true,""]],[false,"Animation 1",0,true]],[[224,96,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,47,[],[[true,""]],[false,"Animation 1",0,true]],[[256,96,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,48,[],[[true,""]],[false,"Animation 1",0,true]],[[384,64,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,50,[],[[true,""]],[false,"Animation 1",0,true]],[[352,96,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,51,[],[[true,""]],[false,"Animation 1",0,true]],[[320,96,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,52,[],[[true,""]],[false,"Animation 1",0,true]],[[384,96,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,53,[],[[true,""]],[false,"Animation 1",0,true]],[[224,160,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,54,[],[[true,""]],[false,"Animation 1",0,true]]],[],0,true,false,false,[]]],[],[]],["Layout 2",576,384,false,false,0.5,0.5,"Event sheet 2",305478987883141,[["board",0,557034616888539,true,[94,94,94],false,1,1,1,false,false,1,0,true,[[[128,32,0,320,320,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],4,16,[],[],[true,"Animation 1",0,true]],[[288,256,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],5,26,[],[[32,32,128,32,200,200,true,false,false],[1]],[true,"Animation 1",0,true]],[[32,64,0,96,30,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],12,27,[],[],["Moves: 0",true,"Arial",10,0,false,false,[1,1,1],0,0,0,0,-1,true,0,false]],[[224,160,0,32,52,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],3,29,[],[],[true,"rook",0,true]],[[384,64,0,32,52,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],3,30,[],[],[true,"rook",0,true]],[[192,96,0,32,48,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],14,31,[],[],[true,"Animation 1",0,true]],[[224,96,0,32,48,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],14,32,[],[],[true,"Animation 1",0,true]],[[160,224,0,32,48,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],14,33,[],[],[true,"Animation 1",0,true]],[[352,96,0,32,48,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],14,34,[],[],[true,"Animation 1",0,true]],[[320,96,0,32,48,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],14,35,[],[],[true,"Animation 1",0,true]],[[288,192,0,32,48,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],14,36,[],[],[true,"Animation 1",0,true]],[[384,288,0,32,48,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],14,37,[],[],[true,"Animation 1",0,true]],[[192,96,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,55,[],[[true,""]],[false,"Animation 1",0,true]],[[224,96,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,56,[],[[true,""]],[false,"Animation 1",0,true]],[[320,96,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,57,[],[[true,""]],[false,"Animation 1",0,true]],[[352,96,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,58,[],[[true,""]],[false,"Animation 1",0,true]],[[384,64,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,59,[],[[true,""]],[false,"Animation 1",0,true]],[[224,160,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,60,[],[[true,""]],[false,"Animation 1",0,true]],[[160,224,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,61,[],[[true,""]],[false,"Animation 1",0,true]],[[288,192,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,62,[],[[true,""]],[false,"Animation 1",0,true]],[[384,288,0,32,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,63,[],[[true,""]],[false,"Animation 1",0,true]],[[288,256,0,32,50,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],2,28,[],[[false],[true]],[true,"knight",0,true]],[[160,288,0,20,20,0,0,[1,1,1,0.3],-0.3,-0.3,0,0,[],null,null,null,["",""]],13,42,[],[],[true,"Animation 1",0,true]]],[],0,true,false,false,[]],["wall",1,804062457630764,true,[94,94,94],true,1,1,1,false,false,1,0,true,[[[128,32,0,288,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,38,[],[[true,""]],[false,"Animation 1",0,true]],[[416,32,0,32,288,0,0.000016257569729782873,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,39,[],[[true,""]],[false,"Animation 1",0,true]],[[128,64,0,32,288,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,40,[],[[true,""]],[false,"Animation 1",0,true]],[[160,320,0,288,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],8,41,[],[[true,""]],[false,"Animation 1",0,true]]],[],0,true,false,false,[]],["event_wall",2,992516395197887,false,[94,94,94],true,1,1,1,false,false,1,0,true,[[[192,128,0,32,32,0,0,[1,1,1,0.3],0,0,0,0,[],null,null,null,["",""]],9,43,[],[],[true,"Animation 1",0,true]]],[],0,true,false,false,[]]],[],[]],["battle",576,384,false,false,0.5,0.5,"battle_sheet",488046501746091,[["Layer 0",0,700584065634715,true,[94,94,94],false,1,1,1,false,false,1,0,true,[[[0,0,0,576,384,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],19,73,[],[],[true,"Animation 1",0,true]],[[288,352,0,578,64,0,0,[1,1,1,1],0.5,0.5,0,0,[],null,null,null,["",""]],20,74,[],[],[true,"Animation 1",0,true]],[[64,320,0,448,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],21,75,[],[],["[color=#ffff00]HP:[/color] 150 | [color=#ffff00]ATK:[/color] 10 | [color=#ffff00]GOLD:[/color] 30",true,"Arial",14,0,false,false,[1,1,1],1,1,0,0,-1,true,0,false]],[[128,224,0,32,50,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],2,76,[],[[false],[true]],[true,"knight",0,true]],[[416,224,0,32,52,0,0,[1,1,1,1],0,0.5,0,0,[],null,null,null,["",""]],3,77,[],[],[true,"rook",0,true]],[[72,350,0,448,32,0,0,[1,1,1,1],0,0,0,0,[],null,null,null,["",""]],22,64,[],[],["[color=#ffff00]\\[Z][/color] Attack [color=#ffff00]\\[X][/color] Run [color=#ffff00]\\[C][/color] Switch target",true,"Arial",14,0,false,false,[1,1,1],1,1,0,0,-1,true,0,false]]],[],0,true,false,false,[]]],[],[]]],[["Event sheet 1",[[1,"currentTime",0,0,false,false,868345153736636,false,31],[1,"countDownTimer",0,0,false,false,208017727022202,false,32],[1,"showCountDown",0,0,false,false,269751428811597,false,33],[1,"Total_moves",0,0,false,false,971543851284678,false,34],[0,0,false,null,665182774446192,1,[[6,10,null,1,false,false,false,319611741113503,null,[[9,39]]]],[[5,11,"TileMovement",761436023487280,0,null,[[0,[0,[0,5,"TileMovement",12,false]]],[0,[1,[0,5,"TileMovement",13,false]]],[3,1]]],[5,14,null,101369932452480,0,null,[[0,[2]]]],[7,15,null,122679029377759,0,null,[[2,["button06",false]],[3,0],[0,[3]],[0,[4]],[1,[5]]]],[-1,16,null,887493093376018,2,null,[[0,[6]]]],[5,14,null,272778992988238,0,null,[[0,[4]]]],[-2,"move_count_up",null,600438320664217,0,null]]],[0,0,false,null,307375416170486,2,[[6,10,null,1,false,false,false,840796860990395,null,[[9,37]]]],[[5,11,"TileMovement",337513584521273,0,null,[[0,[7,[0,5,"TileMovement",12,false]]],[0,[1,[0,5,"TileMovement",13,false]]],[3,1]]],[5,14,null,354001007512528,0,null,[[0,[3]]]],[7,15,null,751411105724240,0,null,[[2,["button06",false]],[3,0],[0,[3]],[0,[4]],[1,[5]]]],[-1,16,null,605055089057306,2,null,[[0,[6]]]],[5,14,null,367561631845744,0,null,[[0,[4]]]],[-2,"move_count_up",null,401977826147397,0,null]]],[0,0,false,null,481251651945527,3,[[6,10,null,1,false,false,false,225494654125292,null,[[9,38]]]],[[5,11,"TileMovement",992043491360149,0,null,[[0,[1,[0,5,"TileMovement",12,false]]],[0,[7,[0,5,"TileMovement",13,false]]],[3,1]]],[5,14,null,269069352984580,0,null,[[0,[3]]]],[7,15,null,186348282345489,0,null,[[2,["button06",false]],[3,0],[0,[4]],[0,[4]],[1,[5]]]],[-1,16,null,261726630999100,2,null,[[0,[6]]]],[5,14,null,471597870004156,0,null,[[0,[4]]]],[-2,"move_count_up",null,354227412992425,0,null]]],[0,0,false,null,487358947559053,4,[[6,10,null,1,false,false,false,272704062440930,null,[[9,40]]]],[[5,11,"TileMovement",408406641930330,0,null,[[0,[1,[0,5,"TileMovement",12,false]]],[0,[0,[0,5,"TileMovement",13,false]]],[3,1]]],[5,14,null,247504047100358,0,null,[[0,[2]]]],[7,15,null,650334303518488,0,null,[[2,["button06",false]],[3,0],[0,[4]],[0,[4]],[1,[5]]]],[-1,16,null,292727999790635,2,null,[[0,[6]]]],[5,14,null,983182289265582,0,null,[[0,[4]]]],[-2,"move_count_up",null,212507504054890,0,null]]],[0,0,false,null,197177146777924,5,[[-1,17,null,1,false,false,false,126500438553815,null]],[[2,18,"Pin",651897554755885,0,null,[[4,5],[16,true],[16,true],[16,true],[3,0],[3,0],[16,false]]]]],[0,0,false,null,549724967631114,6,[[-1,19,null,0,false,false,false,810014499480360,null,[[7,[1,[0,5,"TileMovement",12,false]]],[8,0],[7,[8]]]],[-1,19,null,0,false,false,false,935697122143724,null,[[7,[1,[0,5,"TileMovement",20,false]]],[8,0],[7,[9]]]]],[[2,21,null,589070263710261,0,null]]],[4,["move_count_up",0,[],true,false,false],false,null,343816942270616,7,[],[[-1,22,null,400038836831403,0,null,[[11,971543851284678],[7,[10]]]],[12,23,null,632824752257743,0,null,[[7,[11,[3,971543851284678]]]]]]],[0,0,false,null,525326374834480,8,[[-1,19,null,0,false,false,false,100318824738133,null,[[7,[1,[0,5,"TileMovement",24,false]]],[8,0],[7,[9]]]],[-1,19,null,0,false,false,false,746562240262010,null,[[7,[1,[0,5,"TileMovement",20,false]]],[8,0],[7,[9]]]]],[]],[0,0,false,null,394492878311371,9,[[5,25,null,0,false,false,false,656479464577639,null,[[4,13]]]],[[7,15,null,560859926373823,0,null,[[2,["button06",false]],[3,0],[0,[4]],[0,[4]],[1,[5]]]],[-1,26,null,513750991468018,0,null,[[3,0]]]]],[0,0,false,null,587188389322876,10,[[-1,27,null,0,false,false,false,450993733679270,null],[-1,28,null,0,false,false,false,679749364812301,null,[[11,269751428811597],[8,0],[7,[10]]]]],[[-1,29,null,703508904555734,0,null,[[11,868345153736636],[7,[12,[1,18,30,false],[1,18,31,false]]]]]]],[1,"ENCOUNTER_CHANCE",0,15,false,true,841692727112661,false,35],[0,0,false,null,175772242444385,11,[[5,32,"TileMovement",0,false,false,false,153828903344046,null],[-1,33,null,0,false,false,false,752291645808525,null,[[7,[13,[4,34]]]]]],[[7,15,null,793526336081593,0,null,[[2,["Item2A",true]],[3,0],[0,[4]],[0,[4]],[1,[5]]]],[-1,35,null,401709591603950,0,null,[[6,"battle"]]]]],[5,36,12,null],[0,0,false,null,387643227348308,13,[[5,25,null,0,false,false,false,852987254541469,null,[[4,23]]],[23,37,null,0,false,false,false,953535219439877,null,[[10,0]]]],[[23,38,null,139130550372082,0,null,[[10,0],[3,0]]],[7,15,null,579794684376575,0,null,[[2,["Item2A",true]],[3,0],[0,[4]],[0,[4]],[1,[5]]]],[2,39,null,863844376523965,0,null,[[1,[14]],[3,1]]]]]]],["Event sheet 2",[[1,"Total_moves2",0,0,false,false,183266678405555,false,36],[0,0,false,null,938338220292082,1,[[6,10,null,1,false,false,false,477965970993082,null,[[9,39]]]],[[5,11,"TileMovement",918694053410772,0,null,[[0,[0,[0,5,"TileMovement",12,false]]],[0,[1,[0,5,"TileMovement",13,false]]],[3,1]]],[5,14,null,339660226793541,0,null,[[0,[2]]]],[7,15,null,510300216972806,0,null,[[2,["button06",false]],[3,0],[0,[3]],[0,[4]],[1,[5]]]],[-1,16,null,833910195556097,2,null,[[0,[6]]]],[5,14,null,235662546393897,0,null,[[0,[4]]]],[-2,"move_count_up",null,292094442821927,0,null]]],[0,0,false,null,134712173821526,2,[[6,10,null,1,false,false,false,384406036534104,null,[[9,37]]]],[[5,11,"TileMovement",896098666982738,0,null,[[0,[7,[0,5,"TileMovement",12,false]]],[0,[1,[0,5,"TileMovement",13,false]]],[3,1]]],[5,14,null,463175807754120,0,null,[[0,[3]]]],[7,15,null,397447374155391,0,null,[[2,["button06",false]],[3,0],[0,[3]],[0,[4]],[1,[5]]]],[-1,16,null,459479796622571,2,null,[[0,[6]]]],[5,14,null,627160997861572,0,null,[[0,[4]]]],[-2,"move_count_up",null,940214363534327,0,null]]],[0,0,false,null,891427053878050,3,[[6,10,null,1,false,false,false,945368511705119,null,[[9,38]]]],[[5,11,"TileMovement",546087622074985,0,null,[[0,[1,[0,5,"TileMovement",12,false]]],[0,[7,[0,5,"TileMovement",13,false]]],[3,1]]],[5,14,null,439087643737308,0,null,[[0,[3]]]],[7,15,null,713766026464515,0,null,[[2,["button06",false]],[3,0],[0,[4]],[0,[4]],[1,[5]]]],[-1,16,null,420358882876573,2,null,[[0,[6]]]],[5,14,null,704317072280034,0,null,[[0,[4]]]],[-2,"move_count_up",null,468339520850043,0,null]]],[0,0,false,null,824793830499792,4,[[6,10,null,1,false,false,false,772306967073920,null,[[9,40]]]],[[5,11,"TileMovement",199614398838696,0,null,[[0,[1,[0,5,"TileMovement",12,false]]],[0,[0,[0,5,"TileMovement",13,false]]],[3,1]]],[5,14,null,178189693511055,0,null,[[0,[2]]]],[7,15,null,979224916565778,0,null,[[2,["button06",false]],[3,0],[0,[4]],[0,[4]],[1,[5]]]],[-1,16,null,427945955250838,2,null,[[0,[6]]]],[5,14,null,607635147773027,0,null,[[0,[4]]]],[-2,"move_count_up",null,450098113213600,0,null]]],[0,0,false,null,570533691454857,5,[[-1,17,null,1,false,false,false,431590309249171,null]],[[2,18,"Pin",887673085124569,0,null,[[4,5],[16,true],[16,true],[16,true],[3,0],[3,0],[16,false]]]]],[0,0,false,null,860255138559334,6,[[-1,19,null,0,false,false,false,190552101568074,null,[[7,[1,[0,5,"TileMovement",12,false]]],[8,0],[7,[8]]]],[-1,19,null,0,false,false,false,225401934025820,null,[[7,[1,[0,5,"TileMovement",20,false]]],[8,0],[7,[9]]]]],[[2,21,null,600365115977730,0,null]]],[4,["move_count_up2",0,[],true,false,false],false,null,212000852718906,7,[],[[-1,22,null,206209050001340,0,null,[[11,971543851284678],[7,[10]]]],[12,23,null,148723335291219,0,null,[[7,[11,[3,971543851284678]]]]]]],[0,0,false,null,486265061621105,8,[[-1,19,null,0,false,false,false,135930330515951,null,[[7,[1,[0,5,"TileMovement",24,false]]],[8,0],[7,[9]]]],[-1,19,null,0,false,false,false,487213669693918,null,[[7,[1,[0,5,"TileMovement",20,false]]],[8,0],[7,[9]]]]],[]],[0,0,false,null,310630794921181,9,[[5,25,null,0,false,false,false,993864372662132,null,[[4,13]]]],[[7,15,null,309716815961421,0,null,[[2,["button06",false]],[3,0],[0,[4]],[0,[4]],[1,[5]]]],[-1,26,null,944262111789420,0,null,[[3,1]]]]]]],["opnning_sheet",[[0,0,false,null,394961761923214,1,[[6,40,null,1,false,false,false,507913145228139,null]],[[7,15,null,100435142771580,0,null,[[2,["button06",false]],[3,0],[0,[4]],[0,[4]],[1,[5]]]],[-1,35,null,190659291368938,0,null,[[6,"Layout 1"]]],[-1,29,null,488038030995299,0,null,[[11,208017727022202],[7,[12,[1,18,30,false],[1,18,31,false]]]]],[-1,29,null,455315523085246,0,null,[[11,269751428811597],[7,[10]]]]]],[0,0,false,null,567945330928398,2,[[-1,17,null,1,false,false,false,607330073645465,null]],[[7,15,null,340114258024227,0,null,[[2,["awesomeness",true]],[3,1],[0,[4]],[0,[4]],[1,[5]]]]]]]],["battle_sheet",[[0,0,false,null,425944619417911,1,[[-1,17,null,1,false,false,false,551623259087781,null]],[[7,41,null,665346422383549,0,null],[7,15,null,633311505329185,0,null,[[2,["fight",true]],[3,1],[0,[4]],[0,[4]],[1,[5]]]]]]]]],[["button06",[["audio/webm; codecs=opus",".webm",7960]],false],["awesomeness",[["audio/webm; codecs=opus",".webm",632499]],true],["fight",[["audio/webm; codecs=opus",".webm",330130]],true],["Item2A",[["audio/webm; codecs=opus",".webm",26187]],true]],"media/",true,576,384,5,false,"nearest",false,"1.0.0.0",false,false,4,0,78,false,false,1,true,0.7853981633974483,[],"icons/",[],"normalized","y01qdph2q1z","fonts/",[["Timeline 1",5,0.1,"default","default",[],0,0,1,"",1,1]],"high-performance",[],"standard","vsync","","icons/loading-logo.png",false,4,false,null,[],"folders",1,10000,false,[]]}
\ No newline at end of file
diff --git a/icons/icon-128.png b/icons/icon-128.png
new file mode 100644
index 0000000..34780f7
Binary files /dev/null and b/icons/icon-128.png differ
diff --git a/icons/icon-16.png b/icons/icon-16.png
new file mode 100644
index 0000000..d4e6a43
Binary files /dev/null and b/icons/icon-16.png differ
diff --git a/icons/icon-256.png b/icons/icon-256.png
new file mode 100644
index 0000000..a201353
Binary files /dev/null and b/icons/icon-256.png differ
diff --git a/icons/icon-32.png b/icons/icon-32.png
new file mode 100644
index 0000000..20d38d6
Binary files /dev/null and b/icons/icon-32.png differ
diff --git a/icons/icon-512.png b/icons/icon-512.png
new file mode 100644
index 0000000..9e2ad77
Binary files /dev/null and b/icons/icon-512.png differ
diff --git a/icons/icon-64.png b/icons/icon-64.png
new file mode 100644
index 0000000..06c8d53
Binary files /dev/null and b/icons/icon-64.png differ
diff --git a/icons/loading-logo.png b/icons/loading-logo.png
new file mode 100644
index 0000000..06c8d53
Binary files /dev/null and b/icons/loading-logo.png differ
diff --git a/images/coin-sheet0.webp b/images/coin-sheet0.webp
new file mode 100644
index 0000000..7544374
Binary files /dev/null and b/images/coin-sheet0.webp differ
diff --git a/images/shared-0-sheet0.webp b/images/shared-0-sheet0.webp
new file mode 100644
index 0000000..b477f8a
Binary files /dev/null and b/images/shared-0-sheet0.webp differ
diff --git a/images/shared-0-sheet1.webp b/images/shared-0-sheet1.webp
new file mode 100644
index 0000000..020c2da
Binary files /dev/null and b/images/shared-0-sheet1.webp differ
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..b2186d6
--- /dev/null
+++ b/index.html
@@ -0,0 +1,41 @@
+
+
+
+
+chesssss
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/media/Item2A.webm b/media/Item2A.webm
new file mode 100644
index 0000000..78dfb70
Binary files /dev/null and b/media/Item2A.webm differ
diff --git a/media/awesomeness.webm b/media/awesomeness.webm
new file mode 100644
index 0000000..d5a7f47
Binary files /dev/null and b/media/awesomeness.webm differ
diff --git a/media/button06.webm b/media/button06.webm
new file mode 100644
index 0000000..1bd8201
Binary files /dev/null and b/media/button06.webm differ
diff --git a/media/fight.webm b/media/fight.webm
new file mode 100644
index 0000000..e4c409d
Binary files /dev/null and b/media/fight.webm differ
diff --git a/offline.json b/offline.json
new file mode 100644
index 0000000..0b89a4b
--- /dev/null
+++ b/offline.json
@@ -0,0 +1 @@
+{"version":1709045922290,"fileList":["scripts/c3runtime.js","data.json","style.css","scripts/offlineclient.js","images/shared-0-sheet0.webp","images/shared-0-sheet1.webp","images/coin-sheet0.webp","scripts/opus.wasm.js","scripts/opus.wasm.wasm","scripts/main.js","scripts/dispatchworker.js","scripts/jobworker.js","scripts/supportcheck.js","scripts/project/scriptsInEvents.js","icons/icon-128.png","icons/icon-512.png","icons/icon-16.png","icons/icon-32.png","icons/icon-64.png","icons/icon-256.png","icons/loading-logo.png","media/button06.webm","media/awesomeness.webm","media/fight.webm","media/Item2A.webm","scripts/register-sw.js"]}
\ No newline at end of file
diff --git a/scripts/c3runtime.js b/scripts/c3runtime.js
new file mode 100644
index 0000000..7d0f26d
--- /dev/null
+++ b/scripts/c3runtime.js
@@ -0,0 +1,4646 @@
+// Generated by Construct, the game and app creator :: https://www.construct.net
+// ../3rdparty/glmatrix.js
+{
+/*
+ @fileoverview gl-matrix - High performance matrix and vector operations
+@author Brandon Jones
+@author Colin MacKenzie IV
+@version 3.4.1
+
+Copyright (c) 2015-2021, Brandon Jones, Colin MacKenzie IV.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+*/
+'use strict';(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?factory(exports):typeof define==="function"&&define.amd?define(["exports"],factory):(global=typeof globalThis!=="undefined"?globalThis:global||self,factory(global.glMatrix={}))})(this,function(exports){var EPSILON=1E-6;var ARRAY_TYPE=typeof Float32Array!=="undefined"?Float32Array:Array;var RANDOM=Math.random;var ANGLE_ORDER="zyx";function setMatrixArrayType(type){ARRAY_TYPE=type}var degree=Math.PI/180;function toRadian(a){return a*
+degree}function equals$9(a,b){return Math.abs(a-b)<=EPSILON*Math.max(1,Math.abs(a),Math.abs(b))}if(!Math.hypot)Math.hypot=function(){var y=0,i=arguments.length;while(i--)y+=arguments[i]*arguments[i];return Math.sqrt(y)};var common=Object.freeze({__proto__:null,EPSILON:EPSILON,get ARRAY_TYPE(){return ARRAY_TYPE},RANDOM:RANDOM,ANGLE_ORDER:ANGLE_ORDER,setMatrixArrayType:setMatrixArrayType,toRadian:toRadian,equals:equals$9});function create$8(){var out=new ARRAY_TYPE(4);if(ARRAY_TYPE!=Float32Array){out[1]=
+0;out[2]=0}out[0]=1;out[3]=1;return out}function clone$8(a){var out=new ARRAY_TYPE(4);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out}function copy$8(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out}function identity$5(out){out[0]=1;out[1]=0;out[2]=0;out[3]=1;return out}function fromValues$8(m00,m01,m10,m11){var out=new ARRAY_TYPE(4);out[0]=m00;out[1]=m01;out[2]=m10;out[3]=m11;return out}function set$8(out,m00,m01,m10,m11){out[0]=m00;out[1]=m01;out[2]=m10;out[3]=m11;return out}
+function transpose$2(out,a){if(out===a){var a1=a[1];out[1]=a[2];out[2]=a1}else{out[0]=a[0];out[1]=a[2];out[2]=a[1];out[3]=a[3]}return out}function invert$5(out,a){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var det=a0*a3-a2*a1;if(!det)return null;det=1/det;out[0]=a3*det;out[1]=-a1*det;out[2]=-a2*det;out[3]=a0*det;return out}function adjoint$2(out,a){var a0=a[0];out[0]=a[3];out[1]=-a[1];out[2]=-a[2];out[3]=a0;return out}function determinant$3(a){return a[0]*a[3]-a[2]*a[1]}function multiply$8(out,a,b){var a0=
+a[0],a1=a[1],a2=a[2],a3=a[3];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];out[0]=a0*b0+a2*b1;out[1]=a1*b0+a3*b1;out[2]=a0*b2+a2*b3;out[3]=a1*b2+a3*b3;return out}function rotate$4(out,a,rad){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var s=Math.sin(rad);var c=Math.cos(rad);out[0]=a0*c+a2*s;out[1]=a1*c+a3*s;out[2]=a0*-s+a2*c;out[3]=a1*-s+a3*c;return out}function scale$8(out,a,v){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var v0=v[0],v1=v[1];out[0]=a0*v0;out[1]=a1*v0;out[2]=a2*v1;out[3]=a3*v1;return out}function fromRotation$4(out,
+rad){var s=Math.sin(rad);var c=Math.cos(rad);out[0]=c;out[1]=s;out[2]=-s;out[3]=c;return out}function fromScaling$3(out,v){out[0]=v[0];out[1]=0;out[2]=0;out[3]=v[1];return out}function str$8(a){return"mat2("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+")"}function frob$3(a){return Math.hypot(a[0],a[1],a[2],a[3])}function LDU(L,D,U,a){L[2]=a[2]/a[0];U[0]=a[0];U[1]=a[1];U[3]=a[3]-L[2]*U[1];return[L,D,U]}function add$8(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];out[3]=a[3]+b[3];return out}function subtract$6(out,
+a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];out[3]=a[3]-b[3];return out}function exactEquals$8(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]}function equals$8(a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];return Math.abs(a0-b0)<=EPSILON*Math.max(1,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=EPSILON*Math.max(1,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=EPSILON*Math.max(1,Math.abs(a2),Math.abs(b2))&&Math.abs(a3-b3)<=EPSILON*Math.max(1,Math.abs(a3),
+Math.abs(b3))}function multiplyScalar$3(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;out[3]=a[3]*b;return out}function multiplyScalarAndAdd$3(out,a,b,scale){out[0]=a[0]+b[0]*scale;out[1]=a[1]+b[1]*scale;out[2]=a[2]+b[2]*scale;out[3]=a[3]+b[3]*scale;return out}var mul$8=multiply$8;var sub$6=subtract$6;var mat2=Object.freeze({__proto__:null,create:create$8,clone:clone$8,copy:copy$8,identity:identity$5,fromValues:fromValues$8,set:set$8,transpose:transpose$2,invert:invert$5,adjoint:adjoint$2,determinant:determinant$3,
+multiply:multiply$8,rotate:rotate$4,scale:scale$8,fromRotation:fromRotation$4,fromScaling:fromScaling$3,str:str$8,frob:frob$3,LDU:LDU,add:add$8,subtract:subtract$6,exactEquals:exactEquals$8,equals:equals$8,multiplyScalar:multiplyScalar$3,multiplyScalarAndAdd:multiplyScalarAndAdd$3,mul:mul$8,sub:sub$6});function create$7(){var out=new ARRAY_TYPE(6);if(ARRAY_TYPE!=Float32Array){out[1]=0;out[2]=0;out[4]=0;out[5]=0}out[0]=1;out[3]=1;return out}function clone$7(a){var out=new ARRAY_TYPE(6);out[0]=a[0];
+out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];return out}function copy$7(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];return out}function identity$4(out){out[0]=1;out[1]=0;out[2]=0;out[3]=1;out[4]=0;out[5]=0;return out}function fromValues$7(a,b,c,d,tx,ty){var out=new ARRAY_TYPE(6);out[0]=a;out[1]=b;out[2]=c;out[3]=d;out[4]=tx;out[5]=ty;return out}function set$7(out,a,b,c,d,tx,ty){out[0]=a;out[1]=b;out[2]=c;out[3]=d;out[4]=tx;out[5]=ty;return out}function invert$4(out,
+a){var aa=a[0],ab=a[1],ac=a[2],ad=a[3];var atx=a[4],aty=a[5];var det=aa*ad-ab*ac;if(!det)return null;det=1/det;out[0]=ad*det;out[1]=-ab*det;out[2]=-ac*det;out[3]=aa*det;out[4]=(ac*aty-ad*atx)*det;out[5]=(ab*atx-aa*aty)*det;return out}function determinant$2(a){return a[0]*a[3]-a[1]*a[2]}function multiply$7(out,a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5];var b0=b[0],b1=b[1],b2=b[2],b3=b[3],b4=b[4],b5=b[5];out[0]=a0*b0+a2*b1;out[1]=a1*b0+a3*b1;out[2]=a0*b2+a2*b3;out[3]=a1*b2+a3*b3;out[4]=
+a0*b4+a2*b5+a4;out[5]=a1*b4+a3*b5+a5;return out}function rotate$3(out,a,rad){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5];var s=Math.sin(rad);var c=Math.cos(rad);out[0]=a0*c+a2*s;out[1]=a1*c+a3*s;out[2]=a0*-s+a2*c;out[3]=a1*-s+a3*c;out[4]=a4;out[5]=a5;return out}function scale$7(out,a,v){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5];var v0=v[0],v1=v[1];out[0]=a0*v0;out[1]=a1*v0;out[2]=a2*v1;out[3]=a3*v1;out[4]=a4;out[5]=a5;return out}function translate$3(out,a,v){var a0=a[0],a1=a[1],
+a2=a[2],a3=a[3],a4=a[4],a5=a[5];var v0=v[0],v1=v[1];out[0]=a0;out[1]=a1;out[2]=a2;out[3]=a3;out[4]=a0*v0+a2*v1+a4;out[5]=a1*v0+a3*v1+a5;return out}function fromRotation$3(out,rad){var s=Math.sin(rad),c=Math.cos(rad);out[0]=c;out[1]=s;out[2]=-s;out[3]=c;out[4]=0;out[5]=0;return out}function fromScaling$2(out,v){out[0]=v[0];out[1]=0;out[2]=0;out[3]=v[1];out[4]=0;out[5]=0;return out}function fromTranslation$3(out,v){out[0]=1;out[1]=0;out[2]=0;out[3]=1;out[4]=v[0];out[5]=v[1];return out}function str$7(a){return"mat2d("+
+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+")"}function frob$2(a){return Math.hypot(a[0],a[1],a[2],a[3],a[4],a[5],1)}function add$7(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];out[3]=a[3]+b[3];out[4]=a[4]+b[4];out[5]=a[5]+b[5];return out}function subtract$5(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];out[3]=a[3]-b[3];out[4]=a[4]-b[4];out[5]=a[5]-b[5];return out}function multiplyScalar$2(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;out[3]=a[3]*b;out[4]=
+a[4]*b;out[5]=a[5]*b;return out}function multiplyScalarAndAdd$2(out,a,b,scale){out[0]=a[0]+b[0]*scale;out[1]=a[1]+b[1]*scale;out[2]=a[2]+b[2]*scale;out[3]=a[3]+b[3]*scale;out[4]=a[4]+b[4]*scale;out[5]=a[5]+b[5]*scale;return out}function exactEquals$7(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]}function equals$7(a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5];var b0=b[0],b1=b[1],b2=b[2],b3=b[3],b4=b[4],b5=b[5];return Math.abs(a0-b0)<=EPSILON*Math.max(1,
+Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=EPSILON*Math.max(1,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=EPSILON*Math.max(1,Math.abs(a2),Math.abs(b2))&&Math.abs(a3-b3)<=EPSILON*Math.max(1,Math.abs(a3),Math.abs(b3))&&Math.abs(a4-b4)<=EPSILON*Math.max(1,Math.abs(a4),Math.abs(b4))&&Math.abs(a5-b5)<=EPSILON*Math.max(1,Math.abs(a5),Math.abs(b5))}var mul$7=multiply$7;var sub$5=subtract$5;var mat2d=Object.freeze({__proto__:null,create:create$7,clone:clone$7,copy:copy$7,identity:identity$4,fromValues:fromValues$7,
+set:set$7,invert:invert$4,determinant:determinant$2,multiply:multiply$7,rotate:rotate$3,scale:scale$7,translate:translate$3,fromRotation:fromRotation$3,fromScaling:fromScaling$2,fromTranslation:fromTranslation$3,str:str$7,frob:frob$2,add:add$7,subtract:subtract$5,multiplyScalar:multiplyScalar$2,multiplyScalarAndAdd:multiplyScalarAndAdd$2,exactEquals:exactEquals$7,equals:equals$7,mul:mul$7,sub:sub$5});function create$6(){var out=new ARRAY_TYPE(9);if(ARRAY_TYPE!=Float32Array){out[1]=0;out[2]=0;out[3]=
+0;out[5]=0;out[6]=0;out[7]=0}out[0]=1;out[4]=1;out[8]=1;return out}function fromMat4$1(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[4];out[4]=a[5];out[5]=a[6];out[6]=a[8];out[7]=a[9];out[8]=a[10];return out}function clone$6(a){var out=new ARRAY_TYPE(9);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];return out}function copy$6(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=
+a[8];return out}function fromValues$6(m00,m01,m02,m10,m11,m12,m20,m21,m22){var out=new ARRAY_TYPE(9);out[0]=m00;out[1]=m01;out[2]=m02;out[3]=m10;out[4]=m11;out[5]=m12;out[6]=m20;out[7]=m21;out[8]=m22;return out}function set$6(out,m00,m01,m02,m10,m11,m12,m20,m21,m22){out[0]=m00;out[1]=m01;out[2]=m02;out[3]=m10;out[4]=m11;out[5]=m12;out[6]=m20;out[7]=m21;out[8]=m22;return out}function identity$3(out){out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=1;out[5]=0;out[6]=0;out[7]=0;out[8]=1;return out}function transpose$1(out,
+a){if(out===a){var a01=a[1],a02=a[2],a12=a[5];out[1]=a[3];out[2]=a[6];out[3]=a01;out[5]=a[7];out[6]=a02;out[7]=a12}else{out[0]=a[0];out[1]=a[3];out[2]=a[6];out[3]=a[1];out[4]=a[4];out[5]=a[7];out[6]=a[2];out[7]=a[5];out[8]=a[8]}return out}function invert$3(out,a){var a00=a[0],a01=a[1],a02=a[2];var a10=a[3],a11=a[4],a12=a[5];var a20=a[6],a21=a[7],a22=a[8];var b01=a22*a11-a12*a21;var b11=-a22*a10+a12*a20;var b21=a21*a10-a11*a20;var det=a00*b01+a01*b11+a02*b21;if(!det)return null;det=1/det;out[0]=b01*
+det;out[1]=(-a22*a01+a02*a21)*det;out[2]=(a12*a01-a02*a11)*det;out[3]=b11*det;out[4]=(a22*a00-a02*a20)*det;out[5]=(-a12*a00+a02*a10)*det;out[6]=b21*det;out[7]=(-a21*a00+a01*a20)*det;out[8]=(a11*a00-a01*a10)*det;return out}function adjoint$1(out,a){var a00=a[0],a01=a[1],a02=a[2];var a10=a[3],a11=a[4],a12=a[5];var a20=a[6],a21=a[7],a22=a[8];out[0]=a11*a22-a12*a21;out[1]=a02*a21-a01*a22;out[2]=a01*a12-a02*a11;out[3]=a12*a20-a10*a22;out[4]=a00*a22-a02*a20;out[5]=a02*a10-a00*a12;out[6]=a10*a21-a11*a20;
+out[7]=a01*a20-a00*a21;out[8]=a00*a11-a01*a10;return out}function determinant$1(a){var a00=a[0],a01=a[1],a02=a[2];var a10=a[3],a11=a[4],a12=a[5];var a20=a[6],a21=a[7],a22=a[8];return a00*(a22*a11-a12*a21)+a01*(-a22*a10+a12*a20)+a02*(a21*a10-a11*a20)}function multiply$6(out,a,b){var a00=a[0],a01=a[1],a02=a[2];var a10=a[3],a11=a[4],a12=a[5];var a20=a[6],a21=a[7],a22=a[8];var b00=b[0],b01=b[1],b02=b[2];var b10=b[3],b11=b[4],b12=b[5];var b20=b[6],b21=b[7],b22=b[8];out[0]=b00*a00+b01*a10+b02*a20;out[1]=
+b00*a01+b01*a11+b02*a21;out[2]=b00*a02+b01*a12+b02*a22;out[3]=b10*a00+b11*a10+b12*a20;out[4]=b10*a01+b11*a11+b12*a21;out[5]=b10*a02+b11*a12+b12*a22;out[6]=b20*a00+b21*a10+b22*a20;out[7]=b20*a01+b21*a11+b22*a21;out[8]=b20*a02+b21*a12+b22*a22;return out}function translate$2(out,a,v){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8],x=v[0],y=v[1];out[0]=a00;out[1]=a01;out[2]=a02;out[3]=a10;out[4]=a11;out[5]=a12;out[6]=x*a00+y*a10+a20;out[7]=x*a01+y*a11+a21;out[8]=x*
+a02+y*a12+a22;return out}function rotate$2(out,a,rad){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8],s=Math.sin(rad),c=Math.cos(rad);out[0]=c*a00+s*a10;out[1]=c*a01+s*a11;out[2]=c*a02+s*a12;out[3]=c*a10-s*a00;out[4]=c*a11-s*a01;out[5]=c*a12-s*a02;out[6]=a20;out[7]=a21;out[8]=a22;return out}function scale$6(out,a,v){var x=v[0],y=v[1];out[0]=x*a[0];out[1]=x*a[1];out[2]=x*a[2];out[3]=y*a[3];out[4]=y*a[4];out[5]=y*a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];return out}
+function fromTranslation$2(out,v){out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=1;out[5]=0;out[6]=v[0];out[7]=v[1];out[8]=1;return out}function fromRotation$2(out,rad){var s=Math.sin(rad),c=Math.cos(rad);out[0]=c;out[1]=s;out[2]=0;out[3]=-s;out[4]=c;out[5]=0;out[6]=0;out[7]=0;out[8]=1;return out}function fromScaling$1(out,v){out[0]=v[0];out[1]=0;out[2]=0;out[3]=0;out[4]=v[1];out[5]=0;out[6]=0;out[7]=0;out[8]=1;return out}function fromMat2d(out,a){out[0]=a[0];out[1]=a[1];out[2]=0;out[3]=a[2];out[4]=a[3];
+out[5]=0;out[6]=a[4];out[7]=a[5];out[8]=1;return out}function fromQuat$1(out,q){var x=q[0],y=q[1],z=q[2],w=q[3];var x2=x+x;var y2=y+y;var z2=z+z;var xx=x*x2;var yx=y*x2;var yy=y*y2;var zx=z*x2;var zy=z*y2;var zz=z*z2;var wx=w*x2;var wy=w*y2;var wz=w*z2;out[0]=1-yy-zz;out[3]=yx-wz;out[6]=zx+wy;out[1]=yx+wz;out[4]=1-xx-zz;out[7]=zy-wx;out[2]=zx-wy;out[5]=zy+wx;out[8]=1-xx-yy;return out}function normalFromMat4(out,a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3];var a10=a[4],a11=a[5],a12=a[6],a13=a[7];var a20=
+a[8],a21=a[9],a22=a[10],a23=a[11];var a30=a[12],a31=a[13],a32=a[14],a33=a[15];var b00=a00*a11-a01*a10;var b01=a00*a12-a02*a10;var b02=a00*a13-a03*a10;var b03=a01*a12-a02*a11;var b04=a01*a13-a03*a11;var b05=a02*a13-a03*a12;var b06=a20*a31-a21*a30;var b07=a20*a32-a22*a30;var b08=a20*a33-a23*a30;var b09=a21*a32-a22*a31;var b10=a21*a33-a23*a31;var b11=a22*a33-a23*a32;var det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;if(!det)return null;det=1/det;out[0]=(a11*b11-a12*b10+a13*b09)*det;out[1]=(a12*
+b08-a10*b11-a13*b07)*det;out[2]=(a10*b10-a11*b08+a13*b06)*det;out[3]=(a02*b10-a01*b11-a03*b09)*det;out[4]=(a00*b11-a02*b08+a03*b07)*det;out[5]=(a01*b08-a00*b10-a03*b06)*det;out[6]=(a31*b05-a32*b04+a33*b03)*det;out[7]=(a32*b02-a30*b05-a33*b01)*det;out[8]=(a30*b04-a31*b02+a33*b00)*det;return out}function projection(out,width,height){out[0]=2/width;out[1]=0;out[2]=0;out[3]=0;out[4]=-2/height;out[5]=0;out[6]=-1;out[7]=1;out[8]=1;return out}function str$6(a){return"mat3("+a[0]+", "+a[1]+", "+a[2]+", "+
+a[3]+", "+a[4]+", "+a[5]+", "+a[6]+", "+a[7]+", "+a[8]+")"}function frob$1(a){return Math.hypot(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8])}function add$6(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];out[3]=a[3]+b[3];out[4]=a[4]+b[4];out[5]=a[5]+b[5];out[6]=a[6]+b[6];out[7]=a[7]+b[7];out[8]=a[8]+b[8];return out}function subtract$4(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];out[3]=a[3]-b[3];out[4]=a[4]-b[4];out[5]=a[5]-b[5];out[6]=a[6]-b[6];out[7]=a[7]-b[7];out[8]=
+a[8]-b[8];return out}function multiplyScalar$1(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;out[3]=a[3]*b;out[4]=a[4]*b;out[5]=a[5]*b;out[6]=a[6]*b;out[7]=a[7]*b;out[8]=a[8]*b;return out}function multiplyScalarAndAdd$1(out,a,b,scale){out[0]=a[0]+b[0]*scale;out[1]=a[1]+b[1]*scale;out[2]=a[2]+b[2]*scale;out[3]=a[3]+b[3]*scale;out[4]=a[4]+b[4]*scale;out[5]=a[5]+b[5]*scale;out[6]=a[6]+b[6]*scale;out[7]=a[7]+b[7]*scale;out[8]=a[8]+b[8]*scale;return out}function exactEquals$6(a,b){return a[0]===b[0]&&
+a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]}function equals$6(a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5],a6=a[6],a7=a[7],a8=a[8];var b0=b[0],b1=b[1],b2=b[2],b3=b[3],b4=b[4],b5=b[5],b6=b[6],b7=b[7],b8=b[8];return Math.abs(a0-b0)<=EPSILON*Math.max(1,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=EPSILON*Math.max(1,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=EPSILON*Math.max(1,Math.abs(a2),Math.abs(b2))&&Math.abs(a3-b3)<=EPSILON*
+Math.max(1,Math.abs(a3),Math.abs(b3))&&Math.abs(a4-b4)<=EPSILON*Math.max(1,Math.abs(a4),Math.abs(b4))&&Math.abs(a5-b5)<=EPSILON*Math.max(1,Math.abs(a5),Math.abs(b5))&&Math.abs(a6-b6)<=EPSILON*Math.max(1,Math.abs(a6),Math.abs(b6))&&Math.abs(a7-b7)<=EPSILON*Math.max(1,Math.abs(a7),Math.abs(b7))&&Math.abs(a8-b8)<=EPSILON*Math.max(1,Math.abs(a8),Math.abs(b8))}var mul$6=multiply$6;var sub$4=subtract$4;var mat3=Object.freeze({__proto__:null,create:create$6,fromMat4:fromMat4$1,clone:clone$6,copy:copy$6,
+fromValues:fromValues$6,set:set$6,identity:identity$3,transpose:transpose$1,invert:invert$3,adjoint:adjoint$1,determinant:determinant$1,multiply:multiply$6,translate:translate$2,rotate:rotate$2,scale:scale$6,fromTranslation:fromTranslation$2,fromRotation:fromRotation$2,fromScaling:fromScaling$1,fromMat2d:fromMat2d,fromQuat:fromQuat$1,normalFromMat4:normalFromMat4,projection:projection,str:str$6,frob:frob$1,add:add$6,subtract:subtract$4,multiplyScalar:multiplyScalar$1,multiplyScalarAndAdd:multiplyScalarAndAdd$1,
+exactEquals:exactEquals$6,equals:equals$6,mul:mul$6,sub:sub$4});function create$5(){var out=new ARRAY_TYPE(16);if(ARRAY_TYPE!=Float32Array){out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[11]=0;out[12]=0;out[13]=0;out[14]=0}out[0]=1;out[5]=1;out[10]=1;out[15]=1;return out}function clone$5(a){var out=new ARRAY_TYPE(16);out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];out[9]=a[9];out[10]=a[10];out[11]=a[11];out[12]=
+a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out}function copy$5(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];out[9]=a[9];out[10]=a[10];out[11]=a[11];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out}function fromValues$5(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33){var out=new ARRAY_TYPE(16);out[0]=m00;out[1]=m01;out[2]=m02;out[3]=m03;out[4]=m10;out[5]=m11;out[6]=m12;out[7]=m13;out[8]=
+m20;out[9]=m21;out[10]=m22;out[11]=m23;out[12]=m30;out[13]=m31;out[14]=m32;out[15]=m33;return out}function set$5(out,m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33){out[0]=m00;out[1]=m01;out[2]=m02;out[3]=m03;out[4]=m10;out[5]=m11;out[6]=m12;out[7]=m13;out[8]=m20;out[9]=m21;out[10]=m22;out[11]=m23;out[12]=m30;out[13]=m31;out[14]=m32;out[15]=m33;return out}function identity$2(out){out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=1;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=1;out[11]=
+0;out[12]=0;out[13]=0;out[14]=0;out[15]=1;return out}function transpose(out,a){if(out===a){var a01=a[1],a02=a[2],a03=a[3];var a12=a[6],a13=a[7];var a23=a[11];out[1]=a[4];out[2]=a[8];out[3]=a[12];out[4]=a01;out[6]=a[9];out[7]=a[13];out[8]=a02;out[9]=a12;out[11]=a[14];out[12]=a03;out[13]=a13;out[14]=a23}else{out[0]=a[0];out[1]=a[4];out[2]=a[8];out[3]=a[12];out[4]=a[1];out[5]=a[5];out[6]=a[9];out[7]=a[13];out[8]=a[2];out[9]=a[6];out[10]=a[10];out[11]=a[14];out[12]=a[3];out[13]=a[7];out[14]=a[11];out[15]=
+a[15]}return out}function invert$2(out,a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3];var a10=a[4],a11=a[5],a12=a[6],a13=a[7];var a20=a[8],a21=a[9],a22=a[10],a23=a[11];var a30=a[12],a31=a[13],a32=a[14],a33=a[15];var b00=a00*a11-a01*a10;var b01=a00*a12-a02*a10;var b02=a00*a13-a03*a10;var b03=a01*a12-a02*a11;var b04=a01*a13-a03*a11;var b05=a02*a13-a03*a12;var b06=a20*a31-a21*a30;var b07=a20*a32-a22*a30;var b08=a20*a33-a23*a30;var b09=a21*a32-a22*a31;var b10=a21*a33-a23*a31;var b11=a22*a33-a23*a32;var det=
+b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;if(!det)return null;det=1/det;out[0]=(a11*b11-a12*b10+a13*b09)*det;out[1]=(a02*b10-a01*b11-a03*b09)*det;out[2]=(a31*b05-a32*b04+a33*b03)*det;out[3]=(a22*b04-a21*b05-a23*b03)*det;out[4]=(a12*b08-a10*b11-a13*b07)*det;out[5]=(a00*b11-a02*b08+a03*b07)*det;out[6]=(a32*b02-a30*b05-a33*b01)*det;out[7]=(a20*b05-a22*b02+a23*b01)*det;out[8]=(a10*b10-a11*b08+a13*b06)*det;out[9]=(a01*b08-a00*b10-a03*b06)*det;out[10]=(a30*b04-a31*b02+a33*b00)*det;out[11]=(a21*b02-
+a20*b04-a23*b00)*det;out[12]=(a11*b07-a10*b09-a12*b06)*det;out[13]=(a00*b09-a01*b07+a02*b06)*det;out[14]=(a31*b01-a30*b03-a32*b00)*det;out[15]=(a20*b03-a21*b01+a22*b00)*det;return out}function adjoint(out,a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3];var a10=a[4],a11=a[5],a12=a[6],a13=a[7];var a20=a[8],a21=a[9],a22=a[10],a23=a[11];var a30=a[12],a31=a[13],a32=a[14],a33=a[15];var b00=a00*a11-a01*a10;var b01=a00*a12-a02*a10;var b02=a00*a13-a03*a10;var b03=a01*a12-a02*a11;var b04=a01*a13-a03*a11;var b05=
+a02*a13-a03*a12;var b06=a20*a31-a21*a30;var b07=a20*a32-a22*a30;var b08=a20*a33-a23*a30;var b09=a21*a32-a22*a31;var b10=a21*a33-a23*a31;var b11=a22*a33-a23*a32;out[0]=a11*b11-a12*b10+a13*b09;out[1]=a02*b10-a01*b11-a03*b09;out[2]=a31*b05-a32*b04+a33*b03;out[3]=a22*b04-a21*b05-a23*b03;out[4]=a12*b08-a10*b11-a13*b07;out[5]=a00*b11-a02*b08+a03*b07;out[6]=a32*b02-a30*b05-a33*b01;out[7]=a20*b05-a22*b02+a23*b01;out[8]=a10*b10-a11*b08+a13*b06;out[9]=a01*b08-a00*b10-a03*b06;out[10]=a30*b04-a31*b02+a33*b00;
+out[11]=a21*b02-a20*b04-a23*b00;out[12]=a11*b07-a10*b09-a12*b06;out[13]=a00*b09-a01*b07+a02*b06;out[14]=a31*b01-a30*b03-a32*b00;out[15]=a20*b03-a21*b01+a22*b00;return out}function determinant(a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3];var a10=a[4],a11=a[5],a12=a[6],a13=a[7];var a20=a[8],a21=a[9],a22=a[10],a23=a[11];var a30=a[12],a31=a[13],a32=a[14],a33=a[15];var b0=a00*a11-a01*a10;var b1=a00*a12-a02*a10;var b2=a01*a12-a02*a11;var b3=a20*a31-a21*a30;var b4=a20*a32-a22*a30;var b5=a21*a32-a22*a31;var b6=
+a00*b5-a01*b4+a02*b3;var b7=a10*b5-a11*b4+a12*b3;var b8=a20*b2-a21*b1+a22*b0;var b9=a30*b2-a31*b1+a32*b0;return a13*b6-a03*b7+a33*b8-a23*b9}function multiply$5(out,a,b){var a00=a[0],a01=a[1],a02=a[2],a03=a[3];var a10=a[4],a11=a[5],a12=a[6],a13=a[7];var a20=a[8],a21=a[9],a22=a[10],a23=a[11];var a30=a[12],a31=a[13],a32=a[14],a33=a[15];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];out[0]=b0*a00+b1*a10+b2*a20+b3*a30;out[1]=b0*a01+b1*a11+b2*a21+b3*a31;out[2]=b0*a02+b1*a12+b2*a22+b3*a32;out[3]=b0*a03+b1*a13+b2*a23+
+b3*a33;b0=b[4];b1=b[5];b2=b[6];b3=b[7];out[4]=b0*a00+b1*a10+b2*a20+b3*a30;out[5]=b0*a01+b1*a11+b2*a21+b3*a31;out[6]=b0*a02+b1*a12+b2*a22+b3*a32;out[7]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[8];b1=b[9];b2=b[10];b3=b[11];out[8]=b0*a00+b1*a10+b2*a20+b3*a30;out[9]=b0*a01+b1*a11+b2*a21+b3*a31;out[10]=b0*a02+b1*a12+b2*a22+b3*a32;out[11]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[12];b1=b[13];b2=b[14];b3=b[15];out[12]=b0*a00+b1*a10+b2*a20+b3*a30;out[13]=b0*a01+b1*a11+b2*a21+b3*a31;out[14]=b0*a02+b1*a12+b2*a22+b3*a32;out[15]=
+b0*a03+b1*a13+b2*a23+b3*a33;return out}function translate$1(out,a,v){var x=v[0],y=v[1],z=v[2];var a00,a01,a02,a03;var a10,a11,a12,a13;var a20,a21,a22,a23;if(a===out){out[12]=a[0]*x+a[4]*y+a[8]*z+a[12];out[13]=a[1]*x+a[5]*y+a[9]*z+a[13];out[14]=a[2]*x+a[6]*y+a[10]*z+a[14];out[15]=a[3]*x+a[7]*y+a[11]*z+a[15]}else{a00=a[0];a01=a[1];a02=a[2];a03=a[3];a10=a[4];a11=a[5];a12=a[6];a13=a[7];a20=a[8];a21=a[9];a22=a[10];a23=a[11];out[0]=a00;out[1]=a01;out[2]=a02;out[3]=a03;out[4]=a10;out[5]=a11;out[6]=a12;out[7]=
+a13;out[8]=a20;out[9]=a21;out[10]=a22;out[11]=a23;out[12]=a00*x+a10*y+a20*z+a[12];out[13]=a01*x+a11*y+a21*z+a[13];out[14]=a02*x+a12*y+a22*z+a[14];out[15]=a03*x+a13*y+a23*z+a[15]}return out}function scale$5(out,a,v){var x=v[0],y=v[1],z=v[2];out[0]=a[0]*x;out[1]=a[1]*x;out[2]=a[2]*x;out[3]=a[3]*x;out[4]=a[4]*y;out[5]=a[5]*y;out[6]=a[6]*y;out[7]=a[7]*y;out[8]=a[8]*z;out[9]=a[9]*z;out[10]=a[10]*z;out[11]=a[11]*z;out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out}function rotate$1(out,
+a,rad,axis){var x=axis[0],y=axis[1],z=axis[2];var len=Math.hypot(x,y,z);var s,c,t;var a00,a01,a02,a03;var a10,a11,a12,a13;var a20,a21,a22,a23;var b00,b01,b02;var b10,b11,b12;var b20,b21,b22;if(len0){translation[0]=(ax*bw+aw*bx+ay*bz-
+az*by)*2/magnitude;translation[1]=(ay*bw+aw*by+az*bx-ax*bz)*2/magnitude;translation[2]=(az*bw+aw*bz+ax*by-ay*bx)*2/magnitude}else{translation[0]=(ax*bw+aw*bx+ay*bz-az*by)*2;translation[1]=(ay*bw+aw*by+az*bx-ax*bz)*2;translation[2]=(az*bw+aw*bz+ax*by-ay*bx)*2}fromRotationTranslation$1(out,a,translation);return out}function getTranslation$1(out,mat){out[0]=mat[12];out[1]=mat[13];out[2]=mat[14];return out}function getScaling(out,mat){var m11=mat[0];var m12=mat[1];var m13=mat[2];var m21=mat[4];var m22=
+mat[5];var m23=mat[6];var m31=mat[8];var m32=mat[9];var m33=mat[10];out[0]=Math.hypot(m11,m12,m13);out[1]=Math.hypot(m21,m22,m23);out[2]=Math.hypot(m31,m32,m33);return out}function getRotation(out,mat){var scaling=new ARRAY_TYPE(3);getScaling(scaling,mat);var is1=1/scaling[0];var is2=1/scaling[1];var is3=1/scaling[2];var sm11=mat[0]*is1;var sm12=mat[1]*is2;var sm13=mat[2]*is3;var sm21=mat[4]*is1;var sm22=mat[5]*is2;var sm23=mat[6]*is3;var sm31=mat[8]*is1;var sm32=mat[9]*is2;var sm33=mat[10]*is3;var trace=
+sm11+sm22+sm33;var S=0;if(trace>0){S=Math.sqrt(trace+1)*2;out[3]=.25*S;out[0]=(sm23-sm32)/S;out[1]=(sm31-sm13)/S;out[2]=(sm12-sm21)/S}else if(sm11>sm22&&sm11>sm33){S=Math.sqrt(1+sm11-sm22-sm33)*2;out[3]=(sm23-sm32)/S;out[0]=.25*S;out[1]=(sm12+sm21)/S;out[2]=(sm31+sm13)/S}else if(sm22>sm33){S=Math.sqrt(1+sm22-sm11-sm33)*2;out[3]=(sm31-sm13)/S;out[0]=(sm12+sm21)/S;out[1]=.25*S;out[2]=(sm23+sm32)/S}else{S=Math.sqrt(1+sm33-sm11-sm22)*2;out[3]=(sm12-sm21)/S;out[0]=(sm31+sm13)/S;out[1]=(sm23+sm32)/S;out[2]=
+.25*S}return out}function decompose(out_r,out_t,out_s,mat){out_t[0]=mat[12];out_t[1]=mat[13];out_t[2]=mat[14];var m11=mat[0];var m12=mat[1];var m13=mat[2];var m21=mat[4];var m22=mat[5];var m23=mat[6];var m31=mat[8];var m32=mat[9];var m33=mat[10];out_s[0]=Math.hypot(m11,m12,m13);out_s[1]=Math.hypot(m21,m22,m23);out_s[2]=Math.hypot(m31,m32,m33);var is1=1/out_s[0];var is2=1/out_s[1];var is3=1/out_s[2];var sm11=m11*is1;var sm12=m12*is2;var sm13=m13*is3;var sm21=m21*is1;var sm22=m22*is2;var sm23=m23*is3;
+var sm31=m31*is1;var sm32=m32*is2;var sm33=m33*is3;var trace=sm11+sm22+sm33;var S=0;if(trace>0){S=Math.sqrt(trace+1)*2;out_r[3]=.25*S;out_r[0]=(sm23-sm32)/S;out_r[1]=(sm31-sm13)/S;out_r[2]=(sm12-sm21)/S}else if(sm11>sm22&&sm11>sm33){S=Math.sqrt(1+sm11-sm22-sm33)*2;out_r[3]=(sm23-sm32)/S;out_r[0]=.25*S;out_r[1]=(sm12+sm21)/S;out_r[2]=(sm31+sm13)/S}else if(sm22>sm33){S=Math.sqrt(1+sm22-sm11-sm33)*2;out_r[3]=(sm31-sm13)/S;out_r[0]=(sm12+sm21)/S;out_r[1]=.25*S;out_r[2]=(sm23+sm32)/S}else{S=Math.sqrt(1+
+sm33-sm11-sm22)*2;out_r[3]=(sm12-sm21)/S;out_r[0]=(sm31+sm13)/S;out_r[1]=(sm23+sm32)/S;out_r[2]=.25*S}return out_r}function fromRotationTranslationScale(out,q,v,s){var x=q[0],y=q[1],z=q[2],w=q[3];var x2=x+x;var y2=y+y;var z2=z+z;var xx=x*x2;var xy=x*y2;var xz=x*z2;var yy=y*y2;var yz=y*z2;var zz=z*z2;var wx=w*x2;var wy=w*y2;var wz=w*z2;var sx=s[0];var sy=s[1];var sz=s[2];out[0]=(1-(yy+zz))*sx;out[1]=(xy+wz)*sx;out[2]=(xz-wy)*sx;out[3]=0;out[4]=(xy-wz)*sy;out[5]=(1-(xx+zz))*sy;out[6]=(yz+wx)*sy;out[7]=
+0;out[8]=(xz+wy)*sz;out[9]=(yz-wx)*sz;out[10]=(1-(xx+yy))*sz;out[11]=0;out[12]=v[0];out[13]=v[1];out[14]=v[2];out[15]=1;return out}function fromRotationTranslationScaleOrigin(out,q,v,s,o){var x=q[0],y=q[1],z=q[2],w=q[3];var x2=x+x;var y2=y+y;var z2=z+z;var xx=x*x2;var xy=x*y2;var xz=x*z2;var yy=y*y2;var yz=y*z2;var zz=z*z2;var wx=w*x2;var wy=w*y2;var wz=w*z2;var sx=s[0];var sy=s[1];var sz=s[2];var ox=o[0];var oy=o[1];var oz=o[2];var out0=(1-(yy+zz))*sx;var out1=(xy+wz)*sx;var out2=(xz-wy)*sx;var out4=
+(xy-wz)*sy;var out5=(1-(xx+zz))*sy;var out6=(yz+wx)*sy;var out8=(xz+wy)*sz;var out9=(yz-wx)*sz;var out10=(1-(xx+yy))*sz;out[0]=out0;out[1]=out1;out[2]=out2;out[3]=0;out[4]=out4;out[5]=out5;out[6]=out6;out[7]=0;out[8]=out8;out[9]=out9;out[10]=out10;out[11]=0;out[12]=v[0]+ox-(out0*ox+out4*oy+out8*oz);out[13]=v[1]+oy-(out1*ox+out5*oy+out9*oz);out[14]=v[2]+oz-(out2*ox+out6*oy+out10*oz);out[15]=1;return out}function fromQuat(out,q){var x=q[0],y=q[1],z=q[2],w=q[3];var x2=x+x;var y2=y+y;var z2=z+z;var xx=
+x*x2;var yx=y*x2;var yy=y*y2;var zx=z*x2;var zy=z*y2;var zz=z*z2;var wx=w*x2;var wy=w*y2;var wz=w*z2;out[0]=1-yy-zz;out[1]=yx+wz;out[2]=zx-wy;out[3]=0;out[4]=yx-wz;out[5]=1-xx-zz;out[6]=zy+wx;out[7]=0;out[8]=zx+wy;out[9]=zy-wx;out[10]=1-xx-yy;out[11]=0;out[12]=0;out[13]=0;out[14]=0;out[15]=1;return out}function frustum(out,left,right,bottom,top,near,far){var rl=1/(right-left);var tb=1/(top-bottom);var nf=1/(near-far);out[0]=near*2*rl;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=near*2*tb;out[6]=0;out[7]=
+0;out[8]=(right+left)*rl;out[9]=(top+bottom)*tb;out[10]=(far+near)*nf;out[11]=-1;out[12]=0;out[13]=0;out[14]=far*near*2*nf;out[15]=0;return out}function perspectiveNO(out,fovy,aspect,near,far){var f=1/Math.tan(fovy/2);out[0]=f/aspect;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=f;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[11]=-1;out[12]=0;out[13]=0;out[15]=0;if(far!=null&&far!==Infinity){var nf=1/(near-far);out[10]=(far+near)*nf;out[14]=2*far*near*nf}else{out[10]=-1;out[14]=-2*near}return out}var perspective=
+perspectiveNO;function perspectiveZO(out,fovy,aspect,near,far){var f=1/Math.tan(fovy/2);out[0]=f/aspect;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=f;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[11]=-1;out[12]=0;out[13]=0;out[15]=0;if(far!=null&&far!==Infinity){var nf=1/(near-far);out[10]=far*nf;out[14]=far*near*nf}else{out[10]=-1;out[14]=-near}return out}function perspectiveFromFieldOfView(out,fov,near,far){var upTan=Math.tan(fov.upDegrees*Math.PI/180);var downTan=Math.tan(fov.downDegrees*Math.PI/180);
+var leftTan=Math.tan(fov.leftDegrees*Math.PI/180);var rightTan=Math.tan(fov.rightDegrees*Math.PI/180);var xScale=2/(leftTan+rightTan);var yScale=2/(upTan+downTan);out[0]=xScale;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=yScale;out[6]=0;out[7]=0;out[8]=-((leftTan-rightTan)*xScale*.5);out[9]=(upTan-downTan)*yScale*.5;out[10]=far/(near-far);out[11]=-1;out[12]=0;out[13]=0;out[14]=far*near/(near-far);out[15]=0;return out}function orthoNO(out,left,right,bottom,top,near,far){var lr=1/(left-right);var bt=
+1/(bottom-top);var nf=1/(near-far);out[0]=-2*lr;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=-2*bt;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=2*nf;out[11]=0;out[12]=(left+right)*lr;out[13]=(top+bottom)*bt;out[14]=(far+near)*nf;out[15]=1;return out}var ortho=orthoNO;function orthoZO(out,left,right,bottom,top,near,far){var lr=1/(left-right);var bt=1/(bottom-top);var nf=1/(near-far);out[0]=-2*lr;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=-2*bt;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=nf;out[11]=0;
+out[12]=(left+right)*lr;out[13]=(top+bottom)*bt;out[14]=near*nf;out[15]=1;return out}function lookAt(out,eye,center,up){var x0,x1,x2,y0,y1,y2,z0,z1,z2,len;var eyex=eye[0];var eyey=eye[1];var eyez=eye[2];var upx=up[0];var upy=up[1];var upz=up[2];var centerx=center[0];var centery=center[1];var centerz=center[2];if(Math.abs(eyex-centerx)0){len=1/Math.sqrt(len);z0*=len;z1*=len;z2*=len}var x0=upy*z2-upz*z1,x1=upz*z0-upx*z2,x2=upx*z1-upy*z0;len=x0*x0+x1*x1+x2*x2;if(len>0){len=1/Math.sqrt(len);x0*=len;x1*=len;x2*=len}out[0]=x0;out[1]=x1;out[2]=x2;out[3]=0;out[4]=z1*x2-z2*x1;out[5]=z2*x0-z0*x2;out[6]=
+z0*x1-z1*x0;out[7]=0;out[8]=z0;out[9]=z1;out[10]=z2;out[11]=0;out[12]=eyex;out[13]=eyey;out[14]=eyez;out[15]=1;return out}function str$5(a){return"mat4("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+", "+a[6]+", "+a[7]+", "+a[8]+", "+a[9]+", "+a[10]+", "+a[11]+", "+a[12]+", "+a[13]+", "+a[14]+", "+a[15]+")"}function frob(a){return Math.hypot(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],a[10],a[11],a[12],a[13],a[14],a[15])}function add$5(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=
+a[2]+b[2];out[3]=a[3]+b[3];out[4]=a[4]+b[4];out[5]=a[5]+b[5];out[6]=a[6]+b[6];out[7]=a[7]+b[7];out[8]=a[8]+b[8];out[9]=a[9]+b[9];out[10]=a[10]+b[10];out[11]=a[11]+b[11];out[12]=a[12]+b[12];out[13]=a[13]+b[13];out[14]=a[14]+b[14];out[15]=a[15]+b[15];return out}function subtract$3(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];out[3]=a[3]-b[3];out[4]=a[4]-b[4];out[5]=a[5]-b[5];out[6]=a[6]-b[6];out[7]=a[7]-b[7];out[8]=a[8]-b[8];out[9]=a[9]-b[9];out[10]=a[10]-b[10];out[11]=a[11]-b[11];out[12]=
+a[12]-b[12];out[13]=a[13]-b[13];out[14]=a[14]-b[14];out[15]=a[15]-b[15];return out}function multiplyScalar(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;out[3]=a[3]*b;out[4]=a[4]*b;out[5]=a[5]*b;out[6]=a[6]*b;out[7]=a[7]*b;out[8]=a[8]*b;out[9]=a[9]*b;out[10]=a[10]*b;out[11]=a[11]*b;out[12]=a[12]*b;out[13]=a[13]*b;out[14]=a[14]*b;out[15]=a[15]*b;return out}function multiplyScalarAndAdd(out,a,b,scale){out[0]=a[0]+b[0]*scale;out[1]=a[1]+b[1]*scale;out[2]=a[2]+b[2]*scale;out[3]=a[3]+b[3]*scale;out[4]=
+a[4]+b[4]*scale;out[5]=a[5]+b[5]*scale;out[6]=a[6]+b[6]*scale;out[7]=a[7]+b[7]*scale;out[8]=a[8]+b[8]*scale;out[9]=a[9]+b[9]*scale;out[10]=a[10]+b[10]*scale;out[11]=a[11]+b[11]*scale;out[12]=a[12]+b[12]*scale;out[13]=a[13]+b[13]*scale;out[14]=a[14]+b[14]*scale;out[15]=a[15]+b[15]*scale;return out}function exactEquals$5(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&a[6]===b[6]&&a[7]===b[7]&&a[8]===b[8]&&a[9]===b[9]&&a[10]===b[10]&&a[11]===b[11]&&a[12]===
+b[12]&&a[13]===b[13]&&a[14]===b[14]&&a[15]===b[15]}function equals$5(a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var a4=a[4],a5=a[5],a6=a[6],a7=a[7];var a8=a[8],a9=a[9],a10=a[10],a11=a[11];var a12=a[12],a13=a[13],a14=a[14],a15=a[15];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];var b4=b[4],b5=b[5],b6=b[6],b7=b[7];var b8=b[8],b9=b[9],b10=b[10],b11=b[11];var b12=b[12],b13=b[13],b14=b[14],b15=b[15];return Math.abs(a0-b0)<=EPSILON*Math.max(1,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=EPSILON*Math.max(1,Math.abs(a1),
+Math.abs(b1))&&Math.abs(a2-b2)<=EPSILON*Math.max(1,Math.abs(a2),Math.abs(b2))&&Math.abs(a3-b3)<=EPSILON*Math.max(1,Math.abs(a3),Math.abs(b3))&&Math.abs(a4-b4)<=EPSILON*Math.max(1,Math.abs(a4),Math.abs(b4))&&Math.abs(a5-b5)<=EPSILON*Math.max(1,Math.abs(a5),Math.abs(b5))&&Math.abs(a6-b6)<=EPSILON*Math.max(1,Math.abs(a6),Math.abs(b6))&&Math.abs(a7-b7)<=EPSILON*Math.max(1,Math.abs(a7),Math.abs(b7))&&Math.abs(a8-b8)<=EPSILON*Math.max(1,Math.abs(a8),Math.abs(b8))&&Math.abs(a9-b9)<=EPSILON*Math.max(1,Math.abs(a9),
+Math.abs(b9))&&Math.abs(a10-b10)<=EPSILON*Math.max(1,Math.abs(a10),Math.abs(b10))&&Math.abs(a11-b11)<=EPSILON*Math.max(1,Math.abs(a11),Math.abs(b11))&&Math.abs(a12-b12)<=EPSILON*Math.max(1,Math.abs(a12),Math.abs(b12))&&Math.abs(a13-b13)<=EPSILON*Math.max(1,Math.abs(a13),Math.abs(b13))&&Math.abs(a14-b14)<=EPSILON*Math.max(1,Math.abs(a14),Math.abs(b14))&&Math.abs(a15-b15)<=EPSILON*Math.max(1,Math.abs(a15),Math.abs(b15))}var mul$5=multiply$5;var sub$3=subtract$3;var mat4=Object.freeze({__proto__:null,
+create:create$5,clone:clone$5,copy:copy$5,fromValues:fromValues$5,set:set$5,identity:identity$2,transpose:transpose,invert:invert$2,adjoint:adjoint,determinant:determinant,multiply:multiply$5,translate:translate$1,scale:scale$5,rotate:rotate$1,rotateX:rotateX$3,rotateY:rotateY$3,rotateZ:rotateZ$3,fromTranslation:fromTranslation$1,fromScaling:fromScaling,fromRotation:fromRotation$1,fromXRotation:fromXRotation,fromYRotation:fromYRotation,fromZRotation:fromZRotation,fromRotationTranslation:fromRotationTranslation$1,
+fromQuat2:fromQuat2,getTranslation:getTranslation$1,getScaling:getScaling,getRotation:getRotation,decompose:decompose,fromRotationTranslationScale:fromRotationTranslationScale,fromRotationTranslationScaleOrigin:fromRotationTranslationScaleOrigin,fromQuat:fromQuat,frustum:frustum,perspectiveNO:perspectiveNO,perspective:perspective,perspectiveZO:perspectiveZO,perspectiveFromFieldOfView:perspectiveFromFieldOfView,orthoNO:orthoNO,ortho:ortho,orthoZO:orthoZO,lookAt:lookAt,targetTo:targetTo,str:str$5,frob:frob,
+add:add$5,subtract:subtract$3,multiplyScalar:multiplyScalar,multiplyScalarAndAdd:multiplyScalarAndAdd,exactEquals:exactEquals$5,equals:equals$5,mul:mul$5,sub:sub$3});function create$4(){var out=new ARRAY_TYPE(3);if(ARRAY_TYPE!=Float32Array){out[0]=0;out[1]=0;out[2]=0}return out}function clone$4(a){var out=new ARRAY_TYPE(3);out[0]=a[0];out[1]=a[1];out[2]=a[2];return out}function length$4(a){var x=a[0];var y=a[1];var z=a[2];return Math.hypot(x,y,z)}function fromValues$4(x,y,z){var out=new ARRAY_TYPE(3);
+out[0]=x;out[1]=y;out[2]=z;return out}function copy$4(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];return out}function set$4(out,x,y,z){out[0]=x;out[1]=y;out[2]=z;return out}function add$4(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];return out}function subtract$2(out,a,b){out[0]=a[0]-b[0];out[1]=a[1]-b[1];out[2]=a[2]-b[2];return out}function multiply$4(out,a,b){out[0]=a[0]*b[0];out[1]=a[1]*b[1];out[2]=a[2]*b[2];return out}function divide$2(out,a,b){out[0]=a[0]/b[0];out[1]=a[1]/b[1];
+out[2]=a[2]/b[2];return out}function ceil$2(out,a){out[0]=Math.ceil(a[0]);out[1]=Math.ceil(a[1]);out[2]=Math.ceil(a[2]);return out}function floor$2(out,a){out[0]=Math.floor(a[0]);out[1]=Math.floor(a[1]);out[2]=Math.floor(a[2]);return out}function min$2(out,a,b){out[0]=Math.min(a[0],b[0]);out[1]=Math.min(a[1],b[1]);out[2]=Math.min(a[2],b[2]);return out}function max$2(out,a,b){out[0]=Math.max(a[0],b[0]);out[1]=Math.max(a[1],b[1]);out[2]=Math.max(a[2],b[2]);return out}function round$2(out,a){out[0]=
+Math.round(a[0]);out[1]=Math.round(a[1]);out[2]=Math.round(a[2]);return out}function scale$4(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;return out}function scaleAndAdd$2(out,a,b,scale){out[0]=a[0]+b[0]*scale;out[1]=a[1]+b[1]*scale;out[2]=a[2]+b[2]*scale;return out}function distance$2(a,b){var x=b[0]-a[0];var y=b[1]-a[1];var z=b[2]-a[2];return Math.hypot(x,y,z)}function squaredDistance$2(a,b){var x=b[0]-a[0];var y=b[1]-a[1];var z=b[2]-a[2];return x*x+y*y+z*z}function squaredLength$4(a){var x=
+a[0];var y=a[1];var z=a[2];return x*x+y*y+z*z}function negate$2(out,a){out[0]=-a[0];out[1]=-a[1];out[2]=-a[2];return out}function inverse$2(out,a){out[0]=1/a[0];out[1]=1/a[1];out[2]=1/a[2];return out}function normalize$4(out,a){var x=a[0];var y=a[1];var z=a[2];var len=x*x+y*y+z*z;if(len>0)len=1/Math.sqrt(len);out[0]=a[0]*len;out[1]=a[1]*len;out[2]=a[2]*len;return out}function dot$4(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]}function cross$2(out,a,b){var ax=a[0],ay=a[1],az=a[2];var bx=b[0],by=b[1],
+bz=b[2];out[0]=ay*bz-az*by;out[1]=az*bx-ax*bz;out[2]=ax*by-ay*bx;return out}function lerp$4(out,a,b,t){var ax=a[0];var ay=a[1];var az=a[2];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);out[2]=az+t*(b[2]-az);return out}function slerp$1(out,a,b,t){var angle=Math.acos(Math.min(Math.max(dot$4(a,b),-1),1));var sinTotal=Math.sin(angle);var ratioA=Math.sin((1-t)*angle)/sinTotal;var ratioB=Math.sin(t*angle)/sinTotal;out[0]=ratioA*a[0]+ratioB*b[0];out[1]=ratioA*a[1]+ratioB*b[1];out[2]=ratioA*a[2]+ratioB*b[2];
+return out}function hermite(out,a,b,c,d,t){var factorTimes2=t*t;var factor1=factorTimes2*(2*t-3)+1;var factor2=factorTimes2*(t-2)+t;var factor3=factorTimes2*(t-1);var factor4=factorTimes2*(3-2*t);out[0]=a[0]*factor1+b[0]*factor2+c[0]*factor3+d[0]*factor4;out[1]=a[1]*factor1+b[1]*factor2+c[1]*factor3+d[1]*factor4;out[2]=a[2]*factor1+b[2]*factor2+c[2]*factor3+d[2]*factor4;return out}function bezier(out,a,b,c,d,t){var inverseFactor=1-t;var inverseFactorTimesTwo=inverseFactor*inverseFactor;var factorTimes2=
+t*t;var factor1=inverseFactorTimesTwo*inverseFactor;var factor2=3*t*inverseFactorTimesTwo;var factor3=3*factorTimes2*inverseFactor;var factor4=factorTimes2*t;out[0]=a[0]*factor1+b[0]*factor2+c[0]*factor3+d[0]*factor4;out[1]=a[1]*factor1+b[1]*factor2+c[1]*factor3+d[1]*factor4;out[2]=a[2]*factor1+b[2]*factor2+c[2]*factor3+d[2]*factor4;return out}function random$3(out,scale){scale=scale||1;var r=RANDOM()*2*Math.PI;var z=RANDOM()*2-1;var zScale=Math.sqrt(1-z*z)*scale;out[0]=Math.cos(r)*zScale;out[1]=
+Math.sin(r)*zScale;out[2]=z*scale;return out}function transformMat4$2(out,a,m){var x=a[0],y=a[1],z=a[2];var w=m[3]*x+m[7]*y+m[11]*z+m[15];w=w||1;out[0]=(m[0]*x+m[4]*y+m[8]*z+m[12])/w;out[1]=(m[1]*x+m[5]*y+m[9]*z+m[13])/w;out[2]=(m[2]*x+m[6]*y+m[10]*z+m[14])/w;return out}function transformMat3$1(out,a,m){var x=a[0],y=a[1],z=a[2];out[0]=x*m[0]+y*m[3]+z*m[6];out[1]=x*m[1]+y*m[4]+z*m[7];out[2]=x*m[2]+y*m[5]+z*m[8];return out}function transformQuat$1(out,a,q){var qx=q[0],qy=q[1],qz=q[2],qw=q[3];var x=
+a[0],y=a[1],z=a[2];var uvx=qy*z-qz*y,uvy=qz*x-qx*z,uvz=qx*y-qy*x;var uuvx=qy*uvz-qz*uvy,uuvy=qz*uvx-qx*uvz,uuvz=qx*uvy-qy*uvx;var w2=qw*2;uvx*=w2;uvy*=w2;uvz*=w2;uuvx*=2;uuvy*=2;uuvz*=2;out[0]=x+uvx+uuvx;out[1]=y+uvy+uuvy;out[2]=z+uvz+uuvz;return out}function rotateX$2(out,a,b,rad){var p=[],r=[];p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];r[0]=p[0];r[1]=p[1]*Math.cos(rad)-p[2]*Math.sin(rad);r[2]=p[1]*Math.sin(rad)+p[2]*Math.cos(rad);out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out}function rotateY$2(out,
+a,b,rad){var p=[],r=[];p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];r[0]=p[2]*Math.sin(rad)+p[0]*Math.cos(rad);r[1]=p[1];r[2]=p[2]*Math.cos(rad)-p[0]*Math.sin(rad);out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out}function rotateZ$2(out,a,b,rad){var p=[],r=[];p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];r[0]=p[0]*Math.cos(rad)-p[1]*Math.sin(rad);r[1]=p[0]*Math.sin(rad)+p[1]*Math.cos(rad);r[2]=p[2];out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out}function angle$1(a,b){var ax=
+a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag=Math.sqrt((ax*ax+ay*ay+az*az)*(bx*bx+by*by+bz*bz)),cosine=mag&&dot$4(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))}function zero$2(out){out[0]=0;out[1]=0;out[2]=0;return out}function str$4(a){return"vec3("+a[0]+", "+a[1]+", "+a[2]+")"}function exactEquals$4(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]}function equals$4(a,b){var a0=a[0],a1=a[1],a2=a[2];var b0=b[0],b1=b[1],b2=b[2];return Math.abs(a0-b0)<=EPSILON*Math.max(1,Math.abs(a0),
+Math.abs(b0))&&Math.abs(a1-b1)<=EPSILON*Math.max(1,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=EPSILON*Math.max(1,Math.abs(a2),Math.abs(b2))}var sub$2=subtract$2;var mul$4=multiply$4;var div$2=divide$2;var dist$2=distance$2;var sqrDist$2=squaredDistance$2;var len$4=length$4;var sqrLen$4=squaredLength$4;var forEach$2=function(){var vec=create$4();return function(a,stride,offset,count,fn,arg){var i,l;if(!stride)stride=3;if(!offset)offset=0;if(count)l=Math.min(count*stride+offset,a.length);else l=a.length;
+for(i=offset;i0)len=1/Math.sqrt(len);out[0]=
+x*len;out[1]=y*len;out[2]=z*len;out[3]=w*len;return out}function dot$3(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function cross$1(out,u,v,w){var A=v[0]*w[1]-v[1]*w[0],B=v[0]*w[2]-v[2]*w[0],C=v[0]*w[3]-v[3]*w[0],D=v[1]*w[2]-v[2]*w[1],E=v[1]*w[3]-v[3]*w[1],F=v[2]*w[3]-v[3]*w[2];var G=u[0];var H=u[1];var I=u[2];var J=u[3];out[0]=H*F-I*E+J*D;out[1]=-(G*F)+I*C-J*B;out[2]=G*E-H*C+J*A;out[3]=-(G*D)+H*B-I*A;return out}function lerp$3(out,a,b,t){var ax=a[0];var ay=a[1];var az=a[2];var aw=a[3];out[0]=
+ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);out[2]=az+t*(b[2]-az);out[3]=aw+t*(b[3]-aw);return out}function random$2(out,scale){scale=scale||1;var v1,v2,v3,v4;var s1,s2;do{v1=RANDOM()*2-1;v2=RANDOM()*2-1;s1=v1*v1+v2*v2}while(s1>=1);do{v3=RANDOM()*2-1;v4=RANDOM()*2-1;s2=v3*v3+v4*v4}while(s2>=1);var d=Math.sqrt((1-s1)/s2);out[0]=scale*v1;out[1]=scale*v2;out[2]=scale*v3*d;out[3]=scale*v4*d;return out}function transformMat4$1(out,a,m){var x=a[0],y=a[1],z=a[2],w=a[3];out[0]=m[0]*x+m[4]*y+m[8]*z+m[12]*w;out[1]=
+m[1]*x+m[5]*y+m[9]*z+m[13]*w;out[2]=m[2]*x+m[6]*y+m[10]*z+m[14]*w;out[3]=m[3]*x+m[7]*y+m[11]*z+m[15]*w;return out}function transformQuat(out,a,q){var x=a[0],y=a[1],z=a[2];var qx=q[0],qy=q[1],qz=q[2],qw=q[3];var ix=qw*x+qy*z-qz*y;var iy=qw*y+qz*x-qx*z;var iz=qw*z+qx*y-qy*x;var iw=-qx*x-qy*y-qz*z;out[0]=ix*qw+iw*-qx+iy*-qz-iz*-qy;out[1]=iy*qw+iw*-qy+iz*-qx-ix*-qz;out[2]=iz*qw+iw*-qz+ix*-qy-iy*-qx;out[3]=a[3];return out}function zero$1(out){out[0]=0;out[1]=0;out[2]=0;out[3]=0;return out}function str$3(a){return"vec4("+
+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+")"}function exactEquals$3(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]}function equals$3(a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var b0=b[0],b1=b[1],b2=b[2],b3=b[3];return Math.abs(a0-b0)<=EPSILON*Math.max(1,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=EPSILON*Math.max(1,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=EPSILON*Math.max(1,Math.abs(a2),Math.abs(b2))&&Math.abs(a3-b3)<=EPSILON*Math.max(1,Math.abs(a3),Math.abs(b3))}var sub$1=subtract$1;
+var mul$3=multiply$3;var div$1=divide$1;var dist$1=distance$1;var sqrDist$1=squaredDistance$1;var len$3=length$3;var sqrLen$3=squaredLength$3;var forEach$1=function(){var vec=create$3();return function(a,stride,offset,count,fn,arg){var i,l;if(!stride)stride=4;if(!offset)offset=0;if(count)l=Math.min(count*stride+offset,a.length);else l=a.length;for(i=offset;iEPSILON){out_axis[0]=q[0]/s;out_axis[1]=q[1]/s;out_axis[2]=q[2]/s}else{out_axis[0]=1;out_axis[1]=0;out_axis[2]=0}return rad}function getAngle(a,b){var dotproduct=dot$2(a,b);return Math.acos(2*dotproduct*dotproduct-1)}function multiply$2(out,a,b){var ax=a[0],ay=a[1],az=a[2],aw=a[3];var bx=b[0],by=b[1],bz=b[2],bw=b[3];out[0]=ax*bw+aw*bx+ay*bz-az*by;out[1]=ay*bw+aw*by+az*bx-
+ax*bz;out[2]=az*bw+aw*bz+ax*by-ay*bx;out[3]=aw*bw-ax*bx-ay*by-az*bz;return out}function rotateX$1(out,a,rad){rad*=.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3];var bx=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw+aw*bx;out[1]=ay*bw+az*bx;out[2]=az*bw-ay*bx;out[3]=aw*bw-ax*bx;return out}function rotateY$1(out,a,rad){rad*=.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3];var by=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw-az*by;out[1]=ay*bw+aw*by;out[2]=az*bw+ax*by;out[3]=aw*bw-ay*by;return out}function rotateZ$1(out,a,
+rad){rad*=.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3];var bz=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw+ay*bz;out[1]=ay*bw-ax*bz;out[2]=az*bw+aw*bz;out[3]=aw*bw-az*bz;return out}function calculateW(out,a){var x=a[0],y=a[1],z=a[2];out[0]=x;out[1]=y;out[2]=z;out[3]=Math.sqrt(Math.abs(1-x*x-y*y-z*z));return out}function exp(out,a){var x=a[0],y=a[1],z=a[2],w=a[3];var r=Math.sqrt(x*x+y*y+z*z);var et=Math.exp(w);var s=r>0?et*Math.sin(r)/r:0;out[0]=x*s;out[1]=y*s;out[2]=z*s;out[3]=et*Math.cos(r);return out}
+function ln(out,a){var x=a[0],y=a[1],z=a[2],w=a[3];var r=Math.sqrt(x*x+y*y+z*z);var t=r>0?Math.atan2(r,w)/r:0;out[0]=x*t;out[1]=y*t;out[2]=z*t;out[3]=.5*Math.log(x*x+y*y+z*z+w*w);return out}function pow(out,a,b){ln(out,a);scale$2(out,out,b);exp(out,out);return out}function slerp(out,a,b,t){var ax=a[0],ay=a[1],az=a[2],aw=a[3];var bx=b[0],by=b[1],bz=b[2],bw=b[3];var omega,cosom,sinom,scale0,scale1;cosom=ax*bx+ay*by+az*bz+aw*bw;if(cosom<0){cosom=-cosom;bx=-bx;by=-by;bz=-bz;bw=-bw}if(1-cosom>EPSILON){omega=
+Math.acos(cosom);sinom=Math.sin(omega);scale0=Math.sin((1-t)*omega)/sinom;scale1=Math.sin(t*omega)/sinom}else{scale0=1-t;scale1=t}out[0]=scale0*ax+scale1*bx;out[1]=scale0*ay+scale1*by;out[2]=scale0*az+scale1*bz;out[3]=scale0*aw+scale1*bw;return out}function random$1(out){var u1=RANDOM();var u2=RANDOM();var u3=RANDOM();var sqrt1MinusU1=Math.sqrt(1-u1);var sqrtU1=Math.sqrt(u1);out[0]=sqrt1MinusU1*Math.sin(2*Math.PI*u2);out[1]=sqrt1MinusU1*Math.cos(2*Math.PI*u2);out[2]=sqrtU1*Math.sin(2*Math.PI*u3);
+out[3]=sqrtU1*Math.cos(2*Math.PI*u3);return out}function invert$1(out,a){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var dot=a0*a0+a1*a1+a2*a2+a3*a3;var invDot=dot?1/dot:0;out[0]=-a0*invDot;out[1]=-a1*invDot;out[2]=-a2*invDot;out[3]=a3*invDot;return out}function conjugate$1(out,a){out[0]=-a[0];out[1]=-a[1];out[2]=-a[2];out[3]=a[3];return out}function fromMat3(out,m){var fTrace=m[0]+m[4]+m[8];var fRoot;if(fTrace>0){fRoot=Math.sqrt(fTrace+1);out[3]=.5*fRoot;fRoot=.5/fRoot;out[0]=(m[5]-m[7])*fRoot;out[1]=(m[6]-
+m[2])*fRoot;out[2]=(m[1]-m[3])*fRoot}else{var i=0;if(m[4]>m[0])i=1;if(m[8]>m[i*3+i])i=2;var j=(i+1)%3;var k=(i+2)%3;fRoot=Math.sqrt(m[i*3+i]-m[j*3+j]-m[k*3+k]+1);out[i]=.5*fRoot;fRoot=.5/fRoot;out[3]=(m[j*3+k]-m[k*3+j])*fRoot;out[j]=(m[j*3+i]+m[i*3+j])*fRoot;out[k]=(m[k*3+i]+m[i*3+k])*fRoot}return out}function fromEuler(out,x,y,z){var order=arguments.length>4&&arguments[4]!==undefined?arguments[4]:ANGLE_ORDER;var halfToRad=Math.PI/360;x*=halfToRad;z*=halfToRad;y*=halfToRad;var sx=Math.sin(x);var cx=
+Math.cos(x);var sy=Math.sin(y);var cy=Math.cos(y);var sz=Math.sin(z);var cz=Math.cos(z);switch(order){case "xyz":out[0]=sx*cy*cz+cx*sy*sz;out[1]=cx*sy*cz-sx*cy*sz;out[2]=cx*cy*sz+sx*sy*cz;out[3]=cx*cy*cz-sx*sy*sz;break;case "xzy":out[0]=sx*cy*cz-cx*sy*sz;out[1]=cx*sy*cz-sx*cy*sz;out[2]=cx*cy*sz+sx*sy*cz;out[3]=cx*cy*cz+sx*sy*sz;break;case "yxz":out[0]=sx*cy*cz+cx*sy*sz;out[1]=cx*sy*cz-sx*cy*sz;out[2]=cx*cy*sz-sx*sy*cz;out[3]=cx*cy*cz+sx*sy*sz;break;case "yzx":out[0]=sx*cy*cz+cx*sy*sz;out[1]=cx*sy*
+cz+sx*cy*sz;out[2]=cx*cy*sz-sx*sy*cz;out[3]=cx*cy*cz-sx*sy*sz;break;case "zxy":out[0]=sx*cy*cz-cx*sy*sz;out[1]=cx*sy*cz+sx*cy*sz;out[2]=cx*cy*sz+sx*sy*cz;out[3]=cx*cy*cz-sx*sy*sz;break;case "zyx":out[0]=sx*cy*cz-cx*sy*sz;out[1]=cx*sy*cz+sx*cy*sz;out[2]=cx*cy*sz-sx*sy*cz;out[3]=cx*cy*cz+sx*sy*sz;break;default:throw new Error("Unknown angle order "+order);}return out}function str$2(a){return"quat("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+")"}var clone$2=clone$3;var fromValues$2=fromValues$3;var copy$2=copy$3;
+var set$2=set$3;var add$2=add$3;var mul$2=multiply$2;var scale$2=scale$3;var dot$2=dot$3;var lerp$2=lerp$3;var length$2=length$3;var len$2=length$2;var squaredLength$2=squaredLength$3;var sqrLen$2=squaredLength$2;var normalize$2=normalize$3;var exactEquals$2=exactEquals$3;function equals$2(a,b){return Math.abs(dot$3(a,b))>=1-EPSILON}var rotationTo=function(){var tmpvec3=create$4();var xUnitVec3=fromValues$4(1,0,0);var yUnitVec3=fromValues$4(0,1,0);return function(out,a,b){var dot=dot$4(a,b);if(dot<
+-.999999){cross$2(tmpvec3,xUnitVec3,a);if(len$4(tmpvec3)<1E-6)cross$2(tmpvec3,yUnitVec3,a);normalize$4(tmpvec3,tmpvec3);setAxisAngle(out,tmpvec3,Math.PI);return out}else if(dot>.999999){out[0]=0;out[1]=0;out[2]=0;out[3]=1;return out}else{cross$2(tmpvec3,a,b);out[0]=tmpvec3[0];out[1]=tmpvec3[1];out[2]=tmpvec3[2];out[3]=1+dot;return normalize$2(out,out)}}}();var sqlerp=function(){var temp1=create$2();var temp2=create$2();return function(out,a,b,c,d,t){slerp(temp1,a,d,t);slerp(temp2,b,c,t);slerp(out,
+temp1,temp2,2*t*(1-t));return out}}();var setAxes=function(){var matr=create$6();return function(out,view,right,up){matr[0]=right[0];matr[3]=right[1];matr[6]=right[2];matr[1]=up[0];matr[4]=up[1];matr[7]=up[2];matr[2]=-view[0];matr[5]=-view[1];matr[8]=-view[2];return normalize$2(out,fromMat3(out,matr))}}();var quat=Object.freeze({__proto__:null,create:create$2,identity:identity$1,setAxisAngle:setAxisAngle,getAxisAngle:getAxisAngle,getAngle:getAngle,multiply:multiply$2,rotateX:rotateX$1,rotateY:rotateY$1,
+rotateZ:rotateZ$1,calculateW:calculateW,exp:exp,ln:ln,pow:pow,slerp:slerp,random:random$1,invert:invert$1,conjugate:conjugate$1,fromMat3:fromMat3,fromEuler:fromEuler,str:str$2,clone:clone$2,fromValues:fromValues$2,copy:copy$2,set:set$2,add:add$2,mul:mul$2,scale:scale$2,dot:dot$2,lerp:lerp$2,length:length$2,len:len$2,squaredLength:squaredLength$2,sqrLen:sqrLen$2,normalize:normalize$2,exactEquals:exactEquals$2,equals:equals$2,rotationTo:rotationTo,sqlerp:sqlerp,setAxes:setAxes});function create$1(){var dq=
+new ARRAY_TYPE(8);if(ARRAY_TYPE!=Float32Array){dq[0]=0;dq[1]=0;dq[2]=0;dq[4]=0;dq[5]=0;dq[6]=0;dq[7]=0}dq[3]=1;return dq}function clone$1(a){var dq=new ARRAY_TYPE(8);dq[0]=a[0];dq[1]=a[1];dq[2]=a[2];dq[3]=a[3];dq[4]=a[4];dq[5]=a[5];dq[6]=a[6];dq[7]=a[7];return dq}function fromValues$1(x1,y1,z1,w1,x2,y2,z2,w2){var dq=new ARRAY_TYPE(8);dq[0]=x1;dq[1]=y1;dq[2]=z1;dq[3]=w1;dq[4]=x2;dq[5]=y2;dq[6]=z2;dq[7]=w2;return dq}function fromRotationTranslationValues(x1,y1,z1,w1,x2,y2,z2){var dq=new ARRAY_TYPE(8);
+dq[0]=x1;dq[1]=y1;dq[2]=z1;dq[3]=w1;var ax=x2*.5,ay=y2*.5,az=z2*.5;dq[4]=ax*w1+ay*z1-az*y1;dq[5]=ay*w1+az*x1-ax*z1;dq[6]=az*w1+ax*y1-ay*x1;dq[7]=-ax*x1-ay*y1-az*z1;return dq}function fromRotationTranslation(out,q,t){var ax=t[0]*.5,ay=t[1]*.5,az=t[2]*.5,bx=q[0],by=q[1],bz=q[2],bw=q[3];out[0]=bx;out[1]=by;out[2]=bz;out[3]=bw;out[4]=ax*bw+ay*bz-az*by;out[5]=ay*bw+az*bx-ax*bz;out[6]=az*bw+ax*by-ay*bx;out[7]=-ax*bx-ay*by-az*bz;return out}function fromTranslation(out,t){out[0]=0;out[1]=0;out[2]=0;out[3]=
+1;out[4]=t[0]*.5;out[5]=t[1]*.5;out[6]=t[2]*.5;out[7]=0;return out}function fromRotation(out,q){out[0]=q[0];out[1]=q[1];out[2]=q[2];out[3]=q[3];out[4]=0;out[5]=0;out[6]=0;out[7]=0;return out}function fromMat4(out,a){var outer=create$2();getRotation(outer,a);var t=new ARRAY_TYPE(3);getTranslation$1(t,a);fromRotationTranslation(out,outer,t);return out}function copy$1(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];return out}function identity(out){out[0]=
+0;out[1]=0;out[2]=0;out[3]=1;out[4]=0;out[5]=0;out[6]=0;out[7]=0;return out}function set$1(out,x1,y1,z1,w1,x2,y2,z2,w2){out[0]=x1;out[1]=y1;out[2]=z1;out[3]=w1;out[4]=x2;out[5]=y2;out[6]=z2;out[7]=w2;return out}var getReal=copy$2;function getDual(out,a){out[0]=a[4];out[1]=a[5];out[2]=a[6];out[3]=a[7];return out}var setReal=copy$2;function setDual(out,q){out[4]=q[0];out[5]=q[1];out[6]=q[2];out[7]=q[3];return out}function getTranslation(out,a){var ax=a[4],ay=a[5],az=a[6],aw=a[7],bx=-a[0],by=-a[1],bz=
+-a[2],bw=a[3];out[0]=(ax*bw+aw*bx+ay*bz-az*by)*2;out[1]=(ay*bw+aw*by+az*bx-ax*bz)*2;out[2]=(az*bw+aw*bz+ax*by-ay*bx)*2;return out}function translate(out,a,v){var ax1=a[0],ay1=a[1],az1=a[2],aw1=a[3],bx1=v[0]*.5,by1=v[1]*.5,bz1=v[2]*.5,ax2=a[4],ay2=a[5],az2=a[6],aw2=a[7];out[0]=ax1;out[1]=ay1;out[2]=az1;out[3]=aw1;out[4]=aw1*bx1+ay1*bz1-az1*by1+ax2;out[5]=aw1*by1+az1*bx1-ax1*bz1+ay2;out[6]=aw1*bz1+ax1*by1-ay1*bx1+az2;out[7]=-ax1*bx1-ay1*by1-az1*bz1+aw2;return out}function rotateX(out,a,rad){var bx=
+-a[0],by=-a[1],bz=-a[2],bw=a[3],ax=a[4],ay=a[5],az=a[6],aw=a[7],ax1=ax*bw+aw*bx+ay*bz-az*by,ay1=ay*bw+aw*by+az*bx-ax*bz,az1=az*bw+aw*bz+ax*by-ay*bx,aw1=aw*bw-ax*bx-ay*by-az*bz;rotateX$1(out,a,rad);bx=out[0];by=out[1];bz=out[2];bw=out[3];out[4]=ax1*bw+aw1*bx+ay1*bz-az1*by;out[5]=ay1*bw+aw1*by+az1*bx-ax1*bz;out[6]=az1*bw+aw1*bz+ax1*by-ay1*bx;out[7]=aw1*bw-ax1*bx-ay1*by-az1*bz;return out}function rotateY(out,a,rad){var bx=-a[0],by=-a[1],bz=-a[2],bw=a[3],ax=a[4],ay=a[5],az=a[6],aw=a[7],ax1=ax*bw+aw*bx+
+ay*bz-az*by,ay1=ay*bw+aw*by+az*bx-ax*bz,az1=az*bw+aw*bz+ax*by-ay*bx,aw1=aw*bw-ax*bx-ay*by-az*bz;rotateY$1(out,a,rad);bx=out[0];by=out[1];bz=out[2];bw=out[3];out[4]=ax1*bw+aw1*bx+ay1*bz-az1*by;out[5]=ay1*bw+aw1*by+az1*bx-ax1*bz;out[6]=az1*bw+aw1*bz+ax1*by-ay1*bx;out[7]=aw1*bw-ax1*bx-ay1*by-az1*bz;return out}function rotateZ(out,a,rad){var bx=-a[0],by=-a[1],bz=-a[2],bw=a[3],ax=a[4],ay=a[5],az=a[6],aw=a[7],ax1=ax*bw+aw*bx+ay*bz-az*by,ay1=ay*bw+aw*by+az*bx-ax*bz,az1=az*bw+aw*bz+ax*by-ay*bx,aw1=aw*bw-
+ax*bx-ay*by-az*bz;rotateZ$1(out,a,rad);bx=out[0];by=out[1];bz=out[2];bw=out[3];out[4]=ax1*bw+aw1*bx+ay1*bz-az1*by;out[5]=ay1*bw+aw1*by+az1*bx-ax1*bz;out[6]=az1*bw+aw1*bz+ax1*by-ay1*bx;out[7]=aw1*bw-ax1*bx-ay1*by-az1*bz;return out}function rotateByQuatAppend(out,a,q){var qx=q[0],qy=q[1],qz=q[2],qw=q[3],ax=a[0],ay=a[1],az=a[2],aw=a[3];out[0]=ax*qw+aw*qx+ay*qz-az*qy;out[1]=ay*qw+aw*qy+az*qx-ax*qz;out[2]=az*qw+aw*qz+ax*qy-ay*qx;out[3]=aw*qw-ax*qx-ay*qy-az*qz;ax=a[4];ay=a[5];az=a[6];aw=a[7];out[4]=ax*
+qw+aw*qx+ay*qz-az*qy;out[5]=ay*qw+aw*qy+az*qx-ax*qz;out[6]=az*qw+aw*qz+ax*qy-ay*qx;out[7]=aw*qw-ax*qx-ay*qy-az*qz;return out}function rotateByQuatPrepend(out,q,a){var qx=q[0],qy=q[1],qz=q[2],qw=q[3],bx=a[0],by=a[1],bz=a[2],bw=a[3];out[0]=qx*bw+qw*bx+qy*bz-qz*by;out[1]=qy*bw+qw*by+qz*bx-qx*bz;out[2]=qz*bw+qw*bz+qx*by-qy*bx;out[3]=qw*bw-qx*bx-qy*by-qz*bz;bx=a[4];by=a[5];bz=a[6];bw=a[7];out[4]=qx*bw+qw*bx+qy*bz-qz*by;out[5]=qy*bw+qw*by+qz*bx-qx*bz;out[6]=qz*bw+qw*bz+qx*by-qy*bx;out[7]=qw*bw-qx*bx-qy*
+by-qz*bz;return out}function rotateAroundAxis(out,a,axis,rad){if(Math.abs(rad)0){magnitude=Math.sqrt(magnitude);var a0=a[0]/magnitude;var a1=a[1]/magnitude;var a2=a[2]/magnitude;var a3=
+a[3]/magnitude;var b0=a[4];var b1=a[5];var b2=a[6];var b3=a[7];var a_dot_b=a0*b0+a1*b1+a2*b2+a3*b3;out[0]=a0;out[1]=a1;out[2]=a2;out[3]=a3;out[4]=(b0-a0*a_dot_b)/magnitude;out[5]=(b1-a1*a_dot_b)/magnitude;out[6]=(b2-a2*a_dot_b)/magnitude;out[7]=(b3-a3*a_dot_b)/magnitude}return out}function str$1(a){return"quat2("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+", "+a[6]+", "+a[7]+")"}function exactEquals$1(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===
+b[5]&&a[6]===b[6]&&a[7]===b[7]}function equals$1(a,b){var a0=a[0],a1=a[1],a2=a[2],a3=a[3],a4=a[4],a5=a[5],a6=a[6],a7=a[7];var b0=b[0],b1=b[1],b2=b[2],b3=b[3],b4=b[4],b5=b[5],b6=b[6],b7=b[7];return Math.abs(a0-b0)<=EPSILON*Math.max(1,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=EPSILON*Math.max(1,Math.abs(a1),Math.abs(b1))&&Math.abs(a2-b2)<=EPSILON*Math.max(1,Math.abs(a2),Math.abs(b2))&&Math.abs(a3-b3)<=EPSILON*Math.max(1,Math.abs(a3),Math.abs(b3))&&Math.abs(a4-b4)<=EPSILON*Math.max(1,Math.abs(a4),
+Math.abs(b4))&&Math.abs(a5-b5)<=EPSILON*Math.max(1,Math.abs(a5),Math.abs(b5))&&Math.abs(a6-b6)<=EPSILON*Math.max(1,Math.abs(a6),Math.abs(b6))&&Math.abs(a7-b7)<=EPSILON*Math.max(1,Math.abs(a7),Math.abs(b7))}var quat2=Object.freeze({__proto__:null,create:create$1,clone:clone$1,fromValues:fromValues$1,fromRotationTranslationValues:fromRotationTranslationValues,fromRotationTranslation:fromRotationTranslation,fromTranslation:fromTranslation,fromRotation:fromRotation,fromMat4:fromMat4,copy:copy$1,identity:identity,
+set:set$1,getReal:getReal,getDual:getDual,setReal:setReal,setDual:setDual,getTranslation:getTranslation,translate:translate,rotateX:rotateX,rotateY:rotateY,rotateZ:rotateZ,rotateByQuatAppend:rotateByQuatAppend,rotateByQuatPrepend:rotateByQuatPrepend,rotateAroundAxis:rotateAroundAxis,add:add$1,multiply:multiply$1,mul:mul$1,scale:scale$1,dot:dot$1,lerp:lerp$1,invert:invert,conjugate:conjugate,length:length$1,len:len$1,squaredLength:squaredLength$1,sqrLen:sqrLen$1,normalize:normalize$1,str:str$1,exactEquals:exactEquals$1,
+equals:equals$1});function create(){var out=new ARRAY_TYPE(2);if(ARRAY_TYPE!=Float32Array){out[0]=0;out[1]=0}return out}function clone(a){var out=new ARRAY_TYPE(2);out[0]=a[0];out[1]=a[1];return out}function fromValues(x,y){var out=new ARRAY_TYPE(2);out[0]=x;out[1]=y;return out}function copy(out,a){out[0]=a[0];out[1]=a[1];return out}function set(out,x,y){out[0]=x;out[1]=y;return out}function add(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];return out}function subtract(out,a,b){out[0]=a[0]-b[0];out[1]=
+a[1]-b[1];return out}function multiply(out,a,b){out[0]=a[0]*b[0];out[1]=a[1]*b[1];return out}function divide(out,a,b){out[0]=a[0]/b[0];out[1]=a[1]/b[1];return out}function ceil(out,a){out[0]=Math.ceil(a[0]);out[1]=Math.ceil(a[1]);return out}function floor(out,a){out[0]=Math.floor(a[0]);out[1]=Math.floor(a[1]);return out}function min(out,a,b){out[0]=Math.min(a[0],b[0]);out[1]=Math.min(a[1],b[1]);return out}function max(out,a,b){out[0]=Math.max(a[0],b[0]);out[1]=Math.max(a[1],b[1]);return out}function round(out,
+a){out[0]=Math.round(a[0]);out[1]=Math.round(a[1]);return out}function scale(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;return out}function scaleAndAdd(out,a,b,scale){out[0]=a[0]+b[0]*scale;out[1]=a[1]+b[1]*scale;return out}function distance(a,b){var x=b[0]-a[0],y=b[1]-a[1];return Math.hypot(x,y)}function squaredDistance(a,b){var x=b[0]-a[0],y=b[1]-a[1];return x*x+y*y}function length(a){var x=a[0],y=a[1];return Math.hypot(x,y)}function squaredLength(a){var x=a[0],y=a[1];return x*x+y*y}function negate(out,
+a){out[0]=-a[0];out[1]=-a[1];return out}function inverse(out,a){out[0]=1/a[0];out[1]=1/a[1];return out}function normalize(out,a){var x=a[0],y=a[1];var len=x*x+y*y;if(len>0)len=1/Math.sqrt(len);out[0]=a[0]*len;out[1]=a[1]*len;return out}function dot(a,b){return a[0]*b[0]+a[1]*b[1]}function cross(out,a,b){var z=a[0]*b[1]-a[1]*b[0];out[0]=out[1]=0;out[2]=z;return out}function lerp(out,a,b,t){var ax=a[0],ay=a[1];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);return out}function random(out,scale){scale=scale||
+1;var r=RANDOM()*2*Math.PI;out[0]=Math.cos(r)*scale;out[1]=Math.sin(r)*scale;return out}function transformMat2(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[2]*y;out[1]=m[1]*x+m[3]*y;return out}function transformMat2d(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[2]*y+m[4];out[1]=m[1]*x+m[3]*y+m[5];return out}function transformMat3(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[3]*y+m[6];out[1]=m[1]*x+m[4]*y+m[7];return out}function transformMat4(out,a,m){var x=a[0];var y=a[1];out[0]=m[0]*x+m[4]*y+m[12];out[1]=
+m[1]*x+m[5]*y+m[13];return out}function rotate(out,a,b,rad){var p0=a[0]-b[0],p1=a[1]-b[1],sinC=Math.sin(rad),cosC=Math.cos(rad);out[0]=p0*cosC-p1*sinC+b[0];out[1]=p0*sinC+p1*cosC+b[1];return out}function angle(a,b){var x1=a[0],y1=a[1],x2=b[0],y2=b[1],mag=Math.sqrt((x1*x1+y1*y1)*(x2*x2+y2*y2)),cosine=mag&&(x1*x2+y1*y2)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1))}function zero(out){out[0]=0;out[1]=0;return out}function str(a){return"vec2("+a[0]+", "+a[1]+")"}function exactEquals(a,b){return a[0]===
+b[0]&&a[1]===b[1]}function equals(a,b){var a0=a[0],a1=a[1];var b0=b[0],b1=b[1];return Math.abs(a0-b0)<=EPSILON*Math.max(1,Math.abs(a0),Math.abs(b0))&&Math.abs(a1-b1)<=EPSILON*Math.max(1,Math.abs(a1),Math.abs(b1))}var len=length;var sub=subtract;var mul=multiply;var div=divide;var dist=distance;var sqrDist=squaredDistance;var sqrLen=squaredLength;var forEach=function(){var vec=create();return function(a,stride,offset,count,fn,arg){var i,l;if(!stride)stride=2;if(!offset)offset=0;if(count)l=Math.min(count*
+stride+offset,a.length);else l=a.length;for(i=offset;i=b&&c=a?1024*(d-55296)+(a-56320)+65536:d}return 56320<=b&&57343>=b&&1<=c?(d=a.charCodeAt(c-1),a=b,55296<=d&&56319>=d?1024*(d-55296)+(a-56320)+65536:a):b}function l(a,c,b){var d=[a].concat(c).concat([b]),e=d[d.length-2],g=d.lastIndexOf(14);if(1=a||1757==a||1807==a||2274==a||3406==a||69821==a||70082<=a&&70083>=a||72250==a||72326<=a&&72329>=a||73030==a?12:13==a?0:10==a?1:0<=a&&9>=a||11<=a&&12>=a||14<=a&&31>=a||127<=a&&159>=a||173==a||1564==a||6158==a||8203==a||8206<=a&&8207>=a||8232==a||8233==a||8234<=a&&8238>=a||8288<=a&&8292>=a||8293==a||8294<=a&&8303>=a||55296<=a&&57343>=a||65279==a||65520<=
+a&&65528>=a||65529<=a&&65531>=a||113824<=a&&113827>=a||119155<=a&&119162>=a||917504==a||917505==a||917506<=a&&917535>=a||917632<=a&&917759>=a||918E3<=a&&921599>=a?2:768<=a&&879>=a||1155<=a&&1159>=a||1160<=a&&1161>=a||1425<=a&&1469>=a||1471==a||1473<=a&&1474>=a||1476<=a&&1477>=a||1479==a||1552<=a&&1562>=a||1611<=a&&1631>=a||1648==a||1750<=a&&1756>=a||1759<=a&&1764>=a||1767<=a&&1768>=a||1770<=a&&1773>=a||1809==a||1840<=a&&1866>=a||1958<=a&&1968>=a||2027<=a&&2035>=a||2070<=a&&2073>=a||2075<=a&&2083>=
+a||2085<=a&&2087>=a||2089<=a&&2093>=a||2137<=a&&2139>=a||2260<=a&&2273>=a||2275<=a&&2306>=a||2362==a||2364==a||2369<=a&&2376>=a||2381==a||2385<=a&&2391>=a||2402<=a&&2403>=a||2433==a||2492==a||2494==a||2497<=a&&2500>=a||2509==a||2519==a||2530<=a&&2531>=a||2561<=a&&2562>=a||2620==a||2625<=a&&2626>=a||2631<=a&&2632>=a||2635<=a&&2637>=a||2641==a||2672<=a&&2673>=a||2677==a||2689<=a&&2690>=a||2748==a||2753<=a&&2757>=a||2759<=a&&2760>=a||2765==a||2786<=a&&2787>=a||2810<=a&&2815>=a||2817==a||2876==a||2878==
+a||2879==a||2881<=a&&2884>=a||2893==a||2902==a||2903==a||2914<=a&&2915>=a||2946==a||3006==a||3008==a||3021==a||3031==a||3072==a||3134<=a&&3136>=a||3142<=a&&3144>=a||3146<=a&&3149>=a||3157<=a&&3158>=a||3170<=a&&3171>=a||3201==a||3260==a||3263==a||3266==a||3270==a||3276<=a&&3277>=a||3285<=a&&3286>=a||3298<=a&&3299>=a||3328<=a&&3329>=a||3387<=a&&3388>=a||3390==a||3393<=a&&3396>=a||3405==a||3415==a||3426<=a&&3427>=a||3530==a||3535==a||3538<=a&&3540>=a||3542==a||3551==a||3633==a||3636<=a&&3642>=a||3655<=
+a&&3662>=a||3761==a||3764<=a&&3769>=a||3771<=a&&3772>=a||3784<=a&&3789>=a||3864<=a&&3865>=a||3893==a||3895==a||3897==a||3953<=a&&3966>=a||3968<=a&&3972>=a||3974<=a&&3975>=a||3981<=a&&3991>=a||3993<=a&&4028>=a||4038==a||4141<=a&&4144>=a||4146<=a&&4151>=a||4153<=a&&4154>=a||4157<=a&&4158>=a||4184<=a&&4185>=a||4190<=a&&4192>=a||4209<=a&&4212>=a||4226==a||4229<=a&&4230>=a||4237==a||4253==a||4957<=a&&4959>=a||5906<=a&&5908>=a||5938<=a&&5940>=a||5970<=a&&5971>=a||6002<=a&&6003>=a||6068<=a&&6069>=a||6071<=
+a&&6077>=a||6086==a||6089<=a&&6099>=a||6109==a||6155<=a&&6157>=a||6277<=a&&6278>=a||6313==a||6432<=a&&6434>=a||6439<=a&&6440>=a||6450==a||6457<=a&&6459>=a||6679<=a&&6680>=a||6683==a||6742==a||6744<=a&&6750>=a||6752==a||6754==a||6757<=a&&6764>=a||6771<=a&&6780>=a||6783==a||6832<=a&&6845>=a||6846==a||6912<=a&&6915>=a||6964==a||6966<=a&&6970>=a||6972==a||6978==a||7019<=a&&7027>=a||7040<=a&&7041>=a||7074<=a&&7077>=a||7080<=a&&7081>=a||7083<=a&&7085>=a||7142==a||7144<=a&&7145>=a||7149==a||7151<=a&&7153>=
+a||7212<=a&&7219>=a||7222<=a&&7223>=a||7376<=a&&7378>=a||7380<=a&&7392>=a||7394<=a&&7400>=a||7405==a||7412==a||7416<=a&&7417>=a||7616<=a&&7673>=a||7675<=a&&7679>=a||8204==a||8400<=a&&8412>=a||8413<=a&&8416>=a||8417==a||8418<=a&&8420>=a||8421<=a&&8432>=a||11503<=a&&11505>=a||11647==a||11744<=a&&11775>=a||12330<=a&&12333>=a||12334<=a&&12335>=a||12441<=a&&12442>=a||42607==a||42608<=a&&42610>=a||42612<=a&&42621>=a||42654<=a&&42655>=a||42736<=a&&42737>=a||43010==a||43014==a||43019==a||43045<=a&&43046>=
+a||43204<=a&&43205>=a||43232<=a&&43249>=a||43302<=a&&43309>=a||43335<=a&&43345>=a||43392<=a&&43394>=a||43443==a||43446<=a&&43449>=a||43452==a||43493==a||43561<=a&&43566>=a||43569<=a&&43570>=a||43573<=a&&43574>=a||43587==a||43596==a||43644==a||43696==a||43698<=a&&43700>=a||43703<=a&&43704>=a||43710<=a&&43711>=a||43713==a||43756<=a&&43757>=a||43766==a||44005==a||44008==a||44013==a||64286==a||65024<=a&&65039>=a||65056<=a&&65071>=a||65438<=a&&65439>=a||66045==a||66272==a||66422<=a&&66426>=a||68097<=a&&
+68099>=a||68101<=a&&68102>=a||68108<=a&&68111>=a||68152<=a&&68154>=a||68159==a||68325<=a&&68326>=a||69633==a||69688<=a&&69702>=a||69759<=a&&69761>=a||69811<=a&&69814>=a||69817<=a&&69818>=a||69888<=a&&69890>=a||69927<=a&&69931>=a||69933<=a&&69940>=a||70003==a||70016<=a&&70017>=a||70070<=a&&70078>=a||70090<=a&&70092>=a||70191<=a&&70193>=a||70196==a||70198<=a&&70199>=a||70206==a||70367==a||70371<=a&&70378>=a||70400<=a&&70401>=a||70460==a||70462==a||70464==a||70487==a||70502<=a&&70508>=a||70512<=a&&70516>=
+a||70712<=a&&70719>=a||70722<=a&&70724>=a||70726==a||70832==a||70835<=a&&70840>=a||70842==a||70845==a||70847<=a&&70848>=a||70850<=a&&70851>=a||71087==a||71090<=a&&71093>=a||71100<=a&&71101>=a||71103<=a&&71104>=a||71132<=a&&71133>=a||71219<=a&&71226>=a||71229==a||71231<=a&&71232>=a||71339==a||71341==a||71344<=a&&71349>=a||71351==a||71453<=a&&71455>=a||71458<=a&&71461>=a||71463<=a&&71467>=a||72193<=a&&72198>=a||72201<=a&&72202>=a||72243<=a&&72248>=a||72251<=a&&72254>=a||72263==a||72273<=a&&72278>=a||
+72281<=a&&72283>=a||72330<=a&&72342>=a||72344<=a&&72345>=a||72752<=a&&72758>=a||72760<=a&&72765>=a||72767==a||72850<=a&&72871>=a||72874<=a&&72880>=a||72882<=a&&72883>=a||72885<=a&&72886>=a||73009<=a&&73014>=a||73018==a||73020<=a&&73021>=a||73023<=a&&73029>=a||73031==a||92912<=a&&92916>=a||92976<=a&&92982>=a||94095<=a&&94098>=a||113821<=a&&113822>=a||119141==a||119143<=a&&119145>=a||119150<=a&&119154>=a||119163<=a&&119170>=a||119173<=a&&119179>=a||119210<=a&&119213>=a||119362<=a&&119364>=a||121344<=
+a&&121398>=a||121403<=a&&121452>=a||121461==a||121476==a||121499<=a&&121503>=a||121505<=a&&121519>=a||122880<=a&&122886>=a||122888<=a&&122904>=a||122907<=a&&122913>=a||122915<=a&&122916>=a||122918<=a&&122922>=a||125136<=a&&125142>=a||125252<=a&&125258>=a||917536<=a&&917631>=a||917760<=a&&917999>=a?3:127462<=a&&127487>=a?4:2307==a||2363==a||2366<=a&&2368>=a||2377<=a&&2380>=a||2382<=a&&2383>=a||2434<=a&&2435>=a||2495<=a&&2496>=a||2503<=a&&2504>=a||2507<=a&&2508>=a||2563==a||2622<=a&&2624>=a||2691==
+a||2750<=a&&2752>=a||2761==a||2763<=a&&2764>=a||2818<=a&&2819>=a||2880==a||2887<=a&&2888>=a||2891<=a&&2892>=a||3007==a||3009<=a&&3010>=a||3014<=a&&3016>=a||3018<=a&&3020>=a||3073<=a&&3075>=a||3137<=a&&3140>=a||3202<=a&&3203>=a||3262==a||3264<=a&&3265>=a||3267<=a&&3268>=a||3271<=a&&3272>=a||3274<=a&&3275>=a||3330<=a&&3331>=a||3391<=a&&3392>=a||3398<=a&&3400>=a||3402<=a&&3404>=a||3458<=a&&3459>=a||3536<=a&&3537>=a||3544<=a&&3550>=a||3570<=a&&3571>=a||3635==a||3763==a||3902<=a&&3903>=a||3967==a||4145==
+a||4155<=a&&4156>=a||4182<=a&&4183>=a||4228==a||6070==a||6078<=a&&6085>=a||6087<=a&&6088>=a||6435<=a&&6438>=a||6441<=a&&6443>=a||6448<=a&&6449>=a||6451<=a&&6456>=a||6681<=a&&6682>=a||6741==a||6743==a||6765<=a&&6770>=a||6916==a||6965==a||6971==a||6973<=a&&6977>=a||6979<=a&&6980>=a||7042==a||7073==a||7078<=a&&7079>=a||7082==a||7143==a||7146<=a&&7148>=a||7150==a||7154<=a&&7155>=a||7204<=a&&7211>=a||7220<=a&&7221>=a||7393==a||7410<=a&&7411>=a||7415==a||43043<=a&&43044>=a||43047==a||43136<=a&&43137>=a||
+43188<=a&&43203>=a||43346<=a&&43347>=a||43395==a||43444<=a&&43445>=a||43450<=a&&43451>=a||43453<=a&&43456>=a||43567<=a&&43568>=a||43571<=a&&43572>=a||43597==a||43755==a||43758<=a&&43759>=a||43765==a||44003<=a&&44004>=a||44006<=a&&44007>=a||44009<=a&&44010>=a||44012==a||69632==a||69634==a||69762==a||69808<=a&&69810>=a||69815<=a&&69816>=a||69932==a||70018==a||70067<=a&&70069>=a||70079<=a&&70080>=a||70188<=a&&70190>=a||70194<=a&&70195>=a||70197==a||70368<=a&&70370>=a||70402<=a&&70403>=a||70463==a||70465<=
+a&&70468>=a||70471<=a&&70472>=a||70475<=a&&70477>=a||70498<=a&&70499>=a||70709<=a&&70711>=a||70720<=a&&70721>=a||70725==a||70833<=a&&70834>=a||70841==a||70843<=a&&70844>=a||70846==a||70849==a||71088<=a&&71089>=a||71096<=a&&71099>=a||71102==a||71216<=a&&71218>=a||71227<=a&&71228>=a||71230==a||71340==a||71342<=a&&71343>=a||71350==a||71456<=a&&71457>=a||71462==a||72199<=a&&72200>=a||72249==a||72279<=a&&72280>=a||72343==a||72751==a||72766==a||72873==a||72881==a||72884==a||94033<=a&&94078>=a||119142==
+a||119149==a?5:4352<=a&&4447>=a||43360<=a&&43388>=a?6:4448<=a&&4519>=a||55216<=a&&55238>=a?7:4520<=a&&4607>=a||55243<=a&&55291>=a?8:44032==a||44060==a||44088==a||44116==a||44144==a||44172==a||44200==a||44228==a||44256==a||44284==a||44312==a||44340==a||44368==a||44396==a||44424==a||44452==a||44480==a||44508==a||44536==a||44564==a||44592==a||44620==a||44648==a||44676==a||44704==a||44732==a||44760==a||44788==a||44816==a||44844==a||44872==a||44900==a||44928==a||44956==a||44984==a||45012==a||45040==a||
+45068==a||45096==a||45124==a||45152==a||45180==a||45208==a||45236==a||45264==a||45292==a||45320==a||45348==a||45376==a||45404==a||45432==a||45460==a||45488==a||45516==a||45544==a||45572==a||45600==a||45628==a||45656==a||45684==a||45712==a||45740==a||45768==a||45796==a||45824==a||45852==a||45880==a||45908==a||45936==a||45964==a||45992==a||46020==a||46048==a||46076==a||46104==a||46132==a||46160==a||46188==a||46216==a||46244==a||46272==a||46300==a||46328==a||46356==a||46384==a||46412==a||46440==a||46468==
+a||46496==a||46524==a||46552==a||46580==a||46608==a||46636==a||46664==a||46692==a||46720==a||46748==a||46776==a||46804==a||46832==a||46860==a||46888==a||46916==a||46944==a||46972==a||47E3==a||47028==a||47056==a||47084==a||47112==a||47140==a||47168==a||47196==a||47224==a||47252==a||47280==a||47308==a||47336==a||47364==a||47392==a||47420==a||47448==a||47476==a||47504==a||47532==a||47560==a||47588==a||47616==a||47644==a||47672==a||47700==a||47728==a||47756==a||47784==a||47812==a||47840==a||47868==a||
+47896==a||47924==a||47952==a||47980==a||48008==a||48036==a||48064==a||48092==a||48120==a||48148==a||48176==a||48204==a||48232==a||48260==a||48288==a||48316==a||48344==a||48372==a||48400==a||48428==a||48456==a||48484==a||48512==a||48540==a||48568==a||48596==a||48624==a||48652==a||48680==a||48708==a||48736==a||48764==a||48792==a||48820==a||48848==a||48876==a||48904==a||48932==a||48960==a||48988==a||49016==a||49044==a||49072==a||49100==a||49128==a||49156==a||49184==a||49212==a||49240==a||49268==a||49296==
+a||49324==a||49352==a||49380==a||49408==a||49436==a||49464==a||49492==a||49520==a||49548==a||49576==a||49604==a||49632==a||49660==a||49688==a||49716==a||49744==a||49772==a||49800==a||49828==a||49856==a||49884==a||49912==a||49940==a||49968==a||49996==a||50024==a||50052==a||50080==a||50108==a||50136==a||50164==a||50192==a||50220==a||50248==a||50276==a||50304==a||50332==a||50360==a||50388==a||50416==a||50444==a||50472==a||50500==a||50528==a||50556==a||50584==a||50612==a||50640==a||50668==a||50696==a||
+50724==a||50752==a||50780==a||50808==a||50836==a||50864==a||50892==a||50920==a||50948==a||50976==a||51004==a||51032==a||51060==a||51088==a||51116==a||51144==a||51172==a||51200==a||51228==a||51256==a||51284==a||51312==a||51340==a||51368==a||51396==a||51424==a||51452==a||51480==a||51508==a||51536==a||51564==a||51592==a||51620==a||51648==a||51676==a||51704==a||51732==a||51760==a||51788==a||51816==a||51844==a||51872==a||51900==a||51928==a||51956==a||51984==a||52012==a||52040==a||52068==a||52096==a||52124==
+a||52152==a||52180==a||52208==a||52236==a||52264==a||52292==a||52320==a||52348==a||52376==a||52404==a||52432==a||52460==a||52488==a||52516==a||52544==a||52572==a||52600==a||52628==a||52656==a||52684==a||52712==a||52740==a||52768==a||52796==a||52824==a||52852==a||52880==a||52908==a||52936==a||52964==a||52992==a||53020==a||53048==a||53076==a||53104==a||53132==a||53160==a||53188==a||53216==a||53244==a||53272==a||53300==a||53328==a||53356==a||53384==a||53412==a||53440==a||53468==a||53496==a||53524==a||
+53552==a||53580==a||53608==a||53636==a||53664==a||53692==a||53720==a||53748==a||53776==a||53804==a||53832==a||53860==a||53888==a||53916==a||53944==a||53972==a||54E3==a||54028==a||54056==a||54084==a||54112==a||54140==a||54168==a||54196==a||54224==a||54252==a||54280==a||54308==a||54336==a||54364==a||54392==a||54420==a||54448==a||54476==a||54504==a||54532==a||54560==a||54588==a||54616==a||54644==a||54672==a||54700==a||54728==a||54756==a||54784==a||54812==a||54840==a||54868==a||54896==a||54924==a||54952==
+a||54980==a||55008==a||55036==a||55064==a||55092==a||55120==a||55148==a||55176==a?9:44033<=a&&44059>=a||44061<=a&&44087>=a||44089<=a&&44115>=a||44117<=a&&44143>=a||44145<=a&&44171>=a||44173<=a&&44199>=a||44201<=a&&44227>=a||44229<=a&&44255>=a||44257<=a&&44283>=a||44285<=a&&44311>=a||44313<=a&&44339>=a||44341<=a&&44367>=a||44369<=a&&44395>=a||44397<=a&&44423>=a||44425<=a&&44451>=a||44453<=a&&44479>=a||44481<=a&&44507>=a||44509<=a&&44535>=a||44537<=a&&44563>=a||44565<=a&&44591>=a||44593<=a&&44619>=
+a||44621<=a&&44647>=a||44649<=a&&44675>=a||44677<=a&&44703>=a||44705<=a&&44731>=a||44733<=a&&44759>=a||44761<=a&&44787>=a||44789<=a&&44815>=a||44817<=a&&44843>=a||44845<=a&&44871>=a||44873<=a&&44899>=a||44901<=a&&44927>=a||44929<=a&&44955>=a||44957<=a&&44983>=a||44985<=a&&45011>=a||45013<=a&&45039>=a||45041<=a&&45067>=a||45069<=a&&45095>=a||45097<=a&&45123>=a||45125<=a&&45151>=a||45153<=a&&45179>=a||45181<=a&&45207>=a||45209<=a&&45235>=a||45237<=a&&45263>=a||45265<=a&&45291>=a||45293<=a&&45319>=a||
+45321<=a&&45347>=a||45349<=a&&45375>=a||45377<=a&&45403>=a||45405<=a&&45431>=a||45433<=a&&45459>=a||45461<=a&&45487>=a||45489<=a&&45515>=a||45517<=a&&45543>=a||45545<=a&&45571>=a||45573<=a&&45599>=a||45601<=a&&45627>=a||45629<=a&&45655>=a||45657<=a&&45683>=a||45685<=a&&45711>=a||45713<=a&&45739>=a||45741<=a&&45767>=a||45769<=a&&45795>=a||45797<=a&&45823>=a||45825<=a&&45851>=a||45853<=a&&45879>=a||45881<=a&&45907>=a||45909<=a&&45935>=a||45937<=a&&45963>=a||45965<=a&&45991>=a||45993<=a&&46019>=a||46021<=
+a&&46047>=a||46049<=a&&46075>=a||46077<=a&&46103>=a||46105<=a&&46131>=a||46133<=a&&46159>=a||46161<=a&&46187>=a||46189<=a&&46215>=a||46217<=a&&46243>=a||46245<=a&&46271>=a||46273<=a&&46299>=a||46301<=a&&46327>=a||46329<=a&&46355>=a||46357<=a&&46383>=a||46385<=a&&46411>=a||46413<=a&&46439>=a||46441<=a&&46467>=a||46469<=a&&46495>=a||46497<=a&&46523>=a||46525<=a&&46551>=a||46553<=a&&46579>=a||46581<=a&&46607>=a||46609<=a&&46635>=a||46637<=a&&46663>=a||46665<=a&&46691>=a||46693<=a&&46719>=a||46721<=a&&
+46747>=a||46749<=a&&46775>=a||46777<=a&&46803>=a||46805<=a&&46831>=a||46833<=a&&46859>=a||46861<=a&&46887>=a||46889<=a&&46915>=a||46917<=a&&46943>=a||46945<=a&&46971>=a||46973<=a&&46999>=a||47001<=a&&47027>=a||47029<=a&&47055>=a||47057<=a&&47083>=a||47085<=a&&47111>=a||47113<=a&&47139>=a||47141<=a&&47167>=a||47169<=a&&47195>=a||47197<=a&&47223>=a||47225<=a&&47251>=a||47253<=a&&47279>=a||47281<=a&&47307>=a||47309<=a&&47335>=a||47337<=a&&47363>=a||47365<=a&&47391>=a||47393<=a&&47419>=a||47421<=a&&47447>=
+a||47449<=a&&47475>=a||47477<=a&&47503>=a||47505<=a&&47531>=a||47533<=a&&47559>=a||47561<=a&&47587>=a||47589<=a&&47615>=a||47617<=a&&47643>=a||47645<=a&&47671>=a||47673<=a&&47699>=a||47701<=a&&47727>=a||47729<=a&&47755>=a||47757<=a&&47783>=a||47785<=a&&47811>=a||47813<=a&&47839>=a||47841<=a&&47867>=a||47869<=a&&47895>=a||47897<=a&&47923>=a||47925<=a&&47951>=a||47953<=a&&47979>=a||47981<=a&&48007>=a||48009<=a&&48035>=a||48037<=a&&48063>=a||48065<=a&&48091>=a||48093<=a&&48119>=a||48121<=a&&48147>=a||
+48149<=a&&48175>=a||48177<=a&&48203>=a||48205<=a&&48231>=a||48233<=a&&48259>=a||48261<=a&&48287>=a||48289<=a&&48315>=a||48317<=a&&48343>=a||48345<=a&&48371>=a||48373<=a&&48399>=a||48401<=a&&48427>=a||48429<=a&&48455>=a||48457<=a&&48483>=a||48485<=a&&48511>=a||48513<=a&&48539>=a||48541<=a&&48567>=a||48569<=a&&48595>=a||48597<=a&&48623>=a||48625<=a&&48651>=a||48653<=a&&48679>=a||48681<=a&&48707>=a||48709<=a&&48735>=a||48737<=a&&48763>=a||48765<=a&&48791>=a||48793<=a&&48819>=a||48821<=a&&48847>=a||48849<=
+a&&48875>=a||48877<=a&&48903>=a||48905<=a&&48931>=a||48933<=a&&48959>=a||48961<=a&&48987>=a||48989<=a&&49015>=a||49017<=a&&49043>=a||49045<=a&&49071>=a||49073<=a&&49099>=a||49101<=a&&49127>=a||49129<=a&&49155>=a||49157<=a&&49183>=a||49185<=a&&49211>=a||49213<=a&&49239>=a||49241<=a&&49267>=a||49269<=a&&49295>=a||49297<=a&&49323>=a||49325<=a&&49351>=a||49353<=a&&49379>=a||49381<=a&&49407>=a||49409<=a&&49435>=a||49437<=a&&49463>=a||49465<=a&&49491>=a||49493<=a&&49519>=a||49521<=a&&49547>=a||49549<=a&&
+49575>=a||49577<=a&&49603>=a||49605<=a&&49631>=a||49633<=a&&49659>=a||49661<=a&&49687>=a||49689<=a&&49715>=a||49717<=a&&49743>=a||49745<=a&&49771>=a||49773<=a&&49799>=a||49801<=a&&49827>=a||49829<=a&&49855>=a||49857<=a&&49883>=a||49885<=a&&49911>=a||49913<=a&&49939>=a||49941<=a&&49967>=a||49969<=a&&49995>=a||49997<=a&&50023>=a||50025<=a&&50051>=a||50053<=a&&50079>=a||50081<=a&&50107>=a||50109<=a&&50135>=a||50137<=a&&50163>=a||50165<=a&&50191>=a||50193<=a&&50219>=a||50221<=a&&50247>=a||50249<=a&&50275>=
+a||50277<=a&&50303>=a||50305<=a&&50331>=a||50333<=a&&50359>=a||50361<=a&&50387>=a||50389<=a&&50415>=a||50417<=a&&50443>=a||50445<=a&&50471>=a||50473<=a&&50499>=a||50501<=a&&50527>=a||50529<=a&&50555>=a||50557<=a&&50583>=a||50585<=a&&50611>=a||50613<=a&&50639>=a||50641<=a&&50667>=a||50669<=a&&50695>=a||50697<=a&&50723>=a||50725<=a&&50751>=a||50753<=a&&50779>=a||50781<=a&&50807>=a||50809<=a&&50835>=a||50837<=a&&50863>=a||50865<=a&&50891>=a||50893<=a&&50919>=a||50921<=a&&50947>=a||50949<=a&&50975>=a||
+50977<=a&&51003>=a||51005<=a&&51031>=a||51033<=a&&51059>=a||51061<=a&&51087>=a||51089<=a&&51115>=a||51117<=a&&51143>=a||51145<=a&&51171>=a||51173<=a&&51199>=a||51201<=a&&51227>=a||51229<=a&&51255>=a||51257<=a&&51283>=a||51285<=a&&51311>=a||51313<=a&&51339>=a||51341<=a&&51367>=a||51369<=a&&51395>=a||51397<=a&&51423>=a||51425<=a&&51451>=a||51453<=a&&51479>=a||51481<=a&&51507>=a||51509<=a&&51535>=a||51537<=a&&51563>=a||51565<=a&&51591>=a||51593<=a&&51619>=a||51621<=a&&51647>=a||51649<=a&&51675>=a||51677<=
+a&&51703>=a||51705<=a&&51731>=a||51733<=a&&51759>=a||51761<=a&&51787>=a||51789<=a&&51815>=a||51817<=a&&51843>=a||51845<=a&&51871>=a||51873<=a&&51899>=a||51901<=a&&51927>=a||51929<=a&&51955>=a||51957<=a&&51983>=a||51985<=a&&52011>=a||52013<=a&&52039>=a||52041<=a&&52067>=a||52069<=a&&52095>=a||52097<=a&&52123>=a||52125<=a&&52151>=a||52153<=a&&52179>=a||52181<=a&&52207>=a||52209<=a&&52235>=a||52237<=a&&52263>=a||52265<=a&&52291>=a||52293<=a&&52319>=a||52321<=a&&52347>=a||52349<=a&&52375>=a||52377<=a&&
+52403>=a||52405<=a&&52431>=a||52433<=a&&52459>=a||52461<=a&&52487>=a||52489<=a&&52515>=a||52517<=a&&52543>=a||52545<=a&&52571>=a||52573<=a&&52599>=a||52601<=a&&52627>=a||52629<=a&&52655>=a||52657<=a&&52683>=a||52685<=a&&52711>=a||52713<=a&&52739>=a||52741<=a&&52767>=a||52769<=a&&52795>=a||52797<=a&&52823>=a||52825<=a&&52851>=a||52853<=a&&52879>=a||52881<=a&&52907>=a||52909<=a&&52935>=a||52937<=a&&52963>=a||52965<=a&&52991>=a||52993<=a&&53019>=a||53021<=a&&53047>=a||53049<=a&&53075>=a||53077<=a&&53103>=
+a||53105<=a&&53131>=a||53133<=a&&53159>=a||53161<=a&&53187>=a||53189<=a&&53215>=a||53217<=a&&53243>=a||53245<=a&&53271>=a||53273<=a&&53299>=a||53301<=a&&53327>=a||53329<=a&&53355>=a||53357<=a&&53383>=a||53385<=a&&53411>=a||53413<=a&&53439>=a||53441<=a&&53467>=a||53469<=a&&53495>=a||53497<=a&&53523>=a||53525<=a&&53551>=a||53553<=a&&53579>=a||53581<=a&&53607>=a||53609<=a&&53635>=a||53637<=a&&53663>=a||53665<=a&&53691>=a||53693<=a&&53719>=a||53721<=a&&53747>=a||53749<=a&&53775>=a||53777<=a&&53803>=a||
+53805<=a&&53831>=a||53833<=a&&53859>=a||53861<=a&&53887>=a||53889<=a&&53915>=a||53917<=a&&53943>=a||53945<=a&&53971>=a||53973<=a&&53999>=a||54001<=a&&54027>=a||54029<=a&&54055>=a||54057<=a&&54083>=a||54085<=a&&54111>=a||54113<=a&&54139>=a||54141<=a&&54167>=a||54169<=a&&54195>=a||54197<=a&&54223>=a||54225<=a&&54251>=a||54253<=a&&54279>=a||54281<=a&&54307>=a||54309<=a&&54335>=a||54337<=a&&54363>=a||54365<=a&&54391>=a||54393<=a&&54419>=a||54421<=a&&54447>=a||54449<=a&&54475>=a||54477<=a&&54503>=a||54505<=
+a&&54531>=a||54533<=a&&54559>=a||54561<=a&&54587>=a||54589<=a&&54615>=a||54617<=a&&54643>=a||54645<=a&&54671>=a||54673<=a&&54699>=a||54701<=a&&54727>=a||54729<=a&&54755>=a||54757<=a&&54783>=a||54785<=a&&54811>=a||54813<=a&&54839>=a||54841<=a&&54867>=a||54869<=a&&54895>=a||54897<=a&&54923>=a||54925<=a&&54951>=a||54953<=a&&54979>=a||54981<=a&&55007>=a||55009<=a&&55035>=a||55037<=a&&55063>=a||55065<=a&&55091>=a||55093<=a&&55119>=a||55121<=a&&55147>=a||55149<=a&&55175>=a||55177<=a&&55203>=a?10:9757==
+a||9977==a||9994<=a&&9997>=a||127877==a||127938<=a&&127940>=a||127943==a||127946<=a&&127948>=a||128066<=a&&128067>=a||128070<=a&&128080>=a||128110==a||128112<=a&&128120>=a||128124==a||128129<=a&&128131>=a||128133<=a&&128135>=a||128170==a||128372<=a&&128373>=a||128378==a||128400==a||128405<=a&&128406>=a||128581<=a&&128583>=a||128587<=a&&128591>=a||128675==a||128692<=a&&128694>=a||128704==a||128716==a||129304<=a&&129308>=a||129310<=a&&129311>=a||129318==a||129328<=a&&129337>=a||129341<=a&&129342>=a||
+129489<=a&&129501>=a?13:127995<=a&&127999>=a?14:8205==a?15:9792==a||9794==a||9877<=a&&9878>=a||9992==a||10084==a||127752==a||127806==a||127859==a||127891==a||127908==a||127912==a||127979==a||127981==a||128139==a||128187<=a&&128188>=a||128295==a||128300==a||128488==a||128640==a||128658==a?16:128102<=a&&128105>=a?17:11}this.nextBreak=function(a,c){void 0===c&&(c=0);if(0>c)return 0;if(c>=a.length-1)return a.length;var b=k(h(a,c)),d=[];for(c+=1;c=e.charCodeAt(g)&&56320<=e.charCodeAt(g+1)&&57343>=e.charCodeAt(g+1))){e=k(h(a,c));if(l(b,d,e))return c;d.push(e)}}return a.length};this.splitGraphemes=function(a){for(var c=[],b=0,d;(d=this.nextBreak(a,b))=0&&s<=1&&t>=0&&t<=1}function triangleArea(a,b,c){return(b[0]-a[0])*(c[1]-a[1])-(c[0]-a[0])*(b[1]-a[1])}function isLeft(a,b,c){return triangleArea(a,b,c)>0}function isLeftOn(a,b,c){return triangleArea(a,b,c)>=0}
+function isRight(a,b,c){return triangleArea(a,b,c)<0}function isRightOn(a,b,c){return triangleArea(a,b,c)<=0}var tmpPoint1=[],tmpPoint2=[];
+function collinear(a,b,c,thresholdAngle){if(!thresholdAngle)return triangleArea(a,b,c)===0;else{var ab=tmpPoint1,bc=tmpPoint2;ab[0]=b[0]-a[0];ab[1]=b[1]-a[1];bc[0]=c[0]-b[0];bc[1]=c[1]-b[1];var dot=ab[0]*bc[0]+ab[1]*bc[1],magA=Math.sqrt(ab[0]*ab[0]+ab[1]*ab[1]),magB=Math.sqrt(bc[0]*bc[0]+bc[1]*bc[1]),angle=Math.acos(dot/(magA*magB));return anglev[br][0])br=i;if(!isLeft(polygonAt(polygon,br-1),polygonAt(polygon,br),polygonAt(polygon,br+1))){polygonReverse(polygon);return true}else return false}function polygonReverse(polygon){var tmp=[];var N=polygon.length;for(var i=0;i!==N;i++)tmp.push(polygon.pop());for(var i=0;i!==N;i++)polygon[i]=tmp[i]}
+function polygonIsReflex(polygon,i){return isRight(polygonAt(polygon,i-1),polygonAt(polygon,i),polygonAt(polygon,i+1))}var tmpLine1=[],tmpLine2=[];
+function polygonCanSee(polygon,a,b){var p,dist,l1=tmpLine1,l2=tmpLine2;if(isLeftOn(polygonAt(polygon,a+1),polygonAt(polygon,a),polygonAt(polygon,b))&&isRightOn(polygonAt(polygon,a-1),polygonAt(polygon,a),polygonAt(polygon,b)))return false;dist=sqdist(polygonAt(polygon,a),polygonAt(polygon,b));for(var i=0;i!==polygon.length;++i){if((i+1)%polygon.length===a||i===a)continue;if(isLeftOn(polygonAt(polygon,a),polygonAt(polygon,b),polygonAt(polygon,i+1))&&isRightOn(polygonAt(polygon,a),polygonAt(polygon,
+b),polygonAt(polygon,i))){l1[0]=polygonAt(polygon,a);l1[1]=polygonAt(polygon,b);l2[0]=polygonAt(polygon,i);l2[1]=polygonAt(polygon,i+1);p=lineInt(l1,l2);if(sqdist(polygonAt(polygon,a),p)0)return polygonSlice(polygon,edges);else return[polygon]}
+function polygonSlice(polygon,cutEdges){if(cutEdges.length===0)return[polygon];if(cutEdges instanceof Array&&cutEdges.length&&cutEdges[0]instanceof Array&&cutEdges[0].length===2&&cutEdges[0][0]instanceof Array){var polys=[polygon];for(var i=0;imaxlevel){console.warn("quickDecomp: max level ("+
+maxlevel+") reached.");return result}for(var i=0;iupperIndex)upperIndex+=polygon.length;
+closestDist=Number.MAX_VALUE;if(upperIndex3&&i>=0;--i)if(collinear(polygonAt(polygon,i-1),polygonAt(polygon,i),polygonAt(polygon,i+1),precision)){polygon.splice(i%polygon.length,1);num++}return num}
+function polygonRemoveDuplicatePoints(polygon,precision){for(var i=polygon.length-1;i>=1;--i){var pi=polygon[i];for(var j=i-1;j>=0;--j)if(points_eq(pi,polygon[j],precision)){polygon.splice(i,1);continue}}}function scalar_eq(a,b,precision){precision=precision||0;return Math.abs(a-b)<=precision}function points_eq(a,b,precision){return scalar_eq(a[0],b[0],precision)&&scalar_eq(a[1],b[1],precision)}
+self.polyDecomp={decomp:polygonDecomp,quickDecomp:polygonQuickDecomp,isSimple:polygonIsSimple,removeCollinearPoints:polygonRemoveCollinearPoints,removeDuplicatePoints:polygonRemoveDuplicatePoints,makeCCW:polygonMakeCCW};
+
+}
+
+// lib/c3.js
+{
+'use strict';let isReady=false;let hasAppStarted=false;let buildMode="dev";const C3=self.C3=class C3{constructor(){throw TypeError("static class can't be instantiated");}static SetReady(){isReady=true}static IsReady(){return isReady}static SetAppStarted(){hasAppStarted=true}static HasAppStarted(){return hasAppStarted}static SetBuildMode(m){buildMode=m}static GetBuildMode(){return buildMode}static IsReleaseBuild(){return buildMode==="final"}};C3.isDebug=false;C3.isDebugDefend=false;
+C3.hardwareConcurrency=navigator.hardwareConcurrency||2;self.C3X={};
+
+}
+
+// ../lib/queryParser.js
+{
+'use strict';const C3=self.C3;
+C3.QueryParser=class QueryParser{constructor(queryString){this._queryString=queryString;this._parameters=new Map;this._Parse()}_Parse(){let str=this._queryString;if(str.startsWith("?")||str.startsWith("#"))str=str.substr(1);const arr=str.split("&");for(const p of arr)this._ParseParameter(p)}_ParseParameter(p){if(!p)return;if(!p.includes("=")){this._parameters.set(p,null);return}const i=p.indexOf("=");const parameterName=decodeURIComponent(p.substring(0,i));const parameterValue=decodeURIComponent(p.substring(i+
+1));this._parameters.set(parameterName,parameterValue)}LogAll(){for(const e of this._parameters)console.log("[QueryParser] Parameter '"+e[0]+"' = "+(e[1]===null?"null":"'"+e[1]+"'"))}Has(name){return this._parameters.has(name)}Get(name){const ret=this._parameters.get(name);if(typeof ret==="undefined")return null;else return ret}ClearHash(){history.replaceState("",document.title,location.pathname+location.search)}Reparse(str){this._queryString=str;this._parameters.clear();this._Parse()}};
+C3.QueryString=new C3.QueryParser(location.search);C3.LocationHashString=new C3.QueryParser(location.hash);if(C3.QueryString.Has("perf"))C3.isPerformanceProfiling=true;if(C3.QueryString.Get("mode")!=="dev")C3.SetBuildMode("final");
+
+}
+
+// ../lib/detect/detect.js
+{
+'use strict';const C3=self.C3;const UNKNOWN="(unknown)";C3.Platform={OS:UNKNOWN,OSVersion:UNKNOWN,Browser:UNKNOWN,BrowserVersion:UNKNOWN,BrowserVersionNumber:NaN,BrowserEngine:UNKNOWN,Context:"browser",IsDesktop:true,IsMobile:false,IsAppleOS:false,IsIpadOS:false,GetDetailedInfo:async()=>{}};const windowsNTVerMap=new Map([[5,"2000"],[5.1,"XP"],[5.2,"XP"],[6,"Vista"],[6.1,"7"],[6.2,"8"],[6.3,"8.1"],[10,"10"]]);
+function GetWindowsNTVersionName(ntVer){const num=parseFloat(ntVer);const ret=windowsNTVerMap.get(num);if(ret)return ret;if(num>=13)return"11";return"NT "+ntVer}const uaStr=navigator.userAgent;const uaData=navigator["userAgentData"];
+if(uaData&&uaData["brands"].length>0){C3.Platform.OS=uaData["platform"];C3.Platform.IsMobile=uaData["mobile"];C3.Platform.IsDesktop=!C3.Platform.IsMobile;const RECOGNIZED_BROWSERS=new Map([["Google Chrome","Chrome"],["Microsoft Edge","Edge"],["Opera","Opera"],["Opera GX","Opera GX"],["Mozilla Firefox","Firefox"],["Apple Safari","Safari"],["NW.js","NW.js"]]);const RECOGNIZED_ENGINES=new Map([["Chromium","Chromium"],["Gecko","Gecko"],["WebKit","WebKit"]]);function ReadBrandList(brands){let browser=
+"";let browser_version="";let engine="";let engine_version="";for(const o of brands){const recognizedBrowser=RECOGNIZED_BROWSERS.get(o["brand"]);if(!browser&&recognizedBrowser){browser=recognizedBrowser;browser_version=o["version"]}const recognizedEngine=RECOGNIZED_ENGINES.get(o["brand"]);if(!engine&&recognizedEngine){engine=recognizedEngine;engine_version=o["version"]}}if(!browser&&engine==="Chromium"){C3.Platform.Browser="Chromium";C3.Platform.BrowserVersion=engine_version}C3.Platform.Browser=browser||
+UNKNOWN;C3.Platform.BrowserVersion=browser_version||UNKNOWN;C3.Platform.BrowserEngine=engine||UNKNOWN}ReadBrandList(uaData["brands"]);let didGetDetailedInfo=false;C3.Platform.GetDetailedInfo=async()=>{if(didGetDetailedInfo)return;try{const details=await navigator["userAgentData"]["getHighEntropyValues"](["platformVersion","fullVersionList"]);ReadBrandList(details["fullVersionList"]);if(C3.Platform.OS==="Windows")C3.Platform.OSVersion=GetWindowsNTVersionName(details["platformVersion"]);else C3.Platform.OSVersion=
+details["platformVersion"];didGetDetailedInfo=true}catch(err){console.warn("Failed to get detailed user agent information: ",err)}}}else{function RunTest(regex_or_arr,handler){const arr=Array.isArray(regex_or_arr)?regex_or_arr:[regex_or_arr];for(const regex of arr){const result=regex.exec(uaStr);if(result){handler(result);break}}}RunTest(/windows\s+nt\s+([\d\.]+)/i,result=>{C3.Platform.OS="Windows";const ntVer=result[1];C3.Platform.OSVersion=GetWindowsNTVersionName(ntVer)});RunTest(/mac\s+os\s+x\s+([\d\._]+)/i,
+result=>{C3.Platform.OS="macOS";C3.Platform.OSVersion=result[1].replace(/_/g,".")});RunTest(/CrOS/,()=>{C3.Platform.OS="Chrome OS"});RunTest(/linux|openbsd|freebsd|netbsd/i,()=>{C3.Platform.OS="Linux"});RunTest(/android/i,()=>{C3.Platform.OS="Android"});RunTest(/android\s+([\d\.]+)/i,result=>{C3.Platform.OS="Android";C3.Platform.OSVersion=result[1]});if(C3.Platform.OS===UNKNOWN){RunTest(/(iphone|ipod|ipad)/i,result=>{C3.Platform.OS="iOS"});RunTest([/iphone\s+os\s+([\d\._]+)/i,/ipad[^)]*os\s+([\d\._]+)/i],
+result=>{C3.Platform.OS="iOS";C3.Platform.OSVersion=result[1].replace(/_/g,".")})}const hasChrome=/chrome\//i.test(uaStr);const hasChromium=/chromium\//i.test(uaStr);const hasEdge=/edg\//i.test(uaStr);const hasOpera=/OPR\//.test(uaStr);const hasNWjs=/nwjs/i.test(uaStr);const hasSafari=/safari\//i.test(uaStr);const hasWebKit=/webkit/i.test(uaStr);if(!hasEdge&&!hasOpera)RunTest(/chrome\/([\d\.]+)/i,result=>{C3.Platform.Browser="Chrome";C3.Platform.BrowserVersion=result[1];C3.Platform.BrowserEngine=
+"Chromium"});RunTest(/edg\/([\d\.]+)/i,result=>{C3.Platform.Browser="Edge";C3.Platform.BrowserVersion=result[1];C3.Platform.BrowserEngine="Chromium"});RunTest(/OPR\/([\d\.]+)/,result=>{C3.Platform.Browser="Opera";C3.Platform.BrowserVersion=result[1];C3.Platform.BrowserEngine="Chromium"});RunTest(/chromium\/([\d\.]+)/i,result=>{C3.Platform.Browser="Chromium";C3.Platform.BrowserVersion=result[1];C3.Platform.BrowserEngine="Chromium"});RunTest(/nwjs\/[0-9.]+/i,result=>{C3.Platform.Browser="NW.js";C3.Platform.BrowserVersion=
+result[1];C3.Platform.BrowserEngine="Chromium";C3.Platform.Context="nwjs"});RunTest(/firefox\/([\d\.]+)/i,result=>{C3.Platform.Browser="Firefox";C3.Platform.BrowserVersion=result[1];C3.Platform.BrowserEngine="Gecko"});if(hasSafari&&!hasChrome&&!hasChromium&&!hasEdge&&!hasOpera&&!hasNWjs){C3.Platform.Browser="Safari";C3.Platform.BrowserEngine="WebKit";RunTest(/version\/([\d\.]+)/i,result=>{C3.Platform.BrowserVersion=result[1]});RunTest(/crios\/([\d\.]+)/i,result=>{C3.Platform.Browser="Chrome for iOS";
+C3.Platform.BrowserVersion=result[1]});RunTest(/fxios\/([\d\.]+)/i,result=>{C3.Platform.Browser="Firefox for iOS";C3.Platform.BrowserVersion=result[1]});RunTest(/edgios\/([\d\.]+)/i,result=>{C3.Platform.Browser="Edge for iOS";C3.Platform.BrowserVersion=result[1]})}if(C3.Platform.BrowserEngine===UNKNOWN&&hasWebKit)C3.Platform.BrowserEngine="WebKit";if(C3.Platform.OS==="Android"&&C3.Platform.Browser==="Safari")C3.Platform.Browser="Stock";const desktopOSs=new Set(["Windows","macOS","Linux","Chrome OS"]);
+const isDesktop=desktopOSs.has(C3.Platform.OS)||C3.Platform.Context==="nwjs";C3.Platform.IsDesktop=isDesktop;C3.Platform.IsMobile=!isDesktop}if(C3.Platform.Browser==="Chrome"&&C3.Platform.Context==="browser"&&/wv\)/.test(uaStr))C3.Platform.Context="webview";if(C3.Platform.Context!=="nwjs"&&typeof window!=="undefined"&&(window.matchMedia&&window.matchMedia("(display-mode: standalone)").matches||navigator["standalone"]))C3.Platform.Context="webapp";C3.Platform.BrowserVersionNumber=parseFloat(C3.Platform.BrowserVersion);
+const looksLikeIPadOS=C3.Platform.OS==="macOS"&&navigator["maxTouchPoints"]&&navigator["maxTouchPoints"]>2;if(looksLikeIPadOS){C3.Platform.OS="iOS";C3.Platform.OSVersion=C3.Platform.BrowserVersion;C3.Platform.IsDesktop=false;C3.Platform.IsMobile=true;C3.Platform.IsIpadOS=true}C3.Platform.IsAppleOS=C3.Platform.OS==="macOS"||C3.Platform.OS==="iOS";
+
+}
+
+// ../lib/storage/kvStorage.js
+{
+'use strict';{const VERSION=2;const STORE_NAME="keyvaluepairs";const DATABASE_PROMISE_MAP=new Map;const SUPPORTS_GETALL=typeof IDBObjectStore!=="undefined"&&typeof IDBObjectStore.prototype.getAll==="function";const SUPPORTS_GETALLKEYS=typeof IDBObjectStore!=="undefined"&&typeof IDBObjectStore.prototype.getAllKeys==="function";function asyncifyRequest(request){return new Promise((res,rej)=>{request.onsuccess=()=>res(request.result);request.onerror=()=>rej(request.error)})}function asyncifyTransaction(tx){return new Promise((res,
+rej)=>{tx.oncomplete=()=>res();tx.onerror=()=>rej(tx.error);tx.onabort=()=>rej(tx.error)})}function openReadOnlyTransaction(name,method){return openTransaction(name,method)}function openWriteTransaction(name,method){return openTransaction(name,method,true)}async function openTransaction(name,method,write=false,allowRetry=true){const db=await lazyOpenDatabase(name);try{const tx=db.transaction([STORE_NAME],write?"readwrite":"readonly");return method(tx)}catch(err){if(allowRetry&&err["name"]==="InvalidStateError"){DATABASE_PROMISE_MAP.delete(name);
+return openTransaction(name,method,write,false)}else throw err;}}function lazyOpenDatabase(name){RequireString(name);let dbPromise=DATABASE_PROMISE_MAP.get(name);if(!(dbPromise instanceof Promise)){dbPromise=openDatabase(name);DATABASE_PROMISE_MAP.set(name,dbPromise);dbPromise.catch(err=>DATABASE_PROMISE_MAP.delete(name))}return dbPromise}async function openDatabase(name){RequireString(name);const openRequest=indexedDB.open(name,VERSION);openRequest.addEventListener("upgradeneeded",e=>{try{const db=
+e.target.result;db.createObjectStore(STORE_NAME)}catch(err){console.error(`Failed to create objectstore for database ${name}`,err)}});return asyncifyRequest(openRequest)}function RequireString(x){if(typeof x!=="string")throw new TypeError("expected string");}function getEntriesFromCursor(tx,type){const request=tx.objectStore(STORE_NAME).openCursor();return new Promise(resolve=>{const results=[];request.onsuccess=event=>{const cursor=event.target.result;if(cursor){switch(type){case "entries":results.push([cursor.key,
+cursor.value]);break;case "keys":results.push(cursor.key);break;case "values":results.push(cursor.value);break}cursor.continue()}else resolve(results)}})}class KVStorageContainer{constructor(name){RequireString(name);this.name=name}async ready(){await lazyOpenDatabase(this.name)}set(key,value){RequireString(key);return openWriteTransaction(this.name,async tx=>{const request=tx.objectStore(STORE_NAME).put(value,key);const requestPromise=asyncifyRequest(request);const txPromise=asyncifyTransaction(tx);
+await Promise.all([txPromise,requestPromise])})}get(key){RequireString(key);return openReadOnlyTransaction(this.name,async tx=>{const request=tx.objectStore(STORE_NAME).get(key);const requestPromise=asyncifyRequest(request);const txPromise=asyncifyTransaction(tx);const [_,value]=await Promise.all([txPromise,requestPromise]);return value})}delete(key){RequireString(key);return openWriteTransaction(this.name,async tx=>{const request=tx.objectStore(STORE_NAME).delete(key);const requestPromise=asyncifyRequest(request);
+const txPromise=asyncifyTransaction(tx);await Promise.all([txPromise,requestPromise])})}clear(){return openWriteTransaction(this.name,async tx=>{const request=tx.objectStore(STORE_NAME).clear();const requestPromise=asyncifyRequest(request);const txPromise=asyncifyTransaction(tx);await Promise.all([txPromise,requestPromise])})}keys(){return openReadOnlyTransaction(this.name,async tx=>{let requestPromise;if(SUPPORTS_GETALLKEYS){const request=tx.objectStore(STORE_NAME).getAllKeys();requestPromise=asyncifyRequest(request)}else requestPromise=
+getEntriesFromCursor(tx,"keys");const txPromise=asyncifyTransaction(tx);const [_,value]=await Promise.all([txPromise,requestPromise]);return value})}values(){return openReadOnlyTransaction(this.name,async tx=>{let requestPromise;if(SUPPORTS_GETALL){const request=tx.objectStore(STORE_NAME).getAll();requestPromise=asyncifyRequest(request)}else requestPromise=getEntriesFromCursor(tx,"values");const txPromise=asyncifyTransaction(tx);const [_,value]=await Promise.all([txPromise,requestPromise]);return value})}entries(){return openReadOnlyTransaction(this.name,
+async tx=>{const requestPromise=getEntriesFromCursor(tx,"entries");const txPromise=asyncifyTransaction(tx);const [_,value]=await Promise.all([txPromise,requestPromise]);return value})}}self.KVStorageContainer=KVStorageContainer};
+
+}
+
+// ../lib/storage/localForageAdaptor.js
+{
+'use strict';{const KVStorageContainer=self.KVStorageContainer;const CRITICAL_ERRORS=[/no available storage method found/i,/an attempt was made to break through the security policy of the user agent/i,/the user denied permission to access the database/i,/a mutation operation was attempted on a database that did not allow mutations/i,/idbfactory\.open\(\) called in an invalid security context/i];const memoryStorage=new WeakMap;let isInMemory=false;if(typeof indexedDB==="undefined"){isInMemory=true;
+console.warn("Unable to use local storage because indexedDB is not defined")}function NOT_IMPLEMENTED(name){throw new Error(`"${name}" is not implemented`);}function DISALLOW_CALLBACK(fn){if(typeof fn==="function")throw new Error(`localforage callback API is not implemented; please use the promise API instead`);}function StructuredClone(value){if(typeof value==="object")return new Promise(resolve=>{const {port1,port2}=new MessageChannel;port2.onmessage=ev=>resolve(ev.data);port1.postMessage(value)});
+else return Promise.resolve(value)}class ForageAdaptor{constructor(inst){this._inst=inst;memoryStorage.set(this,new Map)}_MaybeSwitchToMemoryFallback(err){if(isInMemory)return;for(const regex of CRITICAL_ERRORS)if(err&®ex.test(err.message)){console.error("Unable to use local storage, reverting to in-memory store: ",err,err.message);isInMemory=true;break}}async _getItemFallback(name){const value=memoryStorage.get(this).get(name);const ret=await StructuredClone(value);return typeof ret==="undefined"?
+null:ret}async _setItemFallback(name,value){value=await StructuredClone(value);memoryStorage.get(this).set(name,value)}_removeItemFallback(name){memoryStorage.get(this).delete(name)}_clearFallback(){memoryStorage.get(this).clear()}_keysFallback(){return Array.from(memoryStorage.get(this).keys())}IsUsingFallback(){return isInMemory}async getItem(key,successCallback){DISALLOW_CALLBACK(successCallback);if(isInMemory)return await this._getItemFallback(key);let result;try{result=await this._inst.get(key)}catch(err){this._MaybeSwitchToMemoryFallback(err);
+if(isInMemory)return await this._getItemFallback(key);else{console.error(`Error reading '${key}' from storage, returning null: `,err);return null}}return typeof result==="undefined"?null:result}async setItem(key,value,successCallback){DISALLOW_CALLBACK(successCallback);if(typeof value==="undefined")value=null;if(isInMemory){await this._setItemFallback(key,value);return}try{await this._inst.set(key,value)}catch(err){this._MaybeSwitchToMemoryFallback(err);if(isInMemory)await this._setItemFallback(key,
+value);else throw err;}}async removeItem(key,successCallback){DISALLOW_CALLBACK(successCallback);if(isInMemory){this._removeItemFallback(key);return}try{await this._inst.delete(key)}catch(err){this._MaybeSwitchToMemoryFallback(err);if(isInMemory)this._removeItemFallback(key);else console.error(`Error removing '${key}' from storage: `,err)}}async clear(successCallback){DISALLOW_CALLBACK(successCallback);if(isInMemory){this._clearFallback();return}try{await this._inst.clear()}catch(err){this._MaybeSwitchToMemoryFallback(err);
+if(isInMemory)this._clearFallback();else console.error(`Error clearing storage: `,err)}}async keys(successCallback){DISALLOW_CALLBACK(successCallback);if(isInMemory)return this._keysFallback();let result=[];try{result=await this._inst.keys()}catch(err){this._MaybeSwitchToMemoryFallback(err);if(isInMemory)return this._keysFallback();else console.error(`Error getting storage keys: `,err)}return result}ready(successCallback){DISALLOW_CALLBACK(successCallback);if(isInMemory)return Promise.resolve(true);
+else return this._inst.ready()}createInstance(options){if(typeof options!=="object")throw new TypeError("invalid options object");const name=options["name"];if(typeof name!=="string")throw new TypeError("invalid store name");const inst=new KVStorageContainer(name);return new ForageAdaptor(inst)}length(successCallback){NOT_IMPLEMENTED("localforage.length()")}key(index,successCallback){NOT_IMPLEMENTED("localforage.key()")}iterate(iteratorCallback,successCallback){NOT_IMPLEMENTED("localforage.iterate()")}setDriver(driverName){NOT_IMPLEMENTED("localforage.setDriver()")}config(options){NOT_IMPLEMENTED("localforage.config()")}defineDriver(customDriver){NOT_IMPLEMENTED("localforage.defineDriver()")}driver(){NOT_IMPLEMENTED("localforage.driver()")}supports(driverName){NOT_IMPLEMENTED("localforage.supports()")}dropInstance(){NOT_IMPLEMENTED("localforage.dropInstance()")}disableMemoryMode(){isInMemory=
+false}}self["localforage"]=new ForageAdaptor(new KVStorageContainer("localforage"))};
+
+}
+
+// ../lib/misc/supports.js
+{
+'use strict';const C3=self.C3;C3.Supports={};C3.Supports.WebAnimations=(()=>{try{if(typeof document==="undefined")return false;const e=document.createElement("div");if(typeof e.animate==="undefined")return false;const player=e.animate([{opacity:"0"},{opacity:"1"}],1E3);return typeof player.reverse!=="undefined"}catch(e){return false}})();C3.Supports.DialogElement=typeof HTMLDialogElement!=="undefined";C3.Supports.RequestIdleCallback=!!self.requestIdleCallback;C3.Supports.ImageBitmap=!!self.createImageBitmap;
+C3.Supports.ImageBitmapOptions=false;C3.Supports.ImageBitmapOptionsResize=false;
+if(C3.Supports.ImageBitmap){try{self.createImageBitmap(new ImageData(32,32),{"premultiplyAlpha":"none"}).then(()=>{C3.Supports.ImageBitmapOptions=true}).catch(()=>{C3.Supports.ImageBitmapOptions=false})}catch(err){C3.Supports.ImageBitmapOptions=false}try{self.createImageBitmap(new ImageData(32,32),{"resizeWidth":10,"resizeHeight":10}).then(imageBitmap=>{C3.Supports.ImageBitmapOptionsResize=imageBitmap.width===10&&imageBitmap.height===10}).catch(()=>{C3.Supports.ImageBitmapOptionsResize=false})}catch(err){C3.Supports.ImageBitmapOptionsResize=
+false}}C3.Supports.ClipboardReadText=!!(navigator["clipboard"]&&navigator["clipboard"]["readText"]&&C3.Platform.Browser!=="Firefox");C3.Supports.PermissionsQuery=!!(navigator["permissions"]&&navigator["permissions"]["query"]);C3.Supports.ClipboardPermissionsQuery=false;if(C3.Supports.PermissionsQuery){const permission={"name":"clipboard-read"};navigator["permissions"]["query"](permission).then(()=>{C3.Supports.ClipboardPermissionsQuery=true}).catch(()=>{C3.Supports.ClipboardPermissionsQuery=false})}
+C3.Supports.AsyncClipboardApi=!!(navigator["permissions"]&&navigator["clipboard"]&&self["ClipboardItem"]);C3.Supports.Proxies=typeof Proxy!=="undefined";C3.Supports.DownloadAttribute=(()=>{if(typeof document==="undefined")return false;const a=document.createElement("a");return typeof a.download!=="undefined"})();C3.Supports.Fetch=typeof fetch==="function";C3.Supports.PersistentStorage=!!(self.isSecureContext&&C3.Platform.Browser!=="Opera"&&(navigator["storage"]&&navigator["storage"]["persist"]));
+C3.Supports.StorageQuotaEstimate=!!(self.isSecureContext&&(navigator["storage"]&&navigator["storage"]["estimate"]));C3.Supports.Fullscreen=(()=>{if(typeof document==="undefined")return false;if(C3.Platform.OS==="iOS")return false;const elem=document.documentElement;return!!(elem.requestFullscreen||elem.msRequestFullscreen||elem.mozRequestFullScreen||elem.webkitRequestFullscreen)})();C3.Supports.ImageDecoder=typeof self["ImageDecoder"]!=="undefined";C3.Supports.WebCodecs=!!self["VideoEncoder"];
+C3.Supports.NativeFileSystemAPI=!!self["showOpenFilePicker"];C3.Supports.QueryLocalFonts=!!self["queryLocalFonts"];C3.Supports.UserActivation=!!navigator["userActivation"];C3.Supports.CanvasToBlobWebP=false;
+(async()=>{let canvas;if(typeof document==="undefined")canvas=new OffscreenCanvas(32,32);else{canvas=document.createElement("canvas");canvas.width=32;canvas.height=32}const ctx=canvas.getContext("2d");ctx.fillStyle="blue";ctx.fillRect(0,0,32,32);let blob=null;try{if(canvas["convertToBlob"])blob=await canvas["convertToBlob"]({"type":"image/webp","quality":1});else if(canvas.toBlob)blob=await new Promise(resolve=>canvas.toBlob(resolve,"image/webp",1));C3.Supports.CanvasToBlobWebP=blob&&blob.type===
+"image/webp"}catch(err){C3.Supports.CanvasToBlobWebP=false}})();
+
+}
+
+// ../lib/misc/polyfills.js
+{
+'use strict';const C3=self.C3;if(!String.prototype.trimStart){const startWhitespace=/^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]*/;String.prototype.trimStart=function trimStart(){return this.replace(startWhitespace,"")}}
+if(!String.prototype.trimEnd){const endWhitespace=/[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]*$/;String.prototype.trimEnd=function trimEnd(){return this.replace(endWhitespace,"")}}if(!String.prototype.replaceAll)String.prototype.replaceAll=function replaceAll(find,replace){return this.replace(new RegExp(C3.EscapeRegex(find),"g"),replace)};if(!Array.prototype.values)Array.prototype.values=function*(){for(const i of this)yield i};
+if(!Array.prototype.flat){function arrayFlat(arr,depth){return arr.reduce((acc,val)=>{if(depth>0&&Array.isArray(val)){Array.prototype.push.apply(acc,arrayFlat(val,depth-1));return acc}else{acc.push(val);return acc}},[])}Array.prototype.flat=function(depth=1){return arrayFlat(this,depth)}}if(!Array.prototype.at)Array.prototype.at=function at(n){n=Math.trunc(n)||0;if(n<0)n+=this.length;if(n<0||n>=this.length)return undefined;return this[n]};
+if(!String.prototype.at)String.prototype.at=function at(n){n=Math.trunc(n)||0;if(n<0)n+=this.length;if(n<0||n>=this.length)return undefined;return this[n]};if(!RegExp.escape)RegExp.escape=function(s){return String(s).replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")};
+if(navigator["storage"]&&!navigator["storage"]["estimate"]&&navigator["webkitTemporaryStorage"]&&navigator["webkitTemporaryStorage"]["queryUsageAndQuota"])navigator["storage"]["estimate"]=function(){return new Promise((resolve,reject)=>{return navigator["webkitTemporaryStorage"]["queryUsageAndQuota"]((usage,quota)=>resolve({"usage":usage,"quota":quota}),reject)})};if(typeof self.isSecureContext==="undefined")self.isSecureContext=location.protocol==="https:";
+if(typeof self["globalThis"]==="undefined")self["globalThis"]=self;
+
+}
+
+// lib/misc/assert.js
+{
+'use strict';const C3=self.C3;function assertFail(msg_){let stack=C3.GetCallStack();let msg="Assertion failure: "+msg_+"\n\nStack trace:\n"+stack;console.error(msg)}self.assert=function assert(cnd_,msg_){if(!cnd_)assertFail(msg_)};
+
+}
+
+// ../lib/misc/typeChecks.js
+{
+'use strict';const C3=self.C3;const C3X=self.C3X;C3.IsNumber=function IsNumber(x){return typeof x==="number"};C3.IsFiniteNumber=function IsFiniteNumber(x){return C3.IsNumber(x)&&isFinite(x)};C3.RequireNumber=function RequireNumber(x){if(!C3.IsNumber(x))throw new TypeError("expected number");};C3.RequireOptionalNumber=function RequireOptionalNumber(x){if(C3.IsNullOrUndefined(x))return};
+C3.RequireNumberInRange=function RequireNumberInRange(x,low,high){if(!C3.IsNumber(x)||isNaN(x)||low>x||high{console.log(`%c${name}`,"font-weight: bold",...args);logRafIds.set(name,-1)}))};let measures;
+C3.StartMeasure=function StartMeasure(name){performance.mark(name);if(!measures)measures=new Map;if(!measures.has(name))measures.set(name,{current:0,total:0,average:0,calls:1,toString:function(){return`${name} :: current => ${this.current.toPrecision(3)} :: average => ${this.average.toPrecision(3)} :: calls => ${this.calls}`}})};
+C3.EndMeasure=function EndMeasure(name){performance.measure(`measure-${name}`,name);const entry=performance.getEntriesByName(`measure-${name}`)[0];const m=measures.get(name);m.current=entry.duration;m.total+=m.current;m.average=m.total/m.calls;console.log(m.toString());m.calls++;performance.clearMarks(name);performance.clearMeasures(`measure-${name}`)};C3.GetCallStack=function GetCallStack(){return(new Error).stack};C3.Debugger=function Debugger(){debugger};
+C3.cast=function cast(o,T){if(o&&o instanceof T)return o;else return null};
+C3.getName=function getName(o){if(typeof o==="undefined")return"undefined";if(o===null)return"null";if(typeof o==="boolean")return"";if(C3.IsNumber(o))return"";if(C3.IsString(o))return"";if(C3.IsArray(o))return"";if(typeof o==="symbol")return"<"+o.toString()+">";if(C3.IsFunction(o)){if(o.name&&o.name!=="Function")return o.name;return""}if(typeof o==="object"){if(o.constructor&&o.constructor.name&&o.constructor.name!=="Object")return o.constructor.name;
+return""}return""};C3.getType=function getType(o){if(o===null)return"null";if(Array.isArray(o))return"array";return typeof o};C3.range=function*range(a,b){if(!isFinite(Math.abs(a-b)))throw new Error("Invalid parameters");if(a>b)for(let i=a-1;i>=b;i--)yield i;else for(let i=a;i0||ctorProxyToObject.size>0){let uniqueNames=new Set([...ctorObjectToProxy.keys()].map(o=>C3.getName(o)));let leftoverNames=[...uniqueNames].join(",");console.warn(`An object derived from DefendedBase was not protected with debugDefend(). This will disable some checks. See the coding guidelines! Possible affected class names: ${leftoverNames}`);ctorObjectToProxy.clear();ctorProxyToObject.clear()}}
+C3.DefendedBase=class DefendedBase{constructor(){if(!C3.isDebugDefend||!C3.Supports.Proxies)return;let newTarget=new.target;let realObject=Object.create(newTarget.prototype);let proxy=new Proxy(realObject,C3.DefendHandler);ctorObjectToProxy.set(realObject,proxy);ctorProxyToObject.set(proxy,realObject);proxyToObject.set(proxy,realObject);if(checkRafId===-1)checkRafId=requestAnimationFrame(CheckDefendedObjectsUsedCorrectly);return proxy}};
+C3.debugDefend=function debugDefend(o){if(C3.isDebugDefend&&C3.Supports.Proxies&&o instanceof C3.DefendedBase){if(!ctorProxyToObject.has(o))return o;let realObject=ctorProxyToObject.get(o);ctorProxyToObject.delete(o);ctorObjectToProxy.delete(realObject);return o}else if(C3.isDebug)return Object.seal(o);else return o};
+C3.New=function New(Type,...args){let o;try{o=new Type(...args)}catch(e){ctorProxyToObject.clear();ctorObjectToProxy.clear();throw e;}if(C3.isDebugDefend)VerifyObjectPropertiesConsistent(Type,o);return C3.debugDefend(o)};C3.Release=function Release(o){let realObject=proxyToObject.get(o);if(realObject)releasedObjects.set(realObject,C3.GetCallStack())};C3.WasReleased=function(o){let realObject=proxyToObject.get(o);if(!realObject)return false;return!!releasedObjects.get(realObject)};
+let typeProperties=new Map;function getObjectPropertySet(o){let ret=new Set;for(let k in o)ret.add(k);return ret}
+function VerifyObjectPropertiesConsistent(Type,o){let properties=getObjectPropertySet(o);let existingProperties=typeProperties.get(Type);if(existingProperties){let inconsistentProperties=[];for(let k of existingProperties.values())if(properties.has(k))properties.delete(k);else inconsistentProperties.push(k);C3.appendArray(inconsistentProperties,[...properties]);if(inconsistentProperties.length)console.warn(`[Defence] '${C3.getName(Type)}' constructor creates inconsistent properties: ${inconsistentProperties.join(", ")}`)}else typeProperties.set(Type,properties)}
+C3.PerfMark=class PerfMark{constructor(name){this._name="";if(name)this.start(name)}start(name){if(!C3.isPerformanceProfiling)return;this._name=name;performance.mark(this._name+"-Start")}end(){if(!C3.isPerformanceProfiling)return;performance.mark(this._name+"-End");performance.measure(this._name,this._name+"-Start",this._name+"-End")}next(name){if(!C3.isPerformanceProfiling)return;this.end();this._name=name;performance.mark(this._name+"-Start")}};
+
+}
+
+// ../lib/misc/mathutil.js
+{
+'use strict';const C3=self.C3;const TWO_PI=Math.PI*2;const D_TO_R=Math.PI/180;const R_TO_D=180/Math.PI;C3.wrap=function wrap(x,min,max){x=Math.floor(x);min=Math.floor(min);max=Math.floor(max);const diff=max-min;if(diff===0)return max;if(xb)return b;else return x};C3.clampAngle=function clampAngle(a){a%=TWO_PI;if(a<0)a+=TWO_PI;return a};C3.toRadians=function toRadians(x){return x*D_TO_R};C3.toDegrees=function toDegrees(x){return x*R_TO_D};C3.distanceTo=function distanceTo(x1,y1,x2,y2){return Math.hypot(x2-x1,y2-y1)};
+C3.distanceSquared=function distanceSquared(x1,y1,x2,y2){const dx=x2-x1;const dy=y2-y1;return dx*dx+dy*dy};C3.angleTo=function angleTo(x1,y1,x2,y2){return Math.atan2(y2-y1,x2-x1)};C3.angleDiff=function angleDiff(a1,a2){if(a1===a2)return 0;let s1=Math.sin(a1);let c1=Math.cos(a1);let s2=Math.sin(a2);let c2=Math.cos(a2);let n=s1*s2+c1*c2;if(n>=1)return 0;if(n<=-1)return Math.PI;return Math.acos(n)};
+C3.angleRotate=function angleRotate(start,end,step){let ss=Math.sin(start);let cs=Math.cos(start);let se=Math.sin(end);let ce=Math.cos(end);if(Math.acos(ss*se+cs*ce)>step)if(cs*se-ss*ce>0)return C3.clampAngle(start+step);else return C3.clampAngle(start-step);else return C3.clampAngle(end)};C3.angleClockwise=function angleClockwise(a1,a2){let s1=Math.sin(a1);let c1=Math.cos(a1);let s2=Math.sin(a2);let c2=Math.cos(a2);return c1*s2-s1*c2<=0};
+C3.angleLerp=function angleLerp(a,b,x,r=0){let diff=C3.angleDiff(a,b);const revs=TWO_PI*r;if(C3.angleClockwise(b,a))return C3.clampAngle(a+(diff+revs)*x);else return C3.clampAngle(a-(diff+revs)*x)};C3.angleLerpClockwise=function angleLerpClockwise(a,b,x,r=0){const diff=C3.angleDiff(a,b);const revs=TWO_PI*r;if(C3.angleClockwise(b,a))return C3.clampAngle(a+(diff+revs)*x);return C3.clampAngle(a+(TWO_PI-diff+revs)*x)};
+C3.angleLerpAntiClockwise=function angleLerpAntiClockwise(a,b,x,r=0){const diff=C3.angleDiff(a,b);const revs=TWO_PI*r;if(C3.angleClockwise(b,a))return C3.clampAngle(a-(-TWO_PI+diff-revs)*x);return C3.clampAngle(a-(diff+revs)*x)};C3.angleReflect=function angleReflect(a,b){const diff=C3.angleDiff(a,b);if(C3.angleClockwise(a,b))return C3.clampAngle(b-diff);else return C3.clampAngle(b+diff)};C3.lerp=function lerp(a,b,x){return a+x*(b-a)};
+C3.unlerp=function unlerp(a,b,x){if(a===b)return 0;return(x-a)/(b-a)};C3.relerp=function relerp(a,b,x,c,d){return C3.lerp(c,d,C3.unlerp(a,b,x))};C3.qarp=function qarp(a,b,c,x){return C3.lerp(C3.lerp(a,b,x),C3.lerp(b,c,x),x)};C3.cubic=function cubic(a,b,c,d,x){return C3.lerp(C3.qarp(a,b,c,x),C3.qarp(b,c,d,x),x)};C3.cosp=function cosp(a,b,x){return(a+b+(a-b)*Math.cos(x*Math.PI))/2};C3.isPOT=function isPOT(x){return x>0&&(x-1&x)===0};
+C3.nextHighestPowerOfTwo=function nextHighestPowerOfTwo(x){--x;for(let i=1;i<32;i<<=1)x=x|x>>i;return x+1};C3.roundToNearestFraction=function roundToNearestFraction(x,n){return Math.round(x*n)/n};C3.floorToNearestFraction=function floorToNearestFraction(x,n){return Math.floor(x*n)/n};C3.roundToDp=function roundToDp(x,dp){dp=Math.max(Math.floor(dp),0);const m=Math.pow(10,dp);return Math.round(x*m)/m};
+C3.countDecimals=function countDecimals(value){if(Math.floor(value)!==value)return value.toString().split(".")[1].length||0;return 0};C3.toFixed=function toFixed(n,dp){let ret=n.toFixed(dp);let last=ret.length-1;for(;last>=0&&ret.charAt(last)==="0";--last);if(last>=0&&ret.charAt(last)===".")--last;if(last<0)return ret;return ret.substr(0,last+1)};C3.PackRGB=function PackRGB(red,green,blue){return C3.clamp(red,0,255)|C3.clamp(green,0,255)<<8|C3.clamp(blue,0,255)<<16};const ALPHAEX_SHIFT=1024;
+const ALPHAEX_MAX=1023;const RGBEX_SHIFT=16384;const RGBEX_MAX=8191;const RGBEX_MIN=-8192;
+C3.PackRGBAEx=function PackRGBAEx(red,green,blue,alpha){red=C3.clamp(Math.floor(red*1024),RGBEX_MIN,RGBEX_MAX);green=C3.clamp(Math.floor(green*1024),RGBEX_MIN,RGBEX_MAX);blue=C3.clamp(Math.floor(blue*1024),RGBEX_MIN,RGBEX_MAX);alpha=C3.clamp(Math.floor(alpha*ALPHAEX_MAX),0,ALPHAEX_MAX);if(red<0)red+=RGBEX_SHIFT;if(green<0)green+=RGBEX_SHIFT;if(blue<0)blue+=RGBEX_SHIFT;return-(red*RGBEX_SHIFT*RGBEX_SHIFT*ALPHAEX_SHIFT+green*RGBEX_SHIFT*ALPHAEX_SHIFT+blue*ALPHAEX_SHIFT+alpha)};
+C3.PackRGBEx=function PackRGBEx(red,green,blue){return C3.PackRGBAEx(red,green,blue,1)};function isNegativeZero(x){return x===0&&1/x<0}C3.GetRValue=function GetRValue(rgb){if(rgb>=0)return(rgb&255)/255;else{let v=Math.floor(-rgb/(RGBEX_SHIFT*RGBEX_SHIFT*ALPHAEX_SHIFT));if(v>RGBEX_MAX)v-=RGBEX_SHIFT;return v/1024}};
+C3.GetGValue=function GetGValue(rgb){if(rgb>=0)return((rgb&65280)>>8)/255;else{let v=Math.floor(-rgb%(RGBEX_SHIFT*RGBEX_SHIFT*ALPHAEX_SHIFT)/(RGBEX_SHIFT*ALPHAEX_SHIFT));if(v>RGBEX_MAX)v-=RGBEX_SHIFT;return v/1024}};C3.GetBValue=function GetBValue(rgb){if(rgb>=0)return((rgb&16711680)>>16)/255;else{let v=Math.floor(-rgb%(RGBEX_SHIFT*ALPHAEX_SHIFT)/ALPHAEX_SHIFT);if(v>RGBEX_MAX)v-=RGBEX_SHIFT;return v/1024}};
+C3.GetAValue=function GetAValue(rgb){if(isNegativeZero(rgb))return 0;else if(rgb>=0)return 1;else{const v=Math.floor(-rgb%ALPHAEX_SHIFT);return v/ALPHAEX_MAX}};C3.greatestCommonDivisor=function greatestCommonDivisor(a,b){a=Math.floor(a);b=Math.floor(b);while(b!==0){let t=b;b=a%b;a=t}return a};const COMMON_ASPECT_RATIOS=[[3,2],[4,3],[5,4],[5,3],[6,5],[14,9],[16,9],[16,10],[21,9]];
+C3.getAspectRatio=function getAspectRatio(w,h){w=Math.floor(w);h=Math.floor(h);if(w===h)return[1,1];for(let aspect of COMMON_ASPECT_RATIOS){let approxH=w/aspect[0]*aspect[1];if(Math.abs(h-approxH)<1)return aspect.slice(0);approxH=w/aspect[1]*aspect[0];if(Math.abs(h-approxH)<1)return[aspect[1],aspect[0]]}let gcd=C3.greatestCommonDivisor(w,h);return[w/gcd,h/gcd]};
+C3.segmentsIntersect=function segmentsIntersect(a1x,a1y,a2x,a2y,b1x,b1y,b2x,b2y){const min_ax=Math.min(a1x,a2x);const max_ax=Math.max(a1x,a2x);const min_bx=Math.min(b1x,b2x);const max_bx=Math.max(b1x,b2x);if(max_axmax_bx)return false;const min_ay=Math.min(a1y,a2y);const max_ay=Math.max(a1y,a2y);const min_by=Math.min(b1y,b2y);const max_by=Math.max(b1y,b2y);if(max_aymax_by)return false;const dpx=b1x-a1x+b2x-a2x;const dpy=b1y-a1y+b2y-a2y;const qax=a2x-a1x;const qay=a2y-
+a1y;const qbx=b2x-b1x;const qby=b2y-b1y;const d=Math.abs(qay*qbx-qby*qax);const la=qbx*dpy-qby*dpx;if(Math.abs(la)>d)return false;const lb=qax*dpy-qay*dpx;return Math.abs(lb)<=d};
+C3.segmentsIntersectPreCalc=function segmentsIntersectPreCalc(a1x,a1y,a2x,a2y,min_ax,max_ax,min_ay,max_ay,b1x,b1y,b2x,b2y){const min_bx=Math.min(b1x,b2x);const max_bx=Math.max(b1x,b2x);if(max_axmax_bx)return false;const min_by=Math.min(b1y,b2y);const max_by=Math.max(b1y,b2y);if(max_aymax_by)return false;const dpx=b1x-a1x+b2x-a2x;const dpy=b1y-a1y+b2y-a2y;const qax=a2x-a1x;const qay=a2y-a1y;const qbx=b2x-b1x;const qby=b2y-b1y;const d=Math.abs(qay*qbx-qby*qax);const la=
+qbx*dpy-qby*dpx;if(Math.abs(la)>d)return false;const lb=qax*dpy-qay*dpx;return Math.abs(lb)<=d};
+C3.segmentIntersectsQuad=function segmentIntersectsQuad(x1,y1,x2,y2,q){const min_x=Math.min(x1,x2);const max_x=Math.max(x1,x2);const min_y=Math.min(y1,y2);const max_y=Math.max(y1,y2);const tlx=q.getTlx(),tly=q.getTly(),trx=q.getTrx(),try_=q.getTry(),brx=q.getBrx(),bry=q.getBry(),blx=q.getBlx(),bly=q.getBly();return C3.segmentsIntersectPreCalc(x1,y1,x2,y2,min_x,max_x,min_y,max_y,tlx,tly,trx,try_)||C3.segmentsIntersectPreCalc(x1,y1,x2,y2,min_x,max_x,min_y,max_y,trx,try_,brx,bry)||C3.segmentsIntersectPreCalc(x1,
+y1,x2,y2,min_x,max_x,min_y,max_y,brx,bry,blx,bly)||C3.segmentsIntersectPreCalc(x1,y1,x2,y2,min_x,max_x,min_y,max_y,blx,bly,tlx,tly)};
+C3.segmentIntersectsAnyN=function segmentIntersectsAnyN(x1,y1,x2,y2,points){const min_x=Math.min(x1,x2);const max_x=Math.max(x1,x2);const min_y=Math.min(y1,y2);const max_y=Math.max(y1,y2);let i=0;for(let last=points.length-4;i<=last;i+=2)if(C3.segmentsIntersectPreCalc(x1,y1,x2,y2,min_x,max_x,min_y,max_y,points[i],points[i+1],points[i+2],points[i+3]))return true;return C3.segmentsIntersectPreCalc(x1,y1,x2,y2,min_x,max_x,min_y,max_y,points[i],points[i+1],points[0],points[1])};const NO_HIT=2;
+const PADDING=1E-6;C3.rayIntersect=function rayIntersect(rx1,ry1,rx2,ry2,sx1,sy1,sx2,sy2){const rdx=rx2-rx1;const rdy=ry2-ry1;const sdx=sx2-sx1;const sdy=sy2-sy1;const det=rdx*sdy-rdy*sdx;if(det===0)return NO_HIT;const gamma=((ry1-ry2)*(sx2-rx1)+rdx*(sy2-ry1))/det;if(0=0&&v>=0&&u+v<=1};
+C3.triangleCartesianToBarycentric=function triangleCartesianToBarycentric(px,py,tx1,ty1,tx2,ty2,tx3,ty3){const v0x=tx2-tx1;const v0y=ty2-ty1;const v1x=tx3-tx1;const v1y=ty3-ty1;const v2x=px-tx1;const v2y=py-ty1;const dot00=v0x*v0x+v0y*v0y;const dot01=v0x*v1x+v0y*v1y;const dot11=v1x*v1x+v1y*v1y;const dot20=v2x*v0x+v2y*v0y;const dot21=v2x*v1x+v2y*v1y;const denom=dot00*dot11-dot01*dot01;const v=(dot11*dot20-dot01*dot21)/denom;const w=(dot00*dot21-dot01*dot20)/denom;const u=1-v-w;return[u,v,w]};
+C3.triangleBarycentricToCartesian3d=function triangleBarycentricToCartesian3d(u,v,w,tx1,ty1,tz1,tx2,ty2,tz2,tx3,ty3,tz3){return[u*tx1+v*tx2+w*tx3,u*ty1+v*ty2+w*ty3,u*tz1+v*tz2+w*tz3]};
+
+}
+
+// ../lib/misc/miscutil.js
+{
+'use strict';const C3=self.C3;let mainDocument=null;let baseHref="";if(typeof document!=="undefined"){mainDocument=document;const baseElem=document.querySelector("base");baseHref=baseElem&&baseElem.hasAttribute("href")?baseElem.getAttribute("href"):"";if(baseHref){if(baseHref.startsWith("/"))baseHref=baseHref.substr(1);if(!baseHref.endsWith("/"))baseHref+="/"}}C3.GetBaseHref=function GetBaseHref(){return baseHref};
+C3.GetBaseURL=function GetBaseURL(){if(!mainDocument)return"";const loc=mainDocument.location;return C3.GetPathFromURL(loc.origin+loc.pathname)+baseHref};C3.GetPathFromURL=function GetPathFromURL(url){if(!url.length)return url;if(url.endsWith("/")||url.endsWith("\\"))return url;const lastSlash=Math.max(url.lastIndexOf("/"),url.lastIndexOf("\\"));if(lastSlash===-1)return"";return url.substr(0,lastSlash+1)};
+C3.GetFilenameFromURL=function GetFilenameFromURL(url){if(!url.length)return url;if(url.endsWith("/")||url.endsWith("\\"))return"";const lastSlash=Math.max(url.lastIndexOf("/"),url.lastIndexOf("\\"));if(lastSlash===-1)return url;return url.substr(lastSlash+1)};C3.GetFileExtension=function GetFileExtension(filename){let i=filename.lastIndexOf(".");if(i<1)return"";else return filename.substr(i)};
+C3.SetFileExtension=function SetFileExtension(filename,newExt){const i=filename.lastIndexOf(".");if(i===-1)return filename+"."+newExt;else return filename.substr(0,i+1)+newExt};C3.GetFileNamePart=function GetFileNamePart(filename){let i=filename.lastIndexOf(".");if(i<1)return filename;else return filename.substr(0,i)};C3.NormalizeFileSeparator=function NormalizeFileSeparator(path){return path.replace(/\\/g,"/")};
+C3.IsFileExtension=function IsFileExtension(filename,extension){const ext=filename?C3.GetFileExtension(filename).slice(1):"";return extension===ext};
+C3.FileNameEquals=function FileNameEquals(file_or_filename,other_file_or_filename){let firstName;let secondName;if(C3.IsFileLike(file_or_filename))firstName=C3.GetFileNamePart(file_or_filename["name"]);if(C3.IsString(file_or_filename))firstName=C3.GetFileNamePart(file_or_filename);if(C3.IsFileLike(other_file_or_filename))secondName=C3.GetFileNamePart(other_file_or_filename["name"]);if(C3.IsString(other_file_or_filename))secondName=C3.GetFileNamePart(other_file_or_filename);return firstName===secondName};
+C3.ParseFilePath=function ParseFilePath(path){path=C3.NormalizeFileSeparator(path);let root=/^\w:\//.exec(path);if(root){root=root[0];path=path.slice(3);if(path[0]!=="/")path="/"+path}else root="";path=path.replace(/\/{2,}/g,"/");if(path.length>1&&path.slice(-1)==="/")path=path.slice(0,-1);const start=path.lastIndexOf("/")+1;let dir="",base=path,name,ext="";if(start>0){dir=path.slice(0,start);base=path.slice(start)}name=base;const end=base.lastIndexOf(".");if(end>0){ext=base.slice(end);name=base.slice(0,
+-ext.length)}const full=root+dir+base;return{dir,base,name,root,ext,full}};C3.Wait=function Wait(delay,argument){return new Promise((resolve,reject)=>{self.setTimeout(resolve,delay,argument)})};C3.swallowException=function swallowException(f){try{f()}catch(e){if(C3.isDebug)console.warn("Swallowed exception: ",e)}};C3.noop=function noop(){};C3.equalsNoCase=function equalsNoCase(a,b){if(typeof a!=="string"||typeof b!=="string")return false;return a===b||a.normalize().toLowerCase()===b.normalize().toLowerCase()};
+C3.equalsCase=function equalsCase(a,b){if(typeof a!=="string"||typeof b!=="string")return false;if(a===b)return true;return a.normalize()===b.normalize()};C3.typedArraySet16=function typedArraySet16(dest,src,i){dest[i++]=src[0];dest[i++]=src[1];dest[i++]=src[2];dest[i++]=src[3];dest[i++]=src[4];dest[i++]=src[5];dest[i++]=src[6];dest[i++]=src[7];dest[i++]=src[8];dest[i++]=src[9];dest[i++]=src[10];dest[i++]=src[11];dest[i++]=src[12];dest[i++]=src[13];dest[i++]=src[14];dest[i]=src[15]};
+C3.truncateArray=function truncateArray(arr,index){arr.length=index};C3.clearArray=function clearArray(arr){if(!arr)return;if(arr.length===0)return;C3.truncateArray(arr,0)};C3.clear2DArray=function clear2DArray(arr){if(!arr)return;for(let i=0;iarrayLength)C3.extendArray(arr,len,filler)};C3.shallowAssignArray=function shallowAssignArray(dest,src){C3.clearArray(dest);C3.appendArray(dest,src)};C3.appendArray=function appendArray(a,b){if(b.length<1E4)a.push(...b);else for(let i=0,len=b.length;i=arr.length)return;let len=arr.length-1;for(let i=index;i=0)a.splice(i,1)};C3.arraysEqual=function arraysEqual(a,b){let len=a.length;if(b.length!==len)return false;for(let i=0;i=0&&indexy;case 5:return x>=y;default:return false}};
+C3.hasAnyOwnProperty=function hasAnyOwnProperty(o){for(let p in o)if(o.hasOwnProperty(p))return true;return false};
+C3.PromiseAllWithProgress=function PromiseAllWithProgress(arr,progressCallback){if(!arr.length)return Promise.resolve([]);return new Promise((resolve,reject)=>{const results=[];let numberCompleted=0;let cancelled=false;for(let i=0,len=arr.length;i{if(cancelled)return;results[i]=result;++numberCompleted;if(numberCompleted===arr.length)resolve(results);else progressCallback(numberCompleted,arr.length)}).catch(err=>{cancelled=true;reject(err)})}})};
+let memoryCallbacks=[];C3.AddLibraryMemoryCallback=function AddLibraryMemoryCallback(f){memoryCallbacks.push(f)};C3.GetEstimatedLibraryMemoryUsage=function GetEstimatedLibraryMemoryUsage(){let ret=0;for(let f of memoryCallbacks){let m=f();ret+=m}return Math.floor(ret)};let nextTaskId=1;const activeTaskIds=new Map;const taskMessageChannel=new MessageChannel;taskMessageChannel.port2.onmessage=function OnTask(e){const id=e.data;const callback=activeTaskIds.get(id);activeTaskIds.delete(id);if(callback)callback(performance.now())};
+C3.RequestUnlimitedAnimationFrame=function RequestUnlimitedAnimationFrame(callback){const id=nextTaskId++;activeTaskIds.set(id,callback);taskMessageChannel.port1.postMessage(id);return id};C3.CancelUnlimitedAnimationFrame=function CancelUnlimitedAnimationFrame(id){activeTaskIds.delete(id)};C3.PostTask=C3.RequestUnlimitedAnimationFrame;C3.WaitForNextTask=function WaitForNextTask(){return new Promise(resolve=>C3.PostTask(resolve))};const activeRPAFids=new Set;
+C3.RequestPostAnimationFrame=function RequestPostAnimationFrame(callback){const id=self.requestAnimationFrame(async timestamp=>{await C3.WaitForNextTask();if(!activeRPAFids.has(id))return;activeRPAFids.delete(id);callback(timestamp)});activeRPAFids.add(id);return id};C3.CancelPostAnimationFrame=function CancelPostAnimationFrame(id){if(!activeRPAFids.has(id))return;self.cancelAnimationFrame(id);activeRPAFids.delete(id)};
+
+}
+
+// lib/misc/runtimeutil.js
+{
+'use strict';const C3=self.C3;C3.IsAbsoluteURL=function IsAbsoluteURL(url){return/^(?:[a-z\-]+:)?\/\//.test(url)||url.substr(0,5)==="data:"||url.substr(0,5)==="blob:"};C3.IsRelativeURL=function IsRelativeURL(url){return!C3.IsAbsoluteURL(url)};C3.ThrowIfNotOk=function ThrowIfNotOk(response){if(!response.ok)throw new Error(`fetch '${response.url}' response returned ${response.status} ${response.statusText}`);};
+C3.FetchOk=function FetchOk(url,init){return fetch(url,init).then(response=>{C3.ThrowIfNotOk(response);return response})};C3.FetchText=function FetchText(url){return C3.FetchOk(url).then(response=>response.text())};C3.FetchJson=function FetchJson(url){return C3.FetchOk(url).then(response=>response.json())};C3.FetchBlob=function FetchBlob(url){return C3.FetchOk(url).then(response=>response.blob())};C3.FetchArrayBuffer=function FetchArrayBuffer(url){return C3.FetchOk(url).then(response=>response.arrayBuffer())};
+C3.FetchImage=function FetchImage(url){return new Promise((resolve,reject)=>{const img=new Image;img.onload=()=>resolve(img);img.onerror=err=>reject(err);img.src=url})};C3.BlobToArrayBuffer=function BlobToArrayBuffer(blob){if(typeof blob["arrayBuffer"]==="function")return blob["arrayBuffer"]();else return new Promise((resolve,reject)=>{const fileReader=new FileReader;fileReader.onload=()=>resolve(fileReader.result);fileReader.onerror=()=>reject(fileReader.error);fileReader.readAsArrayBuffer(blob)})};
+C3.BlobToString=function BlobToString(blob){if(typeof blob["text"]==="function")return blob["text"]();else return new Promise((resolve,reject)=>{const fileReader=new FileReader;fileReader.onload=()=>resolve(fileReader.result);fileReader.onerror=()=>reject(fileReader.error);fileReader.readAsText(blob)})};C3.BlobToJson=function BlobToJson(blob){return C3.BlobToString(blob).then(text=>JSON.parse(text))};
+C3.BlobToImage=async function BlobToImage(blob,decodeImage){let blobUrl=URL.createObjectURL(blob);try{const img=await C3.FetchImage(blobUrl);URL.revokeObjectURL(blobUrl);blobUrl="";if(decodeImage&&typeof img["decode"]==="function")await img["decode"]();return img}finally{if(blobUrl)URL.revokeObjectURL(blobUrl)}};
+C3.CreateCanvas=function CreateCanvas(width,height){if(typeof document!=="undefined"&&typeof document.createElement==="function"){const canvas=document.createElement("canvas");canvas.width=width;canvas.height=height;return canvas}else return new OffscreenCanvas(width,height)};
+C3.CanvasToBlob=function CanvasToBlob(canvas,type,quality){if(typeof quality!=="number")quality=1;type=type||"image/png";quality=C3.clamp(quality,0,1);if(canvas["convertToBlob"])return canvas["convertToBlob"]({"type":type,"quality":quality});else if(canvas.toBlob)return new Promise(resolve=>canvas.toBlob(resolve,type,quality));else throw new Error("could not convert canvas to blob");};
+C3.DrawableToBlob=function DrawableToBlob(drawable,type,quality){const canvas=C3.CreateCanvas(drawable.width,drawable.height);const ctx=canvas.getContext("2d");ctx.drawImage(drawable,0,0);return C3.CanvasToBlob(canvas,type,quality)};
+C3.ImageDataToBlob=function ImageDataToBlob(imageData,type,quality){if(C3.Supports.ImageBitmapOptions)return createImageBitmap(imageData,{"premultiplyAlpha":"none"}).then(imageBitmap=>C3.DrawableToBlob(imageBitmap,type,quality));else if(C3.Supports.ImageBitmap)return createImageBitmap(imageData).then(imageBitmap=>C3.DrawableToBlob(imageBitmap,type,quality));else{const canvas=C3.CreateCanvas(imageData.width,imageData.height);const ctx=canvas.getContext("2d");ctx.putImageData(imageData,0,0);return C3.CanvasToBlob(canvas,
+type,quality)}};C3.CopySet=function CopySet(dest,src){dest.clear();for(const x of src)dest.add(x)};C3.MapToObject=function MapToObject(map){const ret=Object.create(null);for(const [k,v]of map.entries())ret[k]=v;return ret};C3.ObjectToMap=function ObjectToMap(o,map){map.clear();for(const [k,v]of Object.entries(o))map.set(k,v)};
+C3.ToSuperJSON=function ToSuperJSON(v){if(typeof v==="object"&&v!==null)if(v instanceof Set)return{"_c3type_":"set","data":[...v].map(o=>ToSuperJSON(o))};else if(v instanceof Map)return{"_c3type_":"map","data":[...v].map(pair=>[pair[0],ToSuperJSON(pair[1])])};else{const ret=Object.create(null);for(const [key,value]of Object.entries(v))ret[key]=ToSuperJSON(value);return ret}return v};
+C3.FromSuperJSON=function FromSuperJSON(v){if(typeof v==="object"&v!==null)if(v["_c3type_"]==="set")return new Set(v["data"].map(o=>FromSuperJSON(o)));else if(v["_c3type_"]==="map")return new Map(v["data"].map(pair=>[pair[0],FromSuperJSON(pair[1])]));else{const ret=Object.create(null);for(const [key,value]of Object.entries(v))ret[key]=FromSuperJSON(value);return ret}return v};
+C3.CSSToCamelCase=function(str){if(str.startsWith("--"))return str;let ret="";let isAfterHyphen=false;for(const ch of str)if(ch==="-")isAfterHyphen=true;else if(isAfterHyphen){ret+=ch.toUpperCase();isAfterHyphen=false}else ret+=ch;return ret};C3.IsIterator=function(o){return typeof o==="object"&&typeof o.next==="function"};
+C3.MakeFilledArray=function MakeFilledArray(len,data){const ret=[];if(typeof data==="function")for(let i=0;i1)t-=1;if(t<1/6)return p+(q-p)*6*t;if(t<1/2)return q;if(t<2/3)return p+(q-p)*(2/3-t)*6;return p}
+C3.Color=class Color{constructor(r,g,b,a){this._r=NaN;this._g=NaN;this._b=NaN;this._a=NaN;this._r=0;this._g=0;this._b=0;this._a=0;if(r instanceof C3.Color)this.set(r);else this.setRgba(r||0,g||0,b||0,a||0)}setRgb(r,g,b){this._r=+r;this._g=+g;this._b=+b;this.clamp();return this}setRgba(r,g,b,a){this._r=+r;this._g=+g;this._b=+b;this._a=+a;this.clamp();return this}set(c){this._r=c._r;this._g=c._g;this._b=c._b;this._a=c._a;return this}copy(c){return this.set(c)}add(c){this._r+=c._r;this._g+=c._g;this._b+=
+c._b;this._a+=c._a;this.clamp()}addRgb(r,g,b,a=0){this._r+=+r;this._g+=+g;this._b+=+b;this._a+=+a;this.clamp()}diff(c){this.setR(Math.max(this._r,c._r)-Math.min(this._r,c._r));this.setG(Math.max(this._g,c._g)-Math.min(this._g,c._g));this.setB(Math.max(this._b,c._b)-Math.min(this._b,c._b));this.setA(Math.max(this._a,c._a)-Math.min(this._a,c._a));this.clamp()}copyRgb(c){this._r=c._r;this._g=c._g;this._b=c._b}setR(r){this._r=C3.clamp(+r,0,1)}getR(){return this._r}setG(g){this._g=C3.clamp(+g,0,1)}getG(){return this._g}setB(b){this._b=
+C3.clamp(+b,0,1)}getB(){return this._b}setA(a){this._a=C3.clamp(+a,0,1)}getA(){return this._a}clone(){return C3.New(C3.Color,this._r,this._g,this._b,this._a)}toArray(){return[this._r,this._g,this._b,this._a]}toTypedArray(){return new Float64Array(this.toArray())}writeToTypedArray(ta,i){ta[i++]=this._r;ta[i++]=this._g;ta[i++]=this._b;ta[i]=this._a}writeRGBToTypedArray(ta,i){ta[i++]=this._r;ta[i++]=this._g;ta[i]=this._b}equals(c){return this._r===c._r&&this._g===c._g&&this._b===c._b&&this._a===c._a}equalsIgnoringAlpha(c){return this._r===
+c._r&&this._g===c._g&&this._b===c._b}equalsRgb(r,g,b){return this._r===r&&this._g===g&&this._b===b}equalsRgba(r,g,b,a){return this._r===r&&this._g===g&&this._b===b&&this._a===a}equalsF32Array(arr,offset){return arr[offset]===Math.fround(this._r)&&arr[offset+1]===Math.fround(this._g)&&arr[offset+2]===Math.fround(this._b)&&arr[offset+3]===Math.fround(this._a)}equalsRGBF32Array(arr,offset){return arr[offset]===Math.fround(this._r)&&arr[offset+1]===Math.fround(this._g)&&arr[offset+2]===Math.fround(this._b)}multiply(c){this._r*=
+c._r;this._g*=c._g;this._b*=c._b;this._a*=c._a}multiplyAlpha(a){this._r*=a;this._g*=a;this._b*=a;this._a*=a}premultiply(){this._r*=this._a;this._g*=this._a;this._b*=this._a;return this}unpremultiply(){this._r/=this._a;this._g/=this._a;this._b/=this._a;return this}clamp(){this._r=C3.clamp(this._r,0,1);this._g=C3.clamp(this._g,0,1);this._b=C3.clamp(this._b,0,1);this._a=C3.clamp(this._a,0,1);return this}setFromRgbValue(rgb){this._r=C3.GetRValue(rgb);this._g=C3.GetGValue(rgb);this._b=C3.GetBValue(rgb);
+this._a=C3.GetAValue(rgb)}getCssRgb(_r,_g,_b){const r=C3.IsFiniteNumber(_r)?_r:this.getR();const g=C3.IsFiniteNumber(_g)?_g:this.getG();const b=C3.IsFiniteNumber(_b)?_b:this.getB();return`rgb(${r*100}%, ${g*100}%, ${b*100}%)`}getCssRgba(_r,_g,_b,_a){const r=C3.IsFiniteNumber(_r)?_r:this.getR();const g=C3.IsFiniteNumber(_g)?_g:this.getG();const b=C3.IsFiniteNumber(_b)?_b:this.getB();const a=C3.IsFiniteNumber(_a)?_a:this.getA();return`rgba(${r*100}%, ${g*100}%, ${b*100}%, ${a})`}toHexString(){const rh=
+Math.round(this.getR()*255);const gh=Math.round(this.getG()*255);const bh=Math.round(this.getB()*255);return"#"+padTwoDigits(rh.toString(16))+padTwoDigits(gh.toString(16))+padTwoDigits(bh.toString(16))}parseHexString(str){if(typeof str!=="string")return false;str=str.trim();if(str.charAt(0)==="#")str=str.substr(1);let rv;let gv;let bv;if(str.length===3){rv=parseInt(str[0],16)/15;gv=parseInt(str[1],16)/15;bv=parseInt(str[2],16)/15}else if(str.length===6){rv=parseInt(str.substr(0,2),16)/255;gv=parseInt(str.substr(2,
+2),16)/255;bv=parseInt(str.substr(4,2),16)/255}else return false;if(isFinite(rv))this.setR(rv);if(isFinite(gv))this.setG(gv);if(isFinite(bv))this.setB(bv);this.setA(1);return true}toCommaSeparatedRgb(){const rv=Math.round(this.getR()*255);const gv=Math.round(this.getG()*255);const bv=Math.round(this.getB()*255);return`${rv}, ${gv}, ${bv}`}toRgbArray(){const rv=Math.round(this.getR()*255);const gv=Math.round(this.getG()*255);const bv=Math.round(this.getB()*255);return[rv,gv,bv]}parseCommaSeparatedRgb(str){if(typeof str!==
+"string")return false;str=str.replace(/^rgb\(|\)|%/,"");const arr=str.split(",");if(arr.length<3)return false;const rv=parseInt(arr[0].trim(),10)/255;const gv=parseInt(arr[1].trim(),10)/255;const bv=parseInt(arr[2].trim(),10)/255;if(isFinite(rv))this.setR(rv);if(isFinite(gv))this.setG(gv);if(isFinite(bv))this.setB(bv);this.setA(1);return true}parseCommaSeparatedPercentageRgb(str){if(typeof str!=="string")return false;str=str.replace(/^rgb\(|\)|%/,"");const arr=str.split(",");if(arr.length<3)return false;
+const rv=parseInt(arr[0].trim(),10)/100;const gv=parseInt(arr[1].trim(),10)/100;const bv=parseInt(arr[2].trim(),10)/100;if(isFinite(rv))this.setR(rv);if(isFinite(gv))this.setG(gv);if(isFinite(bv))this.setB(bv);this.setA(1);return true}parseCommaSeparatedRgba(str){if(typeof str!=="string")return false;str=str.replace(/^rgba\(|\)|%/,"");const arr=str.split(",");if(arr.length<4)return false;const rv=parseInt(arr[0].trim(),10)/255;const gv=parseInt(arr[1].trim(),10)/255;const bv=parseInt(arr[2].trim(),
+10)/255;const av=parseFloat(arr[3].trim());if(isFinite(rv))this.setR(rv);if(isFinite(gv))this.setG(gv);if(isFinite(bv))this.setB(bv);if(isFinite(av))this.setA(av);return true}parseCommaSeparatedPercentageRgba(str){if(typeof str!=="string")return false;str=str.replace(/^rgba\(|\)|%/,"");const arr=str.split(",");if(arr.length<4)return false;const rv=parseInt(arr[0].trim(),10)/100;const gv=parseInt(arr[1].trim(),10)/100;const bv=parseInt(arr[2].trim(),10)/100;const av=parseFloat(arr[3].trim());if(isFinite(rv))this.setR(rv);
+if(isFinite(gv))this.setG(gv);if(isFinite(bv))this.setB(bv);if(isFinite(av))this.setA(av);return true}parseString(str){if(typeof str!=="string")return false;str=str.replace(/\s+/,"");if(str.includes(","))if(str.startsWith("rgb("))if(str.includes("%"))return this.parseCommaSeparatedPercentageRgb(str);else return this.parseCommaSeparatedRgb(str);else if(str.startsWith("rgba("))if(str.includes("%"))return this.parseCommaSeparatedPercentageRgba(str);else return this.parseCommaSeparatedRgba(str);else if(str.startsWith("hsl(")||
+str.startsWith("hsla("))return this.parseHSLString(str);else{const components=str.split(",");if(str.includes("%")){if(components.length===3)return this.parseCommaSeparatedPercentageRgb(str);else if(components.length===4)return this.parseCommaSeparatedPercentageRgba(str);return false}else{if(components.length===3)return this.parseCommaSeparatedRgb(str);else if(components.length===4)return this.parseCommaSeparatedRgba(str);return false}}else return this.parseHexString(str)}toJSON(){return[this._r,this._g,
+this._b,this._a]}setFromHSLA(h,s,l,a){let r;let g;let b;h%=360;s=C3.clamp(s,0,100);l=C3.clamp(l,0,100);a=C3.clamp(a,0,1);h/=360;s/=100;l/=100;if(s===0)r=g=b=l;else{const q=l<.5?l*(1+s):l+s-l*s;const p=2*l-q;r=hueToRGB(p,q,h+1/3);g=hueToRGB(p,q,h);b=hueToRGB(p,q,h-1/3)}this.setR(r);this.setG(g);this.setB(b);this.setA(a);return this}parseHSLString(str){const cleanString=str.replace(/ |hsl|hsla|\(|\)|;/gi,"");const hsl=HSL_TEST.exec(cleanString);const hsla=HSLA_TEST.exec(cleanString);if(hsl&&hsl.length===
+4){this.setFromHSLA(+hsl[1],+hsl[2],+hsl[3],1);return true}else if(hsla&&hsla.length===5){this.setFromHSLA(+hsl[1],+hsl[2],+hsl[3],+hsl[4]);return true}return false}toHSLAString(){const r=this._r;const g=this._g;const b=this._b;const a=this._a;const h=C3.Color.GetHue(r,g,b);const s=C3.Color.GetSaturation(r,g,b);const l=C3.Color.GetLuminosity(r,g,b);return`hsla(${h}, ${s}%, ${l}%, ${a})`}toHSLAArray(){const r=this._r;const g=this._g;const b=this._b;return[C3.Color.GetHue(r,g,b),C3.Color.GetSaturation(r,
+g,b),C3.Color.GetLuminosity(r,g,b),this._a]}setFromJSON(arr){if(!Array.isArray(arr))return;if(arr.length<3)return;this._r=arr[0];this._g=arr[1];this._b=arr[2];if(arr.length>=4)this._a=arr[3];else this._a=1}set r(r){this.setR(r)}get r(){return this.getR()}set g(g){this.setG(g)}get g(){return this.getG()}set b(b){this.setB(b)}get b(){return this.getB()}set a(a){this.setA(a)}get a(){return this.getA()}setAtIndex(i,v){switch(i){case 0:this.setR(v);break;case 1:this.setG(v);break;case 2:this.setB(v);break;
+case 3:this.setA(v);break;default:throw new RangeError("invalid color index");}}getAtIndex(i){switch(i){case 0:return this.getR();case 1:return this.getG();case 2:return this.getB();case 3:return this.getA();default:throw new RangeError("invalid color index");}}static Equals(color_or_json_1,color_or_json_2){let c1;let c2;if(Array.isArray(color_or_json_1)){c1=new C3.Color;c1.setFromJSON(color_or_json_1)}else if(color_or_json_1 instanceof C3.Color)c1=color_or_json_1;else throw new Error("unexpected type");
+if(Array.isArray(color_or_json_2)){c2=new C3.Color;c2.setFromJSON(color_or_json_2)}else if(color_or_json_2 instanceof C3.Color)c2=color_or_json_2;else throw new Error("unexpected type");return c1.equals(c2)}static DiffChannel(channel1,channel2){return C3.clamp(Math.max(channel1,channel2)-Math.min(channel1,channel2),0,1)}static Diff(c1,c2){const ret=new C3.Color;ret.setR(Math.max(c1._r,c2._r)-Math.min(c1._r,c2._r));ret.setG(Math.max(c1._g,c2._g)-Math.min(c1._g,c2._g));ret.setB(Math.max(c1._b,c2._b)-
+Math.min(c1._b,c2._b));ret.setA(Math.max(c1._a,c2._a)-Math.min(c1._a,c2._a));return ret}static DiffNoAlpha(c1,c2){const ret=new C3.Color(0,0,0,1);ret.setR(Math.max(c1._r,c2._r)-Math.min(c1._r,c2._r));ret.setG(Math.max(c1._g,c2._g)-Math.min(c1._g,c2._g));ret.setB(Math.max(c1._b,c2._b)-Math.min(c1._b,c2._b));return ret}static GetHue(r,g,b){const max=Math.max(r,g,b);const min=Math.min(r,g,b);if(max===min)return 0;let h=0;switch(max){case r:h=(g-b)/(max-min)+(g.5?d/(2-max-min):d/(max+min);return Math.round(s*100)}static GetLuminosity(r,g,b){const max=Math.max(r,g,b);const min=Math.min(r,g,b);const l=(max+min)/2;if(!max)return 0;return Math.round(l*100)}};C3.Color.White=Object.freeze(C3.New(C3.Color,1,1,1,1));
+C3.Color.Black=Object.freeze(C3.New(C3.Color,0,0,0,1));C3.Color.TransparentBlack=Object.freeze(C3.New(C3.Color,0,0,0,0));
+
+}
+
+// ../lib/misc/vector2.js
+{
+'use strict';const C3=self.C3;
+C3.Vector2=class Vector2{constructor(x,y){this._x=0;this._y=0;if(x instanceof C3.Vector2)this.copy(x);else this.set(x||0,y||0)}set(x,y){this._x=+x;this._y=+y}copy(v){this._x=v._x;this._y=v._y}equals(v){return this._x===v._x&&this._y===v._y}equalsValues(x,y){return this._x===x&&this._y===y}equalsF32Array(arr,offset){return arr[offset]===Math.fround(this._x)&&arr[offset+1]===Math.fround(this._y)}setX(x){this._x=+x}getX(){return this._x}setY(y){this._y=+y}getY(){return this._y}toArray(){return[this._x,this._y]}toTypedArray(){return new Float64Array(this.toArray())}writeToTypedArray(ta,
+i){ta[i++]=this._x;ta[i]=this._y}offset(x,y){this._x+=+x;this._y+=+y}scale(x,y){this._x*=x;this._y*=y}divide(x,y){this._x/=x;this._y/=y}round(){this._x=Math.round(this._x);this._y=Math.round(this._y)}floor(){this._x=Math.floor(this._x);this._y=Math.floor(this._y)}ceil(){this._x=Math.ceil(this._x);this._y=Math.ceil(this._y)}angle(){return C3.angleTo(0,0,this._x,this._y)}lengthSquared(){return this._x*this._x+this._y*this._y}length(){return Math.hypot(this._x,this._y)}rotatePrecalc(sin_a,cos_a){const temp=
+this._x*cos_a-this._y*sin_a;this._y=this._y*cos_a+this._x*sin_a;this._x=temp}rotate(a){if(a===0)return;this.rotatePrecalc(Math.sin(a),Math.cos(a))}rotateAbout(a,x,y){if(a===0||x===this._x&&y===this._y)return;this._x-=x;this._y-=y;this.rotatePrecalc(Math.sin(a),Math.cos(a));this._x+=+x;this._y+=+y}move(a,dist){if(dist===0)return;this._x+=Math.cos(a)*dist;this._y+=Math.sin(a)*dist}normalize(){const m=this.length();if(m!==0&&m!==1){this._x/=m;this._y/=m}}clamp(lower,upper){this._x=C3.clamp(this._x,lower,
+upper);this._y=C3.clamp(this._y,lower,upper)}dot(other){return this._x*other._x+this._y*other._y}reverse(){this._x=-this._x;this._y=-this._y}perp(){let x=this._x;this._x=this._y;this._y=-x;return this}};
+
+}
+
+// ../lib/misc/rect.js
+{
+'use strict';const C3=self.C3;
+C3.Rect=class Rect{constructor(left,top,right,bottom){this._left=NaN;this._top=NaN;this._right=NaN;this._bottom=NaN;this._left=0;this._top=0;this._right=0;this._bottom=0;if(left instanceof C3.Rect)this.copy(left);else this.set(left||0,top||0,right||0,bottom||0)}set(left,top,right,bottom){this._left=+left;this._top=+top;this._right=+right;this._bottom=+bottom}setWH(left,top,width,height){left=+left;top=+top;this._left=left;this._top=top;this._right=left+ +width;this._bottom=top+ +height}copy(rect){this._left=
++rect._left;this._top=+rect._top;this._right=+rect._right;this._bottom=+rect._bottom}clone(){return new C3.Rect(this._left,this._top,this._right,this._bottom)}static Merge(first,second){const ret=new C3.Rect;ret.setLeft(Math.min(first._left,second._left));ret.setTop(Math.min(first._top,second._top));ret.setRight(Math.max(first._right,second._right));ret.setBottom(Math.max(first._bottom,second._bottom));return ret}static FromObject(o){return new C3.Rect(o.left,o.top,o.right,o.bottom)}equals(rect){return this._left===
+rect._left&&this._top===rect._top&&this._right===rect._right&&this._bottom===rect._bottom}equalsWH(x,y,w,h){return this._left===x&&this._top===y&&this.width()===w&&this.height()===h}equalsF32Array(arr,offset){return arr[offset]===Math.fround(this._left)&&arr[offset+1]===Math.fround(this._top)&&arr[offset+2]===Math.fround(this._right)&&arr[offset+3]===Math.fround(this._bottom)}setLeft(l){this._left=+l}getLeft(){return this._left}setTop(t){this._top=+t}getTop(){return this._top}setRight(r){this._right=
++r}getRight(){return this._right}setBottom(b){this._bottom=+b}getBottom(){return this._bottom}toArray(){return[this._left,this._top,this._right,this._bottom]}toTypedArray(){return new Float64Array(this.toArray())}toDOMRect(){return new DOMRect(this._left,this._top,this.width(),this.height())}writeToTypedArray(ta,i){ta[i++]=this._left;ta[i++]=this._top;ta[i++]=this._right;ta[i]=this._bottom}writeAsQuadToTypedArray(ta,i){ta[i++]=this._left;ta[i++]=this._top;ta[i++]=this._right;ta[i++]=this._top;ta[i++]=
+this._right;ta[i++]=this._bottom;ta[i++]=this._left;ta[i]=this._bottom}writeAsQuadToTypedArray3D(ta,i,z){ta[i++]=this._left;ta[i++]=this._top;ta[i++]=z;ta[i++]=this._right;ta[i++]=this._top;ta[i++]=z;ta[i++]=this._right;ta[i++]=this._bottom;ta[i++]=z;ta[i++]=this._left;ta[i++]=this._bottom;ta[i]=z}width(){return this._right-this._left}height(){return this._bottom-this._top}midX(){return(this._left+this._right)/2}midY(){return(this._top+this._bottom)/2}offset(x,y){x=+x;y=+y;this._left+=x;this._top+=
+y;this._right+=x;this._bottom+=y}offsetLeft(x){this._left+=+x}offsetTop(y){this._top+=+y}offsetRight(x){this._right+=+x}offsetBottom(y){this._bottom+=+y}toSquare(axis){if(axis!=="x")throw new Error("invalid axis, only 'x' supported");if(this._topthis._right)this.swapLeftRight();
+if(this._top>this._bottom)this.swapTopBottom()}intersectsRect(rect){return!(rect._rightthis._right||rect._top>this._bottom)}intersectsRectOffset(rect,x,y){return!(rect._right+xthis._right||rect._top+y>this._bottom)}containsPoint(x,y){return x>=this._left&&x<=this._right&&y>=this._top&&y<=this._bottom}containsRect(rect){return rect._left>=this._left&&rect._top>=this._top&&rect._right<=this._right&&rect._bottom<=
+this._bottom}expandToContain(rect){if(rect._leftthis._right)this._right=+rect._right;if(rect._bottom>this._bottom)this._bottom=+rect._bottom}lerpInto(rect){this._left=C3.lerp(rect._left,rect._right,this._left);this._top=C3.lerp(rect._top,rect._bottom,this._top);this._right=C3.lerp(rect._left,rect._right,this._right);this._bottom=C3.lerp(rect._top,rect._bottom,this._bottom)}};
+
+}
+
+// ../lib/misc/quad.js
+{
+'use strict';const C3=self.C3;
+C3.Quad=class Quad{constructor(tlx,tly,trx,try_,brx,bry,blx,bly){this._tlx=NaN;this._tly=NaN;this._trx=NaN;this._try=NaN;this._brx=NaN;this._bry=NaN;this._blx=NaN;this._bly=NaN;this._tlx=0;this._tly=0;this._trx=0;this._try=0;this._brx=0;this._bry=0;this._blx=0;this._bly=0;if(tlx instanceof C3.Quad)this.copy(tlx);else this.set(tlx||0,tly||0,trx||0,try_||0,brx||0,bry||0,blx||0,bly||0)}set(tlx,tly,trx,try_,brx,bry,blx,bly){this._tlx=+tlx;this._tly=+tly;this._trx=+trx;this._try=+try_;this._brx=+brx;this._bry=
++bry;this._blx=+blx;this._bly=+bly}setRect(left,top,right,bottom){this.set(left,top,right,top,right,bottom,left,bottom)}copy(q){this._tlx=q._tlx;this._tly=q._tly;this._trx=q._trx;this._try=q._try;this._brx=q._brx;this._bry=q._bry;this._blx=q._blx;this._bly=q._bly}equals(q){return this._tlx===q._tlx&&this._tly===q._tly&&this._trx===q._trx&&this._try===q._try&&this._brx===q._brx&&this._bry===q._bry&&this._blx===q._blx&&this._bly===q._bly}setTlx(v){this._tlx=+v}getTlx(){return this._tlx}setTly(v){this._tly=
++v}getTly(){return this._tly}setTrx(v){this._trx=+v}getTrx(){return this._trx}setTry(v){this._try=+v}getTry(){return this._try}setBrx(v){this._brx=+v}getBrx(){return this._brx}setBry(v){this._bry=+v}getBry(){return this._bry}setBlx(v){this._blx=+v}getBlx(){return this._blx}setBly(v){this._bly=+v}getBly(){return this._bly}toDOMQuad(){return new DOMQuad(new DOMPoint(this._tlx,this._tly),new DOMPoint(this._trx,this._try),new DOMPoint(this._brx,this._bry),new DOMPoint(this._blx,this._bly))}toArray(){return[this._tlx,
+this._tly,this._trx,this._try,this._brx,this._bry,this._blx,this._bly]}toTypedArray(){return new Float64Array(this.toArray())}writeToTypedArray(ta,i){ta[i++]=this._tlx;ta[i++]=this._tly;ta[i++]=this._trx;ta[i++]=this._try;ta[i++]=this._brx;ta[i++]=this._bry;ta[i++]=this._blx;ta[i]=this._bly}writeToTypedArray3D(ta,i,z){ta[i++]=this._tlx;ta[i++]=this._tly;ta[i++]=z;ta[i++]=this._trx;ta[i++]=this._try;ta[i++]=z;ta[i++]=this._brx;ta[i++]=this._bry;ta[i++]=z;ta[i++]=this._blx;ta[i++]=this._bly;ta[i]=z}offset(x,
+y){x=+x;y=+y;this._tlx+=x;this._tly+=y;this._trx+=x;this._try+=y;this._brx+=x;this._bry+=y;this._blx+=x;this._bly+=y}round(){this._tlx=Math.round(this._tlx);this._tly=Math.round(this._tly);this._trx=Math.round(this._trx);this._try=Math.round(this._try);this._brx=Math.round(this._brx);this._bry=Math.round(this._bry);this._blx=Math.round(this._blx);this._bly=Math.round(this._bly)}floor(){this._tlx=Math.floor(this._tlx);this._tly=Math.floor(this._tly);this._trx=Math.floor(this._trx);this._try=Math.floor(this._try);
+this._brx=Math.floor(this._brx);this._bry=Math.floor(this._bry);this._blx=Math.floor(this._blx);this._bly=Math.floor(this._bly)}ceil(){this._tlx=Math.ceil(this._tlx);this._tly=Math.ceil(this._tly);this._trx=Math.ceil(this._trx);this._try=Math.ceil(this._try);this._brx=Math.ceil(this._brx);this._bry=Math.ceil(this._bry);this._blx=Math.ceil(this._blx);this._bly=Math.ceil(this._bly)}setFromRect(rect){this._tlx=rect._left;this._tly=rect._top;this._trx=rect._right;this._try=rect._top;this._brx=rect._right;
+this._bry=rect._bottom;this._blx=rect._left;this._bly=rect._bottom}setFromRotatedRect(rect,a){if(a===0)this.setFromRect(rect);else this.setFromRotatedRectPrecalc(rect,Math.sin(a),Math.cos(a))}setFromRotatedRectPrecalc(rect,sin_a,cos_a){const left_sin_a=rect._left*sin_a;const top_sin_a=rect._top*sin_a;const right_sin_a=rect._right*sin_a;const bottom_sin_a=rect._bottom*sin_a;const left_cos_a=rect._left*cos_a;const top_cos_a=rect._top*cos_a;const right_cos_a=rect._right*cos_a;const bottom_cos_a=rect._bottom*
+cos_a;this._tlx=left_cos_a-top_sin_a;this._tly=top_cos_a+left_sin_a;this._trx=right_cos_a-top_sin_a;this._try=top_cos_a+right_sin_a;this._brx=right_cos_a-bottom_sin_a;this._bry=bottom_cos_a+right_sin_a;this._blx=left_cos_a-bottom_sin_a;this._bly=bottom_cos_a+left_sin_a}getBoundingBox(rect){rect.set(Math.min(this._tlx,this._trx,this._brx,this._blx),Math.min(this._tly,this._try,this._bry,this._bly),Math.max(this._tlx,this._trx,this._brx,this._blx),Math.max(this._tly,this._try,this._bry,this._bly))}containsPoint(x,
+y){let v0x=this._trx-this._tlx;let v0y=this._try-this._tly;const v1x=this._brx-this._tlx;const v1y=this._bry-this._tly;const v2x=x-this._tlx;const v2y=y-this._tly;let dot00=v0x*v0x+v0y*v0y;let dot01=v0x*v1x+v0y*v1y;let dot02=v0x*v2x+v0y*v2y;const dot11=v1x*v1x+v1y*v1y;const dot12=v1x*v2x+v1y*v2y;let invDenom=1/(dot00*dot11-dot01*dot01);let u=(dot11*dot02-dot01*dot12)*invDenom;let v=(dot00*dot12-dot01*dot02)*invDenom;if(u>=0&&v>0&&u+v<1)return true;v0x=this._blx-this._tlx;v0y=this._bly-this._tly;dot00=
+v0x*v0x+v0y*v0y;dot01=v0x*v1x+v0y*v1y;dot02=v0x*v2x+v0y*v2y;invDenom=1/(dot00*dot11-dot01*dot01);u=(dot11*dot02-dot01*dot12)*invDenom;v=(dot00*dot12-dot01*dot02)*invDenom;return u>=0&&v>0&&u+v<1}midX(){return(this._tlx+this._trx+this._brx+this._blx)/4}midY(){return(this._tly+this._try+this._bry+this._bly)/4}intersectsSegment(x1,y1,x2,y2){if(this.containsPoint(x1,y1)||this.containsPoint(x2,y2))return true;return C3.segmentIntersectsQuad(x1,y1,x2,y2,this)}intersectsQuad(rhs){let midX=rhs.midX();let midY=
+rhs.midY();if(this.containsPoint(midX,midY))return true;midX=this.midX();midY=this.midY();if(rhs.containsPoint(midX,midY))return true;const tlx=this._tlx,tly=this._tly,trx=this._trx,try_=this._try,brx=this._brx,bry=this._bry,blx=this._blx,bly=this._bly;return C3.segmentIntersectsQuad(tlx,tly,trx,try_,rhs)||C3.segmentIntersectsQuad(trx,try_,brx,bry,rhs)||C3.segmentIntersectsQuad(brx,bry,blx,bly,rhs)||C3.segmentIntersectsQuad(blx,bly,tlx,tly,rhs)}rotatePointsAnticlockwise(){const tlx=this._tlx;const tly=
+this._tly;this._tlx=this._trx;this._tly=this._try;this._trx=this._brx;this._try=this._bry;this._brx=this._blx;this._bry=this._bly;this._blx=tlx;this._bly=tly}mirror(){this._swap(0,2);this._swap(1,3);this._swap(6,4);this._swap(7,5)}flip(){this._swap(0,6);this._swap(1,7);this._swap(2,4);this._swap(3,5)}diag(){this._swap(2,6);this._swap(3,7)}_swap(i,j){const tmp=this._getAtIndex(i);this._setAtIndex(i,this._getAtIndex(j));this._setAtIndex(j,tmp)}_getAtIndex(i){switch(i){case 0:return this._tlx;case 1:return this._tly;
+case 2:return this._trx;case 3:return this._try;case 4:return this._brx;case 5:return this._bry;case 6:return this._blx;case 7:return this._bly;default:throw new RangeError("invalid quad point index");}}_setAtIndex(i,v){v=+v;switch(i){case 0:this._tlx=v;break;case 1:this._tly=v;break;case 2:this._trx=v;break;case 3:this._try=v;break;case 4:this._brx=v;break;case 5:this._bry=v;break;case 6:this._blx=v;break;case 7:this._bly=v;break;default:throw new RangeError("invalid quad point index");}}};
+
+}
+
+// lib/misc/collisionPoly.js
+{
+'use strict';const C3=self.C3;const assert=self.assert;const DEFAULT_POLY_POINTS=[0,0,1,0,1,1,0,1];const tempQuad=C3.New(C3.Quad);
+C3.CollisionPoly=class CollisionPoly extends C3.DefendedBase{constructor(pointsArr,enabled=true){super();if(!pointsArr)pointsArr=DEFAULT_POLY_POINTS;this._ptsArr=Float64Array.from(pointsArr);this._bbox=new C3.Rect;this._isBboxChanged=true;this._enabled=enabled}Release(){}pointsArr(){return this._ptsArr}pointCount(){return this._ptsArr.length/2}setPoints(pointsArr){if(this._ptsArr.length===pointsArr.length)this._ptsArr.set(pointsArr);else this._ptsArr=Float64Array.from(pointsArr);this._isBboxChanged=
+true}setDefaultPoints(){this.setPoints(DEFAULT_POLY_POINTS)}copy(poly){this.setPoints(poly._ptsArr)}setBboxChanged(){this._isBboxChanged=true}_updateBbox(){if(!this._isBboxChanged)return;const ptsArr=this._ptsArr;let left=ptsArr[0];let top=ptsArr[1];let right=left;let bottom=top;for(let i=0,len=ptsArr.length;iright)right=x;if(ybottom)bottom=y}this._bbox.set(left,top,right,bottom);this._isBboxChanged=false}setFromRect(rc,
+offX,offY){let ptsArr=this._ptsArr;if(ptsArr.length!==8){ptsArr=new Float64Array(8);this._ptsArr=ptsArr}ptsArr[0]=rc.getLeft()-offX;ptsArr[1]=rc.getTop()-offY;ptsArr[2]=rc.getRight()-offX;ptsArr[3]=rc.getTop()-offY;ptsArr[4]=rc.getRight()-offX;ptsArr[5]=rc.getBottom()-offY;ptsArr[6]=rc.getLeft()-offX;ptsArr[7]=rc.getBottom()-offY;this._bbox.copy(rc);if(offX!==0||offY!==0)this._bbox.offset(-offX,-offY);this._isBboxChanged=false}setFromQuad(q,offX,offY){tempQuad.copy(q);tempQuad.offset(offX,offY);this.setPoints(tempQuad.toArray());
+this._isBboxChanged=true}transform(w,h,a){let sina=0;let cosa=1;if(a!==0){sina=Math.sin(a);cosa=Math.cos(a)}this.transformPrecalc(w,h,sina,cosa)}transformPrecalc(w,h,sina,cosa){const ptsArr=this._ptsArr;for(let i=0,len=ptsArr.length;i!filter.includes(ease))}static GetRuntimeEaseNames(){this._CreateEaseMap();const sortedCustomEases=[...CUSTOM_EASE_RUNTIME_MAP.keys()];sortedCustomEases.sort();return[...PREDEFINED_EASE_MAP.keys()].concat(sortedCustomEases)}static GetCustomRuntimeEaseNames(){this._CreateEaseMap();const sortedCustomEases=[...CUSTOM_EASE_RUNTIME_MAP.keys()];sortedCustomEases.sort();return sortedCustomEases}static IsPredefinedTranslatedName(easeName){for(const k of EASE_TRANSLATION_KEYS){const translatedName=
+self.lang(`ui.bars.timeline.eases.${k}`);if(translatedName===easeName)return true}for(const k of SHORT_EASE_TRANSLATION_KEYS){const translatedName=self.lang(`ui.bars.timeline.short-eases.${k}`);if(translatedName===easeName)return true}}static IsNamePredefined(easeName){this._CreateEaseMap();return[...PREDEFINED_EASE_MAP.keys()].includes(easeName)}static _GetEase(easeName){const realEaseName=ALIAS_MAP.get(easeName);if(realEaseName)return EASE_MAP.get(realEaseName);if(Ease.IsNamePredefined(easeName))return EASE_MAP.get(easeName);
+if(PRIVATE_EASE_MAP.has(easeName))return PRIVATE_EASE_MAP.get(easeName)}static GetBuiltInTransition(builtInTransitionName){this._CreateEaseMap();return BUILT_IN_TRANSITION_MAP.get(builtInTransitionName)}static GetEditorEase(easeName,project){this._CreateEaseMap();const ease=Ease._GetEase(easeName);if(ease)return ease;if(!project)throw new Error("missing ease function");return CUSTOM_EASE_EDITOR_MAP.get(project).get(easeName)}static HasEditorEase(easeName,project){this._CreateEaseMap();const ease=
+Ease._GetEase(easeName);if(ease)return true;return!!CUSTOM_EASE_EDITOR_MAP.get(project).get(easeName)}static GetRuntimeEase(easeName){this._CreateEaseMap();const ease=Ease._GetEase(easeName);if(ease)return ease;return CUSTOM_EASE_RUNTIME_MAP.get(easeName)}static GetEaseFromIndex(index){this._CreateEaseMap();const names=this.GetRuntimeEaseNames();return names[index]}static GetIndexForEase(name,project){this._CreateEaseMap();const names=this.GetEditorEaseNames(project);return names.indexOf(name)}static GetIndexForEaseAtRuntime(name){return this.GetIndexForEase(name)}static _CreateEaseMap(){if(EASE_MAP.size!==
+0)return;this._AddPredifinedEase("default",()=>{});this._AddPredifinedEase("noease",[{"x":0,"y":0,"sax":.336,"say":0,"eax":0,"eay":0,"se":true,"ee":false},{"x":1,"y":1,"sax":0,"say":0,"eax":-.336,"eay":0,"se":false,"ee":true}],true);this._AddPredifinedEase("easeinsine",[{"x":0,"y":0,"sax":.485,"say":0,"eax":0,"eay":0,"se":true,"ee":false},{"x":1,"y":1,"sax":0,"say":0,"eax":-.038,"eay":0,"se":false,"ee":true}]);this._AddPredifinedEase("easeoutsine",[{"x":0,"y":0,"sax":.038,"say":0,"eax":0,"eay":0,
+"se":true,"ee":false},{"x":1,"y":1,"sax":0,"say":0,"eax":-.485,"eay":0,"se":false,"ee":true}]);this._AddPredifinedEase("easeinoutsine",[{"x":0,"y":0,"sax":.336,"say":0,"eax":0,"eay":0,"se":true,"ee":false},{"x":1,"y":1,"sax":0,"say":0,"eax":-.336,"eay":0,"se":false,"ee":true}]);this._AddPredifinedEase("easeinelastic",[{"x":0,"y":0,"sax":.018,"say":0,"eax":0,"eay":0,"se":true,"ee":false},{"x":.116,"y":.002,"sax":.025,"say":0,"eax":-.025,"eay":0,"se":true,"ee":true},{"x":.266,"y":-.005,"sax":.024,"say":0,
+"eax":-.021,"eay":0,"se":true,"ee":true},{"x":.416,"y":.016,"sax":.024,"say":0,"eax":-.026,"eay":0,"se":true,"ee":true},{"x":.566,"y":-.045,"sax":.061,"say":0,"eax":-.025,"eay":0,"se":true,"ee":true},{"x":.716,"y":.132,"sax":.072,"say":-.004,"eax":-.045,"eay":0,"se":true,"ee":true},{"x":.866,"y":-.373,"sax":.06,"say":0,"eax":-.049,"eay":-.002,"se":true,"ee":true},{"x":1,"y":1,"sax":0,"say":0,"eax":-.038,"eay":-.263,"se":false,"ee":true}]);this._AddPredifinedEase("easeoutelastic",[{"x":0,"y":0,"sax":.038,
+"say":.263,"eax":0,"eay":0,"se":true,"ee":false},{"x":.136,"y":1.373,"sax":.049,"say":.002,"eax":-.06,"eay":0,"se":true,"ee":true},{"x":.286,"y":.868,"sax":.045,"say":0,"eax":-.072,"eay":.004,"se":true,"ee":true},{"x":.436,"y":1.045,"sax":.025,"say":0,"eax":-.061,"eay":0,"se":true,"ee":true},{"x":.586,"y":.984,"sax":.026,"say":0,"eax":-.024,"eay":0,"se":true,"ee":true},{"x":.736,"y":1.005,"sax":.021,"say":0,"eax":-.024,"eay":0,"se":true,"ee":true},{"x":.886,"y":.998,"sax":.025,"say":0,"eax":-.025,
+"eay":0,"se":true,"ee":true},{"x":1,"y":1,"sax":0,"say":0,"eax":-.018,"eay":0,"se":false,"ee":true}]);this._AddPredifinedEase("easeinoutelastic",[{"x":0,"y":0,"sax":.025,"say":0,"eax":0,"eay":0,"se":true,"ee":false},{"x":.067,"y":.001,"sax":.025,"say":0,"eax":-.025,"eay":0,"se":true,"ee":true},{"x":.18,"y":-.005,"sax":.025,"say":0,"eax":-.025,"eay":0,"se":true,"ee":true},{"x":.292,"y":.025,"sax":.053,"say":0,"eax":-.025,"eay":0,"se":true,"ee":true},{"x":.405,"y":-.118,"sax":.069,"say":0,"eax":-.027,
+"eay":0,"se":true,"ee":true},{"x":.597,"y":1.118,"sax":.027,"say":0,"eax":-.069,"eay":0,"se":true,"ee":true},{"x":.71,"y":.975,"sax":.025,"say":0,"eax":-.053,"eay":0,"se":true,"ee":true},{"x":.822,"y":1.005,"sax":.025,"say":0,"eax":-.025,"eay":0,"se":true,"ee":true},{"x":.935,"y":.999,"sax":.025,"say":0,"eax":-.025,"eay":0,"se":true,"ee":true},{"x":1,"y":1,"sax":0,"say":0,"eax":-.025,"eay":0,"se":false,"ee":true}]);this._AddPredifinedEase("easeinback",[{"x":0,"y":0,"sax":.35,"say":0,"eax":0,"eay":0,
+"se":true,"ee":false},{"x":1,"y":1,"sax":0,"say":0,"eax":-.34,"eay":-1.579,"se":false,"ee":true}]);this._AddPredifinedEase("easeoutback",[{"x":0,"y":0,"sax":.34,"say":1.579,"eax":0,"eay":0,"se":true,"ee":false},{"x":1,"y":1,"sax":0,"say":0,"eax":-.35,"eay":0,"se":false,"ee":true}]);this._AddPredifinedEase("easeinoutback",[{"x":0,"y":0,"sax":.035,"say":0,"eax":0,"eay":0,"se":true,"ee":false},{"x":.242,"y":-.1,"sax":.258,"say":0,"eax":-.025,"eay":0,"se":true,"ee":true},{"x":.76,"y":1.1,"sax":.025,"say":0,
+"eax":-.26,"eay":0,"se":true,"ee":true},{"x":1,"y":1,"sax":0,"say":0,"eax":-.035,"eay":0,"se":false,"ee":true}]);this._AddPredifinedEase("easeinbounce",[{"x":0,"y":0,"sax":.033,"say":.025,"eax":0,"eay":0,"se":true,"ee":false},{"x":.092,"y":0,"sax":.026,"say":.078,"eax":-.033,"eay":.025,"se":true,"ee":true},{"x":.274,"y":0,"sax":.097,"say":.319,"eax":-.026,"eay":.078,"se":true,"ee":true},{"x":.637,"y":0,"sax":.105,"say":.625,"eax":-.097,"eay":.319,"se":true,"ee":true},{"x":1,"y":1,"sax":0,"say":0,
+"eax":-.125,"eay":-.004,"se":false,"ee":true}]);this._AddPredifinedEase("easeoutbounce",[{"x":0,"y":0,"sax":.125,"say":.004,"eax":0,"eay":0,"se":true,"ee":false},{"x":.365,"y":1,"sax":.097,"say":-.319,"eax":-.105,"eay":-.625,"se":true,"ee":true},{"x":.728,"y":1,"sax":.026,"say":-.078,"eax":-.097,"eay":-.319,"se":true,"ee":true},{"x":.91,"y":1,"sax":.033,"say":-.025,"eax":-.026,"eay":-.078,"se":true,"ee":true},{"x":1,"y":1,"sax":0,"say":0,"eax":-.033,"eay":-.025,"se":false,"ee":true}]);this._AddPredifinedEase("easeinoutbounce",
+[{"x":0,"y":0,"sax":.01,"say":.006,"eax":0,"eay":0,"se":true,"ee":false},{"x":.046,"y":0,"sax":.021,"say":.038,"eax":-.01,"eay":.006,"se":true,"ee":true},{"x":.137,"y":0,"sax":.059,"say":.158,"eax":-.021,"eay":.038,"se":true,"ee":true},{"x":.319,"y":0,"sax":.117,"say":.744,"eax":-.059,"eay":.158,"se":true,"ee":true},{"x":.683,"y":1,"sax":.059,"say":-.158,"eax":-.117,"eay":-.744,"se":true,"ee":true},{"x":.865,"y":1,"sax":.021,"say":-.038,"eax":-.059,"eay":-.158,"se":true,"ee":true},{"x":.956,"y":1,
+"sax":.01,"say":-.006,"eax":-.021,"eay":-.038,"se":true,"ee":true},{"x":1,"y":1,"sax":0,"say":0,"eax":-.01,"eay":-.006,"se":false,"ee":true}]);this._AddPredifinedEase("easeincubic",[{"x":0,"y":0,"sax":.75,"say":0,"eax":0,"eay":0,"se":true,"ee":false},{"x":1,"y":1,"sax":0,"say":0,"eax":-.138,"eay":-.321,"se":false,"ee":true}]);this._AddPredifinedEase("easeoutcubic",[{"x":0,"y":0,"sax":.138,"say":.321,"eax":0,"eay":0,"se":true,"ee":false},{"x":1,"y":1,"sax":0,"say":0,"eax":-.75,"eay":0,"se":false,"ee":true}]);
+this._AddPredifinedEase("easeinoutcubic",[{"x":0,"y":0,"sax":.285,"say":0,"eax":0,"eay":0,"se":true,"ee":false},{"x":.5,"y":.5,"sax":.081,"say":.272,"eax":-.081,"eay":-.272,"se":true,"ee":true},{"x":1,"y":1,"sax":0,"say":0,"eax":-.285,"eay":0,"se":false,"ee":true}]);this._AddPredifinedEase("easeinquad",[{"x":0,"y":0,"sax":.4,"say":0,"eax":0,"eay":0,"se":true,"ee":false},{"x":1,"y":1,"sax":0,"say":0,"eax":-.178,"eay":-.392,"se":false,"ee":true}]);this._AddPredifinedEase("easeoutquad",[{"x":0,"y":0,
+"sax":.178,"say":.392,"eax":0,"eay":0,"se":true,"ee":false},{"x":1,"y":1,"sax":0,"say":0,"eax":-.4,"eay":0,"se":false,"ee":true}]);this._AddPredifinedEase("easeinoutquad",[{"x":0,"y":0,"sax":.25,"say":0,"eax":0,"eay":0,"se":true,"ee":false},{"x":.5,"y":.5,"sax":.03,"say":.065,"eax":-.03,"eay":-.065,"se":true,"ee":true},{"x":1,"y":1,"sax":0,"say":0,"eax":-.25,"eay":0,"se":false,"ee":true}]);this._AddPredifinedEase("easeinquart",[{"x":0,"y":0,"sax":.25,"say":1,"eax":0,"eay":0,"se":true,"ee":false},
+{"x":1,"y":1,"sax":0,"say":0,"eax":-.5,"eay":0,"se":false,"ee":true}]);this._AddPredifinedEase("easeoutquart",[{"x":0,"y":0,"sax":.5,"say":0,"eax":0,"eay":0,"se":true,"ee":false},{"x":1,"y":1,"sax":0,"say":0,"eax":-.25,"eay":-1,"se":false,"ee":true}]);this._AddPredifinedEase("easeinoutquart",[{"x":0,"y":0,"sax":.765,"say":.03,"eax":0,"eay":0,"se":true,"ee":false},{"x":1,"y":1,"sax":0,"say":0,"eax":-.765,"eay":-.03,"se":false,"ee":true}]);this._AddPredifinedEase("easeinquint",[{"x":0,"y":0,"sax":.6,
+"say":0,"eax":0,"eay":0,"se":true,"ee":false},{"x":1,"y":1,"sax":0,"say":0,"eax":-.2,"eay":-1,"se":false,"ee":true}]);this._AddPredifinedEase("easeoutquint",[{"x":0,"y":0,"sax":.2,"say":1,"eax":0,"eay":0,"se":true,"ee":false},{"x":1,"y":1,"sax":0,"say":0,"eax":-.6,"eay":0,"se":false,"ee":true}]);this._AddPredifinedEase("easeinoutquint",[{"eax":0,"eay":0,"ee":false,"sax":.84,"say":0,"se":true,"x":0,"y":0},{"eax":-.84,"eay":0,"ee":true,"sax":0,"say":0,"se":false,"x":1,"y":1}]);this._AddPredifinedEase("easeincirc",
+[{"x":0,"y":0,"sax":.25,"say":0,"eax":0,"eay":0,"se":true,"ee":false},{"x":1,"y":1,"sax":0,"say":0,"eax":-.024,"eay":-.808,"se":false,"ee":true}]);this._AddPredifinedEase("easeoutcirc",[{"x":0,"y":0,"sax":.024,"say":.808,"eax":0,"eay":0,"se":true,"ee":false},{"x":1,"y":1,"sax":0,"say":0,"eax":-.25,"eay":0,"se":false,"ee":true}]);this._AddPredifinedEase("easeinoutcirc",[{"x":0,"y":0,"sax":.125,"say":0,"eax":0,"eay":0,"se":true,"ee":false},{"x":.5,"y":.5,"sax":.02,"say":.428,"eax":-.02,"eay":-.428,
+"se":true,"ee":true},{"x":1,"y":1,"sax":0,"say":0,"eax":-.125,"eay":0,"se":false,"ee":true}]);this._AddPredifinedEase("easeinexpo",[{"x":0,"y":0,"sax":.66,"say":0,"eax":0,"eay":0,"se":true,"ee":false},{"x":1,"y":1,"sax":0,"say":0,"eax":-.14,"eay":-1,"se":false,"ee":true}]);this._AddPredifinedEase("easeoutexpo",[{"x":0,"y":0,"sax":.14,"say":1,"eax":0,"eay":0,"se":true,"ee":false},{"x":1,"y":1,"sax":0,"say":0,"eax":-.66,"eay":0,"se":false,"ee":true}]);this._AddPredifinedEase("easeinoutexpo",[{"eax":0,
+"eay":0,"ee":false,"sax":.345,"say":0,"se":true,"x":0,"y":0},{"eax":-.06,"eay":-.5,"ee":true,"sax":.06,"say":.5,"se":true,"x":.5,"y":.5},{"eax":-.335,"eay":0,"ee":true,"sax":0,"say":0,"se":false,"x":1,"y":1}]);this._AddPrivateCustomEase("cubicbezier",this.EaseCubicBezier);this._AddPrivateCustomEase("spline",this.EaseSpline)}static _AddPredifinedEase(name,dataArray_or_function,linear=false){if(typeof dataArray_or_function==="function")Ease._AddEase(name,dataArray_or_function,"predefined");else if(C3.IsArray(dataArray_or_function))if(self.BuiltInTransition){const builtInTransition=
+C3.New(self.BuiltInTransition,name,linear);builtInTransition.SetFromJson(dataArray_or_function);Ease._AddEase(name,(t,sv,dv,tt)=>builtInTransition.Interpolate(t,sv,dv,tt),"predefined");BUILT_IN_TRANSITION_MAP.set(name,builtInTransition)}else{const builtInTransition=C3.New(C3.Transition,[name,dataArray_or_function.map(data=>{return[data["x"],data["y"],data["sax"],data["say"],data["eax"],data["eay"],data["se"],data["ee"]]})],false);builtInTransition.MakeLinear(linear);Ease._AddEase(name,(t,sv,dv,tt)=>
+builtInTransition.Interpolate(t,sv,dv,tt),"predefined")}else throw new Error("unexpected arguments");}static _AddPrivateCustomEase(name,func){Ease._AddEase(name,func,"private")}static AddCustomEase(name,func,project){this._CreateEaseMap();Ease._AddEase(name,func,"custom",project)}static RemoveCustomEase(name,project){if(this.IsNamePredefined(name))return;if([...PRIVATE_EASE_MAP.keys()].includes(name))return;const customEaseMap=CUSTOM_EASE_EDITOR_MAP.get(project);if(customEaseMap)customEaseMap.delete(name)}static _AddEase(name,
+func,mode,project){switch(mode){case "predefined":{EASE_MAP.set(name,func);PREDEFINED_EASE_MAP.set(name,func);break}case "custom":{if(project){if(!CUSTOM_EASE_EDITOR_MAP.has(project))CUSTOM_EASE_EDITOR_MAP.set(project,new Map);const customEaseMap=CUSTOM_EASE_EDITOR_MAP.get(project);customEaseMap.set(name,func)}else CUSTOM_EASE_RUNTIME_MAP.set(name,func);break}case "private":{EASE_MAP.set(name,func);PRIVATE_EASE_MAP.set(name,func);break}default:throw new Error("unexpected ease mode");}}static NoEase(t,
+b,c,d){return c*t/d+b}static EaseInQuad(t,b,c,d){return c*(t/=d)*t+b}static EaseOutQuad(t,b,c,d){return-c*(t/=d)*(t-2)+b}static EaseInOutQuad(t,b,c,d){if((t/=d/2)<1)return c/2*t*t+b;return-c/2*(--t*(t-2)-1)+b}static EaseInCubic(t,b,c,d){return c*(t/=d)*t*t+b}static EaseOutCubic(t,b,c,d){return c*((t=t/d-1)*t*t+1)+b}static EaseInOutCubic(t,b,c,d){if((t/=d/2)<1)return c/2*t*t*t+b;return c/2*((t-=2)*t*t+2)+b}static EaseInQuart(t,b,c,d){return c*(t/=d)*t*t*t+b}static EaseOutQuart(t,b,c,d){return-c*((t=
+t/d-1)*t*t*t-1)+b}static EaseInOutQuart(t,b,c,d){if((t/=d/2)<1)return c/2*t*t*t*t+b;return-c/2*((t-=2)*t*t*t-2)+b}static EaseInQuint(t,b,c,d){return c*(t/=d)*t*t*t*t+b}static EaseOutQuint(t,b,c,d){return c*((t=t/d-1)*t*t*t*t+1)+b}static EaseInOutQuint(t,b,c,d){if((t/=d/2)<1)return c/2*t*t*t*t*t+b;return c/2*((t-=2)*t*t*t*t+2)+b}static EaseInSine(t,b,c,d){return-c*Math.cos(t/d*(Math.PI/2))+c+b}static EaseOutSine(t,b,c,d){return c*Math.sin(t/d*(Math.PI/2))+b}static EaseInOutSine(t,b,c,d){return-c/2*
+(Math.cos(Math.PI*t/d)-1)+b}static EaseInExpo(t,b,c,d){return t===0?b:c*Math.pow(2,10*(t/d-1))+b}static EaseOutExpo(t,b,c,d){return t===d?b+c:c*(-Math.pow(2,-10*t/d)+1)+b}static EaseInOutExpo(t,b,c,d){if(t===0)return b;if(t===d)return b+c;if((t/=d/2)<1)return c/2*Math.pow(2,10*(t-1))+b;return c/2*(-Math.pow(2,-10*--t)+2)+b}static EaseInCirc(t,b,c,d){return-c*(Math.sqrt(1-(t/=d)*t)-1)+b}static EaseOutCirc(t,b,c,d){return c*Math.sqrt(1-(t=t/d-1)*t)+b}static EaseInOutCirc(t,b,c,d){if((t/=d/2)<1)return-c/
+2*(Math.sqrt(1-t*t)-1)+b;return c/2*(Math.sqrt(1-(t-=2)*t)+1)+b}static EaseInElastic(t,b,c,d){let s=1.70158;let p=0;let a=c;if(t===0)return b;if((t/=d)===1)return b+c;if(!p)p=d*.3;if(a{return p3-3*p2+3*p1-p0};const b=(p0,p1,p2,p3)=>{return 3*p2-6*p1+3*p0};const c=(p0,p1,p2,p3)=>{return 3*(p1-p0)};const calc_bezier=(aT,a,b,c)=>{return((a*aT+b)*aT+c)*aT};const get_slope=(aT,a,b,c)=>{return 3*a*aT*aT+2*b*aT+c};
+const get_t_for_x=(aX,p0,p1,p2,p3,samples)=>{if(aX==1)return 1;let intervalStart=0;let currentSampleIndex=1;let currentSampleValue=samples[currentSampleIndex];let lastSampleIndex=SAMPLE_COUNT-1;let lastSampleValue=samples[SAMPLE_COUNT-1];while(currentSampleIndex!=lastSampleIndex&¤tSampleValue<=aX){currentSampleIndex++;currentSampleValue=samples[currentSampleIndex];intervalStart+=SAMPLE_STEP}currentSampleIndex--;currentSampleValue=samples[currentSampleIndex];const dist=(aX-currentSampleValue)/
+(samples[currentSampleIndex+1]-currentSampleValue);let guess=intervalStart+dist*SAMPLE_STEP;const va=a(p0,p1,p2,p3);const vb=b(p0,p1,p2,p3);const vc=c(p0,p1,p2,p3);const initSlope=get_slope(guess,va,vb,vc);if(initSlope===0)return guess;else if(initSlope>=NEWTON_RAPHSON_MIN_SLOPE){for(let i=0;i0)aB=guess;else aA=guess;precissionLimit=Math.abs(x)>SUBDIVISION_PRECISION;maxIterations=++i0)return;C3.clearArray(this._captureListeners);this._captureListenersSet.clear();C3.clearArray(this._listeners);this._listenersSet.clear();C3.clearArray(this._queueModifyListeners);C3.Release(this)}_AddListener(func,
+capture){if(this._IsFiring()){this._queueModifyListeners.push({op:"add",func,capture});return}if(capture){if(this._captureListenersSet.has(func))return;this._captureListeners.push(func);this._captureListenersSet.add(func)}else{if(this._listenersSet.has(func))return;this._listeners.push(func);this._listenersSet.add(func)}}_RemoveListener(func,capture){if(this._IsFiring()){this._queueModifyListeners.push({op:"remove",func,capture});return}if(capture){if(this._captureListenersSet.has(func)){this._captureListenersSet.delete(func);
+C3.arrayFindRemove(this._captureListeners,func)}}else if(this._listenersSet.has(func)){this._listenersSet.delete(func);C3.arrayFindRemove(this._listeners,func)}}_IsEmpty(){return!this._captureListeners.length&&!this._listeners.length}_IsFiring(){return this._fireDepth>0}_ProcessQueuedListeners(){const removeListenersSet=new Set;const removeCaptureListenersSet=new Set;for(const q of this._queueModifyListeners)if(q.op==="add"){this._AddListener(q.func,q.capture);if(q.capture)removeCaptureListenersSet.delete(q.func);
+else removeListenersSet.delete(q.func)}else if(q.op==="remove")if(q.capture){this._captureListenersSet.delete(q.func);removeCaptureListenersSet.add(q.func)}else{this._listenersSet.delete(q.func);removeListenersSet.add(q.func)}else throw new Error("invalid op");C3.arrayRemoveAllInSet(this._listeners,removeListenersSet);C3.arrayRemoveAllInSet(this._captureListeners,removeCaptureListenersSet);C3.clearArray(this._queueModifyListeners)}_FireCancellable(event){this._IncreaseFireDepth();let isStopped=false;
+for(let i=0,len=this._captureListeners.length;i0)this._ProcessQueuedListeners()}SetDelayRemoveEventsEnabled(e){if(e)this._IncreaseFireDepth();else this._DecreaseFireDepth()}_FireAsync(event){let callbackPromises=[];for(let i=0,len=this._captureListeners.length;i
+func(event)))}for(let i=0,len=this._listeners.length;ifunc(event)))}return Promise.all(callbackPromises).then(()=>!event.defaultPrevented)}_FireAndWait_AsyncOptional(event){const results=[];this._IncreaseFireDepth();for(let i=0,len=this._captureListeners.length;i!event.defaultPrevented);else return!event.defaultPrevented}async _FireAndWaitAsync(event){return await this._FireAndWait_AsyncOptional(event)}async _FireAndWaitAsyncSequential(event){this._IncreaseFireDepth();for(let i=0,len=this._captureListeners.length;i0?1:timerTimeout)}
+function DoAsyncifiedWork(deadline){callbackId=-1;if(!workQueue.length)return;let startTime=performance.now();let curTime=startTime;let jobCount=0;let estimatedNextJobDuration=0;do{DoNextAsyncifiedJob(workQueue.shift());curTime=performance.now();++jobCount;estimatedNextJobDuration=(curTime-startTime)/jobCount*1.1}while(workQueue.length&&(SUPPORTS_RIC&&highThroughputMode===0&&typeof deadline!=="undefined"?estimatedNextJobDuration{workQueue.push({func:func,resolve:resolve,reject:reject,stack:stack});if(asyncifyDisabled){DoNextAsyncifiedJob(workQueue.pop());return}if(callbackId===-1)SetNewCallback(SETTIMEOUT_INTERVAL)})};
+C3.Asyncify.SetHighThroughputMode=function SetHighThroughputMode(m){if(m)++highThroughputMode;else{--highThroughputMode;if(highThroughputMode<0)throw new Error("already turned off high throughput mode");}};
+
+}
+
+// ../lib/util/idleTimeout.js
+{
+'use strict';const C3=self.C3;const IDLE_CHECK_MIN_INTERVAL=1E3;const IDLE_CHECK_TIMER_OVERSHOOT=100;let cachedNowTime=-1;function ClearTimeCache(){cachedNowTime=-1}C3.FastGetDateNow=function FastGetDateNow(){if(cachedNowTime===-1){cachedNowTime=Date.now();self.setTimeout(ClearTimeCache,16)}return cachedNowTime};let timerId=-1;let nextDeadline=-1;let activeIdleTimeouts=new Set;
+function CheckActiveIdleTimeouts(){timerId=-1;nextDeadline=-1;let nowTime=Date.now();for(let i of activeIdleTimeouts)if(i._CheckTimeout(nowTime)){let deadline=i._GetDeadline();if(nextDeadline===-1||deadlinenowTime+
+IDLE_CHECK_MIN_INTERVAL){self.clearTimeout(timerId);nextDeadline=this._deadline;timerId=self.setTimeout(CheckActiveIdleTimeouts,this._timeout+IDLE_CHECK_TIMER_OVERSHOOT)}}_CheckTimeout(nowTime){if(nowTime>=this._deadline){if(this._callback()){this._deadline=nowTime+this._timeout;return true}this._isActive=false;return false}return true}_GetDeadline(){return this._deadline}Cancel(){if(this._isActive){activeIdleTimeouts.delete(this);this._isActive=false;if(activeIdleTimeouts.size===0&&timerId!==-1){self.clearTimeout(timerId);
+timerId=-1;nextDeadline=-1}}}Release(){this.Cancel();this._callback=null}};
+
+}
+
+// ../lib/util/disposable.js
+{
+'use strict';const C3=self.C3;
+C3.Disposable=class Disposable{constructor(disposeAction){this._disposed=false;this._disposeAction=disposeAction}Dispose(){if(this._disposed)return;this._disposed=true;if(this._disposeAction){this._disposeAction();this._disposeAction=null}}IsDisposed(){return this._disposed}Release(){this.Dispose()}static Release(instance){return new Disposable(()=>instance.Release())}static From(eventDispatcher,eventNames,eventHandler,opts,scope){if(typeof opts==="undefined"||opts===null)opts=false;else if(typeof opts!==
+"boolean"&&typeof opts!=="object")throw new TypeError("invalid event listener options");if(scope)eventHandler=eventHandler.bind(scope);if(eventNames.includes(" ")){eventNames=eventNames.split(" ");const disposable=new C3.CompositeDisposable;for(let eventName of eventNames){eventDispatcher.addEventListener(eventName,eventHandler,opts);disposable.Add(C3.New(C3.Disposable,()=>eventDispatcher.removeEventListener(eventName,eventHandler,opts)))}return disposable}else{eventDispatcher.addEventListener(eventNames,
+eventHandler,opts);return C3.New(C3.Disposable,()=>eventDispatcher.removeEventListener(eventNames,eventHandler,opts))}}};C3.StubDisposable=class StubDisposable extends C3.Disposable{SetAction(disposeAction){this._disposeAction=disposeAction}};
+C3.CompositeDisposable=class CompositeDisposable extends C3.Disposable{constructor(...disposables){super();this._disposables=new Set;for(let disposable of disposables)this.Add(disposable)}Add(...disposables){if(this._disposed)throw new Error("already disposed");for(let disposable of disposables)this._disposables.add(disposable)}Remove(disposable){if(this._disposed)throw new Error("already disposed");this._disposables.delete(disposable)}RemoveAll(){if(this._disposed)throw new Error("already disposed");
+if(!this._disposables)return;for(let disposable of this._disposables)disposable.Dispose();this._disposables.clear()}IsDisposed(){return this._disposed}Dispose(){if(this._disposed)throw new Error("already disposed");this._disposed=true;for(let disposable of this._disposables)disposable.Dispose();this._disposables.clear();this._disposables=null}Release(){this.Dispose()}};
+
+}
+
+// lib/util/kahanSum.js
+{
+'use strict';const C3=self.C3;C3.KahanSum=class KahanSum extends C3.DefendedBase{constructor(){super();this._c=0;this._y=0;this._t=0;this._sum=0}Add(v){v=+v;this._y=v-this._c;this._t=this._sum+this._y;this._c=this._t-this._sum-this._y;this._sum=this._t}Subtract(v){this._sum-=+v}Get(){return this._sum}Reset(){this._c=0;this._y=0;this._t=0;this._sum=0}Set(s){this._c=0;this._y=0;this._t=0;this._sum=+s}Copy(ks){this._c=ks._c;this._y=ks._y;this._t=ks._t;this._sum=ks._sum}Release(){}};
+
+}
+
+// lib/util/redblackset.js
+{
+'use strict';const C3=self.C3;const js_cols={};const RED=true;const BLACK=false;js_cols.RBnode=function(tree){this.tree=tree;this.right=this.tree.sentinel;this.left=this.tree.sentinel;this.parent=null;this.color=false;this.key=null};js_cols.RedBlackSet=function(compare_func){this.size=0;this.sentinel=new js_cols.RBnode(this);this.sentinel.color=BLACK;this.root=this.sentinel;this.root.parent=this.sentinel;this.compare=compare_func||this.default_compare};
+js_cols.RedBlackSet.prototype.default_compare=function(a,b){if(a0){var x=this.get_(key);if(x==this.sentinel)return null;if(x.right!=this.sentinel)return this.min(x.right).key;var y=x.parent;while(y!=this.sentinel&&x==y.right){x=y;y=y.parent}if(y!=this.sentinel)return y.key;else return null}else return null};
+js_cols.RedBlackSet.prototype.predecessor=function(key){if(this.size>0){var x=this.get_(key);if(x==this.sentinel)return null;if(x.left!=this.sentinel)return this.max(x.left).key;var y=x.parent;while(y!=this.sentinel&&x==y.left){x=y;y=y.parent}if(y!=this.sentinel)return y.key;else return null}else return null};js_cols.RedBlackSet.prototype.getMin=function(){return this.min(this.root).key};js_cols.RedBlackSet.prototype.getMax=function(){return this.max(this.root).key};
+js_cols.RedBlackSet.prototype.get_=function(key){var x=this.root;while(x!=this.sentinel&&this.compare(x.key,key)!=0)if(this.compare(key,x.key)<0)x=x.left;else x=x.right;return x};js_cols.RedBlackSet.prototype.contains=function(key){return this.get_(key).key!=null};js_cols.RedBlackSet.prototype.getValues=function(){var ret=[];this.forEach(function(x){ret.push(x)});return ret};
+js_cols.RedBlackSet.prototype.insertAll=function(col){if(js_cols.typeOf(col)=="array")for(var i=0;icolCount)return false;var i=0;if(this.isEmpty())return true;for(var n=this.min(this.root);n!=this.sentinel;n=this.successor_(n))if(js_cols.contains.call(col,col,n.key))i++;return i==this.getCount()};
+js_cols.RedBlackSet.prototype.intersection=function(col){var result=new js_cols.RedBlackSet(this.compare);if(this.isEmpty())return result;for(var n=this.min(this.root);n!=this.sentinel;n=this.successor_(n))if(col.contains.call(col,n.key,n.key,this))result.insert(n.key);return result};
+C3.RedBlackSet=class RedBlackSet extends C3.DefendedBase{constructor(sortFunc){super();this._rbSet=new js_cols.RedBlackSet(sortFunc);this._enableQueue=false;this._queueInsert=new Set;this._queueRemove=new Set}Add(item){if(this._enableQueue)if(this._rbSet.contains(item))this._queueRemove.delete(item);else this._queueInsert.add(item);else this._rbSet.insert(item)}Remove(item){if(this._enableQueue)if(this._rbSet.contains(item))this._queueRemove.add(item);else this._queueInsert.delete(item);else this._rbSet.remove(item)}Has(item){if(this._enableQueue){if(this._queueInsert.has(item))return true;
+return!this._queueRemove.has(item)&&this._rbSet.contains(item)}else return this._rbSet.contains(item)}Clear(){this._rbSet.clear();this._queueInsert.clear();this._queueRemove.clear()}toArray(){if(this._enableQueue)throw new Error("cannot be used in queueing mode");return this._rbSet.getValues()}GetSize(){return this._rbSet.getCount()+this._queueInsert.size-this._queueRemove.size}IsEmpty(){return this.GetSize()===0}Front(){if(this.IsEmpty())throw new Error("empty set");if(this._enableQueue)throw new Error("cannot be used in queueing mode");
+const rbSet=this._rbSet;const n=rbSet.min(rbSet.root);return n.key}Shift(){if(this.IsEmpty())throw new Error("empty set");if(this._enableQueue)throw new Error("cannot be used in queueing mode");const item=this.Front();this.Remove(item);return item}SetQueueingEnabled(q){q=!!q;if(this._enableQueue===q)return;this._enableQueue=q;if(!q){for(const item of this._queueRemove)this._rbSet.remove(item);this._queueRemove.clear();for(const item of this._queueInsert)this._rbSet.insert(item);this._queueInsert.clear()}}ForEach(func){this._rbSet.forEach(func)}*values(){if(this.IsEmpty())return;
+const rbSet=this._rbSet;for(let n=rbSet.min(rbSet.root);n!=rbSet.sentinel;n=rbSet.successor_(n))yield n.key}[Symbol.iterator](){return this.values()}};
+
+}
+
+// ../lib/util/promiseThrottle.js
+{
+'use strict';const C3=self.C3;
+C3.PromiseThrottle=class PromiseThrottle{constructor(maxParallel=C3.hardwareConcurrency){this._maxParallel=maxParallel;this._queue=[];this._activeCount=0}Add(func){return new Promise((resolve,reject)=>{this._queue.push({func,resolve,reject});this._MaybeStartNext()})}_FindInQueue(func){for(let i=0,len=this._queue.length;i=this._maxParallel)return;this._activeCount++;const job=this._queue.shift();try{const result=await job.func();job.resolve(result)}catch(err){job.reject(err)}this._activeCount--;this._MaybeStartNext()}static async Batch(concurrency,
+methods){const results=[];let failed=false;const execute=async _=>{let fn;while(fn=methods.pop()){if(failed)return;try{results.push(await fn())}catch(e){failed=true;throw e;}}};const promises=[];while(concurrency--)promises.push(execute());await Promise.all(promises);return results}};
+
+}
+
+// ../lib/util/rateLimiter.js
+{
+'use strict';const C3=self.C3;
+C3.RateLimiter=class RateLimiter{constructor(callback,interval,intervalOnBattery){this._callback=callback;this._interval=interval;this._intervalOnBattery=intervalOnBattery||interval*2;this._timerId=-1;this._lastCallTime=-Infinity;this._timerCallFunc=()=>this._OnTimer();this._ignoreReset=false;this._canRunImmediate=false;this._callbackArguments=null}SetCanRunImmediate(c){this._canRunImmediate=!!c}_GetInterval(){if(typeof C3.Battery!=="undefined"&&C3.Battery.IsOnBatteryPower())return this._intervalOnBattery;else return this._interval}Call(...args){if(this._timerId!==
+-1)return;this._callbackArguments=args;let nowTime=C3.FastGetDateNow();let timeSinceLastCall=nowTime-this._lastCallTime;let interval=this._GetInterval();if(timeSinceLastCall>=interval&&this._canRunImmediate){this._lastCallTime=nowTime;this._RunCallback()}else this._timerId=self.setTimeout(this._timerCallFunc,Math.max(interval-timeSinceLastCall,4))}_RunCallback(){this._ignoreReset=true;const args=this._callbackArguments;this._callbackArguments=null;if(args)this._callback(...args);else this._callback();
+this._ignoreReset=false}Reset(){if(this._ignoreReset)return;this._CancelTimer();this._callbackArguments=null;this._lastCallTime=C3.FastGetDateNow()}_OnTimer(){this._timerId=-1;this._lastCallTime=C3.FastGetDateNow();this._RunCallback()}_CancelTimer(){if(this._timerId!==-1){self.clearTimeout(this._timerId);this._timerId=-1}}Release(){this._CancelTimer();this._callback=null;this._callbackArguments=null;this._timerCallFunc=null}};
+
+}
+
+// ../lib/util/svgRaster/svgRasterManager.js
+{
+'use strict';const C3=self.C3;
+C3.SVGRasterManager=class SVGRasterManager{constructor(){this._images=new Map;this._allowNpotSurfaces=false;this._getBaseSizeCallback=null;this._rasterAtSizeCallback=null;this._releaseResultCallback=null;this._redrawCallback=null}SetNpotSurfaceAllowed(a){this._allowNpotSurfaces=!!a}IsNpotSurfaceAllowed(){return this._allowNpotSurfaces}SetGetBaseSizeCallback(f){this._getBaseSizeCallback=f}GetBaseSize(dataSource){if(!this._getBaseSizeCallback)throw new Error("no get base size callback set");return this._getBaseSizeCallback(dataSource)}SetRasterAtSizeCallback(f){this._rasterAtSizeCallback=
+f}RasterAtSize(dataSource,context,surfaceWidth,surfaceHeight,imageWidth,imageHeight){if(!this._rasterAtSizeCallback)throw new Error("no raster at size callback set");return this._rasterAtSizeCallback(dataSource,context,surfaceWidth,surfaceHeight,imageWidth,imageHeight)}SetReleaseResultCallback(f){this._releaseResultCallback=f}ReleaseResult(rasterizedResult){if(!this._releaseResultCallback)throw new Error("no release result callback set");this._releaseResultCallback(rasterizedResult)}SetRedrawCallback(f){this._redrawCallback=
+f}Redraw(){if(!this._redrawCallback)throw new Error("no redraw callback set");this._redrawCallback()}AddImage(dataSource){let ret=this._images.get(dataSource);if(!ret){ret=C3.New(C3.SVGRasterImage,this,dataSource);this._images.set(dataSource,ret)}ret.IncReference();return ret}_RemoveImage(ri){this._images.delete(ri.GetDataSource())}OnTexturesChanged(){for(const ri of this._images.values()){ri.ReleaseRasterizedResult();ri.ForceRasterAgain()}}};
+
+}
+
+// ../lib/util/svgRaster/svgRasterImage.js
+{
+'use strict';const C3=self.C3;const MAX_SURFACE_SIZE=4096;
+C3.SVGRasterImage=class SVGRasterImage{constructor(manager,dataSource){this._manager=manager;this._dataSource=dataSource;this._refCount=0;this._baseWidth=0;this._baseHeight=0;this._getBaseSizePromise=this._manager.GetBaseSize(dataSource).then(baseSize=>{if(!this._manager)return;this._baseWidth=baseSize[0];this._baseHeight=baseSize[1];this._manager.Redraw()}).catch(err=>{console.error("[SVG] Error loading SVG: ",err);this._hadError=true;if(this._manager)this._manager.Redraw()});this._rasterSurfaceWidth=
+0;this._rasterSurfaceHeight=0;this._rasterImageWidth=0;this._rasterImageHeight=0;this._isRasterizing=false;this._rasterizedResult=null;this._forceRaster=false;this._hadError=false}Release(){if(this._refCount<=0)throw new Error("already released");this._refCount--;if(this._refCount===0)this._Release()}ReleaseRasterizedResult(){if(this._rasterizedResult){this._manager.ReleaseResult(this._rasterizedResult);this._rasterizedResult=null}}_Release(){this.ReleaseRasterizedResult();this._manager._RemoveImage(this);
+this._manager=null}GetDataSource(){return this._dataSource}IncReference(){this._refCount++}HasReferences(){return this._refCount>0}GetRasterizedResult(){return this._rasterizedResult}ForceRasterAgain(){this._forceRaster=true}async StartRasterForSize(context,width,height){if(width===0||height===0||this._hadError)return;if(this._isRasterizing)return;let rasterSurfaceWidth=C3.nextHighestPowerOfTwo(Math.ceil(width));let rasterSurfaceHeight=C3.nextHighestPowerOfTwo(Math.ceil(height));const maxDim=Math.max(rasterSurfaceWidth,
+rasterSurfaceHeight);if(maxDim>MAX_SURFACE_SIZE){const scale=MAX_SURFACE_SIZE/maxDim;width*=scale;height*=scale;rasterSurfaceWidth=Math.min(Math.ceil(rasterSurfaceWidth*scale),MAX_SURFACE_SIZE);rasterSurfaceHeight=Math.min(Math.ceil(rasterSurfaceHeight*scale),MAX_SURFACE_SIZE)}if(widthimageAspectRatio){width=rasterSurfaceHeight*
+imageAspectRatio;height=rasterSurfaceHeight}else{width=rasterSurfaceWidth;height=rasterSurfaceWidth/imageAspectRatio}}if(this._manager.IsNpotSurfaceAllowed()){rasterSurfaceWidth=Math.ceil(width);rasterSurfaceHeight=Math.ceil(height)}if(rasterSurfaceWidth<=this._rasterSurfaceWidth&&rasterSurfaceHeight<=this._rasterSurfaceHeight&&!this._forceRaster)return;this._isRasterizing=true;this._rasterSurfaceWidth=rasterSurfaceWidth;this._rasterSurfaceHeight=rasterSurfaceHeight;const newRasterizedResult=await this._manager.RasterAtSize(this._dataSource,
+context,this._rasterSurfaceWidth,this._rasterSurfaceHeight,width,height);if(!this._manager)return;this.ReleaseRasterizedResult();this._rasterizedResult=newRasterizedResult;this._rasterImageWidth=width;this._rasterImageHeight=height;this._isRasterizing=false;this._forceRaster=false;this._manager.Redraw()}WhenBaseSizeReady(){return this._getBaseSizePromise}GetBaseWidth(){return this._baseWidth}GetBaseHeight(){return this._baseHeight}GetRasterWidth(){return this._rasterImageWidth}GetRasterHeight(){return this._rasterImageHeight}HadError(){return this._hadError}};
+
+}
+
+// ../lib/str/str.js
+{
+'use strict';const C3=self.C3;C3.UTF8_BOM="\ufeff";const NUMERIC_CHARS=new Set([..."0123456789"]);C3.IsNumericChar=function IsNumericChar(c){return NUMERIC_CHARS.has(c)};const WHITESPACE_CHARS=new Set([..." \t\n\r\u00a0\u0085\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u202f\u205f\u3000"]);C3.IsWhitespaceChar=function IsWhitespaceChar(c){return WHITESPACE_CHARS.has(c)};C3.FilterWhitespace=function FilterWhitespace(str){return[...str].filter(ch=>!C3.IsWhitespaceChar(ch)).join("")};
+C3.IsStringAllWhitespace=function IsStringAllWhitespace(str){for(const ch of str)if(!C3.IsWhitespaceChar(ch))return false;return true};C3.IsCharArrayAllWhitespace=function IsStringAllWhitespace(chArr){for(const ch of chArr)if(!C3.IsWhitespaceChar(ch))return false;return true};C3.IsUnprintableChar=function IsUnprintableChar(c){return c.length===1&&c.charCodeAt(0)<32};C3.FilterUnprintableChars=function FilterUnprintableChars(str){return[...str].filter(ch=>!C3.IsUnprintableChar(ch)).join("")};
+const NUMERIC_STRING_CHARS=new Set([..."0123456789.+-e"]);C3.IsStringNumber=function IsStringNumber(str){str=str.trim();if(!str.length)return false;let firstChar=str.charAt(0);if(firstChar!=="-"&&!NUMERIC_CHARS.has(firstChar))return false;for(let ch of str)if(!NUMERIC_STRING_CHARS.has(ch))return false;return true};C3.RemoveTrailingDigits=function RemoveTrailingDigits(str){let i=str.length;while(i>0){let prev_ch=str.charAt(i-1);if(!C3.IsNumericChar(prev_ch))break;--i}return str.substr(0,i)};
+C3.IncrementNumberAtEndOf=function IncrementNumberAtEndOf(str){let baseStr=C3.RemoveTrailingDigits(str);let numberStr=str.substr(baseStr.length);if(numberStr)numberStr=(parseInt(numberStr,10)+1).toString();else numberStr="2";return baseStr+numberStr};const HTML_ENTITY_MAP=new Map([["&","&"],["<","<"],[">",">"],['"',"""],["'","'"]]);function lookupHtmlEntity(s){return HTML_ENTITY_MAP.get(s)}const HTML_ENTITY_REGEX=/[&<>"']/g;
+C3.EscapeHTML=function EscapeHTML(str){return str.replace(HTML_ENTITY_REGEX,lookupHtmlEntity)};C3.EscapeJS=function EscapeJS(str){let ret=C3.ReplaceAll(str,"\\","\\\\");ret=C3.ReplaceAll(ret,'"','\\"');ret=C3.ReplaceAll(ret,"\t","\\t");ret=C3.ReplaceAll(ret,"\r","");return C3.ReplaceAll(ret,"\n","\\n")};C3.EscapeXML=function EscapeXML(str){let ret=C3.ReplaceAll(str,"&","&");ret=C3.ReplaceAll(ret,"<","<");ret=C3.ReplaceAll(ret,">",">");return C3.ReplaceAll(ret,'"',""")};
+const ESCAPE_REGEX=/[-[\]{}()*+?.,\\^$|#\s]/g;C3.EscapeRegex=function EscapeRegex(str){return str.replace(ESCAPE_REGEX,"\\$&")};C3.CountCharsInString=function CountCharsInString(str,ch){let count=0;for(const c of str)if(c===ch)++count;return count};
+C3.FindAll=function FindAll(str,find,matchCase=false){if(!find)return[];if(!matchCase){str=str.toLowerCase();find=find.toLowerCase()}const findLen=find.length;let startIndex=0;let index=0;let ret=[];while((index=str.indexOf(find,startIndex))>-1){ret.push(index);startIndex=index+findLen}return ret};C3.ReplaceAll=function ReplaceAll(str,find,replace){return str.replaceAll(find,()=>replace)};
+C3.ReplaceAllCaseInsensitive=function ReplaceAll(str,find,replace){return str.replace(new RegExp(C3.EscapeRegex(find),"gi"),()=>replace)};C3.SetElementContent=function SetElementContent(elem,stringlike){if(typeof stringlike==="string")elem.textContent=stringlike;else if(stringlike.isPlainText())elem.textContent=stringlike.toString();else{elem.innerHTML=stringlike.toHTML();if(stringlike instanceof C3.BBString)stringlike.attachLinkHandlers(elem)}};
+C3.StringLikeEquals=function StringLikeEquals(a,b){if(a instanceof C3.HtmlString||a instanceof C3.BBString)return a.equals(b);else if(b instanceof C3.HtmlString||b instanceof C3.BBString)return b.equals(a);else return a===b};C3.StringSubstitute=function StringSubstitute(str,...arr){let ret=str;for(let i=0,len=arr.length;i=0&&highestUsedIndex>=0&&lowestMissingIndexb)return 1;else if(alowerB)return 1;else if(lowerA0){secondsTotal-=days*24*3600;parts.push(langPluralSub(".days",null,days))}}if(opts.hours){const hours=Math.floor(secondsTotal/3600);if(hours>0||parts.length){secondsTotal-=hours*3600;parts.push(langPluralSub(".hours",
+null,hours))}}if(opts.minutes){const minutes=Math.floor(secondsTotal/60);if(minutes>0||parts.length||!opts.seconds){secondsTotal-=minutes*60;parts.push(langPluralSub(".minutes",null,minutes))}}if(opts.seconds){const seconds=Math.floor(secondsTotal%60);parts.push(langPluralSub(".seconds",null,seconds))}const ret=(opts.approximate?lang(".approx-prefix"):"")+parts.join(lang(".separator"));C3.Lang.PopContext();return ret};
+C3.ZeroPad=function(n,d){let s=n<0?"-":"";n=Math.abs(n);let nStr=n.toString();let zeroes=d-nStr.length;for(let i=0;it.toUpperCase())};
+C3.CompareVersionStrings=function CompareVersionStrings(v1,v2){let a1=v1.split(".").map(s=>s.trim());let a2=v2.split(".").map(s=>s.trim());C3.resizeArray(a1,4,"0");C3.resizeArray(a2,4,"0");a1=a1.map(s=>parseInt(s,10));a2=a2.map(s=>parseInt(s,10));for(let i=0;i<4;++i){const diff=a1[i]-a2[i];if(diff!==0)return diff<0?-1:1}return 0};C3.CreateGUID=function CreateGUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,c=>{const r=Math.floor(Math.random()*16);const v=c==="x"?r:r&3|8;return v.toString(16)})};
+C3.StringHammingDistance=function StringHammingDistance(a,b){if(a.length!==b.length)throw new Error("strings must be same length");let ret=0;for(let i=0,len=a.length;ib.length){tmp=a;a=b;b=tmp}row=Array(a.length+1);for(i=0;i<=a.length;i++)row[i]=i;for(i=1;i<=b.length;i++){prev=i;for(j=1;j<=a.length;j++){if(b[i-1]===a[j-1])val=row[j-1];else val=Math.min(row[j-1]+1,Math.min(prev+1,row[j]+1));row[j-1]=prev;prev=val}row[a.length]=prev}return row[a.length]};
+
+}
+
+// ../lib/str/bbstring.js
+{
+'use strict';const C3=self.C3;const assert=self.assert;
+const BB_CODE_MAP=new Map([["b","strong"],["i","em"],["s","s"],["u","u"],["sub","sub"],["sup","sup"],["small","small"],["mark","mark"],["code","code"],["a1","a"],["a2","a"],["a3","a"],["a4","a"],["a5","a"],["a6","a"],["a7","a"],["a8","a"],["a9","a"],["tip1","abbr"],["tip2","abbr"],["tip3","abbr"],["tip4","abbr"],["tip5","abbr"],["tip6","abbr"],["tip7","abbr"],["tip8","abbr"],["tip9","abbr"],["bad",["span","bbCodeBad"]],["good",["span","bbCodeGood"]],["info",["span","bbCodeInfo"]],["h1",["span","bbCodeH1"]],
+["h2",["span","bbCodeH2"]],["h3",["span","bbCodeH3"]],["h4",["span","bbCodeH4"]],["item",["span","bbCodeItem"]]]);const SELF_CLOSING_TAGS=new Set(["icon"]);const BBREGEX=/\[(\/?)([a-zA-Z0-9]+)\]/g;const CUSTOM_BBREGEX=/\[(\/?)([^\[\n]*?)\]/g;let linkActions=null;let tipList=null;let classIndex=0;
+function bbToHtmlReplacerFunc(match,closeSlash,tagName){const entry=BB_CODE_MAP.get(tagName);if(entry)if(typeof entry==="string"){if(entry==="a"&&linkActions.length===0||entry==="abbr"&&tipList.length===0)return match;if(entry==="a"&&!closeSlash){const index=parseInt(tagName.substring(1),10)-1;if(index<0||index>=linkActions.length)throw new Error("invalid bbcode link substitution");const linkAction=linkActions[index];if(typeof linkAction==="string")return``;else if(typeof linkAction===
+"function")return``;else throw new TypeError("invalid bbcode link action");}else if(entry==="abbr"&&!closeSlash){const index=parseInt(tagName.substring(3),10)-1;if(index<0||index>=tipList.length)throw new Error("invalid bbcode tip substitution");const tip=tipList[index];let tipStr="";if(typeof tip==="string")tipStr=tip;else if(typeof tip==="function")tipStr=tip();if(typeof tipStr!=="string")throw new TypeError("invalid bbcode tip");return``}else return"<"+closeSlash+entry+">"}else if(Array.isArray(entry)){let tag=entry[0];let className=entry[1];if(closeSlash)return""+tag+">";else return`<${tag} class="${className}">`}else;else if(tagName==="class")if(closeSlash)return"";else return``;else return match}const LINEBREAK_REGEX=/\n/g;
+C3.BBString=class BBString{constructor(str,opts){this._bbstr=opts&&opts.noEscape?str:C3.EscapeHTML(str);this._htmlstr="";this._convertLineBreaks=false;this._linkActions=[];this._tipList=[];if(opts){this._convertLineBreaks=!!opts.convertLineBreaks;if(opts.links){if(opts.links.length>9)throw new Error("too many links");this._linkActions=opts.links}if(opts.tips){if(opts.tips.length>9)throw new Error("too many tips");this._tipList=opts.tips}}this._hasAnyBBtags=this._bbstr.includes("[");this._needsLineBreakConversion=
+this._convertLineBreaks&&this._bbstr.includes("\n");this._isPlain=!this._hasAnyBBtags&&!this._needsLineBreakConversion&&!this._bbstr.includes("&");this._hasParsedFragments=false;this._fragments=[]}toString(){return this._bbstr}valueOf(){return this._bbstr}isPlainText(){return this._isPlain}toPlainText(){if(this._hasAnyBBtags)return this._bbstr.replace(BBREGEX,"");else return this._bbstr}toHTML(){if(this._isPlain)return this._bbstr;if(!this._htmlstr&&this._bbstr){let str=this._bbstr;if(this._hasAnyBBtags){classIndex=
+0;linkActions=this._linkActions;tipList=this._tipList;str=str.replace(BBREGEX,bbToHtmlReplacerFunc);linkActions=null;tipList=null}if(this._needsLineBreakConversion)str=str.replace(LINEBREAK_REGEX,"
");this._htmlstr=str}return this._htmlstr}attachLinkHandlers(parentElem){if(!this._linkActions.length)return;for(let i=0,len=this._linkActions.length;i0&&bbStr.charAt(index-1)==="\\")continue;
+const matchStr=result[0];const closeSlash=result[1];const tagName=result[2];const strFrag=bbStr.substring(prevIndex,index);prevIndex=index+matchStr.length;if(strFrag)fragments.push({text:strFrag,styles:styleStack.slice(0)});if(!tagName)continue;if(closeSlash){const lowerTagName=tagName.toLowerCase();for(let i=styleStack.length-1;i>=0;--i)if(styleStack[i].tag===lowerTagName){styleStack.splice(i,1);break}}else{let tag=tagName;let param=null;const eq=tagName.indexOf("=");if(eq!==-1){tag=tagName.substring(0,
+eq).toLowerCase();param=tagName.substring(eq+1)}else tag=tag.toLowerCase();if(SELF_CLOSING_TAGS.has(tag))if(tag==="icon")fragments.push({icon:param,styles:styleStack.slice(0)});else throw new Error(`unknown self-closing tag ${tag}`);else styleStack.push({tag,param})}}if(prevIndex
+{if(frag.icon)return C3.New(C3.IconFragment,{icon:frag.icon,styles:frag.styles});else return C3.New(C3.TextFragment,{chArr:C3.SplitGraphemes(frag.text),styles:frag.styles})});this._hasParsedFragments=true;return this._fragments}_ProcessBBCodeEscapeSequences(text){text=C3.ReplaceAll(text,"\\[","[");return C3.ReplaceAll(text,"\\\\","\\")}static StripTags(str){return C3.New(C3.BBString,str,{noEscape:true}).toPlainText()}static StripAnyTags(str){return str.replace(CUSTOM_BBREGEX,"")}};
+
+}
+
+// ../lib/str/textLayout/wordWrap.js
+{
+'use strict';const C3=self.C3;function IsWordBreakWhiteSpace(ch){if(ch==="\u00a0"||ch==="\u202f")return false;else return C3.IsWhitespaceChar(ch)}function WordBreakTrimEnd(chArr){while(chArr.length>0&&IsWordBreakWhiteSpace(chArr.at(-1)))chArr.pop()}function IsNewline(ch){return ch==="\n"||ch==="\r\n"}
+C3.WordWrap=class WordWrap{constructor(){this._lines=[];this._iconSet=null}GetLines(){return this._lines}GetLineCount(){return this._lines.length}SetIconSet(iconSet){this._iconSet=iconSet}_MeasureLine(line,measureFunc){let width=0;let height=0;let fbbAscent=0;let fbbDescent=0;let topToAlphabeticDistance=0;for(const frag of line){if(frag.GetWidth()===-1){const m=measureFunc(frag);frag.SetHeight(m.height);frag.SetFontBoundingBoxAscent(m.fontBoundingBoxAscent||0);frag.SetFontBoundingBoxDescent(m.fontBoundingBoxDescent||
+0);frag.SetTopToAlphabeticDistance(m.topToAlphabeticDistance||0);if(frag.IsText())frag.SetWidth(m.width);else if(frag.IsIcon())frag.CalculateWidthFromHeight(this._iconSet)}width+=frag.GetWidth();height=Math.max(height,frag.GetHeight());fbbAscent=Math.max(fbbAscent,frag.GetFontBoundingBoxAscent());fbbDescent=Math.max(fbbDescent,frag.GetFontBoundingBoxDescent());topToAlphabeticDistance=Math.max(topToAlphabeticDistance,frag.GetTopToAlphabeticDistance())}return{width,height,fontBoundingBoxAscent:fbbAscent,
+fontBoundingBoxDescent:fbbDescent,topToAlphabeticDistance}}_AddLine(fragments,width,height,fbbAscent,fbbDescent,topToAlphabeticDistance){this._lines.push(C3.New(C3.WordWrap.Line,{fragments,width,height,fontBoundingBoxAscent:fbbAscent,fontBoundingBoxDescent:fbbDescent,topToAlphabeticDistance}))}WordWrap(fragmentArr,measureFunc,wrapWidth,wrapMode,endOfLineMargin){if(typeof fragmentArr==="string")fragmentArr=[C3.New(C3.TextFragment,{chArr:C3.SplitGraphemes(fragmentArr)})];C3.clearArray(this._lines);
+if(!fragmentArr.length||fragmentArr.length===1&&fragmentArr[0].IsText()&&fragmentArr[0].IsEmpty()||wrapWidth<2)return;if(fragmentArr.length===1){const frag=fragmentArr[0];if(frag.IsText()&&frag.GetLength()<=100&&!frag.HasNewLine()){let {width,height,fontBoundingBoxAscent,fontBoundingBoxDescent,topToAlphabeticDistance}=measureFunc(frag);width+=endOfLineMargin;frag.SetWidth(width);frag.SetHeight(height);frag.SetFontBoundingBoxAscent(fontBoundingBoxAscent||0);frag.SetFontBoundingBoxDescent(fontBoundingBoxDescent||
+0);frag.SetTopToAlphabeticDistance(topToAlphabeticDistance||0);if(width<=wrapWidth){this._AddLine([frag],width,height,fontBoundingBoxAscent,fontBoundingBoxDescent,topToAlphabeticDistance);return}}}let tokenisedFragments;if(wrapMode==="word")tokenisedFragments=this._TokeniseWords(fragmentArr);else{tokenisedFragments=[];for(const frag of fragmentArr)if(frag.IsText()){const chArr=frag.GetCharacterArray();C3.appendArray(tokenisedFragments,chArr.map(ch=>[C3.New(C3.TextFragment,{chArr:[ch],styles:frag.GetStyles()})]))}else tokenisedFragments.push([frag])}this._WrapText(tokenisedFragments,
+measureFunc,wrapWidth,endOfLineMargin)}_TokeniseWords(fragmentArr){const ret=[];let curWord=[];let isCurWhitespace=false;for(const frag of fragmentArr){const styles=frag.GetStyles();if(frag.IsIcon()){if(curWord.length>0)ret.push(curWord);ret.push([frag]);curWord=[];continue}for(const ch of frag.GetCharacterArray())if(IsNewline(ch)){if(curWord.length>0)ret.push(curWord);const newlineFrag=C3.New(C3.TextFragment,{chArr:["\n"],styles});ret.push([newlineFrag]);curWord=[]}else if(curWord.length===0){const newFrag=
+C3.New(C3.TextFragment,{chArr:[ch],styles});curWord.push(newFrag);isCurWhitespace=IsWordBreakWhiteSpace(ch)}else{const isWhitespace=IsWordBreakWhiteSpace(ch);if(isWhitespace===isCurWhitespace){const curFrag=curWord.at(-1);if(curFrag.GetStyles()===styles)curFrag._AppendChar(ch);else{const newFrag=C3.New(C3.TextFragment,{chArr:[ch],styles});curWord.push(newFrag)}}else{ret.push(curWord);curWord=[];const newFrag=C3.New(C3.TextFragment,{chArr:[ch],styles});curWord.push(newFrag);isCurWhitespace=isWhitespace}}}if(curWord.length>
+0)ret.push(curWord);return ret}_CopyLine(line){return line.map(f=>f._Clone())}_AddWordToLine(currentLine,curWord){const lastFrag=currentLine.length?currentLine.at(-1):null;let i=0;if(lastFrag&&lastFrag.IsText()&&curWord[0].IsText()&&curWord[0].GetStyles()===lastFrag.GetStyles()){lastFrag._Append(curWord[0].GetCharacterArray());i=1}for(let len=curWord.length;i=wrapWidth){if(currentLine.length>0)this._AddLine(currentLine,currentLineWidth,currentLineHeight,currentLineFbbAscent,currentLineFbbDescent,currentLineTopToAlphabetic);currentLine=[];if(curWord[0].IsText()&&C3.IsCharArrayAllWhitespace(curWord[0].GetCharacterArray())){currentLineWidth=0;currentLineHeight=0;currentLineFbbAscent=0;currentLineFbbDescent=0;currentLineTopToAlphabetic=0}else{this._AddWordToLine(currentLine,curWord);const metrics=
+this._MeasureLine(currentLine,measureFunc);currentLineWidth=metrics.width;currentLineHeight=metrics.height;currentLineFbbAscent=metrics.fontBoundingBoxAscent;currentLineFbbDescent=metrics.fontBoundingBoxDescent;currentLineTopToAlphabetic=metrics.topToAlphabeticDistance}}else{currentLine=tryLine;currentLineWidth=tryLineWidth;currentLineHeight=tryMetrics.height;currentLineFbbAscent=tryMetrics.fontBoundingBoxAscent;currentLineFbbDescent=tryMetrics.fontBoundingBoxDescent;currentLineTopToAlphabetic=tryMetrics.topToAlphabeticDistance}}if(currentLine.length>
+0)this._AddLine(currentLine,currentLineWidth,currentLineHeight,currentLineFbbAscent,currentLineFbbDescent,currentLineTopToAlphabetic);this._TrimLinesTrailingWhitespace(measureFunc,endOfLineMargin)}_TrimLinesTrailingWhitespace(measureFunc,endOfLineMargin){for(const line of this._lines){const fragments=line._GetFragmentsArray();if(!fragments.length)continue;let lastFrag=fragments.at(-1);if(lastFrag.IsText()){const chArr=lastFrag.GetCharacterArray();const trimmedArr=chArr.slice(0);WordBreakTrimEnd(trimmedArr);
+if(trimmedArr.length===0){line.OffsetWidth(-lastFrag.GetWidth());fragments.pop()}else if(trimmedArr.length0){lastFrag=fragments.at(-1);lastFrag.OffsetWidth(endOfLineMargin);line.OffsetWidth(endOfLineMargin)}}}}Clear(){C3.clearArray(this._lines)}GetMaxLineWidth(){return this._lines.reduce((a,
+v)=>Math.max(a,v.GetWidth()),0)}GetTotalLineHeight(){return this._lines.reduce((a,v)=>a+v.GetHeight(),0)}};
+
+}
+
+// ../lib/str/textLayout/line.js
+{
+'use strict';const C3=self.C3;
+C3.WordWrap.Line=class WordWrapLine{constructor(opts){this._fragments=opts.fragments||[];this._width=opts.width||-1;this._height=opts.height||-1;this._fontBoundingBoxAscent=opts.fontBoundingBoxAscent||-1;this._fontBoundingBoxDescent=opts.fontBoundingBoxDescent||-1;this._topToAlphabeticDistance=opts.topToAlphabeticDistance||-1;this._posX=0;this._posY=0}fragments(){return this._fragments.values()}*fragmentsReverse(){const fragments=this._fragments;for(let i=fragments.length-1;i>=0;--i)yield fragments[i]}_GetFragmentsArray(){return this._fragments}OffsetWidth(w){this._width+=
+w}GetWidth(){return this._width}GetHeight(){return this._height}GetFoundBoundingBoxAscent(){return this._fontBoundingBoxAscent}GetFontBoundingBoxDescent(){return this._fontBoundingBoxDescent}GetTopToAlphabeticDistance(){return this._topToAlphabeticDistance}SetPosX(x){this._posX=x}GetPosX(){return this._posX}SetPosY(y){this._posY=y}GetPosY(){return this._posY}};
+
+}
+
+// ../lib/str/textLayout/fragmentBase.js
+{
+'use strict';const C3=self.C3;
+C3.FragmentBase=class FragmentBase{constructor(opts){this._styles=opts.styles||[];this._width=opts.width||-1;this._height=opts.height||-1;this._fontBoundingBoxAscent=opts.fontBoundingBoxAscent||-1;this._fontBoundingBoxDescent=opts.fontBoundingBoxDescent||-1;this._topToAlphabeticDistance=opts.topToAlphabeticDistance||-1;this._posX=0;this._posY=0}IsText(){return false}IsIcon(){return false}GetStyles(){return this._styles}GetStyleTag(tag){const styles=this._styles;for(let i=styles.length-1;i>=0;--i){const s=
+styles[i];if(s.tag===tag)return s}return null}HasStyleTag(tag){return!!this.GetStyleTag(tag)}GetStyleMap(){const ret=new Map;for(const s of this._styles)ret.set(s.tag,s.param);return ret}OffsetWidth(w){this._width+=w}SetWidth(w){this._width=w}GetWidth(){return this._width}SetHeight(h){this._height=h}GetHeight(){return this._height}SetFontBoundingBoxAscent(v){this._fontBoundingBoxAscent=v}GetFontBoundingBoxAscent(){return this._fontBoundingBoxAscent}SetFontBoundingBoxDescent(v){this._fontBoundingBoxDescent=
+v}GetFontBoundingBoxDescent(){return this._fontBoundingBoxDescent}SetTopToAlphabeticDistance(v){this._topToAlphabeticDistance=v}GetTopToAlphabeticDistance(){return this._topToAlphabeticDistance}SetPosX(x){this._posX=x}GetPosX(){return this._posX}SetPosY(y){this._posY=y}GetPosY(){return this._posY}};
+
+}
+
+// ../lib/str/textLayout/textFragment.js
+{
+'use strict';const C3=self.C3;
+C3.TextFragment=class TextFragment extends C3.FragmentBase{constructor(opts){super(opts);this._chArr=opts.chArr}IsText(){return true}_Append(chArr){C3.appendArray(this._chArr,chArr);this._width=-1;this._height=-1;this._fontBoundingBoxAscent=-1;this._fontBoundingBoxDescent=-1;this._topToAlphabeticDistance=-1}_AppendChar(ch){this._chArr.push(ch)}_Clone(){return C3.New(C3.TextFragment,{chArr:this._chArr.slice(0),styles:this._styles,width:this._width,height:this._height,fontBoundingBoxAscent:this._fontBoundingBoxAscent,
+fontBoundingBoxDescent:this._fontBoundingBoxDescent,topToAlphabeticDistance:this._topToAlphabeticDistance})}GetCharacterArray(){return this._chArr}SetCharacterArray(arr){this._chArr=arr}GetLength(){return this._chArr.length}IsEmpty(){return this._chArr.length===0}HasNewLine(){return this._chArr.includes("\n")}};
+
+}
+
+// ../lib/str/textLayout/iconFragment.js
+{
+'use strict';const C3=self.C3;
+C3.IconFragment=class IconFragment extends C3.FragmentBase{constructor(opts){super(opts);this._icon=opts.icon}IsIcon(){return true}GetIconParameter(){return this._icon}_Clone(){return C3.New(C3.IconFragment,{icon:this._icon,styles:this._styles,width:this._width,height:this._height,fontBoundingBoxAscent:this._fontBoundingBoxAscent,fontBoundingBoxDescent:this._fontBoundingBoxDescent,topToAlphabeticDistance:this._topToAlphabeticDistance})}GetTextIcon(iconSet){if(!iconSet)return null;let index=Number(this._icon);
+if(String(index)===this._icon){index=Math.floor(index);return iconSet.GetTextIconByIndex(index)}else return iconSet.GetTextIconByTag(this._icon)}CalculateWidthFromHeight(iconSet){const textIcon=this.GetTextIcon(iconSet);if(!textIcon){this._width=0;return}this._width=this._height*textIcon.GetWidth()/textIcon.GetHeight()}GetDrawable(iconSet){const textIcon=this.GetTextIcon(iconSet);return textIcon?textIcon.GetDrawable():null}GetLength(){return 1}};
+
+}
+
+// ../lib/str/textLayout/textIconManager.js
+{
+'use strict';const C3=self.C3;
+C3.TextIconManager=class TextIconManager{constructor(opts){this._iconSets=new Map;this._getIconSetMetaCallback=opts.getIconSetMeta;this._getIconSetContentCallback=opts.getIconSetContent}Release(){for(const iconSet of this._iconSets.values())iconSet.Release();this._iconSets.clear()}GetIconSet(iconSource){let iconSet=this._iconSets.get(iconSource);if(iconSet)return iconSet;const iconMeta=this._getIconSetMetaCallback(iconSource);iconSet=C3.New(C3.TextIconSet,this,{source:iconSource,iconMeta});this._iconSets.set(iconSource,
+iconSet);return iconSet}HasIconSet(iconSource){return this._iconSets.has(iconSource)}DeleteIconSet(iconSource){const iconSet=this._iconSets.get(iconSource);if(iconSet)iconSet.Release();this._iconSets.delete(iconSource)}async _GetIconSetContent(iconSource){return await this._getIconSetContentCallback(iconSource)}};
+
+}
+
+// ../lib/str/textLayout/textIconSet.js
+{
+'use strict';const C3=self.C3;
+C3.TextIconSet=class TextIconSet{constructor(textIconManager,opts){this._textIconManager=textIconManager;this._source=opts.source;this._iconsArray=[];this._iconsByTag=new Map;this._hasStartedLoad=false;this._isLoading=false;this._loadPromise=null;const iconMetaArr=opts.iconMeta.icons;for(let i=0,len=iconMetaArr.length;i=this._iconsArray.length)return null;return this._iconsArray[index]}GetTextIconByTag(tag){return this._iconsByTag.get(tag.toLowerCase())||null}};
+
+}
+
+// ../lib/str/textLayout/textIcon.js
+{
+'use strict';const C3=self.C3;C3.TextIcon=class TextIcon{constructor(textIconSet,opts){this._textIconSet=textIconSet;this._source=opts.source||null;this._index=opts.index;this._tag=opts.tag;this._width=opts.width;this._height=opts.height;this._drawable=null}Release(){this._width=0;this._height=0;this._textIconSet=null}GetSource(){return this._source}GetWidth(){return this._width}GetHeight(){return this._height}_SetDrawable(drawable){this._drawable=drawable}GetDrawable(){return this._drawable}};
+
+}
+
+// ../lib/gfx/gfx.js
+{
+'use strict';const C3=self.C3;const glMatrix=self.glMatrix;const vec3=glMatrix.vec3;const vec4=glMatrix.vec4;const mat4=glMatrix.mat4;const tempVec3a=vec3.create();const tempVec3b=vec3.create();const tempVec3c=vec3.create();const tempVec4=vec4.create();const tempMat4=mat4.create();const neartl=vec3.create();const neartr=vec3.create();const nearbl=vec3.create();const nearbr=vec3.create();const fartl=vec3.create();const fartr=vec3.create();const farbl=vec3.create();const farbr=vec3.create();
+const unitViewport=vec4.fromValues(0,0,1,1);
+C3.Gfx={Project(objx,objy,objz,mv,proj,viewport,windowCoordinate){const fTemp0=mv[0]*objx+mv[4]*objy+mv[8]*objz+mv[12];const fTemp1=mv[1]*objx+mv[5]*objy+mv[9]*objz+mv[13];const fTemp2=mv[2]*objx+mv[6]*objy+mv[10]*objz+mv[14];const fTemp3=mv[3]*objx+mv[7]*objy+mv[11]*objz+mv[15];let fTemp4=proj[0]*fTemp0+proj[4]*fTemp1+proj[8]*fTemp2+proj[12]*fTemp3;let fTemp5=proj[1]*fTemp0+proj[5]*fTemp1+proj[9]*fTemp2+proj[13]*fTemp3;let fTemp6=proj[2]*fTemp0+proj[6]*fTemp1+proj[10]*fTemp2+proj[14]*fTemp3;let fTemp7=
+proj[3]*fTemp0+proj[7]*fTemp1+proj[11]*fTemp2+proj[15]*fTemp3;if(fTemp7===0)return false;fTemp7=1/fTemp7;fTemp4*=fTemp7;fTemp5*=fTemp7;fTemp6*=fTemp7;windowCoordinate[0]=(fTemp4*.5+.5)*viewport[2]+viewport[0];windowCoordinate[1]=(fTemp5*.5+.5)*viewport[3]+viewport[1];windowCoordinate[2]=(1+fTemp6)*.5;return true},Unproject(winx,winy,winz,mv,proj,viewport,objectCoordinate){const A=tempMat4;const vec=tempVec4;mat4.multiply(A,proj,mv);if(mat4.invert(A,A)===null)return false;vec[0]=(winx-viewport[0])/
+viewport[2]*2-1;vec[1]=(winy-viewport[1])/viewport[3]*2-1;vec[2]=2*winz-1;vec[3]=1;vec4.transformMat4(vec,vec,A);if(vec[3]===0)return false;vec[3]=1/vec[3];objectCoordinate[0]=vec[0]*vec[3];objectCoordinate[1]=vec[1]*vec[3];objectCoordinate[2]=vec[2]*vec[3];return true},UnprojectScreenToWorldZ(winx,winy,worldZ,mv,proj,viewport,objectCoordinate){const nearPt=tempVec3a;const farPt=tempVec3b;if(!C3.Gfx.Unproject(winx,winy,0,mv,proj,viewport,nearPt))return false;if(!C3.Gfx.Unproject(winx,winy,1,mv,proj,
+viewport,farPt))return false;const dirVec=tempVec3b;vec3.subtract(dirVec,farPt,nearPt);const planeNormal=tempVec3c;vec3.set(planeNormal,0,0,1);const planeConstant=-worldZ;const denominator=vec3.dot(planeNormal,dirVec);let distance=0;if(denominator===0){const planeDistToPt=vec3.dot(planeNormal,nearPt)+planeConstant;if(planeDistToPt!==0)return false}else{distance=-(vec3.dot(nearPt,planeNormal)+planeConstant)/denominator;if(distance<0)return false}vec3.scaleAndAdd(objectCoordinate,nearPt,dirVec,distance);
+return true}};function PlaneFromPoints(ptA,ptB,ptC,plane){const normal=tempVec3c;vec3.subtract(tempVec3a,ptC,ptB);vec3.subtract(tempVec3b,ptA,ptB);vec3.cross(normal,tempVec3a,tempVec3b);vec3.normalize(normal,normal);plane.set(normal[0],normal[1],normal[2],vec3.dot(ptA,normal))}
+function IsInFrontOfPlane(minX,minY,minZ,maxX,maxY,maxZ,plane){const nx=plane.x;const ny=plane.y;const nz=plane.z;const d=plane.w;const nxT=plane.xF;const nyT=plane.yF;const nzT=plane.zF;const nxF=1-nxT;const nyF=1-nyT;const nzF=1-nzT;const minD=nx*minX*nxT+nx*maxX*nxF+ny*minY*nyT+ny*maxY*nyF+nz*minZ*nzT+nz*maxZ*nzF;if(minD>=d)return true;const maxD=nx*maxX*nxT+nx*minX*nxF+ny*maxY*nyT+ny*minY*nyF+nz*maxZ*nzT+nz*minZ*nzF;return maxD>d}
+function IsPointInFrontOfPlane(x,y,z,plane){const nx=plane.x;const ny=plane.y;const nz=plane.z;const d=plane.w;const minD=nx*x+ny*y+nz*z;return minD>=d}class Plane{constructor(){this.x=NaN;this.y=NaN;this.z=NaN;this.w=NaN;this.xF=NaN;this.yF=NaN;this.zF=NaN}set(x,y,z,w){this.x=x;this.y=y;this.z=z;this.w=w;this.xF=x>0?1:0;this.yF=y>0?1:0;this.zF=z>0?1:0}}
+C3.Gfx.ViewFrustum=class ViewFrustum{constructor(){this._leftP=new Plane;this._topP=new Plane;this._rightP=new Plane;this._bottomP=new Plane;this._nearP=new Plane;this._farP=new Plane}CalculatePlanes(mv,proj){const vp=unitViewport;C3.Gfx.Unproject(0,1,0,mv,proj,vp,neartl);C3.Gfx.Unproject(1,1,0,mv,proj,vp,neartr);C3.Gfx.Unproject(0,0,0,mv,proj,vp,nearbl);C3.Gfx.Unproject(1,0,0,mv,proj,vp,nearbr);C3.Gfx.Unproject(0,1,1,mv,proj,vp,fartl);C3.Gfx.Unproject(1,1,1,mv,proj,vp,fartr);C3.Gfx.Unproject(0,0,
+1,mv,proj,vp,farbl);C3.Gfx.Unproject(1,0,1,mv,proj,vp,farbr);PlaneFromPoints(nearbl,neartl,fartl,this._leftP);PlaneFromPoints(neartl,neartr,fartr,this._topP);PlaneFromPoints(neartr,nearbr,farbr,this._rightP);PlaneFromPoints(nearbr,nearbl,farbl,this._bottomP);PlaneFromPoints(farbl,fartl,fartr,this._farP);PlaneFromPoints(nearbr,neartr,neartl,this._nearP)}ContainsAABB(minX,minY,minZ,maxX,maxY,maxZ){return IsInFrontOfPlane(minX,minY,minZ,maxX,maxY,maxZ,this._leftP)&&IsInFrontOfPlane(minX,minY,minZ,maxX,
+maxY,maxZ,this._topP)&&IsInFrontOfPlane(minX,minY,minZ,maxX,maxY,maxZ,this._rightP)&&IsInFrontOfPlane(minX,minY,minZ,maxX,maxY,maxZ,this._bottomP)&&IsInFrontOfPlane(minX,minY,minZ,maxX,maxY,maxZ,this._nearP)&&IsInFrontOfPlane(minX,minY,minZ,maxX,maxY,maxZ,this._farP)}IsBehindNearPlane(x,y,z){return!IsPointInFrontOfPlane(x,y,z,this._nearP)}};
+
+}
+
+// ../lib/gfx/rendererBase.js
+{
+'use strict';const C3=self.C3;const glMatrix=self.glMatrix;const vec3=glMatrix.vec3;const vec4=glMatrix.vec4;const mat4=glMatrix.mat4;const tempMat4=mat4.create();const tmpVec3a=vec3.fromValues(0,0,0);const tmpVec3b=vec3.fromValues(0,0,0);const tmpVec3c=vec3.fromValues(0,0,0);const defaultUpVector=vec3.fromValues(0,1,0);const tmpVec4=vec4.fromValues(0,0,0,0);const tmpQuad=new C3.Quad;const tmpRect=new C3.Rect;const defaultTexCoordsQuad=new C3.Quad(0,0,1,0,1,1,0,1);
+const DEFAULT_RENDERERBASE_OPTS={nearZ:1,farZ:1E4};const matWebGLtoWebGPU=mat4.fromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);
+C3.Gfx.RendererBase=class RendererBase{constructor(opts){opts=Object.assign({},DEFAULT_RENDERERBASE_OPTS,opts);this._width=0;this._height=0;this._fovY=C3.toRadians(45);this._tan_fovY_2=Math.tan(this._fovY/2);this._matP=mat4.create();this._matMV=mat4.create();this._zAxisScale=false;this._nearZ=opts.nearZ;this._farZ=opts.farZ;this._allShaderPrograms=[];this._shaderProgramsByName=new Map;this._spTextureFill=null;this._spPoints=null;this._spTilemapFill=null;this._spTileRandomization=null;this._spColorFill=
+null;this._spLinearGradientFill=null;this._spPenumbraFill=null;this._spHardEllipseFill=null;this._spHardEllipseOutline=null;this._spSmoothEllipseFill=null;this._spSmoothEllipseOutline=null;this._spSmoothLineFill=null;this._stateGroups=new Map;this._currentStateGroup=null;this._blendModeTable=[];this._namedBlendModeMap=new Map;this._baseZ=0;this._currentZ=0;this._lineWidth=1;this._lineWidthStack=[this._lineWidth];this._lineCap=1;this._lineCapStack=[this._lineCap];this._lineOffset=.5;this._lineOffsetStack=
+[this._lineOffset];this._frameNumber=0;this._enableMipmaps=true;this._hasMajorPerformanceCaveat=false}FillIndexBufferData(indexData){let i=0,len=indexData.length,fv=0;while(i=100)throw new Error("pushed too many line widths - check push/pop pairs");
+this._lineWidthStack.push(n);this._lineWidth=n}PopLineWidth(){if(this._lineWidthStack.length<=1)throw new Error("cannot pop last line width - check push/pop pairs");this._lineWidthStack.pop();this._lineWidth=this._lineWidthStack.at(-1)}SetLineCapButt(){this._lineCap=0;this._lineCapStack[this._lineCapStack.length-1]=0}SetLineCapSquare(){this._lineCap=1;this._lineCapStack[this._lineCapStack.length-1]=0}SetLineCapZag(){this._lineCap=2;this._lineCapStack[this._lineCapStack.length-1]=0}PushLineCap(type){if(type===
+"butt")this.PushLineCapButt();else if(type==="square")this.PushLineCapSquare();else if(type==="zag")this.PushLineCapZag();else throw new Error("invalid line cap");}PushLineCapButt(){if(this._lineCapStack.length>=100)throw new Error("pushed too many line caps - check push/pop pairs");this._lineCapStack.push(0);this._lineCap=0}PushLineCapSquare(){if(this._lineCapStack.length>=100)throw new Error("pushed too many line caps - check push/pop pairs");this._lineCapStack.push(1);this._lineCap=1}PushLineCapZag(){if(this._lineCapStack.length>=
+100)throw new Error("pushed too many line caps - check push/pop pairs");this._lineCapStack.push(2);this._lineCap=2}PopLineCap(){if(this._lineCapStack.length<=1)throw new Error("cannot pop last line cap - check push/pop pairs");this._lineCapStack.pop();this._lineCap=this._lineCapStack.at(-1)}SetLineOffset(n){this._lineOffset=n;this._lineOffsetStack[this._lineOffsetStack.length-1]=n}GetLineOffset(){return this._lineOffset}PushLineOffset(n){if(this._lineOffsetStack.length>=100)throw new Error("pushed too many line offsets - check push/pop pairs");
+this._lineOffsetStack.push(n);this._lineOffset=n}PopLineOffset(){if(this._lineOffsetStack.length<=1)throw new Error("cannot pop last line offset - check push/pop pairs");this._lineOffsetStack.pop();this._lineOffset=this._lineOffsetStack.at(-1)}ConvexPoly(pts){const pts_count=pts.length/2;if(pts_count<3)throw new Error("need at least 3 points");const tris=pts_count-2;const last_tri=tris-1;const p0x=pts[0];const p0y=pts[1];for(let i=0;i0)throw new Error("releasing state group still in use");
+this._renderer=null;this._shaderProgram=null;this._shaderProgramName=""}Apply(){const renderer=this._renderer;renderer.SetProgram(this._shaderProgram);renderer.SetBlendMode(this._blendMode);renderer.SetColor(this._color);renderer.SetCurrentZ(this._zElevation);renderer._SetCurrentStateGroup(this)}GetKey(){return C3.Gfx.StateGroup.MakeKey(this._shaderProgramName,this._blendMode,this._color,this._zElevation)}AddRef(){++this._refCount}DecRef(){--this._refCount}_GetRefCount(){return this._refCount}OnContextLost(){this._shaderProgram=
+null}OnContextRestored(renderer){this._shaderProgram=renderer.GetShaderProgramByName(this._shaderProgramName);if(!this._shaderProgram)throw new Error("failed to restore shader program");}static MakeKey(shaderProgram_or_name,blendMode,c,zElevation){const shaderProgramName=typeof shaderProgram_or_name==="string"?shaderProgram_or_name:shaderProgram_or_name.GetName();return shaderProgramName+","+blendMode+","+c.getR()+","+c.getG()+","+c.getB()+","+c.getA()+","+zElevation}};
+
+}
+
+// ../lib/gfx/mesh.js
+{
+'use strict';const C3=self.C3;const tempQuadTex=C3.New(C3.Quad);function interpolateQuad(srcX,srcY,quad){const qtlx=quad.getTlx();const qtly=quad.getTly();const qtrx=quad.getTrx()-qtlx;const qtry=quad.getTry()-qtly;const qblx=quad.getBlx()-qtlx;const qbly=quad.getBly()-qtly;const xix=qtrx*srcX;const xiy=qtry*srcX;const yix=qblx*srcY;const yiy=qbly*srcY;return[qtlx+xix+yix,qtly+xiy+yiy]}
+C3.Gfx.MeshPoint=class MeshPoint{constructor(mesh,col,row){this._mesh=mesh;this._col=col;this._row=row;this._x=NaN;this._y=NaN;this._zElevation=NaN;this._u=NaN;this._v=NaN;this._x=0;this._y=0;this._zElevation=0;this._u=0;this._v=0}_Init(x,y,u,v){this._x=x;this._y=y;this._u=u;this._v=v}GetX(){return this._x}SetX(x){if(this._x===x)return;this._x=x;this._mesh._SetPointsChanged()}GetY(){return this._y}SetY(y){if(this._y===y)return;this._y=y;this._mesh._SetPointsChanged()}GetZElevation(){return this._zElevation}SetZElevation(z){if(this._zElevation===
+z)return;this._zElevation=Math.max(z,0);this._mesh._SetPointsChanged()}GetU(){return this._u}SetU(u){this._u=u}GetV(){return this._v}SetV(v){this._v=v}_Interpolate_TexRect(srcPoint,quadPos,rcTex){[this._x,this._y]=interpolateQuad(srcPoint._x,srcPoint._y,quadPos);this._zElevation=srcPoint._zElevation;this._u=C3.lerp(rcTex.getLeft(),rcTex.getRight(),srcPoint._u);this._v=C3.lerp(rcTex.getTop(),rcTex.getBottom(),srcPoint._v)}_Interpolate_TexQuad(srcPoint,quadPos,quadTex){[this._x,this._y]=interpolateQuad(srcPoint._x,
+srcPoint._y,quadPos);this._zElevation=srcPoint._zElevation;[this._u,this._v]=interpolateQuad(srcPoint._u,srcPoint._v,quadTex)}SaveToJson(){return{"x":this.GetX(),"y":this.GetY(),"z":this.GetZElevation(),"u":this.GetU(),"v":this.GetV()}}LoadFromJson(o){this.SetX(o["x"]);this.SetY(o["y"]);if(o.hasOwnProperty("z"))this.SetZElevation(o["z"]);this.SetU(o["u"]);this.SetV(o["v"])}GetMesh(){return this._mesh}GetColumn(){return this._col}GetRow(){return this._row}};
+C3.Gfx.Mesh=class Mesh{constructor(hsize,vsize,owner){if(hsize<2||vsize<2)throw new Error("invalid mesh size");this._hsize=hsize;this._vsize=vsize;this._owner=owner||null;this._pts=[];this._minX=0;this._minY=0;this._maxX=1;this._maxY=1;this._maxZ=0;this._pointsChanged=false;const lastX=hsize-1;const lastY=vsize-1;for(let y=0;y0}GetMeshPointAt(x,y){x=Math.floor(x);y=Math.floor(y);if(x<0||x>=this._hsize||y<0||y>=this._vsize)return null;return this._pts[y][x]}CalculateTransformedMesh(srcMesh,quadPos,rcTex_or_quad){const isTexRect=rcTex_or_quad instanceof
+C3.Rect;if(srcMesh.GetHSize()!==this.GetHSize()||srcMesh.GetVSize()!==this.GetVSize())throw new Error("source mesh wrong size");const srcPts=srcMesh._pts;const destPts=this._pts;for(let y=0,lenY=destPts.length;y[x,y,z];const pts=this._pts;let prevRow=pts[0];for(let y=1,lenY=pts.length;y{curX=C3.clamp(C3.lerp(curX,nextX,rayHit),0,1);curY=C3.clamp(C3.lerp(curY,nextY,rayHit),0,1);outPts.push(curX,curY)};for(let i=0,len=inPts.length;i1E6)throw new Error("Too many mesh poly points");
+const srcTlx=curCol*colWidthNorm;const srcTly=curRow*rowHeightNorm;const srcBrx=(curCol+1)*colWidthNorm;const srcBry=(curRow+1)*rowHeightNorm;isUpper=C3.isPointInTriangleInclusive(curX,curY,srcTlx,srcTly,srcBrx,srcTly,srcBrx,srcBry);if(disableCheck!==DISABLE_DIAGONAL){rayHit=C3.rayIntersectExtended(curX,curY,nextX,nextY,srcTlx,srcTly,srcBrx,srcBry,-RAY_EXT_DIST);if(rayHit>=MIN_RAY_DIST&&rayHit<=MAX_RAY_DIST){addVertexAtRayHit();isUpper=!isUpper;disableCheck=DISABLE_DIAGONAL;continue}}if(curRow>0&&
+disableCheck!==DISABLE_TOP_EDGE){rayHit=C3.rayIntersectExtended(curX,curY,nextX,nextY,srcTlx,srcTly,srcBrx,srcTly,RAY_EXT_DIST);if(rayHit>=MIN_RAY_DIST&&rayHit<=MAX_RAY_DIST){addVertexAtRayHit();curRow--;isUpper=false;disableCheck=DISABLE_BOTTOM_EDGE;continue}}if(curCol=MIN_RAY_DIST&&rayHit<=MAX_RAY_DIST){addVertexAtRayHit();curCol++;isUpper=false;disableCheck=
+DISABLE_LEFT_EDGE;continue}}if(curCol>0&&disableCheck!==DISABLE_LEFT_EDGE){rayHit=C3.rayIntersectExtended(curX,curY,nextX,nextY,srcTlx,srcTly,srcTlx,srcBry,RAY_EXT_DIST);if(rayHit>=MIN_RAY_DIST&&rayHit<=MAX_RAY_DIST){addVertexAtRayHit();curCol--;isUpper=true;disableCheck=DISABLE_RIGHT_EDGE;continue}}if(curRow=MIN_RAY_DIST&&rayHit<=MAX_RAY_DIST){addVertexAtRayHit();
+curRow++;isUpper=true;disableCheck=DISABLE_TOP_EDGE;continue}}break}}return C3.New(C3.CollisionPoly,outPts)}TransformCollisionPoly(srcPoly,destPoly){const ptsArr=this._TransformPolyPoints(srcPoly);this._SimplifyPoly(ptsArr);destPoly.setPoints(ptsArr)}_TransformPolyPoints(srcPoly){const outPts=[];const ptsArr=srcPoly.pointsArr();for(let i=0,len=ptsArr.length;iR_EPSILON||dx==0&&dy===0)outPts.push(curX,curY);curX=nextX;curY=nextY;lastDx=dx;lastDy=dy}if(outPts.length>=6&&outPts.lengthrow.map(pt=>pt.SaveToJson()))}}LoadFromJson(o){const cols=this.GetHSize();const rows=
+this.GetVSize();if(o["cols"]!==cols||o["rows"]!==rows)throw new Error("mesh data wrong size");const meshRows=o["points"];for(let y=0;ymaxTextureSize||this._height>maxTextureSize)throw new Error("texture data exceeds maximum texture size");const gl=this._renderer.GetContext();const webglVersion=this._renderer.GetWebGLVersionNumber();this._texture=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,this._texture);gl.pixelStorei(gl["UNPACK_PREMULTIPLY_ALPHA_WEBGL"],opts.premultiplyAlpha);
+gl.pixelStorei(gl["UNPACK_FLIP_Y_WEBGL"],false);const formatspec=GetFormatSpecifiers(this._pixelFormat,gl);if(!this._renderer.SupportsNPOTTextures()&&!isPOT&&this._IsTiled()){if(data===null)throw new Error("cannot pass null data when creating a NPOT tiled texture without NPOT support");if(data instanceof ArrayBuffer)data=new ImageData(new Uint8ClampedArray(data),this._width,this._height);if(data instanceof ImageData){const tmpCanvas=C3.CreateCanvas(this._width,this._height);const tmpCtx=tmpCanvas.getContext("2d");
+tmpCtx.putImageData(data,0,0);data=tmpCanvas}const canvas=C3.CreateCanvas(C3.nextHighestPowerOfTwo(this._width),C3.nextHighestPowerOfTwo(this._height));const ctx=canvas.getContext("2d");ctx.imageSmoothingEnabled=this._sampling!=="nearest";ctx.drawImage(data,0,0,this._width,this._height,0,0,canvas.width,canvas.height);gl.texImage2D(gl.TEXTURE_2D,0,formatspec.internalformat,formatspec.format,formatspec.type,canvas)}else if(webglVersion>=2){let levels;if(this._isMipMapped)levels=Math.floor(Math.log2(Math.max(this._width,
+this._height))+1);else levels=1;gl.texStorage2D(gl.TEXTURE_2D,levels,formatspec.sizedinternalformat,this._width,this._height);if(data instanceof ArrayBuffer)gl.texSubImage2D(gl.TEXTURE_2D,0,0,0,this._width,this._height,formatspec.format,formatspec.type,new Uint8Array(data));else if(data!==null)gl.texSubImage2D(gl.TEXTURE_2D,0,0,0,formatspec.format,formatspec.type,data)}else if(data instanceof ArrayBuffer)gl.texImage2D(gl.TEXTURE_2D,0,formatspec.internalformat,this._width,this._height,0,formatspec.format,
+formatspec.type,new Uint8Array(data));else if(data===null)gl.texImage2D(gl.TEXTURE_2D,0,formatspec.internalformat,this._width,this._height,0,formatspec.format,formatspec.type,null);else gl.texImage2D(gl.TEXTURE_2D,0,formatspec.internalformat,formatspec.format,formatspec.type,data);if(data!==null)this._SetTextureParameters(gl);gl.bindTexture(gl.TEXTURE_2D,null);this._renderer._ResetLastTexture();this._refCount=1;allTextures.add(this)}_CreateDynamic(width,height,opts){opts=Object.assign({},CREATEFROM_DEFAULT_OPTIONS,
+opts);if(this._texture)throw new Error("already created texture");this._wrapX=opts.wrapX;this._wrapY=opts.wrapY;this._sampling=opts.sampling;this._pixelFormat=opts.pixelFormat;this._isMipMapped=!!opts.mipMap&&this._renderer.AreMipmapsEnabled();this._mipMapQuality=opts.mipMapQuality;if(!VALID_WRAP_MODES.has(this._wrapX)||!VALID_WRAP_MODES.has(this._wrapY))throw new Error("invalid wrap mode");if(!VALID_SAMPLINGS.has(this._sampling))throw new Error("invalid sampling");if(!VALID_PIXEL_FORMATS.has(this._pixelFormat))throw new Error("invalid pixel format");
+if(!VALID_MIPMAP_QUALITIES.has(this._mipMapQuality))throw new Error("invalid mipmap quality");this._isStatic=false;this._width=Math.floor(width);this._height=Math.floor(height);const isPOT=C3.isPOT(this._width)&&C3.isPOT(this._height);const maxTextureSize=this._renderer.GetMaxTextureSize();if(this._width<=0||this._height<=0)throw new Error("invalid texture size");if(this._width>maxTextureSize||this._height>maxTextureSize)throw new Error("texture exceeds maximum texture size");if(!this._renderer.SupportsNPOTTextures()&&
+this._IsTiled()&&!isPOT)throw new Error("non-power-of-two tiled textures not supported");const gl=this._renderer.GetContext();const webglVersion=this._renderer.GetWebGLVersionNumber();this._texture=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,this._texture);gl.pixelStorei(gl["UNPACK_PREMULTIPLY_ALPHA_WEBGL"],opts.premultiplyAlpha);gl.pixelStorei(gl["UNPACK_FLIP_Y_WEBGL"],false);const formatspec=GetFormatSpecifiers(this._pixelFormat,gl);const internalformat=webglVersion>=2?formatspec.sizedinternalformat:
+formatspec.internalformat;gl.texImage2D(gl.TEXTURE_2D,0,internalformat,this._width,this._height,0,formatspec.format,formatspec.type,null);this._SetTextureParameters(gl);gl.bindTexture(gl.TEXTURE_2D,null);this._renderer._ResetLastTexture();this._refCount=1;allTextures.add(this)}_GetMipMapHint(gl){if(this._mipMapQuality==="default")return this._isStatic?gl.NICEST:gl.FASTEST;else if(this._mipMapQuality==="low")return gl.FASTEST;else if(this._mipMapQuality==="high")return gl.NICEST;else throw new Error("invalid mipmap quality");
+}_IsTiled(){return this._wrapX!=="clamp-to-edge"||this._wrapY!=="clamp-to-edge"}_GetTextureWrapMode(gl,wrapMode){if(wrapMode==="clamp-to-edge")return gl.CLAMP_TO_EDGE;else if(wrapMode==="repeat")return gl.REPEAT;else if(wrapMode==="mirror-repeat")return gl.MIRRORED_REPEAT;else throw new Error("invalid wrap mode");}_SetTextureParameters(gl){const isPOT=C3.isPOT(this._width)&&C3.isPOT(this._height);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,this._GetTextureWrapMode(gl,this._wrapX));gl.texParameteri(gl.TEXTURE_2D,
+gl.TEXTURE_WRAP_T,this._GetTextureWrapMode(gl,this._wrapY));if(this._sampling==="nearest"){gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);this._isMipMapped=false}else{gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR);if((isPOT||this._renderer.SupportsNPOTTextures())&&this._isMipMapped){gl.hint(gl.GENERATE_MIPMAP_HINT,this._GetMipMapHint(gl));gl.generateMipmap(gl.TEXTURE_2D);const useTrilinear=this._sampling===
+"trilinear"&&!this._renderer.HasMajorPerformanceCaveat();gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,useTrilinear?gl.LINEAR_MIPMAP_LINEAR:gl.LINEAR_MIPMAP_NEAREST)}else{gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR);this._isMipMapped=false}}const anisotropicExt=this._renderer._GetAnisotropicExtension();if(anisotropicExt&&this._anisotropy>0&&this._sampling!=="nearest")gl.texParameterf(gl.TEXTURE_2D,anisotropicExt["TEXTURE_MAX_ANISOTROPY_EXT"],Math.min(this._anisotropy,this._renderer._GetMaxAnisotropy()))}_Update(data,
+opts){if((typeof HTMLImageElement==="undefined"||!(data instanceof HTMLImageElement))&&(typeof HTMLVideoElement==="undefined"||!(data instanceof HTMLVideoElement))&&(typeof HTMLCanvasElement==="undefined"||!(data instanceof HTMLCanvasElement))&&(typeof ImageBitmap==="undefined"||!(data instanceof ImageBitmap))&&(typeof OffscreenCanvas==="undefined"||!(data instanceof OffscreenCanvas))&&!(data instanceof ImageData))throw new Error("invalid texture source");if(!this._texture||this._refCount<=0)throw new Error("texture not created");
+if(this._isStatic)throw new Error("cannot update static texture");opts=Object.assign({},UPDATE_DEFAULT_OPTIONS,opts);const dataWidth=data.width||data.videoWidth;const dataHeight=data.height||data.videoHeight;const webglVersion=this._renderer.GetWebGLVersionNumber();const gl=this._renderer.GetContext();gl.bindTexture(gl.TEXTURE_2D,this._texture);gl.pixelStorei(gl["UNPACK_PREMULTIPLY_ALPHA_WEBGL"],opts.premultiplyAlpha);gl.pixelStorei(gl["UNPACK_FLIP_Y_WEBGL"],!!opts.flipY);const formatspec=GetFormatSpecifiers(this._pixelFormat,
+gl);const internalformat=webglVersion>=2?formatspec.sizedinternalformat:formatspec.internalformat;try{if(this._width===dataWidth&&this._height===dataHeight){const isPOT=C3.isPOT(this._width)&&C3.isPOT(this._height);gl.texSubImage2D(gl.TEXTURE_2D,0,0,0,formatspec.format,formatspec.type,data);if((isPOT||this._renderer.SupportsNPOTTextures())&&this._isMipMapped){gl.hint(gl.GENERATE_MIPMAP_HINT,this._GetMipMapHint(gl));gl.generateMipmap(gl.TEXTURE_2D)}}else{this._width=dataWidth;this._height=dataHeight;
+const isPOT=C3.isPOT(this._width)&&C3.isPOT(this._height);if(!this._renderer.SupportsNPOTTextures()&&this._IsTiled()&&!isPOT)throw new Error("non-power-of-two tiled textures not supported");gl.texImage2D(gl.TEXTURE_2D,0,internalformat,formatspec.format,formatspec.type,data);if((isPOT||this._renderer.SupportsNPOTTextures())&&this._isMipMapped){gl.hint(gl.GENERATE_MIPMAP_HINT,this._GetMipMapHint(gl));gl.generateMipmap(gl.TEXTURE_2D)}}}catch(e){console.error("Error updating WebGL texture: ",e)}gl.bindTexture(gl.TEXTURE_2D,
+null);this._renderer._ResetLastTexture()}_Delete(){if(this._refCount>0)throw new Error("texture still has references");if(!this._texture)throw new Error("already deleted texture");allTextures.delete(this);const gl=this._renderer.GetContext();gl.deleteTexture(this._texture);this._texture=null}IsValid(){return!!this._texture}_GetTexture(){return this._texture}GetRenderer(){return this._renderer}AddReference(){this._refCount++}SubtractReference(){if(this._refCount<=0)throw new Error("no more references");
+this._refCount--}GetReferenceCount(){return this._refCount}GetWidth(){return this._width}GetHeight(){return this._height}IsStatic(){return this._isStatic}GetEstimatedMemoryUsage(){let size=this._width*this._height;switch(this._pixelFormat){case "rgba8":size*=4;break;case "rgb8":size*=3;break;case "rgba4":case "rgb5_a1":case "rgb565":size*=2;break}if(this._isMipMapped)size+=Math.floor(size/3);return size}static OnContextLost(){allTextures.clear()}static allTextures(){return allTextures.values()}};
+
+}
+
+// ../lib/gfx/webgl/renderTarget.js
+{
+'use strict';const C3=self.C3;const assert=self.assert;const glMatrix=self.glMatrix;const vec3=glMatrix.vec3;const mat4=glMatrix.mat4;const VALID_SAMPLINGS=new Set(["nearest","bilinear","trilinear"]);const DEFAULT_RENDERTARGET_OPTIONS={sampling:"trilinear",alpha:true,depth:false,isSampled:true,isDefaultSize:true,multisampling:0};const allRenderTargets=new Set;
+C3.Gfx.WebGLRenderTarget=class WebGLRenderTarget{constructor(renderer){this._renderer=renderer;this._frameBuffer=null;this._frameBufferNoDepth=null;this._texture=null;this._renderBuffer=null;this._width=0;this._height=0;this._isDefaultSize=true;this._sampling="trilinear";this._alpha=true;this._depth=false;this._isSampled=true;this._multisampling=0;this._projectionMatrix=mat4.create();this._lastFov=0;this._lastNearZ=0;this._lastFarZ=0}_Create(width,height,opts){opts=Object.assign({},DEFAULT_RENDERTARGET_OPTIONS,
+opts);const webGLVersion=this._renderer.GetWebGLVersionNumber();if(this._texture||this._renderBuffer)throw new Error("already created render target");this._sampling=opts.sampling;this._alpha=!!opts.alpha;this._depth=!!opts.depth;this._isSampled=!!opts.isSampled;this._isDefaultSize=!!opts.isDefaultSize;this._multisampling=opts.multisampling;if(!VALID_SAMPLINGS.has(this._sampling))throw new Error("invalid sampling");if(this._multisampling>0&&(webGLVersion<2||this._isSampled))throw new Error("invalid use of multisampling");
+if(webGLVersion<2)this._isSampled=true;this._width=width;this._height=height;if(this._width<=0||this._height<=0)throw new Error("invalid render target size");this._CalculateProjection();const gl=this._renderer.GetContext();this._frameBuffer=gl.createFramebuffer();if(this._depth)this._frameBufferNoDepth=gl.createFramebuffer();if(this._isSampled){this._texture=this._renderer.CreateDynamicTexture(this._width,this._height,{sampling:this._sampling,pixelFormat:this._alpha?"rgba8":"rgb8",mipMap:false});
+const tex=this._texture._GetTexture();gl.bindFramebuffer(gl.FRAMEBUFFER,this._frameBuffer);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,tex,0);if(this._depth){gl.bindFramebuffer(gl.FRAMEBUFFER,this._frameBufferNoDepth);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,tex,0)}}else{this._renderBuffer=gl.createRenderbuffer();gl.bindRenderbuffer(gl.RENDERBUFFER,this._renderBuffer);const internalFormat=this._alpha?gl.RGBA8:gl.RGB8;if(this._multisampling>
+0){const formatSamples=gl.getInternalformatParameter(gl.RENDERBUFFER,internalFormat,gl.SAMPLES);if(formatSamples&&formatSamples[0]){const maxSamples=formatSamples[0];if(this._multisampling>maxSamples)this._multisampling=maxSamples}else this._multisampling=0}if(this._multisampling===0)gl.renderbufferStorage(gl.RENDERBUFFER,internalFormat,this._width,this._height);else gl.renderbufferStorageMultisample(gl.RENDERBUFFER,this._multisampling,internalFormat,this._width,this._height);gl.bindFramebuffer(gl.FRAMEBUFFER,
+this._frameBuffer);gl.framebufferRenderbuffer(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.RENDERBUFFER,this._renderBuffer);if(this._depth){gl.bindFramebuffer(gl.FRAMEBUFFER,this._frameBufferNoDepth);gl.framebufferRenderbuffer(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.RENDERBUFFER,this._renderBuffer)}gl.bindRenderbuffer(gl.RENDERBUFFER,null)}const rendererDepthBuffer=this._renderer._GetDepthBuffer();if(this._depth&&rendererDepthBuffer){gl.bindFramebuffer(gl.FRAMEBUFFER,this._frameBuffer);if(this._renderer._CanSampleDepth())gl.framebufferTexture2D(gl.FRAMEBUFFER,
+gl.DEPTH_STENCIL_ATTACHMENT,gl.TEXTURE_2D,rendererDepthBuffer,0);else gl.framebufferRenderbuffer(gl.FRAMEBUFFER,gl.DEPTH_STENCIL_ATTACHMENT,gl.RENDERBUFFER,rendererDepthBuffer)}gl.bindFramebuffer(gl.FRAMEBUFFER,null);allRenderTargets.add(this)}_Resize(width,height){if(this._width===width&&this._height===height)return;this._width=width;this._height=height;this._CalculateProjection();const gl=this._renderer.GetContext();gl.bindFramebuffer(gl.FRAMEBUFFER,this._frameBuffer);if(this._texture)this._texture._Update(new ImageData(this._width,
+this._height));else{gl.bindRenderbuffer(gl.RENDERBUFFER,this._renderBuffer);gl.renderbufferStorage(gl.RENDERBUFFER,this._alpha?gl.RGBA8:gl.RGB8,this._width,this._height);gl.bindRenderbuffer(gl.RENDERBUFFER,null)}const rendererDepthBuffer=this._renderer._GetDepthBuffer();if(this._depth&&rendererDepthBuffer)if(this._renderer._CanSampleDepth())gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.DEPTH_STENCIL_ATTACHMENT,gl.TEXTURE_2D,rendererDepthBuffer,0);else gl.framebufferRenderbuffer(gl.FRAMEBUFFER,gl.DEPTH_STENCIL_ATTACHMENT,
+gl.RENDERBUFFER,rendererDepthBuffer);gl.bindFramebuffer(gl.FRAMEBUFFER,null)}_Delete(){if(!this._texture&&!this._renderBuffer)throw new Error("already deleted render target");allRenderTargets.delete(this);const gl=this._renderer.GetContext();if(this._texture){gl.bindFramebuffer(gl.FRAMEBUFFER,this._frameBuffer);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,null,0);if(this._depth){gl.bindFramebuffer(gl.FRAMEBUFFER,this._frameBufferNoDepth);gl.framebufferTexture2D(gl.FRAMEBUFFER,
+gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,null,0)}this._renderer.DeleteTexture(this._texture);this._texture=null}else if(this._renderBuffer){gl.bindFramebuffer(gl.FRAMEBUFFER,this._frameBuffer);gl.framebufferRenderbuffer(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.RENDERBUFFER,null);if(this._depth){gl.bindFramebuffer(gl.FRAMEBUFFER,this._frameBufferNoDepth);gl.framebufferRenderbuffer(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.RENDERBUFFER,null)}gl.deleteRenderbuffer(this._renderBuffer);this._renderBuffer=null}gl.bindFramebuffer(gl.FRAMEBUFFER,
+null);if(this._renderer.GetWebGLVersionNumber()>=2){gl.bindFramebuffer(gl.READ_FRAMEBUFFER,null);gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER,null)}gl.deleteFramebuffer(this._frameBuffer);if(this._depth)gl.deleteFramebuffer(this._frameBufferNoDepth);const batchState=this._renderer.GetBatchState();batchState.currentFramebuffer=null;batchState.currentFramebufferNoDepth=null;this._frameBuffer=null}_CalculateProjection(){this._renderer.CalculatePerspectiveMatrix(this._projectionMatrix,this._width/this._height);
+this._lastFov=this._renderer.GetFovY();this._lastNearZ=this._renderer.GetNearZ();this._lastFarZ=this._renderer.GetFarZ()}_GetFramebuffer(){return this._frameBuffer}_GetFramebufferNoDepth(){return this._frameBufferNoDepth}GetRenderer(){return this._renderer}GetTexture(){return this._texture}GetProjectionMatrix(){if(this._renderer.GetFovY()!==this._lastFov||this._renderer.GetNearZ()!==this._lastNearZ||this._renderer.GetFarZ()!==this._lastFarZ)this._CalculateProjection();return this._projectionMatrix}IsLinearSampling(){return this._sampling!==
+"nearest"}HasAlpha(){return this._alpha}IsSampled(){return this._isSampled}HasDepthBuffer(){return this._depth}GetWidth(){return this._width}GetHeight(){return this._height}IsDefaultSize(){return this._isDefaultSize}GetMultisampling(){return this._multisampling}GetOptions(){const ret={sampling:this._sampling,alpha:this._alpha,isSampled:this._isSampled};if(!this._isDefaultSize){ret.width=this._width;ret.height=this._height}return ret}IsCompatibleWithOptions(opts){opts=Object.assign({},DEFAULT_RENDERTARGET_OPTIONS,
+opts);if(opts.sampling!=="nearest"!==this.IsLinearSampling())return false;if(!!opts.alpha!==this.HasAlpha())return false;if(!!opts.depth!==this.HasDepthBuffer())return false;if(this._renderer.GetWebGLVersionNumber()>=2)if(!!opts.isSampled!==this.IsSampled())return false;if(typeof opts.width==="number"||typeof opts.height==="number")return!this.IsDefaultSize()&&this.GetWidth()===Math.floor(opts.width)&&this.GetHeight()===Math.floor(opts.height);else return this.IsDefaultSize()}_GetWebGLTexture(){if(!this._texture)return null;
+return this._texture._GetTexture()}GetEstimatedMemoryUsage(){if(this._texture)return this._texture.GetEstimatedMemoryUsage();return this._width*this._height*(this._alpha?4:3)}static async DebugReadPixelsToBlob(renderer,renderTarget){const imageData=await renderer.ReadBackRenderTargetToImageData(renderTarget,true);return await C3.ImageDataToBlob(imageData)}static OnContextLost(){allRenderTargets.clear()}static allRenderTargets(){return allRenderTargets.values()}static ResizeAll(width,height){for(const rt of allRenderTargets)if(rt.IsDefaultSize())rt._Resize(width,
+height)}};
+
+}
+
+// ../lib/gfx/webgl/shaderProgram.js
+{
+'use strict';const C3=self.C3;const glMatrix=self.glMatrix;const vec3=glMatrix.vec3;const mat4=glMatrix.mat4;
+const RESERVED_UNIFORM_NAMES=new Set(["aPos","aTex","aPoints","matP","matMV","samplerFront","samplerBack","samplerDepth","destStart","destEnd","srcStart","srcEnd","srcOriginStart","srcOriginEnd","pixelSize","seconds","devicePixelRatio","layerScale","layerAngle","layoutStart","layoutEnd","color","color2_","pointTexStart","pointTexEnd","zElevation","tileSize","tileSpacing","outlineThickness","zNear","zFar"]);
+C3.Gfx.WebGLShaderProgram=class WebGLShaderProgram extends C3.Gfx.ShaderProgramBase{static async Compile(renderer,shaderInfo){const gl=renderer.GetContext();const fragSrc=shaderInfo.src;const vertexSrc=shaderInfo.vertexSrc;const name=shaderInfo.name;const fragmentShader=gl.createShader(gl.FRAGMENT_SHADER);gl.shaderSource(fragmentShader,fragSrc);gl.compileShader(fragmentShader);const vertexShader=gl.createShader(gl.VERTEX_SHADER);gl.shaderSource(vertexShader,vertexSrc);gl.compileShader(vertexShader);
+const shaderProgram=gl.createProgram();gl.attachShader(shaderProgram,fragmentShader);gl.attachShader(shaderProgram,vertexShader);gl.bindAttribLocation(shaderProgram,0,"aPos");gl.bindAttribLocation(shaderProgram,1,"aTex");gl.bindAttribLocation(shaderProgram,2,"aPoints");gl.linkProgram(shaderProgram);const parallelShaderCompileExt=renderer._GetParallelShaderCompileExtension();if(parallelShaderCompileExt)await renderer._WaitForObjectReady(()=>gl.getProgramParameter(shaderProgram,parallelShaderCompileExt["COMPLETION_STATUS_KHR"]));
+else await C3.Wait(5);if(!gl.getShaderParameter(fragmentShader,gl.COMPILE_STATUS)){const log=gl.getShaderInfoLog(fragmentShader);gl.deleteShader(fragmentShader);gl.deleteShader(vertexShader);gl.deleteProgram(shaderProgram);throw new Error("Error compiling fragment shader: "+log);}if(!gl.getShaderParameter(vertexShader,gl.COMPILE_STATUS)){const log=gl.getShaderInfoLog(vertexShader);gl.deleteShader(fragmentShader);gl.deleteShader(vertexShader);gl.deleteProgram(shaderProgram);throw new Error("Error compiling vertex shader: "+
+log);}if(!gl.getProgramParameter(shaderProgram,gl.LINK_STATUS)){const log=gl.getProgramInfoLog(shaderProgram);gl.deleteShader(fragmentShader);gl.deleteShader(vertexShader);gl.deleteProgram(shaderProgram);throw new Error("Error linking shader program: "+log);}const infoLog=C3.FilterUnprintableChars(gl.getProgramInfoLog(shaderProgram)||"").trim();if(infoLog&&!C3.IsStringAllWhitespace(infoLog))console.info(`[WebGL] Shader program '${name}' compilation log: `,infoLog);gl.deleteShader(fragmentShader);
+gl.deleteShader(vertexShader);return shaderProgram}static async Create(renderer,shaderInfo){const shaderProgram=await C3.Gfx.WebGLShaderProgram.Compile(renderer,shaderInfo);return new C3.Gfx.WebGLShaderProgram(renderer,shaderProgram,shaderInfo)}constructor(renderer,shaderProgram,shaderInfo){super(renderer,shaderInfo);const gl=renderer.GetContext();const batchState=renderer.GetBatchState();renderer.EndBatch();gl.useProgram(shaderProgram);this._gl=gl;this._shaderProgram=shaderProgram;this._isDeviceTransform=
+shaderInfo.name==="";const locAPos=gl.getAttribLocation(shaderProgram,"aPos");const locATex=gl.getAttribLocation(shaderProgram,"aTex");this._locAPoints=gl.getAttribLocation(shaderProgram,"aPoints");if(locAPos!==-1){gl.bindBuffer(gl.ARRAY_BUFFER,renderer._vertexBuffer);gl.vertexAttribPointer(locAPos,renderer.GetNumVertexComponents(),gl.FLOAT,false,0,0);gl.enableVertexAttribArray(locAPos)}if(locATex!==-1){gl.bindBuffer(gl.ARRAY_BUFFER,renderer._texcoordBuffer);gl.vertexAttribPointer(locATex,
+2,gl.FLOAT,false,0,0);gl.enableVertexAttribArray(locATex)}if(this._locAPoints!==-1){gl.bindBuffer(gl.ARRAY_BUFFER,renderer._pointBuffer);gl.vertexAttribPointer(this._locAPoints,4,gl.FLOAT,false,0,0);gl.enableVertexAttribArray(this._locAPoints)}gl.bindBuffer(gl.ARRAY_BUFFER,null);this._uMatP=new C3.Gfx.WebGLShaderUniform(this,"matP","mat4");this._uMatMV=new C3.Gfx.WebGLShaderUniform(this,"matMV","mat4");this._uColor=new C3.Gfx.WebGLShaderUniform(this,"color","vec4");this._uSamplerFront=new C3.Gfx.WebGLShaderUniform(this,
+"samplerFront","sampler");this._uPointTexStart=new C3.Gfx.WebGLShaderUniform(this,"pointTexStart","vec2");this._uPointTexEnd=new C3.Gfx.WebGLShaderUniform(this,"pointTexEnd","vec2");this._uZElevation=new C3.Gfx.WebGLShaderUniform(this,"zElevation","float");this._uTileSize=new C3.Gfx.WebGLShaderUniform(this,"tileSize","vec2");this._uTileSpacing=new C3.Gfx.WebGLShaderUniform(this,"tileSpacing","vec2");this._uColor2=new C3.Gfx.WebGLShaderUniform(this,"color2_","vec4");this._uOutlineThickness=new C3.Gfx.WebGLShaderUniform(this,
+"outlineThickness","float");this._uSamplerBack=new C3.Gfx.WebGLShaderUniform(this,"samplerBack","sampler");this._uSamplerDepth=new C3.Gfx.WebGLShaderUniform(this,"samplerDepth","sampler");this._uDestStart=new C3.Gfx.WebGLShaderUniform(this,"destStart","vec2");this._uDestEnd=new C3.Gfx.WebGLShaderUniform(this,"destEnd","vec2");this._uSrcStart=new C3.Gfx.WebGLShaderUniform(this,"srcStart","vec2");this._uSrcEnd=new C3.Gfx.WebGLShaderUniform(this,"srcEnd","vec2");this._uSrcOriginStart=new C3.Gfx.WebGLShaderUniform(this,
+"srcOriginStart","vec2");this._uSrcOriginEnd=new C3.Gfx.WebGLShaderUniform(this,"srcOriginEnd","vec2");this._uPixelSize=new C3.Gfx.WebGLShaderUniform(this,"pixelSize","vec2");this._uSeconds=new C3.Gfx.WebGLShaderUniform(this,"seconds","float");this._uDevicePixelRatio=new C3.Gfx.WebGLShaderUniform(this,"devicePixelRatio","float");this._uLayerScale=new C3.Gfx.WebGLShaderUniform(this,"layerScale","float");this._uLayerAngle=new C3.Gfx.WebGLShaderUniform(this,"layerAngle","float");this._uLayoutStart=new C3.Gfx.WebGLShaderUniform(this,
+"layoutStart","vec2");this._uLayoutEnd=new C3.Gfx.WebGLShaderUniform(this,"layoutEnd","vec2");this._uZNear=new C3.Gfx.WebGLShaderUniform(this,"zNear","float");this._uZFar=new C3.Gfx.WebGLShaderUniform(this,"zFar","float");this._hasAnyOptionalUniforms=!!(this._uPixelSize.IsUsed()||this._uSeconds.IsUsed()||this._uSamplerBack.IsUsed()||this._uDestStart.IsUsed()||this._uDestEnd.IsUsed()||this._uSrcStart.IsUsed()||this._uSrcEnd.IsUsed()||this._uSrcOriginStart.IsUsed()||this._uSrcOriginEnd.IsUsed()||this._uDevicePixelRatio.IsUsed()||
+this._uLayerScale.IsUsed()||this._uLayerAngle.IsUsed()||this._uLayoutStart.IsUsed()||this._uLayoutEnd.IsUsed());const customParameterDefs=shaderInfo.parameters||[];this._uCustomParameters=[];this._usesAnySrcRectOrPixelSize=this._uPixelSize.IsUsed()||this._uSrcStart.IsUsed()||this._uSrcEnd.IsUsed()||this._uSrcOriginStart.IsUsed()||this._uSrcOriginEnd.IsUsed();this._hasCurrentMatP=false;this._hasCurrentMatMV=false;this._uColor.Init4f(1,1,1,1);this._uColor2.Init4f(1,1,1,1);this._uSamplerFront.Init1i(0);
+this._uSamplerBack.Init1i(1);this._uSamplerDepth.Init1i(2);this._uPointTexStart.Init2f(0,0);this._uPointTexEnd.Init2f(1,1);this._uZElevation.Init1f(0);this._uTileSize.Init2f(0,0);this._uTileSpacing.Init2f(0,0);this._uDestStart.Init2f(0,0);this._uDestEnd.Init2f(1,1);this._uSrcStart.Init2f(0,0);this._uSrcEnd.Init2f(0,0);this._uSrcOriginStart.Init2f(0,0);this._uSrcOriginEnd.Init2f(0,0);this._uPixelSize.Init2f(0,0);this._uDevicePixelRatio.Init1f(1);this._uZNear.Init1f(renderer.GetNearZ());this._uZFar.Init1f(renderer.GetFarZ());
+this._uLayerScale.Init1f(1);this._uLayerAngle.Init1f(0);this._uSeconds.Init1f(0);this._uLayoutStart.Init2f(0,0);this._uLayoutEnd.Init2f(0,0);this._uOutlineThickness.Init1f(1);for(const p of customParameterDefs){const uniformName=p[0];const paramType=p[2];const shaderUniform=new C3.Gfx.WebGLShaderUniform(this,uniformName,paramType);if(paramType==="color")shaderUniform.Init3f(0,0,0);else shaderUniform.Init1f(0);this._uCustomParameters.push(shaderUniform)}if(this._isDeviceTransform)this._UpdateDeviceTransformUniforms(batchState.currentMatP);
+else{this.UpdateMatP(batchState.currentMatP,true);this.UpdateMatMV(batchState.currentMV,true)}const currentShader=batchState.currentShader;gl.useProgram(currentShader?currentShader._shaderProgram:null)}Release(){this._gl.deleteProgram(this._shaderProgram);this._shaderProgram=null;this._renderer._RemoveShaderProgram(this);this._gl=null;super.Release()}GetWebGLContext(){return this._gl}GetShaderProgram(){return this._shaderProgram}GetParameterCount(){return this._uCustomParameters.length}GetParameterType(paramIndex){if(paramIndex<
+0||paramIndex>=this._uCustomParameters.length)return null;return this._uCustomParameters[paramIndex].GetType()}AreCustomParametersAlreadySetInBatch(params){for(let i=0,len=params.length;i=2)prefix="#version 300 es\n";else{if(hasFragDepthExt)prefix="#extension GL_EXT_frag_depth : enable\n";if(useDerivatives){prefix+="#extension GL_EXT_shader_texture_lod : enable\n";prefix+="#extension GL_OES_standard_derivatives : enable\n"}}return prefix+
+`
+#ifdef GL_FRAGMENT_PRECISION_HIGH
+#define highmedp highp
+#else
+#define highmedp mediump
+#endif
+precision highmedp float;
+${webGLVer>=2?"in":"varying"} vec2 vTex;
+${webGLVer>=2?"out lowp vec4 outColor;":""}
+uniform lowp vec4 color;
+uniform lowp sampler2D samplerFront;
+uniform vec2 pixelSize;
+
+uniform vec2 tileSize;
+uniform vec2 tileSpacing;
+uniform float outlineThickness;
+
+const float PI = 3.1415926;
+
+lowp vec4 cospVec4(lowp vec4 a, lowp vec4 b, float x)
+{
+ return (a + b + (a - b) * cos(x * PI)) / 2.0;
+}
+
+vec3 randVec3(vec2 seed)
+{
+ return vec3(fract(sin(dot(seed.xy + vec2(0.1, 0.1), vec2(12.9898,78.233))) * 43758.5453),
+ fract(sin(dot(seed.yx + vec2(0.1, 0.1), vec2(12.9898,-78.233))) * 43758.5453),
+ fract(sin(dot(seed.xy + vec2(0.1, 0.1), vec2(-12.9898,-78.233))) * 43758.5453));
+}
+
+lowp vec4 sampleTile(vec2 tile, vec2 uv, vec2 ddx, vec2 ddy)
+{
+ vec2 posRandom = tileSize;
+ float angleRandom = outlineThickness;
+
+ vec3 rand = (randVec3(floor(tile + 0.5)) - 0.5) * 2.0;
+
+ float angle = angleRandom * rand.z * PI;
+ float sin_a = sin(angle);
+ float cos_a = cos(angle);
+ float aspect = pixelSize.x / pixelSize.y;
+
+ vec2 mid = tile + vec2(0.5, 0.5);
+ vec2 dp = uv - mid;
+ dp.x /= aspect;
+ vec2 r = vec2(dp.x * cos_a - dp.y * sin_a,
+ dp.y * cos_a + dp.x * sin_a);
+ r.x *= aspect;
+
+ vec2 p = mid + r + (posRandom * rand.xy / 2.0);
+
+ ${webGLVer>=2?"return textureGrad(samplerFront, p, ddx, ddy);":""}
+ ${webGLVer<2&&useDerivatives?"return texture2DGradEXT(samplerFront, p, ddx, ddy);":""}
+ ${webGLVer<2&&!useDerivatives?"return texture2D(samplerFront, p);":""}
+}
+
+void main(void) {
+
+ ${webGLVer<2?"lowp vec4 outColor;":""}
+
+ float blendMarginX = tileSpacing.x;
+ float blendMarginY = tileSpacing.y;
+
+ vec2 tile = floor(vTex);
+ vec2 tex = fract(vTex);
+ vec2 ddx = ${webGLVer>=2||useDerivatives?"dFdx(vTex)":"vec2(0.0, 0.0)"};
+ vec2 ddy = ${webGLVer>=2||useDerivatives?"dFdy(vTex)":"vec2(0.0, 0.0)"};
+
+ vec4 curTile = sampleTile(tile, vTex, ddx, ddy);
+
+ bool inLeftMargin = (tex.x < blendMarginX);
+ bool inRightMargin = (tex.x > 1.0 - blendMarginX);
+ bool inTopMargin = (tex.y < blendMarginY);
+ bool inBottomMargin = (tex.y > 1.0 - blendMarginY);
+
+ if (inLeftMargin)
+ {
+ lowp vec4 leftTile = sampleTile(tile + vec2(-1.0, 0.0), vTex, ddx, ddy);
+ float leftMix = (tex.x / (blendMarginX * 2.0)) + 0.5;
+ lowp vec4 leftMixedTile = cospVec4(leftTile, curTile, leftMix);
+
+ if (inTopMargin)
+ {
+ lowp vec4 topTile = sampleTile(tile + vec2(0.0, -1.0), vTex, ddx, ddy);
+ lowp vec4 topLeftTile = sampleTile(tile + vec2(-1.0, -1.0), vTex, ddx, ddy);
+ lowp vec4 topLeftMixedTile = cospVec4(topLeftTile, topTile, leftMix);
+
+ outColor = cospVec4(topLeftMixedTile, leftMixedTile, (tex.y / (blendMarginY * 2.0)) + 0.5);
+ }
+ else if (inBottomMargin)
+ {
+ lowp vec4 bottomTile = sampleTile(tile + vec2(0.0, 1.0), vTex, ddx, ddy);
+ lowp vec4 bottomLeftTile = sampleTile(tile + vec2(-1.0, 1.0), vTex, ddx, ddy);
+ lowp vec4 bottomLeftMixedTile = cospVec4(bottomLeftTile, bottomTile, leftMix);
+
+ outColor = cospVec4(leftMixedTile, bottomLeftMixedTile, (tex.y - (1.0 - blendMarginY)) / (blendMarginY * 2.0));
+ }
+ else
+ {
+ outColor = leftMixedTile;
+ }
+ }
+ else if (inRightMargin)
+ {
+ lowp vec4 rightTile = sampleTile(tile + vec2(1.0, 0.0), vTex, ddx, ddy);
+ float rightMix = (tex.x - (1.0 - blendMarginX)) / (blendMarginX * 2.0);
+ lowp vec4 rightMixedTile = cospVec4(curTile, rightTile, rightMix);
+
+ if (inTopMargin)
+ {
+ lowp vec4 topTile = sampleTile(tile + vec2(0.0, -1.0), vTex, ddx, ddy);
+ lowp vec4 topRightTile = sampleTile(tile + vec2(1.0, -1.0), vTex, ddx, ddy);
+ lowp vec4 topRightMixedTile = cospVec4(topTile, topRightTile, rightMix);
+
+ outColor = cospVec4(topRightMixedTile, rightMixedTile, (tex.y / (blendMarginY * 2.0)) + 0.5);
+ }
+ else if (inBottomMargin)
+ {
+ lowp vec4 bottomTile = sampleTile(tile + vec2(0.0, 1.0), vTex, ddx, ddy);
+ lowp vec4 bottomRightTile = sampleTile(tile + vec2(1.0, 1.0), vTex, ddx, ddy);
+ lowp vec4 bottomRightMixedTile = cospVec4(bottomTile, bottomRightTile, rightMix);
+
+ outColor = cospVec4(rightMixedTile, bottomRightMixedTile, (tex.y - (1.0 - blendMarginY)) / (blendMarginY * 2.0));
+ }
+ else
+ {
+ outColor = rightMixedTile;
+ }
+ }
+ else if (inTopMargin)
+ {
+ lowp vec4 topTile = sampleTile(tile + vec2(0.0, -1.0), vTex, ddx, ddy);
+ outColor = cospVec4(topTile, curTile, (tex.y / (blendMarginY * 2.0)) + 0.5);
+ }
+ else if (inBottomMargin)
+ {
+ lowp vec4 bottomTile = sampleTile(tile + vec2(0.0, 1.0), vTex, ddx, ddy);
+ outColor = cospVec4(curTile, bottomTile, (tex.y - (1.0 - blendMarginY)) / (blendMarginY * 2.0));
+ }
+ else
+ {
+ outColor = curTile;
+ }
+
+ outColor *= color;
+ ${webGLVer<2?"gl_FragColor = outColor;":""}
+ ${webGLVer>=2?"gl_FragDepth = (outColor.a == 0.0 ? 1.0 : gl_FragCoord.z);":""}
+ ${webGLVer<2&&hasFragDepthExt?"gl_FragDepthEXT = (outColor.a == 0.0 ? 1.0 : gl_FragCoord.z);":""}
+}
+`}static GetPointVertexShaderSource_WebGL1(){return["attribute vec4 aPoints;","varying float pointOpacity;","uniform float zElevation;","uniform mat4 matP;","uniform mat4 matMV;","void main(void) {","\tgl_Position = matP * matMV * vec4(aPoints.xy, zElevation, 1.0);","\tgl_PointSize = aPoints.z;","\tpointOpacity = aPoints.w;","}"].join("\n")}static GetPointVertexShaderSource_WebGL2(){return["#version 300 es","in vec4 aPoints;","out float pointOpacity;","uniform float zElevation;","uniform mat4 matP;",
+"uniform mat4 matMV;","void main(void) {","\tgl_Position = matP * matMV * vec4(aPoints.xy, zElevation, 1.0);","\tgl_PointSize = aPoints.z;","\tpointOpacity = aPoints.w;","}"].join("\n")}static GetPointFragmentShaderSource_WebGL1_NoFragDepth(){return["uniform lowp sampler2D samplerFront;","varying lowp float pointOpacity;","uniform mediump vec2 pointTexStart;","uniform mediump vec2 pointTexEnd;","uniform lowp vec4 color;","void main(void) {","\tmediump vec2 pointTexMin = min(pointTexStart, pointTexEnd);",
+"\tmediump vec2 pointTexMax = max(pointTexStart, pointTexEnd);","\tmediump vec2 pointCoord = (pointTexEnd.x > pointTexStart.x ? gl_PointCoord : vec2(1.0 - gl_PointCoord.y, gl_PointCoord.x));","\tgl_FragColor = texture2D(samplerFront, mix(pointTexMin, pointTexMax, pointCoord)) * color * pointOpacity;","}"].join("\n")}static GetPointFragmentShaderSource_WebGL1_FragDepthEXT(){return["#extension GL_EXT_frag_depth : enable","uniform lowp sampler2D samplerFront;","varying lowp float pointOpacity;","uniform mediump vec2 pointTexStart;",
+"uniform mediump vec2 pointTexEnd;","uniform lowp vec4 color;","void main(void) {","\tmediump vec2 pointTexMin = min(pointTexStart, pointTexEnd);","\tmediump vec2 pointTexMax = max(pointTexStart, pointTexEnd);","\tmediump vec2 pointCoord = (pointTexEnd.x > pointTexStart.x ? gl_PointCoord : vec2(1.0 - gl_PointCoord.y, gl_PointCoord.x));","\tgl_FragColor = texture2D(samplerFront, mix(pointTexMin, pointTexMax, pointCoord)) * color * pointOpacity;","\tgl_FragDepthEXT = (gl_FragColor.a == 0.0 ? 1.0 : gl_FragCoord.z);",
+"}"].join("\n")}static GetPointFragmentShaderSource_WebGL2(){return["#version 300 es","uniform lowp sampler2D samplerFront;","in lowp float pointOpacity;","uniform mediump vec2 pointTexStart;","uniform mediump vec2 pointTexEnd;","uniform lowp vec4 color;","out lowp vec4 outColor;","void main(void) {","\tmediump vec2 pointTexMin = min(pointTexStart, pointTexEnd);","\tmediump vec2 pointTexMax = max(pointTexStart, pointTexEnd);","\tmediump vec2 pointCoord = (pointTexEnd.x > pointTexStart.x ? gl_PointCoord : vec2(1.0 - gl_PointCoord.y, gl_PointCoord.x));",
+"\toutColor = texture(samplerFront, mix(pointTexMin, pointTexMax, pointCoord)) * color * pointOpacity;","\tgl_FragDepth = (outColor.a == 0.0 ? 1.0 : gl_FragCoord.z);","}"].join("\n")}static GetColorFillFragmentShaderSource(){return["uniform lowp vec4 color;","void main(void) {","\tgl_FragColor = color;","}"].join("\n")}static GetLinearGradientFillFragmentShaderSource(){return["precision lowp float;","varying mediump vec2 vTex;","uniform vec4 color;","uniform vec4 color2_;","vec3 fromLinear(vec3 linearRGB)",
+"{","\tbvec3 cutoff = lessThan(linearRGB, vec3(0.0031308));","\tvec3 higher = vec3(1.055) * pow(abs(linearRGB), vec3(1.0/2.4)) - vec3(0.055);","\tvec3 lower = linearRGB * vec3(12.92);","\treturn mix(higher, lower, vec3(cutoff));","}","vec3 toLinear(vec3 sRGB)","{","\tbvec3 cutoff = lessThan(sRGB, vec3(0.04045));","\tvec3 higher = pow(abs((sRGB + vec3(0.055))/vec3(1.055)), vec3(2.4));","\tvec3 lower = sRGB/vec3(12.92);","\treturn mix(higher, lower, vec3(cutoff));","}","void main(void) {","\tvec3 linearGrad = mix(toLinear(color.rgb), toLinear(color2_.rgb), vTex.x);",
+"\tfloat a = mix(color.a, color2_.a, vTex.x);","\tgl_FragColor = vec4(fromLinear(linearGrad) * a, a);","}"].join("\n")}static GetPenumbraFillFragmentShaderSource(){return[`#ifdef GL_FRAGMENT_PRECISION_HIGH`,`#define highmedp highp`,`#else`,`#define highmedp mediump`,`#endif`,`precision lowp float;`,`varying highmedp vec2 vTex;`,`uniform vec4 color;`,`void main(void) {`,` highmedp float grad = vTex.x / (1.0 - vTex.y);`,` gl_FragColor = color * (1.0 - (cos(grad * 3.141592653589793) + 1.0) / 2.0);`,
+`}`].join("\n")}static GetSmoothLineFillFragmentShaderSource(){return["varying mediump vec2 vTex;","uniform lowp vec4 color;","void main(void) {","\tlowp float f = 1.0 - abs(vTex.y - 0.5) * 2.0;","\tgl_FragColor = color * f;","}"].join("\n")}static GetHardEllipseFillFragmentShaderSource(){return["varying mediump vec2 vTex;","uniform lowp vec4 color;","void main(void) {","\tmediump vec2 diff = vTex - vec2(0.5, 0.5);","\tmediump vec2 diffSq = diff * diff;","\tmediump float f = step(diffSq.x + diffSq.y, 0.25);",
+"\tgl_FragColor = color * f;","}"].join("\n")}static GetHardEllipseOutlineFragmentShaderSource(){return["varying mediump vec2 vTex;","uniform lowp vec4 color;","uniform mediump vec2 pixelSize;","uniform mediump float outlineThickness;","void main(void) {","\tmediump vec2 diff = vTex - vec2(0.5, 0.5);","\tmediump vec2 diffSq = diff * diff;","\tmediump float distSq = diffSq.x + diffSq.y;","\tmediump vec2 norm = normalize(diff);","\tmediump vec2 halfNorm = norm * 0.5;","\tmediump float innerF = step(distSq, 0.25);",
+"\tmediump vec2 innerEdge = halfNorm - pixelSize * norm * outlineThickness;","\tmediump vec2 innerEdgeSq = innerEdge * innerEdge;","\tmediump float outerF = step(innerEdgeSq.x + innerEdgeSq.y, distSq);","\tgl_FragColor = color * innerF * outerF;","}"].join("\n")}static GetSmoothEllipseFillFragmentShaderSource(){return["varying mediump vec2 vTex;","uniform lowp vec4 color;","uniform mediump vec2 pixelSize;","void main(void) {","\tmediump vec2 diff = vTex - vec2(0.5, 0.5);","\tmediump vec2 diffSq = diff * diff;",
+"\tmediump vec2 norm = normalize(diff);","\tmediump vec2 halfNorm = norm * 0.5;","\tmediump vec2 halfNormSq = halfNorm * halfNorm;","\tmediump vec2 innerEdge = halfNorm - pixelSize * norm;","\tmediump vec2 innerEdgeSq = innerEdge * innerEdge;","\tmediump float f = smoothstep(halfNormSq.x + halfNormSq.y, innerEdgeSq.x + innerEdgeSq.y, diffSq.x + diffSq.y);","\tgl_FragColor = color * f;","}"].join("\n")}static GetSmoothEllipseOutlineFragmentShaderSource(){return["varying mediump vec2 vTex;","uniform lowp vec4 color;",
+"uniform mediump vec2 pixelSize;","uniform mediump float outlineThickness;","void main(void) {","\tmediump vec2 diff = vTex - vec2(0.5, 0.5);","\tmediump vec2 diffSq = diff * diff;","\tmediump float distSq = diffSq.x + diffSq.y;","\tmediump vec2 norm = normalize(diff);","\tmediump vec2 halfNorm = norm * 0.5;","\tmediump vec2 halfNormSq = halfNorm * halfNorm;","\tmediump vec2 pxNorm = pixelSize * norm;","\tmediump vec2 innerEdge1 = halfNorm - pxNorm;","\tmediump vec2 innerEdge1Sq = innerEdge1 * innerEdge1;",
+"\tmediump float innerF = smoothstep(halfNormSq.x + halfNormSq.y, innerEdge1Sq.x + innerEdge1Sq.y, distSq);","\tmediump vec2 innerEdge2 = halfNorm - pxNorm * outlineThickness;","\tmediump vec2 innerEdge2Sq = innerEdge2 * innerEdge2;","\tmediump vec2 innerEdge3 = halfNorm - pxNorm * (outlineThickness + 1.0);","\tmediump vec2 innerEdge3Sq = innerEdge3 * innerEdge3;","\tmediump float outerF = smoothstep(innerEdge3Sq.x + innerEdge3Sq.y, innerEdge2Sq.x + innerEdge2Sq.y, distSq);","\tgl_FragColor = color * innerF * outerF;",
+"}"].join("\n")}};
+
+}
+
+// ../lib/gfx/webgl/shaderUniform.js
+{
+'use strict';const C3=self.C3;const glMatrix=self.glMatrix;const mat4=glMatrix.mat4;const TYPE_SIZES=new Map([["float",1],["percent",1],["sampler",1],["vec2",2],["vec3",3],["color",3],["vec4",4],["mat4",16]]);
+C3.Gfx.WebGLShaderUniform=class WebGLShaderUniform{constructor(owner,name,type){if(!TYPE_SIZES.has(type))throw new Error("invalid uniform type");this._owner=owner;this._gl=this._owner.GetWebGLContext();this._name=name;this._type=type;this._isColorType=this._type==="color";this._location=this._gl.getUniformLocation(this._owner.GetShaderProgram(),name);this._isUsed=!!this._location;const typeSize=TYPE_SIZES.get(type);this._lastValue=new Float32Array(typeSize);this._lastBatchValue=new Float32Array(typeSize)}Release(){this._owner=
+null;this._gl=null;this._location=null}IsUsed(){return this._isUsed}GetType(){return this._type}IsColorType(){return this._isColorType}Init1f(v0){if(!this.IsUsed())return;this._lastValue[0]=v0;this._lastBatchValue.set(this._lastValue);this._gl.uniform1f(this._location,v0)}Init1i(v0){if(!this.IsUsed())return;this._lastValue[0]=v0;this._lastBatchValue.set(this._lastValue);this._gl.uniform1i(this._location,v0)}Init2f(v0,v1){if(!this.IsUsed())return;this._lastValue[0]=v0;this._lastValue[1]=v1;this._lastBatchValue.set(this._lastValue);
+this._gl.uniform2f(this._location,v0,v1)}Init3f(v0,v1,v2){if(!this.IsUsed())return;this._lastValue[0]=v0;this._lastValue[1]=v1;this._lastValue[2]=v2;this._lastBatchValue.set(this._lastValue);this._gl.uniform3f(this._location,v0,v1,v2)}Init4f(v0,v1,v2,v3){if(!this.IsUsed())return;this._lastValue[0]=v0;this._lastValue[1]=v1;this._lastValue[2]=v2;this._lastValue[3]=v3;this._lastBatchValue.set(this._lastValue);this._gl.uniform4f(this._location,v0,v1,v2,v3)}Update1f(v0){v0=Math.fround(v0);const lastValue=
+this._lastValue;if(lastValue[0]===v0)return;lastValue[0]=v0;this._gl.uniform1f(this._location,v0)}Update1i(v0){const lastValue=this._lastValue;if(lastValue[0]===v0)return;lastValue[0]=v0;this._gl.uniform1i(this._location,v0)}Update2f(v0,v1){v0=Math.fround(v0);v1=Math.fround(v1);const lastValue=this._lastValue;if(lastValue[0]===v0&&lastValue[1]===v1)return;lastValue[0]=v0;lastValue[1]=v1;this._gl.uniform2f(this._location,v0,v1)}Update3f(v0,v1,v2){v0=Math.fround(v0);v1=Math.fround(v1);v2=Math.fround(v2);
+const lastValue=this._lastValue;if(lastValue[0]===v0&&lastValue[1]===v1&&lastValue[2]===v2)return;lastValue[0]=v0;lastValue[1]=v1;lastValue[2]=v2;this._gl.uniform3f(this._location,v0,v1,v2)}Update4f(v0,v1,v2,v3){v0=Math.fround(v0);v1=Math.fround(v1);v2=Math.fround(v2);v3=Math.fround(v3);const lastValue=this._lastValue;if(lastValue[0]===v0&&lastValue[1]===v1&&lastValue[2]===v2&&lastValue[3]===v3)return;lastValue[0]=v0;lastValue[1]=v1;lastValue[2]=v2;lastValue[3]=v3;this._gl.uniform4f(this._location,
+v0,v1,v2,v3)}UpdateMatrix4fv(m){const lastValue=this._lastValue;if(mat4.exactEquals(lastValue,m))return;C3.typedArraySet16(lastValue,m,0);this._gl.uniformMatrix4fv(this._location,false,m)}IsSetToCustomInBatch(p){const batchValue=this._lastBatchValue;if(this.IsColorType())return batchValue[0]===Math.fround(p.getR())&&batchValue[1]===Math.fround(p.getG())&&batchValue[2]===Math.fround(p.getB());else return batchValue[0]===Math.fround(p)}SetBatchValueCustom(p){const batchValue=this._lastBatchValue;if(this.IsColorType()){batchValue[0]=
+p.getR();batchValue[1]=p.getG();batchValue[2]=p.getB()}else batchValue[0]=p}IsSetTo1InBatch(x){return this._lastBatchValue[0]===Math.fround(x)}IsSetTo2InBatch(x,y){const batchValue=this._lastBatchValue;return batchValue[0]===Math.fround(x)&&batchValue[1]===Math.fround(y)}SetBatch1(x){this._lastBatchValue[0]=x}SetBatch2(x,y){const batchValue=this._lastBatchValue;batchValue[0]=x;batchValue[1]=y}};
+
+}
+
+// ../lib/gfx/webgl/batchJob.js
+{
+'use strict';const C3=self.C3;const glMatrix=self.glMatrix;const vec4=glMatrix.vec4;const mat4=glMatrix.mat4;const BATCH_NULL=0;const BATCH_QUAD=1;const BATCH_SETTEXTURE=2;const BATCH_SETCOLOR=3;const BATCH_SETBLEND=4;const BATCH_SETVIEWPORT=5;const BATCH_SETPROJECTION=6;const BATCH_SETMODELVIEW=7;const BATCH_SETRENDERTARGET=8;const BATCH_CLEARSURFACE=9;const BATCH_POINTS=10;const BATCH_SETPROGRAM=11;const BATCH_SETPROGRAMPARAMETERS=12;const BATCH_SETPROGRAMCUSTOMPARAMETERS=13;
+const BATCH_INVALIDATEFRAMEBUFFER=14;const BATCH_SETPOINTTEXCOORDS=15;const BATCH_SETTILEMAPINFO=16;const BATCH_BLITFRAMEBUFFER=17;const BATCH_STARTQUERY=18;const BATCH_ENDQUERY=19;const BATCH_SETELLIPSEPARAMS=20;const BATCH_SETGRADIENTCOLOR=21;const BATCH_CLEARDEPTH=22;const BATCH_SETDEPTHENABLED=23;const BATCH_SETDEPTHSAMPLINGENABLED=24;const BATCH_COPLANAR_STARTSTENCILPASS=25;const BATCH_COPLANAR_STARTCOLORPASS=26;const BATCH_COPLANAR_RESTORE=27;const BATCH_SET_SCISSOR=28;
+const BATCH_SETTILERANDOMIZATIONINFO=29;C3.Gfx.BatchState=class BatchState{constructor(renderer){this.renderer=renderer;this.currentMV=mat4.create();this.currentMatP=mat4.create();this.currentFramebuffer=null;this.currentFramebufferNoDepth=null;this.isDepthSamplingEnabled=false;this.currentColor=vec4.fromValues(1,1,1,1);this.currentShader=null;this.pointTexCoords=new C3.Rect;this.clearColor=C3.New(C3.Color,0,0,0,0)}};
+C3.Gfx.WebGLBatchJob=class WebGLBatchJob{constructor(batchState){const arrayBuffer=new ArrayBuffer(96);this._type=0;this._batchState=batchState;this._gl=batchState.renderer.GetContext();this._startIndex=0;this._indexCount=0;this._texParam=null;this._mat4param=new Float32Array(arrayBuffer,0,16);this._colorParam=new Float32Array(arrayBuffer,64,4);this._srcOriginRect=new Float32Array(arrayBuffer,80,4);this._shaderParams=[]}InitQuad(startIndex,indexCount){this._type=BATCH_QUAD;this._startIndex=startIndex;
+this._indexCount=indexCount}DoQuad(){const gl=this._gl;gl.drawElements(gl.TRIANGLES,this._indexCount,gl.UNSIGNED_SHORT,this._startIndex)}InitSetTexture(rendererTex){this._type=BATCH_SETTEXTURE;this._texParam=rendererTex}DoSetTexture(){const gl=this._gl;const texParam=this._texParam;gl.bindTexture(gl.TEXTURE_2D,texParam?texParam._GetTexture():null)}InitSetColor(c){this._type=BATCH_SETCOLOR;c.writeToTypedArray(this._colorParam,0)}DoSetColor(){const c=this._colorParam;const batchState=this._batchState;
+vec4.copy(batchState.currentColor,c);batchState.currentShader.UpdateColor(c)}InitSetGradientColor(c){this._type=BATCH_SETGRADIENTCOLOR;c.writeToTypedArray(this._colorParam,0)}DoSetGradientColor(){const c=this._colorParam;const s=this._batchState.currentShader;if(s._uColor2.IsUsed())s._uColor2.Update4f(c[0],c[1],c[2],c[3])}InitSetBlend(s,d){this._type=BATCH_SETBLEND;this._startIndex=s;this._indexCount=d}DoSetBlend(){this._gl.blendFunc(this._startIndex,this._indexCount)}InitSetViewport(x,y,w,h){this._type=
+BATCH_SETVIEWPORT;const colorParam=this._colorParam;colorParam[0]=x;colorParam[1]=y;colorParam[2]=w;colorParam[3]=h}DoSetViewport(){const colorParam=this._colorParam;this._gl.viewport(colorParam[0],colorParam[1],colorParam[2],colorParam[3])}InitSetProjection(m){this._type=BATCH_SETPROJECTION;mat4.copy(this._mat4param,m)}DoSetProjection(){const batchState=this._batchState;const allShaderPrograms=batchState.renderer._allShaderPrograms;const currentShader=batchState.currentShader;const mat4param=this._mat4param;
+for(let i=0,len=allShaderPrograms.length;i{const fontName=e.font.GetName();for(const f of allRendererTexts)if(f.IsBBCodeEnabled()||C3.equalsNoCase(f.GetFontName(),fontName))f._SetWordWrapChanged()});function fillOrStrokeRect(ctx,isStroke,x,y,w,h){if(isStroke)ctx.strokeRect(x,y,w,h);else ctx.fillRect(x,y,w,h)}
+function ptToPx(pt){return pt*(4/3)}function getOffsetParam(paramStr,fragHeight){paramStr=paramStr.trim();const param=parseFloat(paramStr);if(!isFinite(param))return 0;if(paramStr.endsWith("%"))return fragHeight*param/100;else return param}let didCheckFoundBoundingBoxSupport=false;let supportsFontBoundingBoxMeasurements=false;
+C3.Gfx.RendererText=class RendererText{constructor(renderer,opts){opts=Object.assign({},DEFAULT_OPTS,opts);this._renderer=renderer;this._fontName="Arial";this._fontSize=16;this._fontSizeScale=1;this._lineHeight=0;this._isBold=false;this._isItalic=false;this._colorStr="black";this._isBBcodeEnabled=false;this._iconSet=null;this._iconSmoothing=true;this.onloadfont=null;this._alreadyLoadedFonts=new Set;this._horizontalAlign="left";this._verticalAlign="top";this._text="";this._bbString=null;this._wrappedText=
+C3.New(C3.WordWrap);this._wrapMode="word";this._textDirection="ltr";this._wordWrapChanged=false;this._textLayoutChanged=false;this._drawChanged=false;this._drawMaxCharCount=-1;this._drawCharCount=0;this._cssWidth=0;this._cssHeight=0;this._width=0;this._height=0;this._zoom=1;this._textCanvas=null;this._textContext=null;this._measureContext=null;this._measureContextTop=null;this._lastCanvasWidth=-1;this._lastCanvasHeight=-1;this._lastTextCanvasFont="";this._lastMeasureCanvasFont="";this._lastTextCanvasFillStyle=
+"";this._lastTextCanvasOpacity=1;this._lastTextCanvasLineWidth=1;this._measureTextCallback=frag=>this._MeasureText(frag);this._texture=null;this._rcTex=new C3.Rect;this._scaleFactor=1;this._textureTimeout=new C3.IdleTimeout(()=>{this.ReleaseTexture();this._SetTextCanvasSize(8,8)},opts.timeout);this.ontextureupdate=null;this._wasReleased=false;allRendererTexts.add(this)}Release(){this.onloadfont=null;this._alreadyLoadedFonts.clear();this._iconSet=null;this._bbString=null;this._textCanvas=null;this._textContext=
+null;this._measureContext=null;this._measureContextTop=null;this._measureTextCallback=null;this._textureTimeout.Release();this.ontextureupdate=null;this.ReleaseTexture();this._wrappedText.Clear();this._wrappedText=null;this._renderer=null;this._wasReleased=true;allRendererTexts.delete(this)}_SetDrawChanged(){this._drawChanged=true}_SetTextLayoutChanged(){this._SetDrawChanged();this._textLayoutChanged=true}_SetWordWrapChanged(){this._SetTextLayoutChanged();this._wordWrapChanged=true}SetBBCodeEnabled(e){e=
+!!e;if(this._isBBcodeEnabled===e)return;this._isBBcodeEnabled=e;const textBaseline=this._isBBcodeEnabled?"alphabetic":"top";if(this._textContext)this._textContext.textBaseline=textBaseline;if(this._measureContext)this._measureContext.textBaseline=textBaseline;this._SetWordWrapChanged()}IsBBCodeEnabled(){return this._isBBcodeEnabled}SetIconSet(iconSet){if(this._iconSet===iconSet)return;this._iconSet=iconSet;this._wrappedText.SetIconSet(iconSet);if(this._iconSet&&this._iconSet.IsLoading())this._iconSet.LoadContent().then(()=>
+this._SetDrawChanged());this._SetWordWrapChanged()}SetIconSmoothing(s){s=!!s;if(this._iconSmoothing===s)return;this._iconSmoothing=s;this._SetDrawChanged()}SetFontName(fontName){if(!fontName)fontName="serif";if(this._fontName===fontName)return;this._fontName=fontName;this._SetWordWrapChanged()}GetFontName(){return this._fontName}SetFontSize(fontSize){if(fontSize<.1)fontSize=.1;if(this._fontSize===fontSize)return;this._fontSize=fontSize;this._SetWordWrapChanged()}SetFontSizeScale(s){if(this._fontSizeScale===
+s)return;this._fontSizeScale=s;this._SetWordWrapChanged()}SetLineHeight(h){if(this._lineHeight===h)return;this._lineHeight=h;this._SetTextLayoutChanged()}SetBold(bold){bold=!!bold;if(this._isBold===bold)return;this._isBold=bold;this._SetWordWrapChanged()}SetItalic(italic){italic=!!italic;if(this._isItalic===italic)return;this._isItalic=italic;this._SetWordWrapChanged()}SetDrawMaxCharacterCount(n){n=Math.floor(n);if(this._drawMaxCharCount===n)return;this._drawMaxCharCount=n;this._SetDrawChanged()}GetDrawMaxCharacterCount(){return this._drawMaxCharCount}_GetFontString(useCssUnits,
+frag){let ret=[];if(this._isBold||frag.HasStyleTag("b"))ret.push("bold");if(this._isItalic||frag.HasStyleTag("i"))ret.push("italic");const sizeStyle=frag.GetStyleTag("size");const fontSize=(sizeStyle?parseFloat(sizeStyle.param):this._fontSize)*this._fontSizeScale;if(useCssUnits)ret.push(fontSize+"pt");else ret.push(fontSize*this.GetDrawScale()+"pt");let fontName=this._fontName;const fontStyle=frag.GetStyleTag("font");if(fontStyle&&fontStyle.param){fontName=fontStyle.param;if(this.onloadfont&&!this._alreadyLoadedFonts.has(fontName)){this.onloadfont(fontName);
+this._alreadyLoadedFonts.add(fontName)}}if(fontName)if(GENERIC_FONT_FAMILIES.has(fontName))ret.push(fontName);else ret.push('"'+fontName+'"');return ret.join(" ")}SetColor(c){if(c instanceof C3.Color)c=c.getCssRgb();if(this._colorStr===c)return;this._colorStr=c;this._SetDrawChanged()}SetColorRgb(r,g,b){tempColor.setRgb(r,g,b);this.SetColor(tempColor)}SetHorizontalAlignment(h){if(!VALID_HORIZ_ALIGNMENTS.has(h))throw new Error("invalid horizontal alignment");if(this._horizontalAlign===h)return;this._horizontalAlign=
+h;this._SetTextLayoutChanged()}SetVerticalAlignment(v){if(!VALID_VERT_ALIGNMENTS.has(v))throw new Error("invalid vertical alignment");if(this._verticalAlign===v)return;this._verticalAlign=v;this._SetTextLayoutChanged()}SetWordWrapMode(m){if(!VALID_WORD_WRAP_MODES.has(m))throw new Error("invalid word wrap mode");if(this._wrapMode===m)return;this._wrapMode=m;this._SetWordWrapChanged()}SetTextDirection(d){if(!VALID_TEXT_DIRECTIONS.has(d))throw new Error("invalid text direction");if(this._textDirection===
+d)return;this._textDirection=d;if(this._textContext)this._textContext.direction=this._textDirection;if(this._measureContext)this._measureContext.direction=this._textDirection;this._SetWordWrapChanged()}SetText(text){if(this._text===text)return;this._text=text;this._SetWordWrapChanged()}GetDrawScale(){return this._scaleFactor*this._zoom*self.devicePixelRatio}SetSize(cssWidth,cssHeight,zoom){if(typeof zoom==="undefined")zoom=1;if(cssWidth<=0||cssWidth<=0)return;if(this._cssWidth===cssWidth&&this._cssHeight===
+cssHeight&&this._zoom===zoom)return;const oldCssWidth=this._cssWidth;this._cssWidth=cssWidth;this._cssHeight=cssHeight;this._zoom=zoom;const dpr=self.devicePixelRatio;this._width=this._cssWidth*this._zoom*dpr;this._height=this._cssHeight*this._zoom*dpr;const maxDim=Math.max(this._width,this._height);const maxTextureSize=Math.min(this._renderer.GetMaxTextureSize(),MAX_TEXTURE_SIZE);let scale=1;if(maxDim>maxTextureSize){scale=maxTextureSize/maxDim;this._width=Math.min(this._width*scale,maxTextureSize);
+this._height=Math.min(this._height*scale,maxTextureSize)}this._scaleFactor=scale;if(this._cssWidth!==oldCssWidth)this._SetWordWrapChanged();else this._SetTextLayoutChanged()}GetWidth(){return this._width}GetHeight(){return this._height}GetZoom(){return this._zoom}GetTextWidth(){this._UpdateTextMeasurements();return this._wrappedText.GetMaxLineWidth()}GetTextHeight(){this._UpdateTextMeasurements();return this._wrappedText.GetTotalLineHeight()+this._wrappedText.GetLineCount()*(this._lineHeight+EXTRA_LINE_HEIGHT)-
+this._lineHeight}GetLengthInGraphemes(){this._UpdateTextMeasurements();let ret=0;for(const line of this._wrappedText.GetLines())for(const frag of line.fragments())ret+=frag.GetLength();return ret}GetTexture(){this._textureTimeout.Reset();this._MaybeUpdate();return this._texture}HitTestFragment(x,y){this._UpdateTextMeasurements();const scale=this.GetDrawScale();const lines=this._wrappedText.GetLines();for(const line of lines){const yOff=line.GetFontBoundingBoxDescent()*scale;if(y>=line.GetPosY()-line.GetHeight()*
+scale+yOff&&y=frag.GetPosX()&&xa+v.GetHeight()*scale+lineSpaceHeight,0)-lineSpaceHeight;penY=Math.max(this._height/2-linesTotalHeight/2,0);
+if(useFontBoundingBoxMeasurements)firstLineTextHeight=lines[0].GetTopToAlphabeticDistance()*scale}else if(this._verticalAlign==="bottom"){const linesTotalHeight=lines.reduce((a,v)=>a+v.GetHeight()*scale+lineSpaceHeight,0)-this._lineHeight*scale;const lastLineDescentHeight=useFontBoundingBoxMeasurements?lines.at(-1).GetFontBoundingBoxDescent()*scale:0;penY=this._height-linesTotalHeight-lastLineDescentHeight-2}for(let i=0,len=lines.length;i0&&penY>this._height-EXTRA_LINE_HEIGHT*scale)break}else if(i>0&&penY>=this._height-curLineTextHeight)break;if(startPenY>=0)this._LayoutTextLine(line,penY,scale);if(!this._isBBcodeEnabled)penY+=curLineTextHeight;penY+=lineSpaceHeight}}_LayoutTextLine(line,penY,scale){let penX=0;if(this._horizontalAlign==="center")penX=(this._width-line.GetWidth()*scale)/2;else if(this._horizontalAlign==="right")penX=
+this._width-line.GetWidth()*scale;line.SetPosX(penX);line.SetPosY(penY);for(const frag of this._textDirection==="ltr"?line.fragments():line.fragmentsReverse()){this._LayoutFragment(frag,penX,penY,scale);penX+=frag.GetWidth()*scale}}_LayoutFragment(frag,penX,penY,scale){const offsetXStyle=frag.GetStyleTag("offsetx");penX+=offsetXStyle?getOffsetParam(offsetXStyle.param,frag.GetHeight())*scale:0;const offsetYStyle=frag.GetStyleTag("offsety");penY+=offsetYStyle?getOffsetParam(offsetYStyle.param,frag.GetHeight())*
+scale:0;if(frag.IsIcon()){const iconOffsetYStyle=frag.GetStyleTag("iconoffsety");penY+=iconOffsetYStyle?getOffsetParam(iconOffsetYStyle.param,frag.GetHeight())*scale:.2*frag.GetHeight()*scale}frag.SetPosX(penX);frag.SetPosY(penY)}_DrawTextToCanvas(){this._textContext.imageSmoothingEnabled=this._iconSmoothing;this._drawCharCount=0;const scale=this.GetDrawScale();const lines=this._wrappedText.GetLines();for(const line of lines)this._DrawTextLine(line,scale)}_DrawTextLine(line,scale){const penX=line.GetPosX();
+const penY=line.GetPosY();if(!Number.isFinite(penX)||!Number.isFinite(penY))return;for(const frag of this._textDirection==="ltr"?line.fragments():line.fragmentsReverse())this._DrawFragment(frag,scale,line.GetHeight())}_DrawFragment(frag,scale,lineHeight){const textContext=this._textContext;const penX=frag.GetPosX();const penY=frag.GetPosY();if(!Number.isFinite(penX)||!Number.isFinite(penY))return;const lineFontScale=lineHeight/16;let fragWidth=frag.GetWidth()*scale;const fragHeight=frag.GetHeight()*
+scale;const fragFontScale=frag.GetHeight()/16;const lineSpaceHeight=(EXTRA_LINE_HEIGHT+this._lineHeight)*scale;let chArr=frag.IsText()?frag.GetCharacterArray():null;if(this._drawMaxCharCount!==-1){if(this._drawCharCount>=this._drawMaxCharCount)return;if(frag.IsText())if(this._drawCharCount+chArr.length>this._drawMaxCharCount){chArr=chArr.slice(0,this._drawMaxCharCount-this._drawCharCount);fragWidth=this._MeasureText(frag).width*scale}this._drawCharCount+=frag.GetLength()}const backgroundStyle=frag.GetStyleTag("background");
+const hasUnderline=frag.HasStyleTag("u");const hasStrikethrough=frag.HasStyleTag("s");if(frag.IsText()&&C3.IsCharArrayAllWhitespace(chArr)&&!backgroundStyle&&!hasUnderline&&!hasStrikethrough||frag.HasStyleTag("hide"))return;if(backgroundStyle){this._SetDrawCanvasColor(backgroundStyle.param);textContext.fillRect(penX,penY-fragHeight,fragWidth,fragHeight+lineSpaceHeight)}const colorStyle=frag.GetStyleTag("color");const opacityStyle=frag.GetStyleTag("opacity");this._SetDrawCanvasOpacity(opacityStyle?
+parseFloat(opacityStyle.param)/100:1);const lineThicknessStyle=frag.GetStyleTag("linethickness");const lineThicknessScale=lineThicknessStyle?parseFloat(lineThicknessStyle.param):1;const isStroke=frag.HasStyleTag("stroke");if(isStroke)this._SetDrawCanvasLineWith(fragFontScale*.5*lineThicknessScale*this.GetDrawScale());if(frag.IsText()){const text=chArr.join("");this._SetDrawFontString(this._GetFontString(false,frag));if(!isStroke){this._SetDrawCanvasLineWith(fragFontScale*.5*lineThicknessScale*this.GetDrawScale());
+const outlineBackStyle=frag.GetStyleTag("outlineback");if(outlineBackStyle){this._SetDrawCanvasColor(outlineBackStyle.param);this._FillOrStrokeText(true,text,penX,penY,fragWidth)}}this._SetDrawCanvasColor(colorStyle?colorStyle.param:this._colorStr);this._FillOrStrokeText(isStroke,text,penX,penY,fragWidth);if(!isStroke){this._SetDrawCanvasLineWith(fragFontScale*.5*lineThicknessScale*this.GetDrawScale());const outlineStyle=frag.GetStyleTag("outline");if(outlineStyle){this._SetDrawCanvasColor(outlineStyle.param);
+this._FillOrStrokeText(true,text,penX,penY,fragWidth)}}}else if(frag.IsIcon())if(frag.GetWidth()>0){const drawable=frag.GetDrawable(this._iconSet);if(drawable)textContext.drawImage(drawable,penX,penY-fragHeight,fragWidth,fragHeight)}this._SetDrawCanvasColor(colorStyle?colorStyle.param:this._colorStr);if(hasUnderline)fillOrStrokeRect(textContext,isStroke,penX,penY+scale*lineFontScale,fragWidth,scale*lineFontScale*lineThicknessScale);if(hasStrikethrough){const defaultStrikeY=penY-fragHeight/4;const defaultStrikeHeight=
+scale*fragFontScale;const strikeYMid=defaultStrikeY+defaultStrikeHeight/2;textContext.fillRect(penX,strikeYMid-defaultStrikeHeight*lineThicknessScale/2,fragWidth,defaultStrikeHeight*lineThicknessScale)}}_FillOrStrokeText(isStroke,text,x,y,width){if(this._textDirection==="rtl")x+=width;if(isStroke)if(C3.Platform.BrowserEngine==="Gecko")this._textContext.strokeText(text,x,y,width);else this._textContext.strokeText(text,x,y);else if(C3.Platform.BrowserEngine==="Gecko")this._textContext.fillText(text,
+x,y,width);else this._textContext.fillText(text,x,y)}_UpdateTexture(){if(this._renderer.IsContextLost())return;if(!this._texture)this._texture=this._renderer.CreateDynamicTexture(this._textCanvas.width,this._textCanvas.height,{mipMap:true,mipMapQuality:"high"});this._renderer.UpdateTexture(this._textCanvas,this._texture);this._rcTex.set(0,0,this._width/this._texture.GetWidth(),this._height/this._texture.GetHeight());if(this.ontextureupdate)this.ontextureupdate()}GetTexRect(){return this._rcTex}ReleaseTexture(){if(this._texture){if(!this._renderer.IsContextLost())this._renderer.DeleteTexture(this._texture);
+this._texture=null}}static OnContextLost(){for(const rendererText of allRendererTexts)rendererText.ReleaseTexture()}static GetAll(){return allRendererTexts.values()}};
+
+}
+
+// ../lib/gfx/webgl/query.js
+{
+'use strict';const C3=self.C3;
+class WebGLRealTimeElapsedQuery{constructor(renderer){this._gl=renderer.GetContext();this._version=renderer.GetWebGLVersionNumber();this._timerExt=renderer._GetDisjointTimerQueryExtension();this._query=null;this._isActive=false;this._hasResult=false;this._result=0;if(this._version===1)this._query=this._timerExt["createQueryEXT"]();else this._query=this._gl["createQuery"]()}Release(){this._DeleteQueryObject();this._gl=null;this._timerExt=null;this._hasResult=false}_DeleteQueryObject(){if(!this._query)return;if(this._version===
+1)this._timerExt["deleteQueryEXT"](this._query);else this._gl["deleteQuery"](this._query);this._query=null}BeginTimeElapsed(){if(this._isActive)throw new Error("query already active");if(this._version===1)this._timerExt["beginQueryEXT"](this._timerExt["TIME_ELAPSED_EXT"],this._query);else this._gl["beginQuery"](this._timerExt["TIME_ELAPSED_EXT"],this._query);this._isActive=true}EndTimeElapsed(){if(!this._isActive)throw new Error("query not active");if(this._version===1)this._timerExt["endQueryEXT"](this._timerExt["TIME_ELAPSED_EXT"]);
+else this._gl["endQuery"](this._timerExt["TIME_ELAPSED_EXT"]);this._isActive=false}CheckForResult(){if(!this._query||this._hasResult||this._isActive)return;let available=false;if(this._version===1)available=this._timerExt["getQueryObjectEXT"](this._query,this._timerExt["QUERY_RESULT_AVAILABLE_EXT"]);else available=this._gl["getQueryParameter"](this._query,this._gl["QUERY_RESULT_AVAILABLE"]);const disjoint=this._gl.getParameter(this._timerExt["GPU_DISJOINT_EXT"]);if(available&&!disjoint){if(this._version===
+1)this._result=this._timerExt["getQueryObjectEXT"](this._query,this._timerExt["QUERY_RESULT_EXT"]);else this._result=this._gl["getQueryParameter"](this._query,this._gl["QUERY_RESULT"]);this._result/=1E9;this._hasResult=true}if(available||disjoint)this._DeleteQueryObject()}HasResult(){return this._hasResult}GetResult(){if(!this._hasResult)throw new Error("no result available");return this._result}}
+C3.Gfx.WebGLTimeElapsedQuery=class WebGLTimeElapsedQuery{constructor(renderer){this._renderer=renderer;this._frameNumber=renderer.GetFrameNumber();this._isActive=false;this._parentQuery=null;this._isNested=false;this._realQuery=null;this._queries=[]}Release(){for(const q of this._queries)if(q instanceof WebGLRealTimeElapsedQuery)q.Release();C3.clearArray(this._queries);this._parentQuery=null;this._realQuery=null;this._renderer=null}BeginTimeElapsed(){if(this._isActive)throw new Error("query already active");
+const stack=this._renderer._GetTimeQueryStack();if(stack.length>0){this._isNested=true;this._parentQuery=stack.at(-1);this._parentQuery._EndReal();this._parentQuery._queries.push(this)}else{this._isNested=false;this._parentQuery=null}this._isActive=true;stack.push(this);this._StartReal()}EndTimeElapsed(){if(!this._isActive)throw new Error("query not active");const top=this._renderer._GetTimeQueryStack().pop();if(top!==this)throw new Error("can only end most nested query");this._isActive=false;this._EndReal();
+if(this._parentQuery){this._parentQuery._StartReal();this._parentQuery=null}}_StartReal(){this._realQuery=C3.New(WebGLRealTimeElapsedQuery,this._renderer);this._queries.push(this._realQuery);this._realQuery.BeginTimeElapsed()}_EndReal(){this._realQuery.EndTimeElapsed();this._realQuery=null}CheckForResult(){for(const q of this._queries)q.CheckForResult()}IsNested(){return this._isNested}HasResult(){return this._queries.every(q=>q.HasResult())}GetResult(){return this._queries.reduce((a,v)=>a+v.GetResult(),
+0)}GetFrameNumber(){return this._frameNumber}};
+
+}
+
+// ../lib/gfx/webgl/queryResultBuffer.js
+{
+'use strict';const C3=self.C3;
+C3.Gfx.WebGLQueryResultBuffer=class WebGLQueryResultBuffer{constructor(renderer,maxQueries=1E3){this._renderer=renderer;this._maxQueries=maxQueries;this._buffer=[];this._renderer._AddQueryResultBuffer(this)}Release(){this.Clear();this._renderer._RemoveQueryResultBuffer(this);this._renderer=null}Clear(){for(const q of this._buffer)q.Release();C3.clearArray(this._buffer)}AddTimeElapsedQuery(){const ret=new C3.Gfx.WebGLTimeElapsedQuery(this._renderer);this._buffer.push(ret);if(this._buffer.length>this._maxQueries){const oldest=
+this._buffer.shift();oldest.Release()}return ret}CheckForResults(toFrameNumber){for(const q of this._buffer){if(q.GetFrameNumber()>=toFrameNumber)return;if(q.IsNested())return;q.CheckForResult()}}GetFrameRangeResultSum(startFrame,endFrame){if(endFrame<=startFrame)return NaN;let sum=0;for(const q of this._buffer){if(q.GetFrameNumber()>=endFrame)break;if(q.GetFrameNumber()0)this._buffer.splice(0,i);return}}}};
+
+}
+
+// ../lib/gfx/webgl/webglRenderer.js
+{
+'use strict';const C3=self.C3;const assert=self.assert;const glMatrix=self.glMatrix;const vec3=glMatrix.vec3;const vec4=glMatrix.vec4;const mat4=glMatrix.mat4;const DEFAULT_WEBGLRENDERER_OPTS={powerPreference:"default",enableGpuProfiling:true,alpha:false,lowLatency:false,depth:false,canSampleDepth:false,maxWebGLVersion:2,failIfMajorPerformanceCaveat:false};const VALID_POWER_PREFERENCES=new Set(["default","low-power","high-performance"]);const MAX_VERTICES=8E3;const MAX_INDICES=MAX_VERTICES/2*3;
+const MAX_POINTS=8E3;const LAST_POINT=MAX_POINTS-4;const PARTIAL_TEXTURE_UPLOAD_CHUNK_SIZE=256*1024;const defaultTexCoordsQuad=new C3.Quad(0,0,1,0,1,1,0,1);const tmpProjection=mat4.create();const tmpModelView=mat4.create();const tmpQuad=new C3.Quad;const tmpRect=new C3.Rect;let loseContextExtension=null;
+if(C3.isDebug){self.debug_lose_webgl_context=function(){if(!loseContextExtension){console.warn("WEBGL_lose_context not supported");return}loseContextExtension.loseContext()};self.debug_restore_webgl_context=function(){if(!loseContextExtension){console.warn("WEBGL_lose_context not supported");return}loseContextExtension.restoreContext()}}const pendingPolls=new Set;let pollRafId=-1;
+function CheckPendingPolls(){pollRafId=-1;for(const info of pendingPolls)if(info.checkFunc()){info.resolve();pendingPolls.delete(info)}if(pendingPolls.size>0)pollRafId=self.requestAnimationFrame(CheckPendingPolls)}
+C3.Gfx.WebGLRenderer=class WebGLRenderer extends C3.Gfx.RendererBase{constructor(canvas,opts){super(opts);opts=Object.assign({},DEFAULT_WEBGLRENDERER_OPTS,opts);if(!VALID_POWER_PREFERENCES.has(opts.powerPreference))throw new Error("invalid power preference");const attribs={"alpha":!!opts.alpha,"depth":false,"antialias":false,"powerPreference":opts.powerPreference,"failIfMajorPerformanceCaveat":!!opts.failIfMajorPerformanceCaveat};if(opts.lowLatency){attribs["desynchronized"]=true;attribs["preserveDrawingBuffer"]=
+true}let gl=null;let version=0;if(opts.maxWebGLVersion>=2){gl=canvas.getContext("webgl2",attribs);version=2}if(!gl){gl=canvas.getContext("webgl",attribs);version=1}if(!gl)throw new Error("renderer-unavailable (could not get WebGL context)");this._gl=gl;this._attribs=gl.getContextAttributes();if(opts.lowLatency&&!this._attribs["desynchronized"])console.info("[WebGLRenderer] Low-latency mode specified but is not supported here");this._versionString=gl.getParameter(gl.VERSION);this._version=version;
+this._viewport=vec4.create();this._didChangeTransform=false;this._bbProjectionMatrix=mat4.create();this._usesDepthBuffer=!!opts.depth;this._canSampleDepth=!!(opts.depth&&opts.canSampleDepth);this._isDepthEnabled=this._usesDepthBuffer;this._isDepthSamplingEnabled=false;this._depthBuffer=null;this._isAutoSizeDepthBuffer=true;this._depthBufferWidth=0;this._depthBufferHeight=0;this._vertexBuffer=null;this._texcoordBuffer=null;this._indexBuffer=null;this._pointBuffer=null;this._vertexData=new Float32Array(MAX_VERTICES*
+this.GetNumVertexComponents());this._indexData=new Uint16Array(MAX_INDICES);this._texcoordData=new Float32Array(MAX_VERTICES*2);this._pointData=new Float32Array(MAX_POINTS*4);this._vertexPtr=0;this._texPtr=0;this._pointPtr=0;this._lastVertexPtr=0;this._lastProgram=null;this._spDeviceTransformTextureFill=null;this._batch=[];this._batchPtr=0;this._topOfBatch=0;this._currentRenderTarget=null;this._lastPointZ=0;this._batchState=C3.New(C3.Gfx.BatchState,this);this._lastColor=C3.New(C3.Color,1,1,1,1);this._lastTexture0=
+null;this._lastTexture1=null;this._lastSrcBlend=0;this._lastDestBlend=0;this._lastPointTexCoords=new C3.Rect;this._lastScissorRect=C3.New(C3.Rect,0,0,-1,-1);this._coplanarMode=0;this._maxTextureSize=-1;this._minPointSize=0;this._maxPointSize=0;this._highpPrecision=0;this._unmaskedVendor="(unavailable)";this._unmaskedRenderer="(unavailable)";this._extensions=[];this._isInitialisingAfterContextRestored=false;this._parallelShaderCompileExt=null;this._anisotropicExt=null;this._depthTextureExt=null;this._fragDepthExt=
+null;this._stdDerivativesExt=null;this._textureLodExt=null;this._maxAnisotropy=0;this._isGpuProfilingEnabled=!!opts.enableGpuProfiling;this._timerExt=null;this._allQueryResultBuffers=new Set;this._timeQueryStack=[];this.FillIndexBufferData(this._indexData)}IsWebGL(){return true}async InitState(){super.InitState();const gl=this._gl;const numVertexComponents=this.GetNumVertexComponents();this._lastColor.setRgba(1,1,1,1);this._lastTexture0=null;this._lastTexture1=null;this._vertexPtr=0;this._pointPtr=
+0;this._lastVertexPtr=MAX_VERTICES*numVertexComponents-4*numVertexComponents;C3.clearArray(this._batch);this._batchPtr=0;this._topOfBatch=0;this._lastProgram=null;this._currentRenderTarget=null;this._lastPointTexCoords.set(0,0,1,1);this._lastPointZ=0;const batchState=this._batchState;batchState.currentShader=null;batchState.currentFramebuffer=null;batchState.currentFramebufferNoDepth=null;vec4.set(batchState.currentColor,1,1,1,1);batchState.clearColor.setRgba(0,0,0,0);batchState.pointTexCoords.set(0,
+0,1,1);gl.clearColor(0,0,0,0);gl.clear(gl.COLOR_BUFFER_BIT);gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);this._lastSrcBlend=gl.ONE;this._lastDestBlend=gl.ONE_MINUS_SRC_ALPHA;this._InitBlendModes(gl);gl.disable(gl.CULL_FACE);gl.disable(gl.STENCIL_TEST);gl.disable(gl.DITHER);if(this._usesDepthBuffer){gl.enable(gl.DEPTH_TEST);gl.depthMask(true);gl.depthFunc(gl.LEQUAL)}else{gl.disable(gl.DEPTH_TEST);gl.depthMask(false)}this._isDepthEnabled=this._usesDepthBuffer;this._isDepthSamplingEnabled=
+false;this._pointBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this._pointBuffer);gl.bufferData(gl.ARRAY_BUFFER,this._pointData.byteLength,gl.DYNAMIC_DRAW);this._vertexBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this._vertexBuffer);gl.bufferData(gl.ARRAY_BUFFER,this._vertexData.byteLength,gl.DYNAMIC_DRAW);this._texcoordBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this._texcoordBuffer);gl.bufferData(gl.ARRAY_BUFFER,this._texcoordData.byteLength,gl.DYNAMIC_DRAW);this._indexBuffer=
+gl.createBuffer();gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,this._indexBuffer);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,this._indexData,gl.STATIC_DRAW);gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,null);this._maxTextureSize=gl.getParameter(gl.MAX_TEXTURE_SIZE);const pointsizes=gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE);this._minPointSize=pointsizes[0];this._maxPointSize=pointsizes[1];const highpVertex=gl.getShaderPrecisionFormat(gl.VERTEX_SHADER,gl.HIGH_FLOAT);const highpFrag=gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER,
+gl.HIGH_FLOAT);if(highpVertex&&highpFrag)this._highpPrecision=Math.min(highpVertex["precision"],highpFrag["precision"]);else this._highpPrecision=0;if(this._maxPointSize>2048)this._maxPointSize=2048;this._extensions=gl.getSupportedExtensions();const debug_ext=gl.getExtension("WEBGL_debug_renderer_info");if(debug_ext){this._unmaskedVendor=gl.getParameter(debug_ext["UNMASKED_VENDOR_WEBGL"]);this._unmaskedRenderer=gl.getParameter(debug_ext["UNMASKED_RENDERER_WEBGL"])}this._parallelShaderCompileExt=gl.getExtension("KHR_parallel_shader_compile");
+if(C3.isDebug)loseContextExtension=gl.getExtension("WEBGL_lose_context");if(this._isGpuProfilingEnabled)if(this.GetWebGLVersionNumber()===1){if(C3.Platform.BrowserEngine!=="Chromium"||C3.Platform.BrowserVersionNumber>=81||typeof document!=="undefined")this._timerExt=gl.getExtension("EXT_disjoint_timer_query")}else this._timerExt=gl.getExtension("EXT_disjoint_timer_query_webgl2")||gl.getExtension("EXT_disjoint_timer_query");this._anisotropicExt=gl.getExtension("EXT_texture_filter_anisotropic");if(this._anisotropicExt)this._maxAnisotropy=
+gl.getParameter(this._anisotropicExt["MAX_TEXTURE_MAX_ANISOTROPY_EXT"]);else this._maxAnisotropy=0;if(this.GetWebGLVersionNumber()<2&&this._usesDepthBuffer&&this._canSampleDepth){this._depthTextureExt=gl.getExtension("WEBGL_depth_texture");if(!this._depthTextureExt)throw new Error("no depth texture support");}if(this.GetWebGLVersionNumber()<2){this._fragDepthExt=gl.getExtension("EXT_frag_depth");this._stdDerivativesExt=gl.getExtension("OES_standard_derivatives");this._textureLodExt=gl.getExtension("EXT_shader_texture_lod")}const WebGLShaderProgram=
+C3.Gfx.WebGLShaderProgram;const vsSource=WebGLShaderProgram.GetDefaultVertexShaderSource(false);let textureFillFragmentSrc=WebGLShaderProgram.GetTextureFillFragmentShaderSource_WebGL1_NoFragDepth();let textureFillVertexSrc=vsSource;let pointFragmentSrc=WebGLShaderProgram.GetPointFragmentShaderSource_WebGL1_NoFragDepth();let pointVertexSrc=WebGLShaderProgram.GetPointVertexShaderSource_WebGL1();let tilemapFragmentSrc=WebGLShaderProgram.GetTilemapFragmentShaderSource_WebGL1_NoFragDepth();let tilemapVertexSrc=
+WebGLShaderProgram.GetDefaultVertexShaderSource(true);let useFragDepthExt=false;if(this._usesDepthBuffer)if(this.GetWebGLVersionNumber()<2){if(this._fragDepthExt){textureFillFragmentSrc=WebGLShaderProgram.GetTextureFillFragmentShaderSource_WebGL1_FragDepthEXT();pointFragmentSrc=WebGLShaderProgram.GetPointFragmentShaderSource_WebGL1_FragDepthEXT();tilemapFragmentSrc=WebGLShaderProgram.GetTilemapFragmentShaderSource_WebGL1_FragDepthEXT();useFragDepthExt=true}}else{textureFillVertexSrc=WebGLShaderProgram.GetDefaultVertexShaderSource_WebGL2();
+textureFillFragmentSrc=WebGLShaderProgram.GetTextureFillFragmentShaderSource_WebGL2();pointFragmentSrc=WebGLShaderProgram.GetPointFragmentShaderSource_WebGL2();pointVertexSrc=WebGLShaderProgram.GetPointVertexShaderSource_WebGL2();tilemapFragmentSrc=WebGLShaderProgram.GetTilemapFragmentShaderSource_WebGL2();tilemapVertexSrc=WebGLShaderProgram.GetDefaultVertexShaderSource_WebGL2(true)}const tileRandomizationFragmentSrc=WebGLShaderProgram.GetTileRandomizationFragmentShaderSource(this.GetWebGLVersionNumber(),
+useFragDepthExt,this._stdDerivativesExt&&this._textureLodExt);const tileRandomizationVertexSrc=this.GetWebGLVersionNumber()>=2?WebGLShaderProgram.GetDefaultVertexShaderSource_WebGL2():vsSource;const DEFAULT_SHADER_PROGRAMS=[[textureFillFragmentSrc,textureFillVertexSrc,""],[textureFillFragmentSrc,textureFillVertexSrc,""],[pointFragmentSrc,pointVertexSrc,""],[WebGLShaderProgram.GetColorFillFragmentShaderSource(),vsSource,""],[WebGLShaderProgram.GetLinearGradientFillFragmentShaderSource(),
+vsSource,""],[WebGLShaderProgram.GetPenumbraFillFragmentShaderSource(),vsSource,""],[WebGLShaderProgram.GetHardEllipseFillFragmentShaderSource(),vsSource,""],[WebGLShaderProgram.GetHardEllipseOutlineFragmentShaderSource(),vsSource,""],[WebGLShaderProgram.GetSmoothEllipseFillFragmentShaderSource(),vsSource,""],[WebGLShaderProgram.GetSmoothEllipseOutlineFragmentShaderSource(),vsSource,""],[WebGLShaderProgram.GetSmoothLineFillFragmentShaderSource(),
+vsSource,""],[tilemapFragmentSrc,tilemapVertexSrc,""],[tileRandomizationFragmentSrc,tileRandomizationVertexSrc,""]];const defaultShaders=await Promise.all(DEFAULT_SHADER_PROGRAMS.map(i=>this.CreateShaderProgram({src:i[0],vertexSrc:i[1],name:i[2]})));this._spTextureFill=defaultShaders[0];this._spDeviceTransformTextureFill=defaultShaders[1];this._spPoints=defaultShaders[2];this._spColorFill=defaultShaders[3];this._spLinearGradientFill=defaultShaders[4];this._spPenumbraFill=
+defaultShaders[5];this._spHardEllipseFill=defaultShaders[6];this._spHardEllipseOutline=defaultShaders[7];this._spSmoothEllipseFill=defaultShaders[8];this._spSmoothEllipseOutline=defaultShaders[9];this._spSmoothLineFill=defaultShaders[10];this._spTilemapFill=defaultShaders[11];this._spTileRandomization=defaultShaders[12];this.SetTextureFillMode()}async CreateShaderProgram(shaderInfo){const ret=await C3.Gfx.WebGLShaderProgram.Create(this,shaderInfo);this._AddShaderProgram(ret);return ret}ResetLastProgram(){this._lastProgram=
+null}SetSize(w,h,force){if(this._width===w&&this._height===h&&!force)return;this.EndBatch();const gl=this._gl;const batchState=this._batchState;this._width=w;this._height=h;this._SetViewport(0,0,w,h);this.CalculatePerspectiveMatrix(this._bbProjectionMatrix,w/h);this.SetProjectionMatrix(this._bbProjectionMatrix);if(this._spDeviceTransformTextureFill){gl.useProgram(this._spDeviceTransformTextureFill.GetShaderProgram());this._spDeviceTransformTextureFill._UpdateDeviceTransformUniforms(this._matP);this._lastProgram=
+this._spDeviceTransformTextureFill;this._batchState.currentShader=this._spDeviceTransformTextureFill}gl.bindTexture(gl.TEXTURE_2D,null);gl.activeTexture(gl.TEXTURE1);gl.bindTexture(gl.TEXTURE_2D,null);gl.activeTexture(gl.TEXTURE0);this._lastTexture0=null;this._lastTexture1=null;if(this._usesDepthBuffer&&this._isAutoSizeDepthBuffer)this._SetDepthBufferSize(this._width,this._height);if(this._currentRenderTarget)this._currentRenderTarget._Resize(this._width,this._height);gl.bindFramebuffer(gl.FRAMEBUFFER,
+null);this._currentRenderTarget=null;batchState.currentFramebuffer=null;batchState.currentFramebufferNoDepth=null}_SetDepthBufferSize(width,height){const gl=this._gl;if(this._depthBuffer&&this._depthBufferWidth===width&&this._depthBufferHeight===height)return;if(this._canSampleDepth){if(this._depthBuffer)gl.deleteTexture(this._depthBuffer);this._depthBuffer=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,this._depthBuffer);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,
+gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);if(this.GetWebGLVersionNumber()>=2)gl.texImage2D(gl.TEXTURE_2D,0,gl.DEPTH24_STENCIL8,width,height,0,gl.DEPTH_STENCIL,gl.UNSIGNED_INT_24_8,null);else if(this._depthTextureExt)gl.texImage2D(gl.TEXTURE_2D,0,gl.DEPTH_STENCIL,width,height,0,gl.DEPTH_STENCIL,this._depthTextureExt["UNSIGNED_INT_24_8_WEBGL"],null);else;gl.bindTexture(gl.TEXTURE_2D,
+null)}else{if(this._depthBuffer)gl.deleteRenderbuffer(this._depthBuffer);this._depthBuffer=gl.createRenderbuffer();gl.bindRenderbuffer(gl.RENDERBUFFER,this._depthBuffer);gl.renderbufferStorage(gl.RENDERBUFFER,this._version>=2?gl.DEPTH24_STENCIL8:gl.DEPTH_STENCIL,width,height);gl.bindRenderbuffer(gl.RENDERBUFFER,null)}this._depthBufferWidth=width;this._depthBufferHeight=height}SetFixedSizeDepthBuffer(width,height){if(!this._usesDepthBuffer)return;this._isAutoSizeDepthBuffer=false;this._SetDepthBufferSize(width,
+height)}SetAutoSizeDepthBuffer(){if(!this._usesDepthBuffer)return;this._isAutoSizeDepthBuffer=true;this._SetDepthBufferSize(this._width,this._height)}_SetViewport(x,y,w,h){const viewport=this._viewport;if(viewport[0]===x&&viewport[1]===y&&viewport[2]===w&&viewport[3]===h)return;const b=this.PushBatch();b.InitSetViewport(x,y,w,h);vec4.set(viewport,x,y,w,h);this._topOfBatch=0}SetFovY(f){super.SetFovY(f);this.CalculatePerspectiveMatrix(this._bbProjectionMatrix,this._width/this._height)}SetNearZ(z){super.SetNearZ(z);
+this.CalculatePerspectiveMatrix(this._bbProjectionMatrix,this._width/this._height)}SetFarZ(z){super.SetFarZ(z);this.CalculatePerspectiveMatrix(this._bbProjectionMatrix,this._width/this._height)}SetProjectionMatrix(matP){if(mat4.exactEquals(this._matP,matP))return;const b=this.PushBatch();b.InitSetProjection(matP);mat4.copy(this._matP,matP);this._topOfBatch=0;this._didChangeTransform=true}SetDefaultRenderTargetProjectionState(){let projectionMatrix;let viewportWidth,viewportHeight;const currentRenderTarget=
+this._currentRenderTarget;if(currentRenderTarget===null){projectionMatrix=this._bbProjectionMatrix;viewportWidth=this.GetWidth();viewportHeight=this.GetHeight()}else{projectionMatrix=currentRenderTarget.GetProjectionMatrix();viewportWidth=currentRenderTarget.GetWidth();viewportHeight=currentRenderTarget.GetHeight()}this.SetProjectionMatrix(projectionMatrix);this._SetViewport(0,0,viewportWidth,viewportHeight)}SetModelViewMatrix(matMV){if(mat4.exactEquals(this._matMV,matMV))return;const b=this.PushBatch();
+b.InitSetModelView(matMV);mat4.copy(this._matMV,matMV);this._topOfBatch=0;this._didChangeTransform=true}ResetDidChangeTransformFlag(){this._didChangeTransform=false}DidChangeTransform(){return this._didChangeTransform}GetBatchState(){return this._batchState}PushBatch(){const batch=this._batch;if(this._batchPtr===batch.length)batch.push(new C3.Gfx.WebGLBatchJob(this._batchState));return batch[this._batchPtr++]}EndBatch(){if(this._batchPtr===0)return;if(this.IsContextLost())return;this._WriteBuffers();
+this._ExecuteBatch();this._batchPtr=0;this._vertexPtr=0;this._texPtr=0;this._pointPtr=0;this._topOfBatch=0}_WriteBuffers(){const gl=this._gl;if(this._pointPtr>0){gl.bindBuffer(gl.ARRAY_BUFFER,this._pointBuffer);gl.bufferSubData(gl.ARRAY_BUFFER,0,this._pointData.subarray(0,this._pointPtr))}if(this._vertexPtr>0){gl.bindBuffer(gl.ARRAY_BUFFER,this._vertexBuffer);gl.bufferSubData(gl.ARRAY_BUFFER,0,this._vertexData.subarray(0,this._vertexPtr));gl.bindBuffer(gl.ARRAY_BUFFER,this._texcoordBuffer);gl.bufferSubData(gl.ARRAY_BUFFER,
+0,this._texcoordData.subarray(0,this._texPtr))}}_ExecuteBatch(){const batch=this._batch;for(let i=0,len=this._batchPtr;i=this._lastVertexPtr){this.EndBatch();
+v=0}if(this._topOfBatch===1)this._batch[this._batchPtr-1]._indexCount+=6;else{const b=this.PushBatch();b.InitQuad(v,6);this._topOfBatch=1}}_WriteQuadToVertexBuffer(quad){quad.writeToTypedArray3D(this._vertexData,this._vertexPtr,this._baseZ+this._currentZ);this._vertexPtr+=12}Quad(quad){this._ExtendQuadBatch();this._WriteQuadToVertexBuffer(quad);defaultTexCoordsQuad.writeToTypedArray(this._texcoordData,this._texPtr);this._texPtr+=8}Quad2(tlx,tly,trx,try_,brx,bry,blx,bly){this._ExtendQuadBatch();const vd=
+this._vertexData;let v=this._vertexPtr;const z=this._baseZ+this._currentZ;vd[v++]=tlx;vd[v++]=tly;vd[v++]=z;vd[v++]=trx;vd[v++]=try_;vd[v++]=z;vd[v++]=brx;vd[v++]=bry;vd[v++]=z;vd[v++]=blx;vd[v++]=bly;vd[v++]=z;this._vertexPtr=v;defaultTexCoordsQuad.writeToTypedArray(this._texcoordData,this._texPtr);this._texPtr+=8}Quad3(quad,rcTex){this._ExtendQuadBatch();this._WriteQuadToVertexBuffer(quad);rcTex.writeAsQuadToTypedArray(this._texcoordData,this._texPtr);this._texPtr+=8}Quad4(quad,uv){this._ExtendQuadBatch();
+this._WriteQuadToVertexBuffer(quad);uv.writeToTypedArray(this._texcoordData,this._texPtr);this._texPtr+=8}Quad3D(tlx,tly,tlz,trx,try_,trz,brx,bry,brz,blx,bly,blz,rcTex){this._ExtendQuadBatch();const vd=this._vertexData;let v=this._vertexPtr;const z=this._baseZ+this._currentZ;vd[v++]=tlx;vd[v++]=tly;vd[v++]=z+tlz;vd[v++]=trx;vd[v++]=try_;vd[v++]=z+trz;vd[v++]=brx;vd[v++]=bry;vd[v++]=z+brz;vd[v++]=blx;vd[v++]=bly;vd[v++]=z+blz;this._vertexPtr=v;rcTex.writeAsQuadToTypedArray(this._texcoordData,this._texPtr);
+this._texPtr+=8}Quad3D2(tlx,tly,tlz,trx,try_,trz,brx,bry,brz,blx,bly,blz,uv){this._ExtendQuadBatch();const vd=this._vertexData;let v=this._vertexPtr;const z=this._baseZ+this._currentZ;vd[v++]=tlx;vd[v++]=tly;vd[v++]=z+tlz;vd[v++]=trx;vd[v++]=try_;vd[v++]=z+trz;vd[v++]=brx;vd[v++]=bry;vd[v++]=z+brz;vd[v++]=blx;vd[v++]=bly;vd[v++]=z+blz;this._vertexPtr=v;uv.writeToTypedArray(this._texcoordData,this._texPtr);this._texPtr+=8}FullscreenQuad(mode,curTex){this.SetCurrentZ(0);mat4.copy(tmpProjection,this._matP);
+mat4.copy(tmpModelView,this._matMV);this.SetDefaultRenderTargetProjectionState();const [width,height]=this.GetRenderTargetSize(this._currentRenderTarget);const tempMat4b=this.CalculateLookAtModelView2(0,0,this.GetDefaultCameraZ(height),0,0,0,height);this.SetModelViewMatrix(tempMat4b);if(mode==="crop"&&this._currentRenderTarget&&curTex){const left=this._width/2;const top=this._height/2;const srcW=curTex.GetWidth();const srcH=curTex.GetHeight();const destW=this._currentRenderTarget.GetWidth();const destH=
+this._currentRenderTarget.GetHeight();const copyW=Math.min(destW,srcW);const copyH=Math.min(destH,srcH);const srcOffY=Math.max(srcH-destH,0);const destOffY=Math.max(destH-srcH,0);tmpRect.set(-left,top-destOffY,-left+copyW,top-copyH-destOffY);tmpQuad.setFromRect(tmpRect);tmpRect.set(0,srcOffY,copyW,copyH+srcOffY);tmpRect.divide(srcW,srcH);this.Quad3(tmpQuad,tmpRect)}else{const halfW=width/2;const halfH=height/2;this.Rect2(-halfW,halfH,halfW,-halfH)}this.SetProjectionMatrix(tmpProjection);this.SetModelViewMatrix(tmpModelView)}StartRenderingPoints(rect){if(this._lastPointTexCoords.equals(rect))return;
+this._lastPointTexCoords.copy(rect);const b=this.PushBatch();b.InitSetPointTexCoords(rect);this._topOfBatch=0}FinishRenderingPoints(){}Point(x_,y_,size_,opacity_){if(this._pointPtr>=LAST_POINT)this.EndBatch();let p=this._pointPtr;const z=this._baseZ+this._currentZ;if(this._topOfBatch===2&&this._lastPointZ===z)this._batch[this._batchPtr-1]._indexCount++;else{const b=this.PushBatch();b.InitPoints(p,z);this._topOfBatch=2;this._lastPointZ=z}const pd=this._pointData;pd[p++]=x_;pd[p++]=y_;pd[p++]=size_;
+pd[p++]=opacity_;this._pointPtr=p}SetProgram(program){if(this._lastProgram===program)return;const b=this.PushBatch();b.InitSetProgram(program);this._lastProgram=program;this._topOfBatch=0;this._currentStateGroup=null}SetDeviceTransformTextureFillMode(){this.SetProgram(this._spDeviceTransformTextureFill)}SetGradientColor(c){const b=this.PushBatch();b.InitSetGradientColor(c);this._topOfBatch=0}SetEllipseParams(pixelW,pixelH,outlineThickness=1){const b=this.PushBatch();b.InitSetEllipseParams(pixelW,
+pixelH,outlineThickness);this._topOfBatch=0}SetTilemapInfo(srcRect,textureWidth,textureHeight,tileWidth,tileHeight,tileSpacingX,tileSpacingY){if(this._lastProgram!==this._spTilemapFill)throw new Error("must set tilemap fill mode first");const b=this.PushBatch();b.InitSetTilemapInfo(srcRect,textureWidth,textureHeight,tileWidth,tileHeight,tileSpacingX,tileSpacingY);this._topOfBatch=0}SetTileRandomizationInfo(textureWidth,textureHeight,xRandom,yRandom,angleRandom,blendMarginX,blendMarginY){if(this._lastProgram!==
+this._spTileRandomization)throw new Error("must set tile randomization mode first");const b=this.PushBatch();b.InitSetTileRandomizationInfo(textureWidth,textureHeight,xRandom,yRandom,angleRandom,blendMarginX,blendMarginY);this._topOfBatch=0}SetProgramParameters(backTex,destRect,srcRect,srcOriginRect,layoutRect,pixelWidth,pixelHeight,dpr,layerScale,layerAngle,time){const s=this._lastProgram;time=time%10800;if(!s._hasAnyOptionalUniforms||s.AreOptionalUniformsAlreadySetInBatch(destRect,srcRect,srcOriginRect,
+layoutRect,pixelWidth,pixelHeight,dpr,layerScale,layerAngle,time))return;const b=this.PushBatch();b.InitSetProgramParameters();s.SetOptionalUniformsInBatch(destRect,srcRect,srcOriginRect,layoutRect,pixelWidth,pixelHeight,dpr,layerScale,layerAngle,time);const mat4param=b._mat4param;mat4param[0]=pixelWidth;mat4param[1]=pixelHeight;destRect.writeToTypedArray(mat4param,2);mat4param[6]=layerScale;mat4param[7]=layerAngle;srcRect.writeToTypedArray(mat4param,12);const colorParam=b._colorParam;layoutRect.writeToTypedArray(colorParam,
+0);const tmp=colorParam[1];colorParam[1]=colorParam[3];colorParam[3]=tmp;srcOriginRect.writeToTypedArray(b._srcOriginRect,0);b._startIndex=time;b._indexCount=dpr;if(s._uSamplerBack.IsUsed())b._texParam=backTex?backTex.GetTexture():null;else b._texParam=null;this._topOfBatch=0}SetProgramCustomParameters(params){const s=this._lastProgram;if(params.length===0||s.AreCustomParametersAlreadySetInBatch(params))return;const b=this.PushBatch();b.InitSetProgramCustomParameters();s.SetCustomParametersInBatch(params);
+C3.shallowAssignArray(b._shaderParams,params);this._topOfBatch=0}ClearRgba(r,g,b_,a){const b=this.PushBatch();b.InitClearSurface2(r,g,b_,a);this._topOfBatch=0}Clear(c){const b=this.PushBatch();b.InitClearSurface(c);this._topOfBatch=0}Start(){}Finish(){super.Finish();this._gl.flush()}ClearDepth(){if(!this._usesDepthBuffer||!this._currentRenderTarget||!this._currentRenderTarget.HasDepthBuffer())return;const batch=this.PushBatch();batch.InitClearDepth(this._isDepthEnabled);this._topOfBatch=0}SetDepthEnabled(e){e=
+!!e;if(this._isDepthEnabled===e)return;if(!this._usesDepthBuffer)return;this._isDepthEnabled=e;const batch=this.PushBatch();batch.InitSetDepthEnabled(e);this._topOfBatch=0}IsDepthEnabled(){return this._isDepthEnabled}_GetDepthBuffer(){return this._depthBuffer}_CanSampleDepth(){return this._canSampleDepth}SetDepthSamplingEnabled(e){e=!!e;if(!this._canSampleDepth)return;if(this._isDepthSamplingEnabled===e)return;if(e&&this.IsDepthEnabled())throw new Error("depth still enabled");this._isDepthSamplingEnabled=
+e;const batch=this.PushBatch();batch.InitSetDepthSamplingEnabled(e);this._topOfBatch=0}SetScissorRect(x,y,w,h,rtHeight_=0){x=Math.floor(x);y=Math.floor(y);w=Math.floor(w);h=Math.floor(h);if(this._lastScissorRect.equalsWH(x,y,w,h))return;this._lastScissorRect.setWH(x,y,w,h);const rtHeight=rtHeight_||this.GetRenderTargetSize(this.GetRenderTarget())[1];y=rtHeight-y-h;const batch=this.PushBatch();batch.InitSetScissor(true,x,y,w,h);this._topOfBatch=0}RemoveScissorRect(){if(this._lastScissorRect.getRight()===
+-1)return;this._lastScissorRect.set(0,0,-1,-1);const batch=this.PushBatch();batch.InitSetScissor(false,0,0,0,0);this._topOfBatch=0}CheckForQueryResults(){for(const qrb of this._allQueryResultBuffers)qrb.CheckForResults(this._frameNumber)}IsContextLost(){return!this._gl||this._gl.isContextLost()||this._isInitialisingAfterContextRestored}OnContextLost(){super.OnDeviceOrContextLost();C3.Gfx.WebGLRendererTexture.OnContextLost();C3.Gfx.WebGLRenderTarget.OnContextLost();C3.Gfx.RendererText.OnContextLost();
+for(const qrb of this._allQueryResultBuffers)qrb.Clear();this._extensions=[];this._timerExt=null;this._parallelShaderCompileExt=null;this._anisotropicExt=null;this._depthTextureExt=null;this._fragDepthExt=null;this._stdDerivativesExt=null;this._textureLodExt=null;this._maxAnisotropy=0;this._unmaskedVendor="(unavailable)";this._unmaskedRenderer="(unavailable)";this._lastProgram=null;this._spDeviceTransformTextureFill=null;this._depthBuffer=null;for(const stateGroup of this._stateGroups.values())stateGroup.OnContextLost()}async OnContextRestored(){this._isInitialisingAfterContextRestored=
+true;await this.InitState();this._isInitialisingAfterContextRestored=false;for(const stateGroup of this._stateGroups.values())stateGroup.OnContextRestored(this);this.SetSize(this._width,this._height,true)}CreateStaticTexture(data,opts){if(this.IsContextLost())throw new Error("context lost");this.EndBatch();const rendererTex=C3.New(C3.Gfx.WebGLRendererTexture,this);rendererTex._CreateStatic(data,opts);return rendererTex}async CreateStaticTextureAsync(data,opts){if(this.IsContextLost())throw new Error("context lost");
+opts=Object.assign({},opts);if(C3.Supports.ImageBitmapOptions){let imageBitmap=await createImageBitmap(data,{"premultiplyAlpha":"premultiply"});const isTiled=opts.wrapX&&opts.wrapX!=="clamp-to-edge"||opts.wrapY&&opts.wrapY!=="clamp-to-edge";const isPOT=C3.isPOT(imageBitmap.width)&&C3.isPOT(imageBitmap.height);if(!this.SupportsNPOTTextures()&&!isPOT&&isTiled)if(C3.Supports.ImageBitmapOptionsResize){imageBitmap=await createImageBitmap(data,{"premultiplyAlpha":"premultiply","resizeWidth":C3.nextHighestPowerOfTwo(imageBitmap.width),
+"resizeHeight":C3.nextHighestPowerOfTwo(imageBitmap.height)});opts.premultiplyAlpha=false}else imageBitmap=await createImageBitmap(data,{"premultiplyAlpha":"none"});else opts.premultiplyAlpha=false;return await C3.Asyncify(()=>this.CreateStaticTexture(imageBitmap,opts))}else{if(data instanceof Blob){if(typeof Image==="undefined")throw new Error("texture upload variant not supported in worker");const img=await C3.BlobToImage(data);data=img}return await C3.Asyncify(()=>this.CreateStaticTexture(data,
+opts))}}CreateDynamicTexture(width,height,opts){this.EndBatch();const rendererTex=C3.New(C3.Gfx.WebGLRendererTexture,this);rendererTex._CreateDynamic(width,height,opts);return rendererTex}UpdateTexture(data,rendererTex,opts){this.EndBatch();rendererTex._Update(data,opts)}DeleteTexture(rendererTex){if(!rendererTex)return;rendererTex.SubtractReference();if(rendererTex.GetReferenceCount()>0)return;this.EndBatch();if(rendererTex===this._lastTexture0){this._gl.bindTexture(this._gl.TEXTURE_2D,null);this._lastTexture0=
+null}if(rendererTex===this._lastTexture1){this._gl.activeTexture(this._gl.TEXTURE1);this._gl.bindTexture(this._gl.TEXTURE_2D,null);this._gl.activeTexture(this._gl.TEXTURE0);this._lastTexture1=null}rendererTex._Delete()}CreateRenderTarget(opts){let width=this._width;let height=this._height;let isDefaultSize=true;if(opts){if(typeof opts.width==="number"){width=Math.floor(opts.width);isDefaultSize=false}if(typeof opts.height==="number"){height=Math.floor(opts.height);isDefaultSize=false}}if(width<=0||
+height<=0)throw new Error("invalid size");this.EndBatch();const renderTarget=C3.New(C3.Gfx.WebGLRenderTarget,this);renderTarget._Create(width,height,Object.assign({isDefaultSize},opts));this._currentRenderTarget=null;this._batchState.currentFramebuffer=null;this._batchState.currentFramebufferNoDepth=null;return renderTarget}SetRenderTarget(renderTarget,updateProjection=true){if(renderTarget===this._currentRenderTarget)return;if(renderTarget&&renderTarget.IsDefaultSize())renderTarget._Resize(this._width,
+this._height);const b=this.PushBatch();b.InitSetRenderTarget(renderTarget);this._currentRenderTarget=renderTarget;this._topOfBatch=0;if(updateProjection)this.SetDefaultRenderTargetProjectionState()}GetRenderTarget(){return this._currentRenderTarget}GetRenderTargetSize(renderTarget){if(renderTarget)return[renderTarget.GetWidth(),renderTarget.GetHeight()];else return[this._width,this._height]}CopyRenderTarget(renderTarget,mode="stretch"){if(this._version<2||this._currentRenderTarget&&this._currentRenderTarget.GetMultisampling()>
+0){this.SetCopyBlend();this.ResetColor();this.DrawRenderTarget(renderTarget,mode)}else{const b=this.PushBatch();b.InitBlitFramebuffer(renderTarget,this._currentRenderTarget,mode);this._topOfBatch=0}}DrawRenderTarget(renderTarget,mode="stretch"){const tex=renderTarget.GetTexture();if(!tex)throw new Error("not a texture-backed render target");this.SetTexture(tex);this.FullscreenQuad(mode,tex)}InvalidateRenderTarget(renderTarget){if(this._version<2)return;const b=this.PushBatch();b.InitInvalidateFramebuffer(renderTarget._GetFramebuffer());
+this._topOfBatch=0}DeleteRenderTarget(renderTarget){this.SetRenderTarget(null);this.EndBatch();const renderTex=renderTarget.GetTexture();if(renderTex===this._lastTexture0){this._gl.bindTexture(this._gl.TEXTURE_2D,null);this._lastTexture0=null}if(renderTex===this._lastTexture1){this._gl.activeTexture(this._gl.TEXTURE1);this._gl.bindTexture(this._gl.TEXTURE_2D,null);this._gl.activeTexture(this._gl.TEXTURE0);this._lastTexture1=null}renderTarget._Delete()}async ReadBackRenderTargetToImageData(renderTarget,
+forceSynchronous,areaRect){this.EndBatch();const oldRenderTarget=this._currentRenderTarget;let width,height,framebuffer;if(renderTarget){width=renderTarget.GetWidth();height=renderTarget.GetHeight();framebuffer=renderTarget._GetFramebuffer()}else{width=this.GetWidth();height=this.GetHeight();framebuffer=null}let x=0;let y=0;let areaWidth=width;let areaHeight=height;if(areaRect){x=C3.clamp(Math.floor(areaRect.getLeft()),0,width-1);y=C3.clamp(Math.floor(areaRect.getTop()),0,height-1);let w=areaRect.width();
+if(w===0)w=width-x;else w=C3.clamp(Math.floor(w),0,width-x);let h=areaRect.height();if(h===0)h=height-y;else h=C3.clamp(Math.floor(h),0,height-y);areaWidth=w;areaHeight=h;y=height-(y+areaHeight)}const gl=this._gl;gl.bindFramebuffer(gl.FRAMEBUFFER,framebuffer);const restorePreviousRenderTarget=()=>{gl.bindFramebuffer(gl.FRAMEBUFFER,null);this._currentRenderTarget=null;this._batchState.currentFramebuffer=null;this._batchState.currentFramebufferNoDepth=null;this.SetRenderTarget(oldRenderTarget)};let imageData;
+if(!forceSynchronous&&this.GetWebGLVersionNumber()>=2){gl.bindFramebuffer(gl.READ_FRAMEBUFFER,framebuffer);const pixelBuffer=gl.createBuffer();const bufferSize=areaWidth*areaHeight*4;const PIXEL_PACK_BUFFER=gl["PIXEL_PACK_BUFFER"];gl.bindBuffer(PIXEL_PACK_BUFFER,pixelBuffer);gl.bufferData(PIXEL_PACK_BUFFER,bufferSize,gl["STREAM_READ"]);gl.readPixels(x,y,areaWidth,areaHeight,gl.RGBA,gl.UNSIGNED_BYTE,0);gl.bindFramebuffer(gl.READ_FRAMEBUFFER,null);gl.bindBuffer(PIXEL_PACK_BUFFER,null);restorePreviousRenderTarget();
+const sync=gl["fenceSync"](gl["SYNC_GPU_COMMANDS_COMPLETE"],0);await this._WaitForObjectReady(()=>gl["getSyncParameter"](sync,gl["SYNC_STATUS"])===gl["SIGNALED"]);gl["deleteSync"](sync);imageData=new ImageData(areaWidth,areaHeight);gl.bindBuffer(PIXEL_PACK_BUFFER,pixelBuffer);gl["getBufferSubData"](PIXEL_PACK_BUFFER,0,new Uint8Array(imageData.data.buffer),0,bufferSize);gl.bindBuffer(PIXEL_PACK_BUFFER,null);gl.deleteBuffer(pixelBuffer)}else{imageData=new ImageData(areaWidth,areaHeight);gl.readPixels(x,
+y,areaWidth,areaHeight,gl.RGBA,gl.UNSIGNED_BYTE,new Uint8Array(imageData.data.buffer));restorePreviousRenderTarget()}return imageData}CoplanarStartStencilPass(){this.SetDepthEnabled(true);const batch=this.PushBatch();batch.InitCoplanarStartStencilPass();this._topOfBatch=0;this._coplanarMode=1}CoplanarStartColorPass(){this.SetDepthEnabled(false);const batch=this.PushBatch();batch.InitCoplanarStartColorPass();this._topOfBatch=0;this._coplanarMode=2}IsCoplanarColorPass(){return this._coplanarMode===
+2}CoplanarRestoreStandardRendering(){this.SetDepthEnabled(true);const batch=this.PushBatch();batch.InitCoplanarRestore();this._topOfBatch=0;this._coplanarMode=0}StartQuery(query){if(!this.SupportsGPUProfiling())return;const b=this.PushBatch();b.InitStartQuery(query);this._topOfBatch=0}EndQuery(query){if(!this.SupportsGPUProfiling())return;const b=this.PushBatch();b.InitEndQuery(query);this._topOfBatch=0}_WaitForObjectReady(checkFunc){const ret=new Promise(resolve=>pendingPolls.add({resolve,checkFunc}));
+if(pollRafId===-1)pollRafId=self.requestAnimationFrame(CheckPendingPolls);return ret}IsDesynchronized(){return!!this._attribs["desynchronized"]}GetEstimatedBackBufferMemoryUsage(){return this._width*this._height*(this._attribs["alpha"]?4:3)}GetEstimatedRenderBufferMemoryUsage(){let ret=0;for(const t of C3.Gfx.WebGLRenderTarget.allRenderTargets()){if(t.GetTexture())continue;ret+=t.GetEstimatedMemoryUsage()}return ret}GetEstimatedTextureMemoryUsage(){let ret=0;for(const t of C3.Gfx.WebGLRendererTexture.allTextures())ret+=
+t.GetEstimatedMemoryUsage();return ret}GetWebGLVersionString(){return this._versionString}GetWebGLVersionNumber(){return this._version}GetDisplayName(){return"webgl"+this.GetWebGLVersionNumber()}SupportsNPOTTextures(){return this.GetWebGLVersionNumber()>=2}GetMaxTextureSize(){return this._maxTextureSize}GetMinPointSize(){return this._minPointSize}GetMaxPointSize(){return this._maxPointSize}SupportsHighP(){return this._highpPrecision!==0}GetHighPPrecision(){return this._highpPrecision}GetUnmaskedVendor(){return this._unmaskedVendor}GetUnmaskedRenderer(){return this._unmaskedRenderer}GetWebGLExtensionsAnalyticsString(){if(this.GetWebGLVersionNumber()>=
+2)return"webgl2";else{const exts=[];if(this._fragDepthExt)exts.push("EXT_frag_depth");if(this._stdDerivativesExt)exts.push("OES_standard_derivatives");if(this._textureLodExt)exts.push("EXT_shader_texture_lod");if(exts.length>0)return"webgl1:"+exts.join(",");else return"webgl1:none"}}GetExtensions(){return this._extensions}SupportsGPUProfiling(){return!!this._timerExt}_GetDisjointTimerQueryExtension(){return this._timerExt}_GetParallelShaderCompileExtension(){return this._parallelShaderCompileExt}_GetAnisotropicExtension(){return this._anisotropicExt}_GetMaxAnisotropy(){return this._maxAnisotropy}_AddQueryResultBuffer(qrb){this._allQueryResultBuffers.add(qrb)}_RemoveQueryResultBuffer(qrb){this._allQueryResultBuffers.delete(qrb)}_GetTimeQueryStack(){return this._timeQueryStack}GetContext(){return this._gl}_InitBlendModes(gl){this._InitBlendModeData([["normal",
+gl.ONE,gl.ONE_MINUS_SRC_ALPHA],["additive",gl.ONE,gl.ONE],["xor",gl.ONE,gl.ONE_MINUS_SRC_ALPHA],["copy",gl.ONE,gl.ZERO],["destination-over",gl.ONE_MINUS_DST_ALPHA,gl.ONE],["source-in",gl.DST_ALPHA,gl.ZERO],["destination-in",gl.ZERO,gl.SRC_ALPHA],["source-out",gl.ONE_MINUS_DST_ALPHA,gl.ZERO],["destination-out",gl.ZERO,gl.ONE_MINUS_SRC_ALPHA],["source-atop",gl.DST_ALPHA,gl.ONE_MINUS_SRC_ALPHA],["destination-atop",gl.ONE_MINUS_DST_ALPHA,gl.SRC_ALPHA]])}CreateRendererText(){return C3.New(C3.Gfx.RendererText,
+this)}CreateWebGLText(){return this.CreateRendererText()}};
+
+}
+
+// ../lib/gfx/effectCompositor/effectChainManager.js
+{
+'use strict';const C3=self.C3;const DEFAULT_CTOR_OPTS={getDrawSize:null,getRenderTarget:null,releaseRenderTarget:null,getTime:null,redraw:null};
+C3.Gfx.EffectChainManager=class EffectChainManager{constructor(opts){opts=Object.assign({},DEFAULT_CTOR_OPTS,opts);this._cbGetDrawSize=opts.getDrawSize;this._cbGetRenderTarget=opts.getRenderTarget;this._cbReleaseRenderTarget=opts.releaseRenderTarget;this._cbGetTime=opts.getTime;this._cbRedraw=opts.redraw;this._webgpuBackTexture=null;this._allEffectChains=new Set}_AddEffectChain(ec){this._allEffectChains.add(ec)}_RemoveEffectChain(ec){this._allEffectChains.delete(ec)}OnContextLost(){this._webgpuBackTexture=
+null;for(const ec of this._allEffectChains)ec.OnContextLost()}GetDrawSize(renderer){if(this._cbGetDrawSize)return this._cbGetDrawSize(renderer);else return[renderer.GetWidth(),renderer.GetHeight()]}GetRenderTarget(effectChain){return this._cbGetRenderTarget(effectChain)}ReleaseRenderTarget(rt,effectChain){this._cbReleaseRenderTarget(rt,effectChain)}GetTime(){return this._cbGetTime()}Redraw(effectChain){this._cbRedraw(effectChain)}_GetWebGPUBackTexture(renderer,width,height){width=Math.floor(width);
+height=Math.floor(height);if(this._webgpuBackTexture&&(this._webgpuBackTexture.GetWidth()!==width||this._webgpuBackTexture.GetHeight()!==height)){renderer.DeleteTexture(this._webgpuBackTexture);this._webgpuBackTexture=null}if(this._webgpuBackTexture===null)this._webgpuBackTexture=renderer.CreateStaticTexture(null,{width,height,sampling:"nearest",mipMap:false});return this._webgpuBackTexture}};
+
+}
+
+// ../lib/gfx/effectCompositor/effectChain.js
+{
+'use strict';const C3=self.C3;const assert=self.assert;const glMatrix=self.glMatrix;const mat4=glMatrix.mat4;const tempRect=C3.New(C3.Rect);const tempRect2=C3.New(C3.Rect);const tempRect3=C3.New(C3.Rect);const tempRect4=C3.New(C3.Rect);const tempMat4a=mat4.create();const tempMat4b=mat4.create();const DEFAULT_CTOR_OPTS={drawContent:null,getSourceTextureInfo:null,getShaderParameters:null,invalidateRenderTargets:false};
+const DEFAULT_BUILDSTEPS_OPTS={indexMap:null,forcePreDraw:false,forcePostDraw:false,is3D:false,isSourceTextureRotated:false,isRotatedOrNegativeSizeInstance:false,useFullSurface:false};
+C3.Gfx.EffectChain=class EffectChain{constructor(manager,opts){opts=Object.assign({},DEFAULT_CTOR_OPTS,opts);this._manager=manager;this._cbDrawContent=opts.drawContent;this._cbGetSourceTextureInfo=opts.getSourceTextureInfo;this._cbGetShaderParameters=opts.getShaderParameters;this._cbDrawContentHook=null;this._shaderProgramList=[];this._shaderProgramIndices=[];this._steps=[];this._needsRebuild=false;this._blendMode=0;this._isAnyShaderAnimated=false;this._isAnyShaderDepthSampling=false;this._isAnyShaderBackgroundBlending=
+false;this._isAnyShaderCrossSampling=false;this._isAnyIsSrcTexRotated=false;this._useCopyTextureBackgroundSampling=false;this._didChangeTransform=false;this._depthEnabledAtStart=false;this._coplanarColorPassAtStart=false;this._canUseFastPath=false;this._useFullSurface=false;this._isSourceTextureRotated=false;this._numTempSurfacesRequired=0;this._renderTargets=[null,null,null];this._invalidateRenderTargets=!!opts.invalidateRenderTargets;this._boxExtendHorizontal=0;this._boxExtendVertical=0;this._drawWidth=
+0;this._drawHeight=0;this._contentObject=null;this._contextObject=null;this._layoutRect=C3.New(C3.Rect);this._drawSurfaceRect=C3.New(C3.Rect);this._rcTexOriginal=C3.New(C3.Rect);this._rcTexBounce=C3.New(C3.Rect);this._rcTexDest=C3.New(C3.Rect);this._devicePixelRatio=1;this._layerScale=1;this._layerAngle=0;this._time=0;this._destRenderTarget=null;this._backTex=null;this._compositOffX=0;this._compositOffY=0;this._updateOwnProjection=false;this._projectionMatrix=mat4.create();this._modelViewMatrix=mat4.create();
+this._manager._AddEffectChain(this)}Release(){this._manager._RemoveEffectChain(this);C3.clearArray(this._steps);C3.clearArray(this._shaderProgramList);C3.clearArray(this._shaderProgramIndices);this._contentObject=null;this._contextObject=null;this._cbDrawContent=null;this._cbGetSourceTextureInfo=null;this._cbGetShaderParameters=null}OnContextLost(){this._needsRebuild=true;C3.clearArray(this._steps);C3.clearArray(this._shaderProgramList);C3.clearArray(this._shaderProgramIndices)}NeedsRebuild(){return this._needsRebuild}BuildSteps(shaderProgramList,
+opts){opts=Object.assign({},DEFAULT_BUILDSTEPS_OPTS,opts);C3.clearArray(this._steps);this._boxExtendHorizontal=0;this._boxExtendVertical=0;this._isAnyShaderAnimated=false;this._isAnyShaderDepthSampling=false;this._isAnyShaderBackgroundBlending=false;this._isAnyShaderCrossSampling=false;this._isAnyIsSrcTexRotated=false;this._useCopyTextureBackgroundSampling=false;this._numTempSurfacesRequired=0;this._isSourceTextureRotated=!!opts.isSourceTextureRotated;this._useFullSurface=!!opts.useFullSurface;this._needsRebuild=
+false;C3.shallowAssignArray(this._shaderProgramList,shaderProgramList);if(shaderProgramList.length===0)return;if(opts.indexMap){if(opts.indexMap.length!==shaderProgramList.length)throw new Error("incorrect indexMap length");C3.shallowAssignArray(this._shaderProgramIndices,opts.indexMap)}else{C3.clearArray(this._shaderProgramIndices);for(let i=0,len=shaderProgramList.length;i=1?this._GetRenderTarget():null;this._renderTargets[2]=this._numTempSurfacesRequired===
+2?this._GetRenderTarget():null;for(const step of this._steps){const srcTarget=this._GetRenderTargetForId(step.GetSrcTargetId());const destTarget=this._GetRenderTargetForId(step.GetDestTargetId());if(renderer.IsWebGPU())step.Run_WebGPU(renderer,srcTarget,destTarget);else step.Run_WebGL(renderer,srcTarget,destTarget)}if(this._renderTargets[1])this._ReleaseRenderTarget(this._renderTargets[1]);if(this._renderTargets[2])this._ReleaseRenderTarget(this._renderTargets[2]);this._renderTargets.fill(null);this._OnAfterEndEffectChain(renderer);
+this._destRenderTarget=null;this._backTex=null;this._contentObject=null;this._contextObject=null;this._cbDrawContentHook=null}_CalculateDrawSizeAndRectangles(renderer,opts){const [drawWidth,drawHeight]=this._manager.GetDrawSize(renderer);this._SetDrawSize(renderer,drawWidth,drawHeight);this._CalculateRectangles(opts)}_SetDrawSize(renderer,drawWidth,drawHeight){if(drawWidth<=0||drawHeight<=0)throw new Error("invalid draw size");if(this._drawWidth!==drawWidth||this._drawHeight!==drawHeight)this._CalculateDeviceTransformMatrices(renderer,
+drawWidth,drawHeight,0,0,this._projectionMatrix,this._modelViewMatrix);this._drawWidth=drawWidth;this._drawHeight=drawHeight}_CalculateDeviceTransformMatrices(renderer,width,height,offX,offY,projMat,mvMat){const scrollX=width/2+offX;const scrollY=height/2+offY;renderer.CalculatePerspectiveMatrix(projMat,width/height);const tempMat4=renderer.CalculateLookAtModelView2(scrollX,scrollY,renderer.GetDefaultCameraZ(height),scrollX,scrollY,0,height);mat4.copy(mvMat,tempMat4)}_CalculateRectangles(opts){this._layoutRect.copy(opts.layoutRect);
+if(opts.drawSurfaceRect)this._drawSurfaceRect.copy(opts.drawSurfaceRect);else this._drawSurfaceRect.set(0,0,this._drawWidth,this._drawHeight);this._rcTexOriginal.copy(this._drawSurfaceRect);this._rcTexOriginal.divide(this._drawWidth,this._drawHeight);const boxScale=this._layerScale*this._devicePixelRatio;this._drawSurfaceRect.inflate(this._boxExtendHorizontal*boxScale,this._boxExtendVertical*boxScale);this._rcTexDest.copy(this._drawSurfaceRect);this._rcTexDest.divide(this._drawWidth,this._drawHeight);
+this._drawSurfaceRect.clampBoth(0,0,this._drawWidth,this._drawHeight);this._rcTexBounce.copy(this._drawSurfaceRect);this._rcTexBounce.divide(this._drawWidth,this._drawHeight)}_OnBeforeStartEffectChain(renderer){this._depthEnabledAtStart=renderer.IsDepthEnabled();this._coplanarColorPassAtStart=renderer.IsCoplanarColorPass();if(this._useFullSurface){renderer.SetDepthEnabled(false);if(this._isAnyShaderDepthSampling)renderer.SetDepthSamplingEnabled(true)}else{tempRect.copy(this._drawSurfaceRect);if(renderer.IsWebGL()){const boxScale=
+this._layerScale*this._devicePixelRatio;tempRect.inflate(Math.max(this._boxExtendHorizontal,1)*boxScale,Math.max(this._boxExtendVertical,1)*boxScale);tempRect.roundOuter();tempRect.clamp(0,0,this._drawWidth,this._drawHeight)}else tempRect.roundOuter();renderer.SetScissorRect(tempRect.getLeft(),tempRect.getTop(),tempRect.width(),tempRect.height(),this._drawHeight)}}_OnAfterEffectChainDrawContent(renderer){renderer.ResetColor();if(!this._useFullSurface){if(this._coplanarColorPassAtStart)renderer.CoplanarRestoreStandardRendering();
+renderer.SetDepthEnabled(false);if(this._isAnyShaderDepthSampling)renderer.SetDepthSamplingEnabled(true)}if(renderer.IsWebGPU())renderer.SetNormalizedCoordsProgramVariant(true)}_OnAfterEndEffectChain(renderer){renderer.SetDepthSamplingEnabled(false);if(this._coplanarColorPassAtStart)renderer.CoplanarStartColorPass();renderer.SetDepthEnabled(this._depthEnabledAtStart);if(!this._useFullSurface)renderer.RemoveScissorRect();if(renderer.IsWebGPU())renderer.SetNormalizedCoordsProgramVariant(false);this._didChangeTransform=
+renderer.DidChangeTransform()}_ClampRcTexDest(){this._rcTexDest.clamp(0,0,1,1)}_GetRenderTargetForId(id){return id<0?null:this._renderTargets[id]}_GetRenderTarget(){return this._manager.GetRenderTarget(this)}_GetDestRenderTarget(){return this._destRenderTarget}_ReleaseRenderTarget(rt){this._manager.ReleaseRenderTarget(rt,this)}_GetShaderProgramAt(i){return this._shaderProgramList[i]}_DrawContent(renderer){if(this._cbDrawContentHook)this._cbDrawContentHook(this,renderer,()=>this._cbDrawContent(renderer,
+this));else this._cbDrawContent(renderer,this);if(!this._canUseFastPath)this._OnAfterEffectChainDrawContent(renderer)}_IsRenderTargetSameSizeAndOffset(renderer){if(this._useFullSurface)return true;if(this._compositOffX!==0||this._compositOffY!==0)return false;const [rtWidth,rtHeight]=renderer.GetRenderTargetSize(renderer.GetRenderTarget());if(rtWidth!==this._drawWidth||rtHeight!==this._drawHeight)return false;return true}_SetDeviceTransform(renderer,isLast){let projMat=this._projectionMatrix;let mvMat=
+this._modelViewMatrix;if(isLast&&!this._IsRenderTargetSameSizeAndOffset(renderer)){projMat=tempMat4a;mvMat=tempMat4b;const [rtWidth,rtHeight]=renderer.GetRenderTargetSize(renderer.GetRenderTarget());this._CalculateDeviceTransformMatrices(renderer,rtWidth,rtHeight,this._compositOffX,this._compositOffY,projMat,mvMat);if(!this._useFullSurface)renderer.RemoveScissorRect()}renderer.SetProjectionMatrix(projMat);renderer.SetModelViewMatrix(mvMat)}_Redraw(){this._manager.Redraw(this)}_GetShaderParameters(index,
+renderer){return this._cbGetShaderParameters(this._shaderProgramIndices[index],renderer)}_SetProgramParameters(renderer,index){let rcTexDest=this._rcTexDest;let srcRect=this._rcTexBounce;let srcOriginRect=this._rcTexOriginal;if(renderer.IsWebGL()){tempRect2.copy(rcTexDest);tempRect2.flipAround(1);rcTexDest=tempRect2;tempRect3.copy(srcRect);tempRect3.flipAround(1);srcRect=tempRect3;tempRect4.copy(srcOriginRect);tempRect4.flipAround(1);srcOriginRect=tempRect4}this._DoSetProgramParameters(renderer,index,
+srcRect,srcOriginRect,rcTexDest,1/this._drawWidth,1/this._drawHeight)}_SetFirstBounceProgramParameters(renderer,index){let srcRect=this._rcTexBounce;let srcOriginRect=this._rcTexOriginal;let pixelWidth=1/this._drawWidth;let pixelHeight=1/this._drawHeight;if(this._cbGetSourceTextureInfo){let {srcTexRect,srcWidth,srcHeight}=this._cbGetSourceTextureInfo(this._contentObject);if(!srcTexRect){tempRect.set(0,0,0,0);srcTexRect=tempRect}if(!srcWidth)srcWidth=this._drawWidth;if(!srcHeight)srcHeight=this._drawHeight;
+srcRect=srcTexRect;srcOriginRect=srcTexRect;pixelWidth=1/srcWidth;pixelHeight=1/srcHeight}else if(renderer.IsWebGL()){tempRect3.copy(srcRect);tempRect3.flipAround(1);srcRect=tempRect3;tempRect4.copy(srcOriginRect);tempRect4.flipAround(1);srcOriginRect=tempRect4}let rcTexDest=this._rcTexDest;if(renderer.IsWebGL()){rcTexDest=tempRect2;rcTexDest.copy(this._rcTexDest);rcTexDest.flipAround(1)}this._DoSetProgramParameters(renderer,index,srcRect,srcOriginRect,rcTexDest,pixelWidth,pixelHeight);if(renderer.IsWebGPU()&&
+this._isAnyIsSrcTexRotated)renderer.SetProgramParameter_IsSrcTexRotated(this._isSourceTextureRotated)}_GetBackTex(renderer){if(this._isAnyShaderBackgroundBlending)if(renderer.IsWebGPU())if(this._UseCopyTextureBackgroundSampling())return this._backTex;else return this._destRenderTarget.GetTexture();else return this._destRenderTarget;else return null}_DoSetProgramParameters(renderer,index,srcRect,srcOriginRect,rcTexDest,pixelWidth,pixelHeight){renderer.SetProgramParameters(this._GetBackTex(renderer),
+rcTexDest,srcRect,srcOriginRect,this._layoutRect,pixelWidth,pixelHeight,this._devicePixelRatio,this._layerScale,this._layerAngle,this._time);renderer.SetProgramCustomParameters(this._GetShaderParameters(index,renderer))}_Render_FastPath(renderer,opts){const shaderProgram=this._shaderProgramList[0];const wasDepthEnabled=renderer.IsDepthEnabled();const usesDepth=shaderProgram.UsesDepth();if(usesDepth){renderer.SetDepthEnabled(false);renderer.SetDepthSamplingEnabled(true);this._rcTexDest.set(0,0,1,1);
+this._rcTexOriginal.set(0,0,1,1)}renderer.SetProgram(shaderProgram);renderer.SetBlendMode(this._blendMode);renderer.SetRenderTarget(this._destRenderTarget);let pixelWidth=0;let pixelHeight=1;this._rcTexOriginal.set(0,0,1,1);if(shaderProgram.UsesAnySrcRectOrPixelSize()&&this._cbGetSourceTextureInfo){const {srcTexRect,srcWidth,srcHeight}=this._cbGetSourceTextureInfo(this._contentObject);if(srcTexRect)this._rcTexOriginal.copy(srcTexRect);pixelWidth=Number.isFinite(srcWidth)?1/srcWidth:0;pixelHeight=
+Number.isFinite(srcHeight)?1/srcHeight:0}else{const [drawWidth,drawHeight]=this._manager.GetDrawSize(renderer);pixelWidth=1/drawWidth;pixelHeight=1/drawHeight}if(opts.layoutRect)this._layoutRect.copy(opts.layoutRect);else this._layoutRect.set(0,0,0,0);renderer.SetProgramParameters(this._GetBackTex(renderer),this._rcTexDest,this._rcTexOriginal,this._rcTexOriginal,this._layoutRect,pixelWidth,pixelHeight,this._devicePixelRatio,this._layerScale,this._layerAngle,this._time);renderer.SetProgramCustomParameters(this._GetShaderParameters(0,
+renderer));if(renderer.IsWebGPU()&&this._isAnyIsSrcTexRotated)renderer.SetProgramParameter_IsSrcTexRotated(this._isSourceTextureRotated);renderer.SetBaseZ(0);this._DrawContent(renderer);if(usesDepth){renderer.SetDepthSamplingEnabled(false);renderer.SetDepthEnabled(wasDepthEnabled)}}_UseCopyTextureBackgroundSampling(){return this._useCopyTextureBackgroundSampling}_UseRenderTargetBackgroundSampling(){return!this._useCopyTextureBackgroundSampling}IsAnyShaderBackgroundBlending(){return this._isAnyShaderBackgroundBlending}CanSkipCalculatingDrawSurfaceRect(){if(!this._canUseFastPath)return false;
+if(this._UseCopyTextureBackgroundSampling())return false;return true}UseFullSurface(){return this._useFullSurface}GetContentObject(){return this._contentObject}GetContextObject(){return this._contextObject}_GetBlendMode(){return this._blendMode}_UpdateOwnProjection(){return this._updateOwnProjection}DidChangeTransform(){return this._didChangeTransform}_GetDrawSurfaceRect(){return this._drawSurfaceRect}_GetRcTexBounce(){return this._rcTexBounce}_ShouldInvalidateRenderTargets(){return this._invalidateRenderTargets}async DebugLogRenderTargetContents(msg,
+renderer,renderTarget){}};
+
+}
+
+// ../lib/gfx/effectCompositor/step.js
+{
+'use strict';const C3=self.C3;
+C3.Gfx.EffectChain.Step=class EffectChainStep{constructor(effectChain,srcTargetId,destTargetId,index=-1){this._effectChain=effectChain;this._srcTargetId=srcTargetId;this._destTargetId=destTargetId;this._index=index}GetEffectChain(){return this._effectChain}GetSrcTargetId(){return this._srcTargetId}GetDestTargetId(){return this._destTargetId}GetIndex(){return this._index}GetShaderProgram(){return this.GetEffectChain()._GetShaderProgramAt(this.GetIndex())}Run_WebGL(renderer,srcRenderTarget,destRenderTarget){}Run_WebGPU(renderer,
+srcRenderTarget,destRenderTarget){}};
+
+}
+
+// ../lib/gfx/effectCompositor/preDrawStep.js
+{
+'use strict';const C3=self.C3;
+C3.Gfx.EffectChain.Step.PreDraw=class PreDrawStep extends C3.Gfx.EffectChain.Step{constructor(effectChain,srcTargetId,destTargetId,index){super(effectChain,srcTargetId,destTargetId,index)}Run_WebGL(renderer,srcRenderTarget,destRenderTarget){const effectChain=this.GetEffectChain();renderer.SetAlphaBlend();renderer.SetTextureFillMode();renderer.SetRenderTarget(destRenderTarget,effectChain._UpdateOwnProjection());renderer.ClearRgba(0,0,0,0);effectChain._DrawContent(renderer);effectChain._ClampRcTexDest()}Run_WebGPU(renderer,
+srcRenderTarget,destRenderTarget){const effectChain=this.GetEffectChain();renderer.SetAlphaBlend();renderer.SetTextureFillMode();renderer.SetRenderTarget(destRenderTarget,false);renderer.ClearRgba(0,0,0,0);effectChain._DrawContent(renderer);effectChain._ClampRcTexDest()}};
+
+}
+
+// ../lib/gfx/effectCompositor/postDrawStep.js
+{
+'use strict';const C3=self.C3;const tempRect=C3.New(C3.Rect);const tempQuad=C3.New(C3.Quad);
+C3.Gfx.EffectChain.Step.PostDraw=class PostDrawStep extends C3.Gfx.EffectChain.Step{constructor(effectChain,srcTargetId,destTargetId,index){super(effectChain,srcTargetId,destTargetId,index)}Run_WebGL(renderer,srcRenderTarget,destRenderTarget){const effectChain=this.GetEffectChain();renderer.SetTextureFillMode();renderer.SetRenderTarget(destRenderTarget);effectChain._SetDeviceTransform(renderer,true);renderer.SetBlendMode(effectChain._GetBlendMode());renderer.SetTexture(srcRenderTarget.GetTexture());
+tempQuad.setFromRect(effectChain._GetDrawSurfaceRect());tempRect.copy(effectChain._GetRcTexBounce());tempRect.flipAround(1);renderer.Quad3(tempQuad,tempRect);if(effectChain._ShouldInvalidateRenderTargets())renderer.InvalidateRenderTarget(srcRenderTarget)}Run_WebGPU(renderer,srcRenderTarget,destRenderTarget){const effectChain=this.GetEffectChain();renderer.SetTextureFillMode();renderer.SetRenderTarget(destRenderTarget,false);if(effectChain._IsRenderTargetSameSizeAndOffset(renderer))tempQuad.setFromRect(effectChain._GetRcTexBounce());
+else{renderer.SetNormalizedCoordsProgramVariant(false);effectChain._SetDeviceTransform(renderer,true);tempQuad.setFromRect(effectChain._GetDrawSurfaceRect())}renderer.SetBackTexture(null);renderer.SetBlendMode(effectChain._GetBlendMode());renderer.SetTexture(srcRenderTarget.GetTexture());if(effectChain.UseFullSurface())renderer.FullscreenQuad();else renderer.Quad3(tempQuad,effectChain._GetRcTexBounce())}};
+
+}
+
+// ../lib/gfx/effectCompositor/firstBounceStep.js
+{
+'use strict';const C3=self.C3;
+C3.Gfx.EffectChain.Step.FirstBounce=class FirstBounceStep extends C3.Gfx.EffectChain.Step{constructor(effectChain,srcTargetId,destTargetId,index){super(effectChain,srcTargetId,destTargetId,index)}Run_WebGL(renderer,srcRenderTarget,destRenderTarget){const effectChain=this.GetEffectChain();renderer.SetRenderTarget(destRenderTarget,effectChain._UpdateOwnProjection());renderer.ClearRgba(0,0,0,0);renderer.SetCopyBlend();renderer.SetProgram(this.GetShaderProgram());effectChain._SetFirstBounceProgramParameters(renderer,this.GetIndex());
+effectChain._DrawContent(renderer);effectChain._ClampRcTexDest()}Run_WebGPU(renderer,srcRenderTarget,destRenderTarget){const effectChain=this.GetEffectChain();renderer.SetRenderTarget(destRenderTarget,false);renderer.ClearRgba(0,0,0,0);renderer.SetCopyBlend();renderer.SetProgram(this.GetShaderProgram());effectChain._SetFirstBounceProgramParameters(renderer,this.GetIndex());effectChain._DrawContent(renderer);effectChain._ClampRcTexDest()}};
+
+}
+
+// ../lib/gfx/effectCompositor/bounceStep.js
+{
+'use strict';const C3=self.C3;const tempRect=C3.New(C3.Rect);const tempQuad=C3.New(C3.Quad);
+C3.Gfx.EffectChain.Step.Bounce=class BounceStep extends C3.Gfx.EffectChain.Step{constructor(effectChain,srcTargetId,destTargetId,index){super(effectChain,srcTargetId,destTargetId,index)}Run_WebGL(renderer,srcRenderTarget,destRenderTarget){const effectChain=this.GetEffectChain();renderer.SetRenderTarget(destRenderTarget);const isLast=this.GetDestTargetId()===0;if(isLast)renderer.SetBlendMode(effectChain._GetBlendMode());else{renderer.ClearRgba(0,0,0,0);renderer.SetCopyBlend()}renderer.SetProgram(this.GetShaderProgram());
+effectChain._SetProgramParameters(renderer,this.GetIndex());renderer.SetTexture(srcRenderTarget.GetTexture());effectChain._SetDeviceTransform(renderer,isLast);tempQuad.setFromRect(effectChain._GetDrawSurfaceRect());tempRect.copy(effectChain._GetRcTexBounce());tempRect.flipAround(1);renderer.Quad3(tempQuad,tempRect);if(effectChain._ShouldInvalidateRenderTargets())renderer.InvalidateRenderTarget(srcRenderTarget)}Run_WebGPU(renderer,srcRenderTarget,destRenderTarget){const effectChain=this.GetEffectChain();
+renderer.SetRenderTarget(destRenderTarget,false);const isLast=this.GetDestTargetId()===0;if(isLast){renderer.SetBlendMode(effectChain._GetBlendMode());renderer.SetBackTexture(null);if(effectChain._IsRenderTargetSameSizeAndOffset(renderer))tempQuad.setFromRect(effectChain._GetRcTexBounce());else{renderer.SetNormalizedCoordsProgramVariant(false);effectChain._SetDeviceTransform(renderer,true);tempQuad.setFromRect(effectChain._GetDrawSurfaceRect())}}else{renderer.ClearRgba(0,0,0,0);renderer.SetCopyBlend();
+tempQuad.setFromRect(effectChain._GetRcTexBounce())}renderer.SetProgram(this.GetShaderProgram());effectChain._SetProgramParameters(renderer,this.GetIndex());renderer.SetTexture(srcRenderTarget.GetTexture());if(effectChain.UseFullSurface())renderer.FullscreenQuad();else renderer.Quad3(tempQuad,effectChain._GetRcTexBounce())}};
+
+}
+
+// interfaces/IRuntime.js
+{
+'use strict';const C3=self.C3;const C3X=self.C3X;let runtime=null;const keysDownByKey=new Set;function SortZOrderList(a,b){const layerA=a[0];const layerB=b[0];const diff=layerA-layerB;if(diff!==0)return diff;const indexA=a[1];const indexB=b[1];return indexA-indexB}const tempZOrderList=[];const tempInstances=[];let didWarnInAlertPolyfill=false;
+self.IRuntime=class IRuntime{constructor(runtime_,objects){runtime=runtime_;Object.defineProperties(this,{assets:{value:runtime.GetAssetManager().GetIAssetManager(),writable:false},collisions:{value:runtime.GetCollisionEngine().GetICollisionEngine(),writable:false},objects:{value:objects,writable:false},globalVars:{value:{},writable:false},projectName:{value:runtime.GetProjectName(),writable:false},projectVersion:{value:runtime.GetProjectVersion(),writable:false},storage:{value:new self.IStorage(runtime),
+writable:false},isInWorker:{value:runtime.IsInWorker(),writable:false},viewportWidth:{value:runtime.GetOriginalViewportWidth(),writable:false},viewportHeight:{value:runtime.GetOriginalViewportHeight(),writable:false}});runtime.UserScriptDispatcher().addEventListener("keydown",e=>{if(keysDownByKey.has(e["key"])){e.stopPropagation();return}keysDownByKey.add(e["key"])});runtime.UserScriptDispatcher().addEventListener("keyup",e=>keysDownByKey.delete(e["key"]));runtime.Dispatcher().addEventListener("window-blur",
+()=>keysDownByKey.clear());if(runtime.IsInWorker())self["alert"]=message=>{if(!didWarnInAlertPolyfill){didWarnInAlertPolyfill=true;console.warn("[Construct] alert() was called from a Web Worker, because the project 'Use worker' setting is enabled. This method is not normally available in a Web Worker. Construct has implemented the alert for you, but note that other features may be missing in worker mode. You may wish to disable 'Use worker', or use a more convenient function like console.log(). For more information please refer to the scripting section of the manual.")}return this.alert(message)}}_InitGlobalVars(globalVarDescriptors){Object.defineProperties(this.globalVars,
+globalVarDescriptors)}addEventListener(name,func){runtime.UserScriptDispatcher().addEventListener(name,func)}removeEventListener(name,func){runtime.UserScriptDispatcher().removeEventListener(name,func)}callFunction(name,...params){C3X.RequireString(name);const eventSheetManager=runtime.GetEventSheetManager();const functionBlock=eventSheetManager.GetFunctionBlockByName(name);if(!functionBlock)throw new Error(`cannot find function name '${name}'`);if(!functionBlock.IsEnabled())return functionBlock.GetDefaultReturnValue();
+if(params.lengthlayout.GetILayout())}goToLayout(nameOrIndex){const layoutManager=runtime.GetLayoutManager();let layout=null;if(typeof nameOrIndex==="number"||typeof nameOrIndex==="string")layout=layoutManager.GetLayout(nameOrIndex);else throw new TypeError("expected string or number");
+if(!layout)throw new Error("invalid layout");if(layoutManager.IsPendingChangeMainLayout())return;layoutManager.ChangeMainLayout(layout)}get keyboard(){const ret=runtime._GetCommonScriptInterfaces().keyboard;if(!ret)throw new Error("runtime.keyboard used but Keyboard object missing - add it to your project first");return ret}get mouse(){const ret=runtime._GetCommonScriptInterfaces().mouse;if(!ret)throw new Error("runtime.mouse used but Mouse object missing - add it to your project first");return ret}get touch(){const ret=
+runtime._GetCommonScriptInterfaces().touch;if(!ret)throw new Error("runtime.touch used but Touch object missing - add it to your project first");return ret}invokeDownload(url,filename){C3X.RequireString(url);C3X.RequireString(filename);runtime.InvokeDownload(url,filename)}getInstanceByUid(uid){C3X.RequireFiniteNumber(uid);const ret=runtime.GetInstanceByUID(uid);return ret?ret.GetInterfaceClass():null}sortZOrder(iterable,callback){C3X.RequireFunction(callback);const layout=runtime.GetCurrentLayout();
+for(const iinst of iterable){const inst=runtime._UnwrapIWorldInstance(iinst);const wi=inst.GetWorldInfo();tempZOrderList.push([wi.GetLayer().GetIndex(),wi.GetZIndex()]);tempInstances.push(inst)}if(tempZOrderList.length===0)return;tempZOrderList.sort(SortZOrderList);tempInstances.sort((a,b)=>callback(a.GetInterfaceClass(),b.GetInterfaceClass()));let anyChanged=false;for(let i=0,len=tempZOrderList.length;iruntime._UnwrapIObjectClass(ioc));else objectClasses=[runtime._UnwrapIObjectClass(iObjectClasses)];const bbox=C3.Rect.FromObject(domrect);const ret=[];collisionEngine.GetObjectClassesCollisionCandidates(null,
+objectClasses,bbox,ret);return ret.map(wi=>wi.GetInterfaceClass())}};
+
+}
+
+// interfaces/IStorage.js
+{
+'use strict';const C3=self.C3;const C3X=self.C3X;self.IStorage=class IStorage{constructor(runtime){this._storage=runtime._GetProjectStorage()}getItem(key){C3X.RequireString(key);return this._storage.getItem(key)}setItem(key,value){C3X.RequireString(key);return this._storage.setItem(key,value)}removeItem(key){C3X.RequireString(key);return this._storage.removeItem(key)}clear(){return this._storage.clear()}keys(){return this._storage.keys()}};
+
+}
+
+// interfaces/IObjectClass.js
+{
+'use strict';const C3=self.C3;const C3X=self.C3X;const map=new WeakMap;
+self.IObjectClass=class IObjectClass{constructor(objectClass){map.set(this,objectClass);Object.defineProperties(this,{name:{value:objectClass.GetName(),writable:false}});objectClass.GetRuntime()._MapScriptInterface(this,objectClass)}addEventListener(type,func){C3X.RequireString(type);C3X.RequireFunction(func);map.get(this).UserScriptDispatcher().addEventListener(type,func)}removeEventListener(type,func){C3X.RequireString(type);C3X.RequireFunction(func);map.get(this).UserScriptDispatcher().removeEventListener(type,
+func)}getAllInstances(){return[...this.instances()]}getFirstInstance(){return C3.first(this.instances())}getPickedInstances(){return[...this.pickedInstances()]}getFirstPickedInstance(){return C3.first(this.pickedInstances())}*instances(){for(const inst of map.get(this).instancesIncludingPendingCreate())yield inst.GetInterfaceClass()}*pickedInstances(){for(const inst of map.get(this).GetCurrentSol().GetInstances())yield inst.GetInterfaceClass()}setInstanceClass(Class){C3X.RequireFunction(Class);const objectClass=
+map.get(this);if(objectClass.GetInstanceCount()>0)throw new Error("setInstanceClass() called too late, because instances have already been created - call in runOnStartup");map.get(this)._SetUserScriptInstanceClass(Class)}createInstance(layerNameOrIndex,x,y,createHierarchy,template){C3X.RequireNumber(x);C3X.RequireNumber(y);if(typeof layerNameOrIndex!=="number"&&typeof layerNameOrIndex!=="string")throw new TypeError("invalid layer parameter");const objectClass=map.get(this);const runtime=objectClass.GetRuntime();
+const layer=runtime.GetMainRunningLayout().GetLayer(layerNameOrIndex);if(!layer)throw new Error("invalid layer");const inst=runtime.CreateInstance(objectClass,layer,x,y,createHierarchy,template);if(createHierarchy)layer.SortAndAddInstancesByZIndex(inst);const eventSheetManager=runtime.GetEventSheetManager();eventSheetManager.BlockFlushingInstances(true);inst._TriggerOnCreatedOnSelfAndRelated();eventSheetManager.BlockFlushingInstances(false);if(!eventSheetManager.IsInEventEngine()&&!runtime.GetLayoutManager().IsEndingLayout())runtime.FlushPendingInstances();
+return inst.GetInterfaceClass()}};
+
+}
+
+// interfaces/ILayout.js
+{
+'use strict';const C3=self.C3;const C3X=self.C3X;const map=new WeakMap;const VALID_WHERE_STRINGS=["above","below","top-sublayer","bottom-sublayer"];
+self.ILayout=class ILayout{constructor(layout){map.set(this,layout);const effectInstanceArr=[];const effectList=layout.GetEffectList();const effectCount=effectList.GetAllEffectTypes().length;for(let i=0;ilayer.GetILayer())}*allLayers(){for(const layer of map.get(this).allLayers())yield layer.GetILayer()}addLayer(layerName,iInsertBy,whereStr){const ILayer=self.ILayer;C3X.RequireString(layerName);C3X.RequireOptionalInstanceOf(iInsertBy,ILayer);const insertBy=iInsertBy?ILayer._Unwrap(iInsertBy):null;const where=VALID_WHERE_STRINGS.indexOf(whereStr);if(where<0)throw new Error("invalid location");
+map.get(this).AddLayer(layerName,insertBy,where)}moveLayer(iLayer,iInsertBy,whereStr){const ILayer=self.ILayer;C3X.RequireInstanceOf(iLayer,ILayer);const layer=ILayer._Unwrap(iLayer);if(!layer)throw new Error("invalid layer");C3X.RequireOptionalInstanceOf(iInsertBy,ILayer);const insertBy=iInsertBy?ILayer._Unwrap(iInsertBy):null;const where=VALID_WHERE_STRINGS.indexOf(whereStr);if(where<0)throw new Error("invalid location");map.get(this).MoveLayer(layer,insertBy,where)}removeLayer(iLayer){const ILayer=
+self.ILayer;C3X.RequireInstanceOf(iLayer,ILayer);const layer=ILayer._Unwrap(iLayer);if(!layer)throw new Error("invalid layer");const runtime=layer.GetRuntime();map.get(this).RemoveLayer(layer);if(!runtime.GetEventSheetManager().IsInEventEngine())runtime.FlushPendingInstances()}removeAllDynamicLayers(){const layout=map.get(this);const runtime=layout.GetRuntime();layout.RemoveAllDynamicLayers();if(!runtime.GetEventSheetManager().IsInEventEngine())runtime.FlushPendingInstances()}setVanishingPoint(vpX,
+vpY){C3X.RequireFiniteNumber(vpX);C3X.RequireFiniteNumber(vpY);map.get(this).SetVanishingPointXY(vpX,vpY)}getVanishingPoint(){return map.get(this)._GetVanishingPoint()}set projection(p){C3X.RequireString(p);const layout=map.get(this);if(p==="perspective")layout.SetPerspectiveProjection();else if(p==="orthographic")layout.SetOrthographicProjection();else throw new Error("invalid projection");}get projection(){if(map.get(this).IsOrthographicProjection())return"orthographic";else return"perspective"}};
+
+}
+
+// interfaces/ILayer.js
+{
+'use strict';const C3=self.C3;const C3X=self.C3X;const map=new WeakMap;const BLEND_MODE_TO_INDEX=new Map([["normal",0],["additive",1],["copy",3],["destination-over",4],["source-in",5],["destination-in",6],["source-out",7],["destination-out",8],["source-atop",9],["destination-atop",10]]);const INDEX_TO_BLEND_MODE=new Map([...BLEND_MODE_TO_INDEX.entries()].map(a=>[a[1],a[0]]));const tempColor=C3.New(C3.Color);
+self.ILayer=class ILayer{constructor(layer){map.set(this,layer);const effectInstanceArr=[];const effectList=layer.GetEffectList();const effectCount=effectList.GetAllEffectTypes().length;for(let i=0;is.GetInterfaceClass()):[]}*otherContainerInstances(){const inst=map.get(this);if(!inst.IsInContainer())return;for(const s of inst.siblings())yield s.GetInterfaceClass()}get templateName(){return map.get(this).GetTemplateName()}set timeScale(t){C3X.RequireFiniteNumber(t);
+map.get(this).SetTimeScale(t)}get timeScale(){return map.get(this).GetActiveTimeScale()}restoreTimeScale(){map.get(this).RestoreTimeScale()}};
+
+}
+
+// interfaces/IWorldInstance.js
+{
+'use strict';const C3=self.C3;const C3X=self.C3X;const IInstance=self.IInstance;const ILayer=self.ILayer;const map=new WeakMap;const BLEND_MODE_TO_INDEX=new Map([["normal",0],["additive",1],["copy",3],["destination-over",4],["source-in",5],["destination-in",6],["source-out",7],["destination-out",8],["source-atop",9],["destination-atop",10]]);const INDEX_TO_BLEND_MODE=new Map([...BLEND_MODE_TO_INDEX.entries()].map(a=>[a[1],a[0]]));const tempColor=C3.New(C3.Color);
+self.IWorldInstance=class IWorldInstance extends IInstance{constructor(){super();const inst=IInstance._GetInitInst();map.set(this,inst);const effectInstanceArr=[];const wi=inst.GetWorldInfo();const instanceEffectList=wi.GetInstanceEffectList();if(instanceEffectList){const effectCount=wi.GetObjectClass().GetEffectList().GetAllEffectTypes().length;for(let i=0;iinst.GetInterfaceClass())}};
+
+}
+
+// interfaces/IEffectInstance.js
+{
+'use strict';const C3=self.C3;const C3X=self.C3X;const map=new WeakMap;const tempColor=C3.New(C3.Color);
+self.IEffectInstance=class IEffectInstance{constructor(effectList,index){map.set(this,effectList);const descriptors={index:{value:index,writable:false}};Object.defineProperties(this,descriptors)}get name(){const effectTypes=map.get(this).GetAllEffectTypes();return effectTypes[this.index].GetName()}get isActive(){return map.get(this).IsEffectIndexActive(this.index)}set isActive(a){a=!!a;const fxList=map.get(this);if(fxList.IsEffectIndexActive(this.index)===a)return;fxList.SetEffectIndexActive(this.index,
+a);fxList.UpdateActiveEffects();fxList.GetRuntime().UpdateRender()}setParameter(i,v){C3X.RequireFiniteNumber(i);i=Math.floor(+i);const fxList=map.get(this);const oldValue=fxList.GetEffectParameter(this.index,i);if(oldValue===null)throw new RangeError("invalid index");if(oldValue instanceof C3.Color){if(!Array.isArray(v)||v.length<3)throw new TypeError("expected array with 3 elements");tempColor.setRgb(v[0],v[1],v[2]);v=tempColor}else if(typeof v!=="number")throw new TypeError("expected number");const didChange=
+fxList.SetEffectParameter(this.index,i,v);if(didChange&&fxList.IsEffectIndexActive(this.index))fxList.GetRuntime().UpdateRender()}getParameter(i){C3X.RequireFiniteNumber(i);i=Math.floor(+i);const fxList=map.get(this);const ret=fxList.GetEffectParameter(this.index,i);if(ret===null)throw new RangeError("invalid index");if(ret instanceof C3.Color)return[ret.getR(),ret.getG(),ret.getB()];else return ret}};
+
+}
+
+// interfaces/IAnimation.js
+{
+'use strict';const C3=self.C3;const C3X=self.C3X;const map=new WeakMap;
+self.IAnimation=class IAnimation{constructor(animationInfo){map.set(this,animationInfo);Object.defineProperties(this,{name:{value:animationInfo.GetName(),writable:false},speed:{value:animationInfo.GetSpeed(),writable:false},isLooping:{value:animationInfo.IsLooping(),writable:false},repeatCount:{value:animationInfo.GetRepeatCount(),writable:false},repeatTo:{value:animationInfo.GetRepeatTo(),writable:false},isPingPong:{value:animationInfo.IsPingPong(),writable:false},frameCount:{value:animationInfo.GetFrameCount(),
+writable:false}})}getFrames(){return map.get(this).GetFrames().map(f=>f.GetIAnimationFrame())}*frames(){for(const f of map.get(this).GetFrames())yield f.GetIAnimationFrame()}};
+
+}
+
+// interfaces/IImageInfo.js
+{
+'use strict';const C3=self.C3;const C3X=self.C3X;const map=new WeakMap;self.IImageInfo=class IImageInfo{constructor(imageInfo){map.set(this,imageInfo)}get width(){return map.get(this).GetWidth()}get height(){return map.get(this).GetHeight()}getSize(){const imageInfo=map.get(this);return[imageInfo.GetWidth(),imageInfo.GetHeight()]}};
+
+}
+
+// interfaces/IAnimationFrame.js
+{
+'use strict';const C3=self.C3;const C3X=self.C3X;const map=new WeakMap;
+self.IAnimationFrame=class IAnimationFrame extends self.IImageInfo{constructor(animationFrameInfo){super(animationFrameInfo.GetImageInfo());map.set(this,animationFrameInfo);Object.defineProperties(this,{duration:{value:animationFrameInfo.GetDuration(),writable:false},originX:{value:animationFrameInfo.GetOriginX(),writable:false},originY:{value:animationFrameInfo.GetOriginY(),writable:false}})}getOrigin(){const afi=map.get(this);return[afi.GetOriginX(),afi.GetOriginY()]}getImagePointCount(){return map.get(this).GetImagePointCount()}getImagePointX(nameOrIndex){return this.getImagePoint(nameOrIndex)[0]}getImagePointY(nameOrIndex){return this.getImagePoint(nameOrIndex)[1]}getImagePoint(nameOrIndex){const afi=
+map.get(this);let ip=null;if(typeof nameOrIndex==="number")ip=afi.GetImagePointByIndex(Math.floor(nameOrIndex));else if(typeof nameOrIndex==="string")ip=afi.GetImagePointByName(nameOrIndex);else throw new TypeError("expected string or number");if(!ip)return this.getOrigin();return[ip.GetX(),ip.GetY()]}getPolyPointCount(){const poly=map.get(this).GetCollisionPoly();return poly?poly.pointCount():0}getPolyPointX(index){return this.getPolyPoint(index)[0]}getPolyPointY(index){return this.getPolyPoint(index)[1]}getPolyPoint(index){C3X.RequireFiniteNumber(index);
+index=Math.floor(index);const poly=map.get(this).GetCollisionPoly();if(!poly||index<0||index>=poly.pointCount())return[0,0];const pointsArr=poly.pointsArr();const ptX=pointsArr[index*2];const ptY=pointsArr[index*2+1];return[ptX,ptY]}get tag(){return map.get(this).GetTag()}};
+
+}
+
+// interfaces/ITimelineState.js
+{
+'use strict';const C3=self.C3;const C3X=self.C3X;const map=new WeakMap;function GetTimelineState(iface){const timelineState=map.get(iface);if(timelineState.IsReleased())throw new Error("timeline/tween was released and is no longer valid");return timelineState}
+self.ITimelineState=class ITimelineState{constructor(timelineState){map.set(this,timelineState)}pause(){GetTimelineState(this).Stop()}resume(){GetTimelineState(this).Resume()}hasTags(tags){return GetTimelineState(this).HasTags(tags)}set time(t){C3X.RequireFiniteNumber(t);GetTimelineState(this).SetTime(t)}get time(){return GetTimelineState(this).GetTime()}set totalTime(t){C3X.RequireFiniteNumber(t);GetTimelineState(this).SetTotalTime(t)}get totalTime(){return GetTimelineState(this).GetTotalTime()}set isLooping(l){GetTimelineState(this).SetLoop(!!l)}get isLooping(){return GetTimelineState(this).GetLoop()}set isPingPong(p){GetTimelineState(this).SetPingPong(!!p)}get isPingPong(){return GetTimelineState(this).GetPingPong()}set playbackRate(p){C3X.RequireFiniteNumber(p);
+GetTimelineState(this).SetPlaybackRate(p)}get playbackRate(){return GetTimelineState(this).GetPlaybackRate()}get progress(){const timelineState=GetTimelineState(this);return timelineState.GetTime()/timelineState.GetTotalTime()}get tags(){return GetTimelineState(this).GetTags()}get finished(){return GetTimelineState(this).GetPlayPromise()}get isPlaying(){return GetTimelineState(this).IsPlaying()}get isPaused(){return GetTimelineState(this).IsPaused()}get isReleased(){return map.get(this).IsReleased()}};
+
+}
+
+// interfaces/ITweenState.js
+{
+'use strict';const C3=self.C3;const C3X=self.C3X;const map=new WeakMap;const behInstMap=new WeakMap;let easeToIndexFunc=null;function GetTweenState(iface){const tweenState=map.get(iface);if(tweenState.IsReleased())throw new Error("timeline/tween was released and is no longer valid");return tweenState}
+self.ITweenState=class ITweenState extends self.ITimelineState{constructor(tweenState,behInst,opts){super(tweenState);if(!easeToIndexFunc)easeToIndexFunc=opts.easeToIndexFunc;map.set(this,tweenState);if(behInst)behInstMap.set(this,behInst)}stop(){const tweenState=GetTweenState(this);const behInst=behInstMap.get(this);behInst.ReleaseTween(tweenState)}setEase(easeName){C3X.RequireString(easeName);const ease=self.Ease.GetEaseFromIndex(easeToIndexFunc(easeName));GetTweenState(this).SetEase(ease)}get instance(){const inst=
+GetTweenState(this).GetInstance();return inst?inst.GetInterfaceClass():null}get isDestroyOnComplete(){return GetTweenState(this).GetDestroyInstanceOnComplete()}set isDestroyOnComplete(d){GetTweenState(this).SetDestroyInstanceOnComplete(!!d)}get value(){const tweenState=GetTweenState(this);if(tweenState.GetId()!=="value")throw new Error("not a value tween");return tweenState.GetPropertyTrack("value").GetSourceAdapterValue()}};
+
+}
+
+// assets/assetManager.js
+{
+'use strict';const C3=self.C3;const VALID_LOAD_POLICIES=new Set(["local","remote"]);const EXT_TO_TYPE=new Map([["mp4","video/mp4"],["webm","video/webm"],["m4a","audio/mp4"],["mp3","audio/mpeg"],["js","application/javascript"],["wasm","application/wasm"],["svg","image/svg+xml"],["html","text/html"]]);function GetTypeFromFileExtension(filename){if(!filename)return"";const parts=filename.split(".");if(parts.length<2)return"";const ext=parts.at(-1).toLowerCase();return EXT_TO_TYPE.get(ext)||""}
+function AddScript(url){return new Promise((resolve,reject)=>{const elem=document.createElement("script");elem.onload=resolve;elem.onerror=reject;elem.async=false;elem.type="module";elem.src=url;document.head.appendChild(elem)})}
+C3.AssetManager=class AssetManager extends C3.DefendedBase{constructor(runtime,opts){super();const exportType=opts["exportType"];this._runtime=runtime;this._fileStructure="folders";this._localUrlBlobs=new Map;this._localBlobUrlCache=new Map;this._localBlobSWUrls=new Map;this._isCordova=exportType==="cordova";this._isiOSCordova=!!opts["isiOSCordova"];this._isFileProtocol=!!opts["isFileProtocol"];this._swClientId=opts["swClientId"];this._supportedAudioFormats=opts["supportedAudioFormats"]||{};this._audioFiles=
+new Map;this._preloadSounds=false;this._mediaSubfolder="";this._fontsSubfolder="";this._iconsSubfolder="";const isRemoteLoadPolicy=exportType==="html5"||exportType==="scirra-arcade"||exportType==="instant-games";this._defaultLoadPolicy=isRemoteLoadPolicy?"remote":"local";this._allAssets=[];this._assetsByUrl=new Map;this._webFonts=[];this._loadPromises=[];this._hasFinishedInitialLoad=false;this._totalAssetSizeToLoad=0;this._assetSizeLoaded=0;this._lastLoadProgress=0;this._hasHadErrorLoading=false;
+this._loadingRateLimiter=C3.New(C3.RateLimiter,()=>this._FireLoadingProgressEvent(),50);this._localPromiseThrottle=C3.New(C3.PromiseThrottle,Math.max(C3.hardwareConcurrency,8));this._remotePromiseThrottle=C3.New(C3.PromiseThrottle,20);const localUrlBlobs=opts["previewImageBlobs"];if(localUrlBlobs){const projectFileBlobs=opts["previewProjectFileBlobs"];if(projectFileBlobs)Object.assign(localUrlBlobs,projectFileBlobs);const projectData=opts["projectData"];if(projectData)localUrlBlobs["data.json"]=projectData;
+for(const [url,blob]of Object.entries(localUrlBlobs))this._localUrlBlobs.set(url,blob)}const localSWUrlMap=opts["previewProjectFileSWUrls"];if(localSWUrlMap)for(const [srcUrl,destUrl]of Object.entries(localSWUrlMap))this._localBlobSWUrls.set(srcUrl,destUrl);this._iAssetManager=new self.IAssetManager(this)}Release(){this._localUrlBlobs.clear();for(const url of this._localBlobUrlCache.values())if(url.startsWith("blob:"))URL.revokeObjectURL(url);this._localBlobUrlCache.clear();for(const asset of this._allAssets)asset.Release();
+C3.clearArray(this._allAssets);this._assetsByUrl.clear();C3.clearArray(this._loadPromises);this._runtime=null}GetRuntime(){return this._runtime}_SetFileStructure(f){this._fileStructure=f;if(f==="flat"){const newMap=new Map;for(const [url,blob]of this._localUrlBlobs.entries())newMap.set(url.toLowerCase(),blob);this._localUrlBlobs=newMap}}GetFileStructure(){return this._fileStructure}_SetMediaSubfolder(folder){this._mediaSubfolder=folder}GetMediaSubfolder(){return this._mediaSubfolder}_SetFontsSubfolder(folder){this._fontsSubfolder=
+folder}GetFontsSubfolder(){return this._fontsSubfolder}_SetIconsSubfolder(folder){this._iconsSubfolder=folder}GetIconsSubfolder(){return this._iconsSubfolder}IsFileProtocol(){return this._isFileProtocol}_HasLocalUrlBlob(url){if(this._fileStructure==="flat")url=url.toLowerCase();return this._localUrlBlobs.has(url)}_GetLocalUrlBlob(url){if(this._fileStructure==="flat")url=url.toLowerCase();return this._localUrlBlobs.get(url)||null}GetLocalUrlAsBlobUrl(url){if(this._fileStructure==="flat")url=url.toLowerCase();
+if(!this._HasLocalUrlBlob(url))return url;let ret=this._localBlobUrlCache.get(url);if(!ret){const blob=this._GetLocalUrlBlob(url);ret=URL.createObjectURL(blob);this._localBlobUrlCache.set(url,ret)}return ret}FetchBlob(url,loadPolicy){loadPolicy=loadPolicy||this._defaultLoadPolicy;const localBlob=this._GetLocalUrlBlob(url);if(localBlob)return Promise.resolve(localBlob);else if(C3.IsRelativeURL(url)){if(this._fileStructure==="flat")url=url.toLowerCase();if(this._isCordova&&this._isFileProtocol)return this.CordovaFetchLocalFileAsBlob(url);
+else if(loadPolicy==="local")return this._localPromiseThrottle.Add(()=>C3.FetchBlob(url));else return this._remotePromiseThrottle.Add(()=>C3.FetchBlob(url))}else return C3.FetchBlob(url)}FetchArrayBuffer(url){const localBlob=this._GetLocalUrlBlob(url);if(localBlob)return C3.BlobToArrayBuffer(localBlob);else if(C3.IsRelativeURL(url)){if(this._fileStructure==="flat")url=url.toLowerCase();if(this._isCordova&&this._isFileProtocol)return this.CordovaFetchLocalFileAsArrayBuffer(url);else if(this._defaultLoadPolicy===
+"local")return this._localPromiseThrottle.Add(()=>C3.FetchArrayBuffer(url));else return this._remotePromiseThrottle.Add(()=>C3.FetchArrayBuffer(url))}else return C3.FetchArrayBuffer(url)}FetchText(url){const localBlob=this._GetLocalUrlBlob(url);if(localBlob)return C3.BlobToString(localBlob);else if(C3.IsRelativeURL(url)){if(this._fileStructure==="flat")url=url.toLowerCase();if(this._isCordova&&this._isFileProtocol)return this.CordovaFetchLocalFileAsText(url);else if(this._defaultLoadPolicy==="local")return this._localPromiseThrottle.Add(()=>
+C3.FetchText(url));else return this._remotePromiseThrottle.Add(()=>C3.FetchText(url))}else return C3.FetchText(url)}async FetchJson(url){const text=await this.FetchText(url);return JSON.parse(text)}_CordovaFetchLocalFileAs(filename,as_){if(this._fileStructure==="flat")filename=filename.toLowerCase();return this._runtime.PostComponentMessageToDOMAsync("runtime","cordova-fetch-local-file",{"filename":filename,"as":as_})}CordovaFetchLocalFileAsText(filename){return this._CordovaFetchLocalFileAs(filename,
+"text")}async CordovaFetchLocalFileAsBlob(filename){const buffer=await this._CordovaFetchLocalFileAs(filename,"buffer");const type=GetTypeFromFileExtension(filename);return new Blob([buffer],{"type":type})}async CordovaFetchLocalFileAsBlobURL(filename){if(this._fileStructure==="flat")filename=filename.toLowerCase();let blobUrl=this._localBlobUrlCache.get(filename);if(blobUrl)return blobUrl;const blob=await this.CordovaFetchLocalFileAsBlob(filename);blobUrl=URL.createObjectURL(blob);this._localBlobUrlCache.set(filename,
+blobUrl);return blobUrl}CordovaFetchLocalFileAsArrayBuffer(filename){return this._CordovaFetchLocalFileAs(filename,"buffer")}GetMediaFileUrl(filename){if(this._fileStructure==="flat")filename=filename.toLowerCase();filename=this._mediaSubfolder+filename;if(this._HasLocalUrlBlob(filename))return this.GetLocalUrlAsBlobUrl(filename);else return filename}GetProjectFileUrl(url){if(C3.IsAbsoluteURL(url))return Promise.resolve(url);else if(this._HasLocalUrlBlob(url))return Promise.resolve(this.GetLocalUrlAsBlobUrl(url));
+else if(this._isCordova&&this._isFileProtocol)return this.CordovaFetchLocalFileAsBlobURL(url);else{if(this._fileStructure==="flat")url=url.toLowerCase();return Promise.resolve(url)}}GetProjectFileIframeUrl(url){if(C3.IsAbsoluteURL(url))return Promise.resolve(url);else{const queryIndex=url.indexOf("?");const queryStr=queryIndex===-1?"":url.substr(queryIndex);const urlNoSearch=queryIndex===-1?url:url.substr(0,queryIndex);if(this._HasLocalUrlBlob(urlNoSearch)){let localUrl=this._localBlobSWUrls.get(urlNoSearch)||
+this.GetLocalUrlAsBlobUrl(urlNoSearch);if(!localUrl.startsWith("blob:")&&this._swClientId){const asUrl=new URL(localUrl);const params=new URLSearchParams(queryStr);params.set("__c3_client_id",this._swClientId);asUrl.search=params.toString();localUrl=asUrl.toString()}return Promise.resolve(localUrl)}else if(this._isCordova&&this._isFileProtocol)return this.CordovaFetchLocalFileAsBlobURL(urlNoSearch);else{if(this._fileStructure==="flat")url=url.toLowerCase();return Promise.resolve(url)}}}LoadProjectFileUrl(url){return this.GetProjectFileUrl(url)}LoadImage(opts){if(opts.loadPolicy&&
+!VALID_LOAD_POLICIES.has(opts.loadPolicy))throw new Error("invalid load policy");let asset=this._assetsByUrl.get(opts.url);if(asset)return asset;asset=C3.New(C3.ImageAsset,this,{url:opts.url,size:opts.size||0,loadPolicy:opts.loadPolicy||this._defaultLoadPolicy});this._allAssets.push(asset);this._assetsByUrl.set(asset.GetURL(),asset);if(!this._hasFinishedInitialLoad){this._totalAssetSizeToLoad+=asset.GetSize();this._loadPromises.push(asset.Load().then(()=>this._AddLoadedSize(asset.GetSize())))}return asset}async WaitForAllToLoad(){try{await Promise.all(this._loadPromises);
+this._lastLoadProgress=1}catch(err){console.error("Error loading: ",err);this._hasHadErrorLoading=true;this._FireLoadingProgressEvent()}}SetInitialLoadFinished(){this._hasFinishedInitialLoad=true}HasHadErrorLoading(){return this._hasHadErrorLoading}_AddLoadedSize(s){this._assetSizeLoaded+=s;this._loadingRateLimiter.Call()}_FireLoadingProgressEvent(){const event=C3.New(C3.Event,"loadingprogress");this._lastLoadProgress=C3.clamp(this._assetSizeLoaded/this._totalAssetSizeToLoad,0,1);event.progress=this._lastLoadProgress;
+this._runtime.Dispatcher().dispatchEvent(event)}GetLoadProgress(){return this._lastLoadProgress}_SetWebFonts(arr){C3.shallowAssignArray(this._webFonts,arr);if(this._webFonts.length)this._loadPromises.push(this._LoadWebFonts())}async _LoadWebFonts(){const promises=[];const loadFontsForDOM=[];for(const [name,filename,size]of this._webFonts){this._totalAssetSizeToLoad+=size;promises.push(this._LoadWebFont(name,filename,loadFontsForDOM).then(()=>this._AddLoadedSize(size)))}await Promise.all(promises);
+if(this._runtime.IsInWorker()&&loadFontsForDOM.length>0)await this._runtime.PostComponentMessageToDOMAsync("runtime","load-webfonts",{"webfonts":loadFontsForDOM})}async _LoadWebFont(name,filename,loadFontsForDOM){try{const url=await this.GetProjectFileUrl(filename);const fontFace=new FontFace(name,`url('${url}')`);if(this._runtime.IsInWorker())self.fonts.add(fontFace);else document.fonts.add(fontFace);await fontFace.load();if(this._runtime.IsInWorker())loadFontsForDOM.push({name,url})}catch(err){console.warn(`[C3 runtime] Failed to load web font '${name}': `,
+err)}}IsAudioFormatSupported(type){return!!this._supportedAudioFormats[type]}_SetAudioFiles(arr,preloadSounds){this._preloadSounds=!!preloadSounds;for(const [fileName,projectFilesInfo,isMusic]of arr)this._audioFiles.set(fileName,{fileName,formats:projectFilesInfo.map(si=>({type:si[0],fileExtension:si[1],fullName:fileName+si[1],fileSize:si[2]})),isMusic})}GetPreferredAudioFile(namePart){if(this._fileStructure==="flat")namePart=namePart.toLowerCase();const info=this._audioFiles.get(namePart);if(!info)return null;
+let webMOpusFile=null;for(const formatInfo of info.formats){if(!webMOpusFile&&formatInfo.type==="audio/webm; codecs=opus")webMOpusFile=formatInfo;if(this.IsAudioFormatSupported(formatInfo.type))return formatInfo}return webMOpusFile}GetProjectAudioFileUrl(namePart){const formatInfo=this.GetPreferredAudioFile(namePart);if(!formatInfo)return null;return{url:this.GetMediaFileUrl(formatInfo.fullName),type:formatInfo.type}}GetAudioToPreload(){if(this._preloadSounds){const ret=[];for(const info of this._audioFiles.values()){if(info.isMusic)continue;
+const formatInfo=this.GetPreferredAudioFile(info.fileName);if(!formatInfo)continue;ret.push({originalUrl:info.fileName,url:this.GetMediaFileUrl(formatInfo.fullName),type:formatInfo.type,fileSize:formatInfo.fileSize})}return ret}else return[]}GetIAssetManager(){return this._iAssetManager}async LoadScripts(...urls){const scriptUrls=await Promise.all(urls.map(url=>this.GetProjectFileUrl(url)));if(this._runtime.IsInWorker())if(urls.length===1){const url=urls[0];await self.c3_import((C3.IsRelativeURL(url)?
+"./":"")+url)}else{const scriptStr=urls.map(url=>`import "${C3.IsRelativeURL(url)?"./":""}${url}";`).join("\n");const blobUrl=URL.createObjectURL(new Blob([scriptStr],{type:"application/javascript"}));await self.c3_import(blobUrl)}else await Promise.all(scriptUrls.map(url=>AddScript(url)))}async CompileWebAssembly(url){if(WebAssembly.compileStreaming){const fetchUrl=await this.GetProjectFileUrl(url);return await WebAssembly.compileStreaming(fetch(fetchUrl))}else{const arrayBuffer=await C3.FetchArrayBuffer(url);
+return await WebAssembly.compile(arrayBuffer)}}async LoadStyleSheet(url){const fetchUrl=await this.GetProjectFileUrl(url);return await this._runtime.PostComponentMessageToDOMAsync("runtime","add-stylesheet",{"url":fetchUrl})}};
+
+}
+
+// assets/asset.js
+{
+'use strict';const C3=self.C3;
+C3.Asset=class Asset extends C3.DefendedBase{constructor(assetManager,opts){super();this._assetManager=assetManager;this._runtime=assetManager.GetRuntime();this._url=opts.url||"";this._size=opts.size;this._loadPolicy=opts.loadPolicy;this._blob=opts.blob||null;this._isLoaded=!!this._blob;this._loadPromise=null}Release(){this._loadPromise=null;this._assetManager=null;this._runtime=null;this._blob=null}GetURL(){return this._url}GetSize(){return this._size}Load(){if(this._loadPolicy==="local"||this._blob){this._isLoaded=
+true;return Promise.resolve()}if(this._loadPromise)return this._loadPromise;this._loadPromise=this._assetManager.FetchBlob(this._url,this._loadPolicy).then(blob=>{this._isLoaded=true;this._loadPromise=null;this._blob=blob;return blob}).catch(err=>{console.error("Error loading resource: ",err);this._loadPromise=null});return this._loadPromise}IsLoaded(){return this._isLoaded}GetBlob(){if(this._blob)return Promise.resolve(this._blob);if(this._loadPromise)return this._loadPromise;return this._assetManager.FetchBlob(this._url,
+this._loadPolicy)}};
+
+}
+
+// assets/imageAsset.js
+{
+'use strict';const C3=self.C3;const promiseThrottle=new C3.PromiseThrottle;const allImageAssets=new Set;
+C3.ImageAsset=class ImageAsset extends C3.Asset{constructor(assetManager,opts){super(assetManager,opts);this._texturePromise=null;this._webglTexture=null;this._refCount=0;this._imageWidth=-1;this._imageHeight=-1;allImageAssets.add(this)}Release(){this.ReleaseTexture();if(this._refCount!==0)throw new Error("released image asset which still has texture references");this._texturePromise=null;allImageAssets.delete(this);super.Release()}static OnRendererContextLost(){for(const imageAsset of allImageAssets){imageAsset._texturePromise=
+null;imageAsset._webglTexture=null;imageAsset._refCount=0}}LoadStaticTexture(renderer,opts){opts=opts||{};this._refCount++;if(this._webglTexture)return Promise.resolve(this._webglTexture);if(this._texturePromise)return this._texturePromise;opts.anisotropy=this._runtime.GetCanvasManager().GetTextureAnisotropy();this._texturePromise=this.GetBlob().then(blob=>promiseThrottle.Add(()=>renderer.CreateStaticTextureAsync(blob,opts).then(texture=>{this._texturePromise=null;if(this._refCount===0){renderer.DeleteTexture(texture);
+return null}this._webglTexture=texture;this._imageWidth=texture.GetWidth();this._imageHeight=texture.GetHeight();return this._webglTexture}))).catch(err=>{console.error("Failed to load texture: ",err);throw err;});return this._texturePromise}ReleaseTexture(){if(this._refCount<=0)throw new Error("texture released too many times");this._refCount--;if(this._refCount===0&&this._webglTexture){const renderer=this._webglTexture.GetRenderer();renderer.DeleteTexture(this._webglTexture);this._webglTexture=
+null}}GetTexture(){return this._webglTexture}GetWidth(){return this._imageWidth}GetHeight(){return this._imageHeight}async LoadToDrawable(){const blob=await this.GetBlob();if(C3.Supports.ImageBitmap)return await createImageBitmap(blob);else return await C3.BlobToImage(blob)}};
+
+}
+
+// layouts/renderCell.js
+{
+'use strict';const C3=self.C3;const assert=self.assert;function SortByInstLastCachedZIndex(a,b){return a.GetWorldInfo()._GetLastCachedZIndex()-b.GetWorldInfo()._GetLastCachedZIndex()}
+C3.RenderCell=class RenderCell extends C3.DefendedBase{constructor(grid,x,y){super();this._grid=grid;this._x=x;this._y=y;this._instances=[];this._isSorted=true;this._pendingRemoval=new Set;this._isAnyPendingRemoval=false}Release(){C3.clearArray(this._instances);this._pendingRemoval.clear();this._grid=null}Reset(){C3.clearArray(this._instances);this._isSorted=true;this._pendingRemoval.clear();this._isAnyPendingRemoval=false}SetChanged(){this._isSorted=false}IsEmpty(){if(!this._instances.length)return true;
+if(this._instances.length>this._pendingRemoval.size)return false;this._FlushPending();return true}Insert(inst){if(this._pendingRemoval.has(inst)){this._pendingRemoval.delete(inst);if(this._pendingRemoval.size===0)this._isAnyPendingRemoval=false;return}this._instances.push(inst);this._isSorted=this._instances.length===1}Remove(inst){this._pendingRemoval.add(inst);this._isAnyPendingRemoval=true;if(this._pendingRemoval.size>=50)this._FlushPending()}_FlushPending(){if(!this._isAnyPendingRemoval)return;
+if(this._instances.length===this._pendingRemoval.size){this.Reset();return}C3.arrayRemoveAllInSet(this._instances,this._pendingRemoval);this._pendingRemoval.clear();this._isAnyPendingRemoval=false}_EnsureSorted(){if(this._isSorted)return;this._instances.sort(SortByInstLastCachedZIndex);this._isSorted=true}Dump(result){this._FlushPending();this._EnsureSorted();if(this._instances.length)result.push(this._instances)}};
+
+}
+
+// layouts/renderGrid.js
+{
+'use strict';const C3=self.C3;
+C3.RenderGrid=class RenderGrid extends C3.DefendedBase{constructor(cellWidth,cellHeight){super();this._cellWidth=cellWidth;this._cellHeight=cellHeight;this._cells=C3.New(C3.PairMap)}Release(){this._cells.Release();this._cells=null}GetCell(x,y,createIfMissing){let ret=this._cells.Get(x,y);if(ret)return ret;else if(createIfMissing){ret=C3.New(C3.RenderCell,this,x,y);this._cells.Set(x,y,ret);return ret}else return null}XToCell(x){return Math.floor(x/this._cellWidth)}YToCell(y){return Math.floor(y/this._cellHeight)}Update(inst,
+oldRange,newRange){if(oldRange)for(let x=oldRange.getLeft(),lenx=oldRange.getRight();x<=lenx;++x)for(let y=oldRange.getTop(),leny=oldRange.getBottom();y<=leny;++y){if(newRange&&newRange.containsPoint(x,y))continue;const cell=this.GetCell(x,y,false);if(!cell)continue;cell.Remove(inst);if(cell.IsEmpty())this._cells.Delete(x,y)}if(newRange)for(let x=newRange.getLeft(),lenx=newRange.getRight();x<=lenx;++x)for(let y=newRange.getTop(),leny=newRange.getBottom();y<=leny;++y){if(oldRange&&oldRange.containsPoint(x,
+y))continue;this.GetCell(x,y,true).Insert(inst)}}QueryRange(rc,result){let x=this.XToCell(rc.getLeft());const ystart=this.YToCell(rc.getTop());const lenx=this.XToCell(rc.getRight());const leny=this.YToCell(rc.getBottom());for(;x<=lenx;++x)for(let y=ystart;y<=leny;++y){const cell=this.GetCell(x,y,false);if(!cell)continue;cell.Dump(result)}}MarkRangeChanged(rc){let x=rc.getLeft();const ystart=rc.getTop();const lenx=rc.getRight();const leny=rc.getBottom();for(;x<=lenx;++x)for(let y=ystart;y<=leny;++y){const cell=
+this.GetCell(x,y,false);if(!cell)continue;cell.SetChanged()}}};
+
+}
+
+// layouts/layer.js
+{
+'use strict';const C3=self.C3;const assert=self.assert;const tmpRect=new C3.Rect;const tmpQuad=new C3.Quad;const renderCellArr=[];const tmpDestRect=new C3.Rect;const tmpSrcRect=new C3.Rect;const glMatrix=self.glMatrix;const vec3=glMatrix.vec3;const vec4=glMatrix.vec4;const mat4=glMatrix.mat4;const tempMat4=mat4.create();const tempVec3=vec3.create();const tempVec4=vec4.create();const camVector=vec3.create();const lookVector=vec3.create();const upVector=vec3.create();const tempVec2=C3.New(C3.Vector2);
+const tempRect=C3.New(C3.Rect);function SortByInstLastCachedZIndex(a,b){return a.GetWorldInfo()._GetLastCachedZIndex()-b.GetWorldInfo()._GetLastCachedZIndex()}function SortByInstZElevation(a,b){return a.GetWorldInfo().GetZElevation()-b.GetWorldInfo().GetZElevation()}const tempInstanceList1=[];const tempInstanceList2=[];const tempInstancesByCameraDist=[];
+const DEFAULT_LAYER_OPTIONS={name:"",sid:-1,isDynamic:false,isVisible:true,isInteractive:true,isHTMLElementsLayer:false,backgroundColor:[1,1,1,1],isTransparent:true,parallax:[1,1],opacity:1,isForceOwnTexture:false,renderAs3d:false,useCameraDistanceDrawOrder:false,useRenderCells:false,scaleRate:1,blendMode:0,zElevation:0,initialInstancesData:[],effectListData:[],subLayersData:[]};
+C3.Layer=class Layer extends C3.DefendedBase{constructor(layout,parentLayer,opts){super();opts=Object.assign({},DEFAULT_LAYER_OPTIONS,opts);this._layout=layout;this._runtime=layout.GetRuntime();this._parentLayer=parentLayer;this._name=opts.name;this._index=-1;this._isHTMLElementsLayer=!!opts.isHTMLElementsLayer;this._htmlIndex=-1;this._sid=opts.sid;this._isDynamic=!!opts.isDynamic;this._isVisible=!!opts.isVisible;this._isInteractive=!!opts.isInteractive;this._backgroundColor=C3.New(C3.Color);this._backgroundColor.setFromJSON(opts.backgroundColor);
+this._isTransparent=!!opts.isTransparent;this._parallaxX=opts.parallax[0];this._parallaxY=opts.parallax[1];this._color=C3.New(C3.Color,1,1,1,opts.opacity);this._premultipliedColor=C3.New(C3.Color);this._isForceOwnTexture=!!opts.isForceOwnTexture;this._renderAs3d=!!opts.renderAs3d;this._useCameraDistanceDrawOrder=!!opts.useCameraDistanceDrawOrder;this._useRenderCells=!!opts.useRenderCells;this._scaleRate=opts.scaleRate;this._blendMode=opts.blendMode;this._curRenderTarget=null;this._scale=1;this._zElevation=
+opts.zElevation;this._angle=0;this._scrollX=0;this._scrollY=0;this._hasOwnScrollPosition=false;this._viewport=C3.New(C3.Rect);this._viewportZ0=C3.New(C3.Rect);this._viewport3D=C3.New(C3.Rect);this._isViewportChanged=true;this._projectionMatrix=mat4.create();this._isProjectionMatrixChanged=true;this._modelViewMatrix=mat4.create();this._isMVMatrixChanged=true;this._viewFrustum=C3.New(C3.Gfx.ViewFrustum);this._isViewFrustumChanged=true;this._startupInitialInstances=[];this._initialInstancesData=opts.initialInstancesData;
+this._initialInstances=[];this._createdGlobalUids=[];this._initialUIDsToInstanceData=new Map;this._instances=[];this._zIndicesUpToDate=false;this._htmlZIndicesUpToDate=false;this._anyInstanceZElevated=false;const canvasManager=this._runtime.GetCanvasManager();this._effectList=C3.New(C3.EffectList,this,opts.effectListData);this._effectChain=C3.New(C3.Gfx.EffectChain,canvasManager.GetEffectChainManager(),{drawContent:(renderer,effectChain)=>{const layer=effectChain.GetContentObject();const renderSurface=
+layer.GetRenderTarget();renderer.SetColor(layer.GetPremultipliedColor());renderer.DrawRenderTarget(renderSurface);renderer.InvalidateRenderTarget(renderSurface);canvasManager.ReleaseAdditionalRenderTarget(renderSurface)},getShaderParameters:index=>this.GetEffectList()._GetEffectChainShaderParametersForIndex(index)});this._needsRebuildEffectChainSteps=true;this._wasDefaultColor=true;this._renderGrid=null;this._lastRenderList=[];this._isRenderListUpToDate=false;this._lastRenderCells=C3.New(C3.Rect,
+0,0,-1,-1);this._curRenderCells=C3.New(C3.Rect,0,0,-1,-1);this._iLayer=new self.ILayer(this);this._UpdatePremultipliedColor();if(this.UsesRenderCells())this._renderGrid=C3.New(C3.RenderGrid,this._runtime.GetOriginalViewportWidth(),this._runtime.GetOriginalViewportHeight());this._subLayers=opts.subLayersData.map(ld=>C3.Layer.CreateFromExportData(this._layout,this,ld))}_InitInitialInstances(){for(const instData of this._initialInstancesData){const objectClass=this._runtime.GetObjectClassByIndex(instData[1]);
+this._layout._AddInitialObjectClass(objectClass);if(!objectClass.GetDefaultInstanceData()){objectClass.SetDefaultInstanceData(instData);objectClass._SetDefaultLayerIndex(this._index)}this._initialInstances.push(instData);this._initialUIDsToInstanceData.set(instData[2],instData)}C3.shallowAssignArray(this._startupInitialInstances,this._initialInstances);this._initialInstancesData=null}static CreateFromExportData(layout,parentLayer,data){return C3.New(C3.Layer,layout,parentLayer,{name:data[0],sid:data[2],
+isVisible:data[3],isInteractive:data[13],isHTMLElementsLayer:data[19],backgroundColor:data[4].map(x=>x/255),isTransparent:data[5],parallax:[data[6],data[7]],opacity:data[8],isForceOwnTexture:data[9],renderAs3d:data[17],useCameraDistanceDrawOrder:data[18],useRenderCells:data[10],scaleRate:data[11],blendMode:data[12],zElevation:data[16],initialInstancesData:data[14],effectListData:data[15],subLayersData:data[20]})}Release(){for(const subLayer of this._subLayers)subLayer.Release();C3.clearArray(this._subLayers);
+for(const inst of this._instances)this._runtime.DestroyInstance(inst);C3.clearArray(this._instances);this._effectList.Release();this._effectList=null;this._effectChain.Release();this._effectChain=null;this._iLayer=null;this._parentLayer=null;this._layout=null;this._runtime=null}GetInitialInstanceData(uid){return this._initialUIDsToInstanceData.get(uid)}CreateInitialInstances(createdInstances){const isFirstVisit=this._layout.IsFirstVisit();let k=0;const initialInstances=this._initialInstances;for(let i=
+0,len=initialInstances.length;i=0)assignedZIndices.add(cachedZIndex)}let index=-1;for(const inst of this._instances){const wi=inst.GetWorldInfo();if(wi._GetLastCachedZIndex()>=0)continue;++index;while(assignedZIndices.has(index))++index;wi._SetZIndex(index)}}this._instances.sort(SortByInstLastCachedZIndex)}_Start(){}_End(){for(const inst of this._instances)if(!inst.GetObjectClass().IsGlobal())this._runtime.DestroyInstance(inst);this._runtime.FlushPendingInstances();C3.clearArray(this._instances);
+this._anyInstanceZElevated=false;this.SetZIndicesChanged()}RecreateInitialObjects(objectClass,rc,offsetX,offsetY,createHierarchy){const eventSheetManager=this._runtime.GetEventSheetManager();const allObjectClasses=this._runtime.GetAllObjectClasses();const isFamily=objectClass.IsFamily();const ret=[];for(const instData of this._initialInstances){const worldData=instData[0];const x=worldData[0];const y=worldData[1];if(!rc.containsPoint(x,y))continue;const objectType=allObjectClasses[instData[1]];if(objectType!==
+objectClass)if(isFamily){if(!objectClass.FamilyHasMember(objectType))continue}else continue;let createOnLayer=this;const runningLayout=this._runtime.GetCurrentLayout();if(this.GetLayout()!==runningLayout){createOnLayer=runningLayout.GetLayerByName(this.GetName());if(!createOnLayer)createOnLayer=runningLayout.GetLayerByIndex(this.GetIndex())}const inst=this._runtime.CreateInstanceFromData(instData,createOnLayer,false,undefined,undefined,false,createHierarchy);createOnLayer.SortAndAddInstancesByZIndex(inst);
+const wi=inst.GetWorldInfo();wi.OffsetXY(offsetX,offsetY);wi.SetBboxChanged();eventSheetManager.BlockFlushingInstances(true);inst._TriggerOnCreatedOnSelfAndRelated();eventSheetManager.BlockFlushingInstances(false);ret.push(inst)}return ret}GetInstanceCount(){return this._instances.length}GetLayout(){return this._layout}GetName(){return this._name}_SetIndex(i){this._index=i}GetIndex(){return this._index}_SetHTMLIndex(i){this._htmlIndex=i}GetHTMLIndex(){return this._htmlIndex}IsHTMLElementsLayer(){return this._isHTMLElementsLayer}SetIsHTMLElementsLayer(i){i=
+!!i;if(this._isHTMLElementsLayer===i)return;this._isHTMLElementsLayer=i;this._layout._ReindexAndUpdateAllLayers();this._runtime.UpdateRender()}_GetSiblingIndex(){let ret=-1;const parentLayer=this.GetParentLayer();if(parentLayer)ret=parentLayer.GetSubLayers().indexOf(this);else ret=this.GetLayout()._GetRootLayers().indexOf(this);return ret}GetSID(){return this._sid}GetRuntime(){return this._runtime}IsDynamic(){return this._isDynamic}HasAnyDynamicParentLayer(){for(const parent of this.parentLayers())if(parent.IsDynamic())return true;
+return false}GetDevicePixelRatio(){return this._runtime.GetDevicePixelRatio()}GetEffectList(){return this._effectList}GetEffectChain(){this._MaybeRebuildEffectChainSteps();return this._effectChain}_MaybeRebuildEffectChainSteps(){const isDefaultColor=this.HasDefaultColor();if(!this._needsRebuildEffectChainSteps&&isDefaultColor===this._wasDefaultColor&&!this._effectChain.NeedsRebuild())return;const activeEffectTypes=this.GetEffectList().GetActiveEffectTypes();this._effectChain.BuildSteps(activeEffectTypes.map(e=>
+e.GetShaderProgram()),{indexMap:activeEffectTypes.map(e=>e.GetIndex()),forcePreDraw:!isDefaultColor,useFullSurface:true});this._needsRebuildEffectChainSteps=false;this._wasDefaultColor=isDefaultColor}UpdateActiveEffects(){this.GetEffectList().UpdateActiveEffects();this._needsRebuildEffectChainSteps=true}UsesRenderCells(){return this._useRenderCells&&!this._useCameraDistanceDrawOrder}GetRenderGrid(){return this._renderGrid}SetRenderListStale(){this._isRenderListUpToDate=false}IsVisible(){for(const layer of this.selfAndParentLayers())if(!layer._IsVisibleFlagSet())return false;
+return true}_IsVisibleFlagSet(){return this._isVisible}SetVisible(v){v=!!v;if(this._isVisible===v)return;this._isVisible=v;this._runtime.UpdateRender()}SetInteractive(i){this._isInteractive=!!i}IsInteractive(){return this._isInteractive}IsSelfAndParentsInteractive(){for(const layer of this.selfAndParentLayers())if(!layer.IsInteractive())return false;return true}SetOwnScrollPositionEnabled(e){e=!!e;if(this._hasOwnScrollPosition===e)return;this._hasOwnScrollPosition=e;if(e){const layout=this.GetLayout();
+this._scrollX=layout.GetScrollX();this._scrollY=layout.GetScrollY()}this._SetMVMatrixChanged();this._runtime.UpdateRender()}IsOwnScrollPositionEnabled(){return this._hasOwnScrollPosition}SetScrollX(x){const layout=this.GetLayout();const lbound=layout.GetScrollLeftBound();const rbound=layout.GetScrollRightBound();if(x>rbound)x=rbound;if(xbbound)y=bbound;if(y0}_GetInstances(){return this._instances}_GetInstancesInDrawOrder(){if(this.RendersIn3DMode()&&
+this._useCameraDistanceDrawOrder){C3.shallowAssignArray(tempInstancesByCameraDist,this._GetInstances());tempInstancesByCameraDist.sort((a,b)=>this._SortInstancesByCameraDistance(a,b));return tempInstancesByCameraDist}else return this._GetInstances()}_AppendAllInstancesIncludingSubLayersInDrawOrder(arr){C3.appendArray(arr,this._GetInstancesInDrawOrder());for(const subLayer of this._subLayers)if(subLayer.IsVisible()&&subLayer.GetOpacity()>0)subLayer._AppendAllInstancesIncludingSubLayersInDrawOrder(arr)}_SortInstancesByCameraDistance(a,
+b){const camVec=this.GetLayout().Get3DCameraPosition();const camX=camVec[0];const camY=camVec[1];const camZ=camVec[2];const wiA=a.GetWorldInfo();const wiB=b.GetWorldInfo();const dxA=wiA.GetX()-camX;const dyA=wiA.GetY()-camY;const dzA=wiA.GetZElevation()-camZ;const dxB=wiB.GetX()-camX;const dyB=wiB.GetY()-camY;const dzB=wiB.GetZElevation()-camZ;return dxB*dxB+dyB*dyB+dzB*dzB-(dxA*dxA+dyA*dyA+dzA*dzA)}GetBackgroundColor(){return this._backgroundColor}IsTransparent(){return this._isTransparent}SetTransparent(t){t=
+!!t;if(this._isTransparent===t)return;this._isTransparent=t;this._runtime.UpdateRender()}IsForceOwnTexture(){return this._isForceOwnTexture}SetForceOwnTexture(f){f=!!f;if(this._isForceOwnTexture===f)return;this._isForceOwnTexture=f;this._runtime.UpdateRender()}RendersIn2DMode(){return!this.GetRuntime().Uses3DFeatures()||!this._renderAs3d}RendersIn3DMode(){return!this.RendersIn2DMode()}Has3DCamera(){return this.RendersIn3DMode()&&this.GetLayout().Is3DCameraEnabled()}SelfAndAllSubLayersHave3DCamera(){if(!this.Has3DCamera())return false;
+for(const subLayer of this._subLayers)if(!subLayer.SelfAndAllSubLayersHave3DCamera())return false;return true}SetBlendMode(bm){if(this._blendMode===bm)return;this._blendMode=bm;this._runtime.UpdateRender()}GetBlendMode(){return this._blendMode}IsRootLayer(){return!this._parentLayer}GetParentLayer(){return this._parentLayer}_SetParentLayer(layer){this._parentLayer=layer}GetSubLayers(){return this._subLayers}HasAnySubLayers(){return this._subLayers.length>0}_AddSubLayer(layer,atTop=true){if(atTop)this._subLayers.push(layer);
+else this._subLayers.unshift(layer)}_InsertSubLayer(layer,insertBy,isAbove){let i=this._subLayers.indexOf(insertBy);if(i===-1)throw new Error("cannot find layer to insert by");if(isAbove)++i;this._subLayers.splice(i,0,layer)}_RemoveSubLayer(layer){const i=this._subLayers.indexOf(layer);if(i===-1)throw new Error("cannot find layer to remove");this._subLayers.splice(i,1)}HasAnyVisibleSubLayer(){for(const subLayer of this._subLayers)if(subLayer.ShouldDraw())return true;return false}*selfAndAllSubLayers(){for(const subLayer of this._subLayers)yield*subLayer.selfAndAllSubLayers();
+yield this}*parentLayers(){let parentLayer=this.GetParentLayer();while(parentLayer){yield parentLayer;parentLayer=parentLayer.GetParentLayer()}}*selfAndParentLayers(){yield this;yield*this.parentLayers()}HasParentLayer(layer){for(const p of this.parentLayers())if(p===layer)return true;return false}IsTransformCompatibleWith(otherLayer){return this===otherLayer||this._parallaxX===otherLayer._parallaxX&&this._parallaxY===otherLayer._parallaxY&&this._scale===otherLayer._scale&&this._scaleRate===otherLayer._scaleRate&&
+this._angle===otherLayer._angle&&this.GetScrollX()===otherLayer.GetScrollX()&&this.GetScrollY()===otherLayer.GetScrollY()}SaveTransform(){return{"parallaxX":this.GetParallaxX(),"parallaxY":this.GetParallaxY(),"scale":this.GetOwnScale(),"scaleRate":this.GetScaleRate(),"angle":this.GetOwnAngle(),"hasOwnScroll":this.IsOwnScrollPositionEnabled(),"scrollX":this.GetScrollX(),"scrollY":this.GetScrollY()}}RestoreTransform(t){this.SetParallax(t["parallaxX"],t["parallaxY"]);this.SetOwnScale(t["scale"]);this.SetScaleRate(t["scaleRate"]);
+this.SetAngle(t["angle"]);this.SetOwnScrollPositionEnabled(t["hasOwnScroll"]);this.SetScrollX(t["scrollX"]);this.SetScrollY(t["scrollY"]);this._MaybeUpdateViewport()}_RemoveAllInstancesInSet(s){if(s.size===0)return;const numRemoved=C3.arrayRemoveAllInSet(this._instances,s);if(numRemoved>0){this._MaybeResetAnyInstanceZElevatedFlag();this.SetZIndicesChanged()}}SetZIndicesChanged(inst){this._zIndicesUpToDate=false;this._isRenderListUpToDate=false;if(!inst||inst.GetObjectClass().GetPlugin().IsHTMLElementType())this._htmlZIndicesUpToDate=
+false}_UpdateZIndices(){if(this._zIndicesUpToDate)return;this._instances.sort(SortByInstZElevation);if(this.UsesRenderCells())for(let i=0,len=this._instances.length;i[...l.selfAndAllSubLayers()]).flat();let htmlZIndex=0;for(const layer of allLayers){for(const inst of layer._GetInstances())if(inst.GetObjectClass().GetPlugin().IsHTMLElementType())inst.GetWorldInfo()._SetHTMLZIndex(htmlZIndex++);layer._SetHTMLZIndicesUpToDate()}}_SetHTMLZIndicesUpToDate(){this._htmlZIndicesUpToDate=true}MoveInstanceAdjacent(inst,other,isAfter){const instWi=inst.GetWorldInfo();const otherWi=
+other.GetWorldInfo();if(instWi.GetLayer()!==this||otherWi.GetLayer()!==this)throw new Error("can't arrange Z order unless both objects on this layer");const myZ=instWi.GetZIndex();let insertZ=otherWi.GetZIndex();if(myZ===insertZ+(isAfter?1:-1))return false;C3.arrayRemove(this._instances,myZ);if(myZ1)arr=this._MergeAllSortedZArrays_pass(arr);return arr[0]}_GetRenderCellInstancesToDraw(){this._UpdateZIndices();C3.clearArray(renderCellArr);this._renderGrid.QueryRange(this.GetViewport(),renderCellArr);if(!renderCellArr.length)return[];if(renderCellArr.length===1)return renderCellArr[0];return this._MergeAllSortedZArrays(renderCellArr)}ShouldDraw(){return this.IsVisible()&&this.GetOpacity()>0&&this._DrawsAnyContentInSelfOrSubLayers()}_DrawsAnyContentInSelfOrSubLayers(){if(this.HasInstances()||
+!this.IsTransparent())return true;for(const subLayer of this._subLayers)if(subLayer._DrawsAnyContentInSelfOrSubLayers())return true;return false}UsesOwnTexture(){return this.IsForceOwnTexture()||!this.HasDefaultColor()||this.GetBlendMode()!==0||this._effectList.HasAnyActiveEffect()}SelfOrAnySubLayerUsesOwnTexture(){if(this.UsesOwnTexture())return true;for(const subLayer of this._subLayers)if(subLayer.SelfOrAnySubLayerUsesOwnTexture())return true;return false}GetRenderTarget(){return this._curRenderTarget}Get2DScaleFactorToZ(z){if(this._layout.IsOrthographicProjection())return 1;
+else{const camZ=this.GetCameraZ();return camZ/(camZ-z)}}GetCameraZ(viewH){return this.GetDefaultCameraZ(viewH)/this.GetNormalScale()}_SetMVMatrixChanged(){this._isMVMatrixChanged=true;this._isViewFrustumChanged=true;this._isViewportChanged=true}_GetModelViewMatrix(renderer){if(this._isMVMatrixChanged){this._CalculateModelViewMatrix(renderer,this._modelViewMatrix,0,0,null);this._isMVMatrixChanged=false}return this._modelViewMatrix}GetCameraPosition(){if(this.Has3DCamera()){const camPos=this.GetLayout().Get3DCameraPosition();
+return[camPos[0],camPos[1],camPos[2]]}else return this._Get2DCameraPosition()}_Get2DCameraPosition(offX=0,offY=0,viewH=0){const runtime=this._runtime;const layout=this.GetLayout();const parallaxOriginX=runtime.GetParallaxXOrigin();const parallaxOriginY=runtime.GetParallaxYOrigin();let scrollOriginX=(this.GetScrollX()-parallaxOriginX)*this._parallaxX+parallaxOriginX;let scrollOriginY=(this.GetScrollY()-parallaxOriginY)*this._parallaxY+parallaxOriginY;if(runtime.IsPixelRoundingEnabled()){scrollOriginX=
+Math.round(scrollOriginX);scrollOriginY=Math.round(scrollOriginY)}let camX=scrollOriginX+offX;let camY=scrollOriginY+offY;const camZ=layout.IsOrthographicProjection()?this.GetDefaultCameraZ(viewH):this.GetCameraZ(viewH);const [vpX,vpY]=this._GetVanishingPoint();if(vpX!==.5||vpY!==.5){const zf=this.GetDefaultCameraZ(viewH)/camZ;let camOffX=(vpX-.5)*runtime.GetViewportWidth()/zf;let camOffY=(vpY-.5)*runtime.GetViewportHeight()/zf;const a=this.GetAngle();if(a!==0){tempVec2.set(camOffX,camOffY);tempVec2.rotate(a);
+camOffX=tempVec2.getX();camOffY=tempVec2.getY()}camX+=camOffX;camY+=camOffY}return[camX,camY,camZ]}_CalculateModelViewMatrix(renderer,outMat,offX,offY,viewH){const runtime=this._runtime;const layout=this.GetLayout();if(this.Has3DCamera()){vec3.copy(camVector,layout.Get3DCameraPosition());vec3.copy(lookVector,layout.Get3DCameraLookAt());vec3.copy(upVector,layout.Get3DCameraUpVector());const parallaxOriginX=runtime.GetParallaxXOrigin();const parallaxOriginY=runtime.GetParallaxYOrigin();const lookDx=
+lookVector[0]-camVector[0];const lookDy=lookVector[1]-camVector[1];const lookDz=lookVector[2]-camVector[2];camVector[0]=(camVector[0]-parallaxOriginX)*this._parallaxX+parallaxOriginX;camVector[1]=(camVector[1]-parallaxOriginY)*this._parallaxY+parallaxOriginY;camVector[2]*=Math.max(this._parallaxX,this._parallaxY);lookVector[0]=camVector[0]+lookDx;lookVector[1]=camVector[1]+lookDy;lookVector[2]=camVector[2]+lookDz}else{const [camX,camY,camZ]=this._Get2DCameraPosition(offX,offY,viewH);vec3.set(camVector,
+camX,camY,camZ);vec3.set(lookVector,camX,camY,camZ-100);const a=this.GetAngle();if(a===0)vec3.set(upVector,0,1,0);else vec3.set(upVector,Math.sin(a),Math.cos(a),0)}renderer.CalculateLookAtModelView(outMat,camVector,lookVector,upVector,viewH||runtime.GetViewportHeight())}_SetProjectionMatrixChanged(){this._isProjectionMatrixChanged=true;this._isViewFrustumChanged=true;this._isViewportChanged=true}_GetProjectionMatrix(renderer){if(this._isProjectionMatrixChanged){this._CalculateProjectionMatrix(renderer);
+this._isProjectionMatrixChanged=false}return this._projectionMatrix}_CalculateProjectionMatrix(renderer){const canvasManager=this._runtime.GetCanvasManager();const [vpX,vpY]=this._GetVanishingPoint();if(this._layout.IsOrthographicProjection())renderer.CalculateOrthographicMatrix(this._projectionMatrix,canvasManager.GetDrawWidth(),canvasManager.GetDrawHeight());else if(vpX===.5&&vpY===.5)mat4.copy(this._projectionMatrix,canvasManager.GetDefaultProjectionMatrix());else{const drawW=canvasManager.GetDrawWidth();
+const drawH=canvasManager.GetDrawHeight();renderer.CalculatePerspectiveMatrix(this._projectionMatrix,drawW/drawH,vpX,vpY)}}_SetTransform(renderer,updateProjection=true,offX=0,offY=0,viewH=0){if(updateProjection)renderer.SetProjectionMatrix(this._GetProjectionMatrix(renderer));let modelViewMatrix=null;if(offX===0&&offY===0&&viewH===0)modelViewMatrix=this._GetModelViewMatrix(renderer);else{this._CalculateModelViewMatrix(renderer,tempMat4,offX,offY,viewH);modelViewMatrix=tempMat4}renderer.SetModelViewMatrix(modelViewMatrix)}PrepareForDraw(renderer){this._SetTransform(renderer);
+renderer.SetBaseZ(this.GetZElevation())}Draw(renderer,destinationRenderTarget,isFirstToTarget){const canvasManager=this._runtime.GetCanvasManager();const useOwnTexture=this.UsesOwnTexture();let ownRenderTarget=null;let layerQuery=null;if(this._runtime.IsGPUProfiling())if(renderer.IsWebGL()){const timingsBuffer=canvasManager.GetLayerTimingsBuffer(this);if(timingsBuffer){layerQuery=timingsBuffer.AddTimeElapsedQuery();renderer.StartQuery(layerQuery)}}else if(renderer.IsWebGPU())renderer.WriteTimestamp((this.GetIndex()+
+1)*2);if(useOwnTexture){const rtOpts={sampling:this._runtime.GetSampling(),isSampled:true,canReadPixels:renderer.IsWebGPU()?this._runtime.UsesAnyBackgroundBlending():false};if(canvasManager.GetCurrentFullscreenScalingQuality()==="low"){rtOpts.width=canvasManager.GetDrawWidth();rtOpts.height=canvasManager.GetDrawHeight()}ownRenderTarget=this._runtime.GetAdditionalRenderTarget(rtOpts);this._curRenderTarget=ownRenderTarget;renderer.SetRenderTarget(ownRenderTarget);if(this.IsTransparent())renderer.ClearRgba(0,
+0,0,0)}else{this._curRenderTarget=destinationRenderTarget;renderer.SetRenderTarget(destinationRenderTarget)}if(!this.IsTransparent())renderer.Clear(this._backgroundColor);this._layout._DrawLayerList(renderer,this._curRenderTarget,this._subLayers,useOwnTexture&&this.IsTransparent());this._SetTransform(renderer);renderer.SetBaseZ(this.GetZElevation());renderer.SetDepthEnabled(this.RendersIn3DMode());if(this.GetNormalScale()>Number.EPSILON){this._UpdateZIndices();const useRenderCells=this.UsesRenderCells()&&
+this.GetZElevation()===0&&!this._anyInstanceZElevated;if(this.Has3DCamera())this._DrawInstances_3DCamera(renderer);else if(useRenderCells)this._DrawInstances_RenderCells(renderer);else this._DrawInstances(renderer,this._GetInstancesInDrawOrder())}renderer.SetBaseZ(0);renderer.SetCurrentZ(0);if(useOwnTexture){renderer.SetDepthEnabled(false);this._DrawLayerOwnTextureToRenderTarget(renderer,ownRenderTarget,destinationRenderTarget,isFirstToTarget)}if(layerQuery)renderer.EndQuery(layerQuery);if(this._runtime.IsGPUProfiling()&&
+renderer.IsWebGPU())renderer.WriteTimestamp((this.GetIndex()+1)*2+1);this._curRenderTarget=null}_DrawInstances(renderer,instances){const viewport=this.GetViewport();const renderTarget=this._curRenderTarget;const isOrthographic=this.GetLayout().IsOrthographicProjection();const hasVanishingPointOutsideViewport=this.GetLayout().HasVanishingPointOutsideViewport();let lastInst=null;for(let i=0,len=instances.length;i0)postRenderInstances.push(inst);const startZ=inst.GetWorldInfo().GetTotalZElevation();coplanarInstances.push(inst);let endIndex=i+1;for(;endIndex0)postRenderInstances.push(nextInst);coplanarInstances.push(nextInst)}if(coplanarInstances.length===1&&!coplanarInstances[0].MustMitigateZFighting()){this._DrawInstanceMaybeWithEffects(inst,wi,renderer,renderTarget);for(let j=0,lenj=postRenderInstances.length;j0)if(this._IsPointBehindNearPlane(bbLeft,bbTop,topZ)||this._IsPointBehindNearPlane(bbRight,bbTop,topZ)||this._IsPointBehindNearPlane(bbRight,bbBottom,topZ)||this._IsPointBehindNearPlane(bbLeft,bbBottom,topZ))return null}else if(topZ>=this.GetCameraZ())return null;let [stlx,stly]=this.LayerToDrawSurface(bbLeft,bbTop,z);let [sbrx,
+sbry]=this.LayerToDrawSurface(bbRight,bbBottom,z);if(this.GetAngle()!==0||depth>0||this.Has3DCamera()){const [strx,stry]=this.LayerToDrawSurface(bbRight,bbTop,z);const [sblx,sbly]=this.LayerToDrawSurface(bbLeft,bbBottom,z);if(depth>0){const [stlxTop,stlyTop]=this.LayerToDrawSurface(bbLeft,bbTop,topZ);const [strxTop,stryTop]=this.LayerToDrawSurface(bbRight,bbTop,topZ);const [sbrxTop,sbryTop]=this.LayerToDrawSurface(bbRight,bbBottom,topZ);const [sblxTop,sblyTop]=this.LayerToDrawSurface(bbLeft,bbBottom,
+topZ);let temp=Math.min(stlx,sbrx,strx,sblx,stlxTop,strxTop,sbrxTop,sblxTop);sbrx=Math.max(stlx,sbrx,strx,sblx,stlxTop,strxTop,sbrxTop,sblxTop);stlx=temp;temp=Math.min(stly,sbry,stry,sbly,stlyTop,stryTop,sbryTop,sblyTop);sbry=Math.max(stly,sbry,stry,sbly,stlyTop,stryTop,sbryTop,sblyTop);stly=temp}else{let temp=Math.min(stlx,sbrx,strx,sblx);sbrx=Math.max(stlx,sbrx,strx,sblx);stlx=temp;temp=Math.min(stly,sbry,stry,sbly);sbry=Math.max(stly,sbry,stry,sbly);stly=temp}}tmpRect.set(stlx,stly,sbrx,sbry);
+return tmpRect}_GetViewFrustum(){if(this._isViewFrustumChanged){this._UpdateViewFrustum();this._isViewFrustumChanged=false}return this._viewFrustum}_UpdateViewFrustum(){const renderer=this._runtime.GetRenderer();const matP=this._GetProjectionMatrix(renderer);const matMV=this._GetModelViewMatrix(renderer);this._viewFrustum.CalculatePlanes(matMV,matP)}_IsPointBehindNearPlane(x,y,z){return this._GetViewFrustum().IsBehindNearPlane(x,y,z)}_SaveToJson(){const o={"d":this.IsDynamic(),"s":this.GetOwnScale(),
+"a":this.GetOwnAngle(),"v":this._IsVisibleFlagSet(),"i":this.IsInteractive(),"html":this.IsHTMLElementsLayer(),"bc":this._backgroundColor.toJSON(),"t":this.IsTransparent(),"sx":this._scrollX,"sy":this._scrollY,"hosp":this._hasOwnScrollPosition,"px":this.GetParallaxX(),"py":this.GetParallaxY(),"c":this._color.toJSON(),"sr":this.GetScaleRate(),"fx":this._effectList.SaveToJson(),"cg":this._createdGlobalUids};return o}_LoadFromJson(o){this._isDynamic=!!o["d"];this._scale=o["s"];this._angle=o["a"];this._isVisible=
+!!o["v"];this._isInteractive=o.hasOwnProperty("i")?o["i"]:true;this._isHTMLElementsLayer=!!o["html"];this._backgroundColor.setFromJSON(o["bc"]);this._isTransparent=!!o["t"];if(o.hasOwnProperty("sx"))this._scrollX=o["sx"];if(o.hasOwnProperty("sy"))this._scrollY=o["sy"];if(o.hasOwnProperty("hosp"))this._hasOwnScrollPosition=!!o["hosp"];this._parallaxX=o["px"];this._parallaxY=o["py"];this._color.setFromJSON(o["c"]);this._UpdatePremultipliedColor();this._scaleRate=o["sr"];C3.shallowAssignArray(this._createdGlobalUids,
+o["cg"]);C3.shallowAssignArray(this._initialInstances,this._startupInitialInstances);const tempSet=new Set(this._createdGlobalUids);let j=0;for(let i=0,len=this._initialInstances.length;i{const firstZIndex=f.GetWorldInfo().GetSceneGraphZIndex();const secondZIndex=s.GetWorldInfo().GetSceneGraphZIndex();return firstZIndex-secondZIndex});return}if(inst.HasChildren()){const instances=[...inst.allChildren()];instances.push(inst);instances.sort((f,s)=>{const firstZIndex=
+f.GetWorldInfo().GetSceneGraphZIndex();const secondZIndex=s.GetWorldInfo().GetSceneGraphZIndex();return firstZIndex-secondZIndex});for(const instanceToAdd of instances){if(!instanceToAdd.IsInContainer())continue;for(const instanceToAddSibling of instanceToAdd.siblings()){if(instances.includes(instanceToAddSibling))continue;const siblingAndChildren=[...instanceToAddSibling.allChildren()];siblingAndChildren.push(instanceToAddSibling);siblingAndChildren.sort((f,s)=>{const firstZIndex=f.GetWorldInfo().GetSceneGraphZIndex();
+const secondZIndex=s.GetWorldInfo().GetSceneGraphZIndex();return firstZIndex-secondZIndex});if(!siblingAndChildren||!siblingAndChildren.length)continue;instances.splice(instances.length,0,...siblingAndChildren)}}for(const instance of instances)if(instance.GetPlugin().IsWorldType())this._AddInstance(instance,true)}else{if(inst.GetPlugin().IsWorldType())this._AddInstance(inst,true);if(!inst.IsInContainer())return;for(const sibling of inst.siblings()){const siblingAndChildren=[...sibling.allChildren()];
+siblingAndChildren.push(sibling);siblingAndChildren.sort((f,s)=>{const firstZIndex=f.GetWorldInfo().GetSceneGraphZIndex();const secondZIndex=s.GetWorldInfo().GetSceneGraphZIndex();return firstZIndex-secondZIndex});if(!siblingAndChildren||!siblingAndChildren.length)continue;for(const instance of siblingAndChildren)if(instance.GetPlugin().IsWorldType())this._AddInstance(instance,true)}}}};
+
+}
+
+// layouts/layout.js
+{
+'use strict';const C3=self.C3;const C3Debugger=self.C3Debugger;const assert=self.assert;const tempDestRect=C3.New(C3.Rect);const tempSrcRect=C3.New(C3.Rect);const tempLayoutRect=C3.New(C3.Rect);const tempColor=C3.New(C3.Color);const glMatrix=self.glMatrix;const vec3=glMatrix.vec3;const tempRender3dList=[];const tempInstanceList1=[];const tempInstanceList2=[];const tempInstanceList3=[];function vec3EqualsXYZ(v,x,y,z){return v[0]===Math.fround(x)&&v[1]===Math.fround(y)&&v[2]===Math.fround(z)}
+let lastLayerPreparedForDrawing=null;function MaybePrepareLayerDraw(layer,renderer){if(lastLayerPreparedForDrawing===layer)return;layer.PrepareForDraw(renderer);lastLayerPreparedForDrawing=layer}
+C3.Layout=class Layout extends C3.DefendedBase{constructor(layoutManager,index,data){super();this._layoutManager=layoutManager;this._runtime=layoutManager.GetRuntime();this._name=data[0];this._originalWidth=data[1];this._originalHeight=data[2];this._width=data[1];this._height=data[2];this._isUnboundedScrolling=!!data[3];this._isOrthographicProjection=!!data[4];this._vanishingPointX=data[5];this._vanishingPointY=data[6];this._eventSheetName=data[7];this._eventSheet=null;this._sid=data[8];this._index=
+index;this._scrollX=0;this._scrollY=0;this._scale=1;this._angle=0;this._initialObjectClasses=new Set;this._textureLoadedTypes=new Set;this._textureLoadPendingPromises=new Set;this._createdInstances=[];this._createdPersistedInstances=[];this._createdPersistedInstancesToDataMap=new Map;this._createdPersistedIndexToInstanceMap=new Map;this._initialNonWorld=[];this._is3dCameraEnabled=false;this._cam3dposition=vec3.create();this._cam3dlook=vec3.create();this._cam3dup=vec3.create();this._rootLayers=[];
+this._allLayersFlat=[];this._layersByName=new Map;this._layersBySid=new Map;this._pendingSetHTMLLayerCount=-1;const canvasManager=this._runtime.GetCanvasManager();this._effectList=C3.New(C3.EffectList,this,data[11]);this._effectChain=C3.New(C3.Gfx.EffectChain,canvasManager.GetEffectChainManager(),{drawContent:(renderer,effectChain)=>{const layout=effectChain.GetContentObject();const renderSurface=layout.GetRenderTarget();renderer.ResetColor();renderer.DrawRenderTarget(renderSurface);renderer.InvalidateRenderTarget(renderSurface);
+canvasManager.ReleaseAdditionalRenderTarget(renderSurface)},getShaderParameters:index=>this.GetEffectList()._GetEffectChainShaderParametersForIndex(index)});this._needsRebuildEffectChainSteps=true;this._wasFullScreenQualityLow=false;this._curRenderTarget=null;this._persistData={};this._persistedIntances=new Map;this._isFirstVisit=true;this._iLayout=new self.ILayout(this);this._userScriptDispatcher=C3.New(C3.Event.Dispatcher);for(const layerData of data[9])this._rootLayers.push(C3.Layer.CreateFromExportData(this,
+null,layerData));this._ReindexLayers();for(const layer of this.allLayers())layer._InitInitialInstances();for(const instData of data[10]){const objectClass=this._runtime.GetObjectClassByIndex(instData[1]);if(!objectClass)throw new Error("missing nonworld object class");if(!objectClass.GetDefaultInstanceData())objectClass.SetDefaultInstanceData(instData);this._initialNonWorld.push(instData);this._AddInitialObjectClass(objectClass)}}Release(){for(const l of this._allLayersFlat)l.Release();C3.clearArray(this._allLayersFlat);
+this._textureLoadPendingPromises.clear();this._eventSheet=null;this._layoutManager=null;this._runtime=null}GetRuntime(){return this._runtime}GetName(){return this._name}GetSID(){return this._sid}GetIndex(){return this._index}GetEffectList(){return this._effectList}GetEffectChain(){this._MaybeRebuildEffectChainSteps();return this._effectChain}_MaybeRebuildEffectChainSteps(){const isFullscreenQualityLow=this._runtime.GetCanvasManager().GetCurrentFullscreenScalingQuality()==="low";if(!this._needsRebuildEffectChainSteps&&
+this._wasFullScreenQualityLow===isFullscreenQualityLow&&!this._effectChain.NeedsRebuild())return;const activeEffectTypes=this.GetEffectList().GetActiveEffectTypes();this._effectChain.BuildSteps(activeEffectTypes.map(e=>e.GetShaderProgram()),{indexMap:activeEffectTypes.map(e=>e.GetIndex()),forcePostDraw:isFullscreenQualityLow,useFullSurface:true});this._needsRebuildEffectChainSteps=false;this._wasFullScreenQualityLow=isFullscreenQualityLow}UpdateActiveEffects(){this.GetEffectList().UpdateActiveEffects();
+this._needsRebuildEffectChainSteps=true}GetMinLayerScale(){let m=this._allLayersFlat[0].GetNormalScale();for(let i=1,len=this._allLayersFlat.length;irbound)x=rbound;if(xbbound)y=bbound;if(y1||vpY<0||vpY>1}SetPerspectiveProjection(){if(!this._isOrthographicProjection)return;this._isOrthographicProjection=false;this._SetAllLayersProjectionChanged();this._SetAllLayersMVChanged();this._runtime.UpdateRender()}SetOrthographicProjection(){if(this._isOrthographicProjection)return;
+this._isOrthographicProjection=true;this._SetAllLayersProjectionChanged();this._SetAllLayersMVChanged();this._runtime.UpdateRender()}IsOrthographicProjection(){return this._isOrthographicProjection}IsPerspectiveProjection(){return!this.IsOrthographicProjection()}Set3DCameraEnabled(e){e=!!e;if(this._is3dCameraEnabled===e)return;this._is3dCameraEnabled=e;this._SetAllLayersMVChanged();this._runtime.UpdateRender()}Is3DCameraEnabled(){return this._is3dCameraEnabled}Set3DCameraOrientation(camX,camY,camZ,
+lookX,lookY,lookZ,upX,upY,upZ){if(vec3EqualsXYZ(this._cam3dposition,camX,camY,camZ)&&vec3EqualsXYZ(this._cam3dlook,lookX,lookY,lookZ)&&vec3EqualsXYZ(this._cam3dup,upX,upY,upZ))return;vec3.set(this._cam3dposition,camX,camY,camZ);vec3.set(this._cam3dlook,lookX,lookY,lookZ);vec3.set(this._cam3dup,upX,upY,upZ);this.Set3DCameraChanged()}Set3DCameraChanged(){this._SetAllLayersMVChanged();this._runtime.UpdateRender()}Get3DCameraPosition(){return this._cam3dposition}Get3DCameraLookAt(){return this._cam3dlook}Get3DCameraUpVector(){return this._cam3dup}GetScale(){return this._scale}SetScale(s){if(this._scale===
+s)return;this._scale=s;this._SetAllLayersMVChanged();this.BoundScrolling();this._runtime.UpdateRender()}SetAngle(a){a=C3.clampAngle(a);if(this._angle===a)return;this._angle=a;this._SetAllLayersMVChanged();this._runtime.UpdateRender()}GetAngle(){return this._angle}GetWidth(){return this._width}SetWidth(w){if(!isFinite(w)||w<1)return;this._width=w}GetHeight(){return this._height}SetHeight(h){if(!isFinite(h)||h<1)return;this._height=h}GetEventSheet(){return this._eventSheet}_GetRootLayers(){return this._rootLayers}*allLayers(){for(const rootLayer of this._rootLayers)yield*rootLayer.selfAndAllSubLayers()}GetLayers(){return this._allLayersFlat}GetLayerCount(){return this._allLayersFlat.length}GetLayer(p){if(typeof p===
+"number")return this.GetLayerByIndex(p);else return this.GetLayerByName(p.toString())}GetLayerByIndex(i){i=C3.clamp(Math.floor(i),0,this._allLayersFlat.length-1);return this._allLayersFlat[i]}GetLayerByName(name){return this._layersByName.get(name.toLowerCase())||null}HasLayerByName(name){return!!this.GetLayerByName(name)}GetLayerBySID(sid){return this._layersBySid.get(sid)||null}_SetAllLayersProjectionChanged(){for(const layer of this._allLayersFlat)layer._SetProjectionMatrixChanged()}_SetAllLayersMVChanged(){for(const layer of this._allLayersFlat)layer._SetMVMatrixChanged()}AddLayer(layerName,
+insertBy,where){if(this.HasLayerByName(layerName))throw new Error(`layer name '${layerName}' already in use`);if(!insertBy&&where<2)throw new Error("invalid insert position");const parentLayer=where>=2?insertBy:insertBy.GetParentLayer();const layer=C3.New(C3.Layer,this,parentLayer,{name:layerName,sid:Math.floor(Math.random()*1E15),isDynamic:true});this._InsertLayer(layer,insertBy,where);this.GetRuntime().UpdateRender();this._ReindexAndUpdateAllLayers()}MoveLayer(layer,insertBy,where){if(!insertBy&&
+where<2)throw new Error("invalid insert position");if(layer===insertBy&&where<2)return;this._RemoveLayer(layer);this._InsertLayer(layer,insertBy,where);this.GetRuntime().UpdateRender();this._ReindexAndUpdateAllLayers()}RemoveLayer(layer){if(this._RemoveLayer(layer)){const eventSheetManager=this._runtime.GetEventSheetManager();eventSheetManager.BlockFlushingInstances(true);layer.Release();eventSheetManager.BlockFlushingInstances(false);this.GetRuntime().UpdateRender();this._ReindexAndUpdateAllLayers()}}RemoveAllDynamicLayers(){const toRemove=
+new Set;for(const layer of this.allLayers())if(layer.IsDynamic()&&!layer.HasAnyDynamicParentLayer())toRemove.add(layer);if(toRemove.size===0)return;const eventSheetManager=this._runtime.GetEventSheetManager();eventSheetManager.BlockFlushingInstances(true);for(const layer of toRemove){this._RemoveLayer(layer);layer.Release()}eventSheetManager.BlockFlushingInstances(false);this.GetRuntime().UpdateRender();this._ReindexAndUpdateAllLayers()}_InsertLayer(layer,insertBy,where){if(where>=2)if(insertBy){if(insertBy===
+layer||insertBy.HasParentLayer(layer))throw new Error(`cannot move layer '${layer.GetName()}' to sub-layer of itself`);insertBy._AddSubLayer(layer,where===2);layer._SetParentLayer(insertBy)}else{if(where===2)this._rootLayers.push(layer);else this._rootLayers.unshift(layer);layer._SetParentLayer(null)}else{const parentLayer=insertBy.GetParentLayer();if(parentLayer){if(insertBy.HasParentLayer(layer))throw new Error(`cannot move layer '${layer.GetName()}' to sub-layer of itself`);parentLayer._InsertSubLayer(layer,
+insertBy,where===0);layer._SetParentLayer(parentLayer)}else{let i=this._rootLayers.indexOf(insertBy);if(i===-1)throw new Error("cannot find layer to insert by");if(where===0)++i;this._rootLayers.splice(i,0,layer);layer._SetParentLayer(null)}}}_RemoveLayer(layer){const parentLayer=layer.GetParentLayer();if(parentLayer){parentLayer._RemoveSubLayer(layer);return true}else if(this._rootLayers.length>1){const i=this._rootLayers.indexOf(layer);if(i===-1)throw new Error("cannot find layer to remove");this._rootLayers.splice(i,
+1);return true}return false}_ReindexLayers(){this._allLayersFlat=[...this.allLayers()];this._layersByName.clear();this._layersBySid.clear();for(let i=0,len=this._allLayersFlat.length;ii)break}return ret}SaveTransform(){return{"scrollX":this.GetScrollX(),"scrollY":this.GetScrollY(),"scale":this.GetScale(),"angle":this.GetAngle(),"vpX":this.GetVanishingPointX(),"vpY":this.GetVanishingPointY()}}RestoreTransform(t){this.SetScrollX(t["scrollX"]);this.SetScrollY(t["scrollY"]);this.SetScale(t["scale"]);this.SetAngle(t["angle"]);this.SetVanishingPointXY(t["vpX"],t["vpY"])}GetLayoutBackgroundColor(){let firstDrawLayer=this._rootLayers.filter(l=>
+l.ShouldDraw())[0];while(firstDrawLayer){if(!firstDrawLayer.IsTransparent()){tempColor.copyRgb(firstDrawLayer.GetBackgroundColor());tempColor.setA(1);return tempColor}else if(firstDrawLayer.UsesOwnTexture()){tempColor.setRgba(0,0,0,0);return tempColor}firstDrawLayer=firstDrawLayer.GetSubLayers().filter(l=>l.ShouldDraw())[0]}tempColor.setRgba(0,0,0,0);return tempColor}IsFirstVisit(){return this._isFirstVisit}_GetInitialObjectClasses(){return[...this._initialObjectClasses]}_AddInitialObjectClass(objectClass){if(objectClass.IsInContainer())for(const containerType of objectClass.GetContainer().GetObjectTypes())this._initialObjectClasses.add(containerType);
+else this._initialObjectClasses.add(objectClass)}_GetTextureLoadedObjectTypes(){return[...this._textureLoadedTypes]}_Load(previousLayout,renderer){if(previousLayout===this||!renderer)return Promise.resolve();if(previousLayout){C3.CopySet(this._textureLoadedTypes,previousLayout._textureLoadedTypes);previousLayout._textureLoadedTypes.clear()}const promises=[];for(const oc of this._initialObjectClasses)if(!this._textureLoadedTypes.has(oc)){promises.push(oc.LoadTextures(renderer));this._textureLoadedTypes.add(oc)}return Promise.all(promises)}async MaybeLoadTexturesFor(objectClass){if(objectClass.IsFamily())throw new Error("cannot load textures for family");
+const renderer=this._runtime.GetRenderer();if(!renderer||renderer.IsContextLost()||this._textureLoadedTypes.has(objectClass))return;this._textureLoadedTypes.add(objectClass);const loadPromise=objectClass.LoadTextures(renderer);this._AddPendingTextureLoadPromise(loadPromise);await loadPromise;objectClass.OnDynamicTextureLoadComplete();this._runtime.UpdateRender()}_AddPendingTextureLoadPromise(promise){this._textureLoadPendingPromises.add(promise);promise.then(()=>this._textureLoadPendingPromises.delete(promise)).catch(()=>
+this._textureLoadPendingPromises.delete(promise))}WaitForPendingTextureLoadsToComplete(){return Promise.all([...this._textureLoadPendingPromises])}MaybeUnloadTexturesFor(objectClass){if(objectClass.IsFamily()||objectClass.GetInstanceCount()>0)throw new Error("cannot unload textures");const renderer=this._runtime.GetRenderer();if(!renderer||!this._textureLoadedTypes.has(objectClass))return;this._textureLoadedTypes.delete(objectClass);objectClass.ReleaseTextures(renderer)}_Unload(nextLayout,renderer){if(nextLayout===
+this||!renderer)return;for(const oc of this._textureLoadedTypes)if(!oc.IsGlobal()&&!nextLayout._initialObjectClasses.has(oc)){oc.ReleaseTextures();this._textureLoadedTypes.delete(oc)}}_OnRendererContextLost(){this._textureLoadedTypes.clear()}async _StartRunning(isFirstLayout){const runtime=this._runtime;const layoutManager=this._layoutManager;const eventSheetManager=runtime.GetEventSheetManager();if(this._eventSheetName){this._eventSheet=eventSheetManager.GetEventSheetByName(this._eventSheetName);
+this._eventSheet._UpdateDeepIncludes()}layoutManager._SetMainRunningLayout(this);this._width=this._originalWidth;this._height=this._originalHeight;this._scrollX=runtime.GetOriginalViewportWidth()/2;this._scrollY=runtime.GetOriginalViewportHeight()/2;this.BoundScrolling();this._SetAllLayersProjectionChanged();this._SetAllLayersMVChanged();this._ReindexHTMLLayers();await this._runtime.GetCanvasManager().SetHTMLLayerCount(this.GetHTMLLayerCount(),true);this._MoveGlobalObjectsToThisLayout(isFirstLayout);
+this._runtime.SetUsingCreatePromises(true);this._CreateInitialInstances();if(!this._isFirstVisit)this._CreatePersistedInstances();this._CreateAndLinkContainerInstances(this._createdInstances);this._CreateAndLinkContainerInstances(this._createdPersistedInstances);this._CreateInitialNonWorldInstances();layoutManager.ClearPendingChangeLayout();runtime.FlushPendingInstances();this._runtime.SetUsingCreatePromises(false);const createPromises=this._runtime.GetCreatePromises();await Promise.all(createPromises);
+C3.clearArray(createPromises);if(!runtime.IsLoadingState()){for(const inst of this._createdInstances)inst.SetupInitialSceneGraphConnections();for(const inst of this._createdPersistedInstances)inst.SetupPersistedSceneGraphConnections(this._createdPersistedInstancesToDataMap,this._createdPersistedIndexToInstanceMap);for(const [sidStr,typeData]of Object.entries(this._persistData)){const objectClass=this._runtime.GetObjectClassBySID(parseInt(sidStr,10));if(!objectClass||objectClass.IsFamily()||!objectClass.HasPersistBehavior())continue;
+C3.clearArray(typeData)}for(const inst of this._createdInstances)inst._TriggerOnCreated();for(const inst of this._createdPersistedInstances)inst._TriggerOnCreated()}C3.clearArray(this._createdInstances);C3.clearArray(this._createdPersistedInstances);this._createdPersistedInstancesToDataMap.clear();this._createdPersistedIndexToInstanceMap.clear();await Promise.all([...this._initialObjectClasses].map(oc=>oc.PreloadTexturesWithInstances(this._runtime.GetRenderer())));if(isFirstLayout){runtime.Dispatcher().dispatchEvent(new C3.Event("beforefirstlayoutstart"));
+await runtime.DispatchUserScriptEventAsyncWait(new C3.Event("beforeprojectstart"))}runtime.Dispatcher().dispatchEvent(new C3.Event("beforelayoutstart"));await this.DispatchUserScriptEventAsyncWait(new C3.Event("beforelayoutstart"));if(!runtime.IsLoadingState())await runtime.TriggerAsync(C3.Plugins.System.Cnds.OnLayoutStart,null,null);runtime.Dispatcher().dispatchEvent(new C3.Event("afterlayoutstart"));await this.DispatchUserScriptEventAsyncWait(new C3.Event("afterlayoutstart"));if(isFirstLayout){runtime.Dispatcher().dispatchEvent(new C3.Event("afterfirstlayoutstart"));
+await runtime.DispatchUserScriptEventAsyncWait(new C3.Event("afterprojectstart"))}eventSheetManager._RunQueuedTriggers(layoutManager);await this.WaitForPendingTextureLoadsToComplete();this._isFirstVisit=false}_MoveGlobalObjectsToThisLayout(isFirstLayout){for(const objectClass of this._runtime.GetAllObjectClasses()){if(objectClass.IsFamily()||!objectClass.IsWorldType())continue;for(const inst of objectClass.GetInstances()){const wi=inst.GetWorldInfo();const oldLayer=wi.GetLayer();const layerIndex=
+C3.clamp(oldLayer.GetIndex(),0,this._allLayersFlat.length-1);const newLayer=this._allLayersFlat[layerIndex];wi._SetLayer(newLayer,true);newLayer._MaybeAddInstance(inst)}}if(!isFirstLayout)for(const layer of this._allLayersFlat)layer._SortInstancesByLastCachedZIndex(false)}_CreateInitialInstances(){for(const layer of this._allLayersFlat){layer.CreateInitialInstances(this._createdInstances);layer._Start()}}_CreatePersistedInstances(){let uidsChanged=false;for(const [sidStr,typeData]of Object.entries(this._persistData)){const objectClass=
+this._runtime.GetObjectClassBySID(parseInt(sidStr,10));if(!objectClass||objectClass.IsFamily()||!objectClass.HasPersistBehavior())continue;for(const instData of typeData){let layer=null;if(objectClass.IsWorldType()){if(instData.hasOwnProperty("instJson"))layer=this.GetLayerBySID(instData["instJson"]["w"]["l"]);else layer=this.GetLayerBySID(instData["w"]["l"]);if(!layer)continue}const inst=this._runtime.CreateInstanceFromData(objectClass,layer,false,0,0,true);if(instData.hasOwnProperty("instJson"))inst.LoadFromJson(instData["instJson"]);
+else inst.LoadFromJson(instData);uidsChanged=true;this._createdPersistedInstances.push(inst);if(instData.hasOwnProperty("instJson")){this._createdPersistedInstancesToDataMap.set(inst,instData);this._createdPersistedIndexToInstanceMap.set(instData["index"],inst)}}}for(const layer of this._allLayersFlat){layer._SortInstancesByLastCachedZIndex(true);layer.SetZIndicesChanged()}if(uidsChanged){this._runtime.FlushPendingInstances();this._runtime._RefreshUidMap()}}_CreateAndLinkContainerInstances(createdInstances){for(const inst of createdInstances){if(!inst.IsInContainer())continue;
+const wi=inst.GetWorldInfo();const iid=inst.GetIID();for(const containerType of inst.GetObjectClass().GetContainer().objectTypes()){if(containerType===inst.GetObjectClass())continue;const instances=containerType.GetInstances();if(instances.length>iid)inst._AddSibling(instances[iid]);else{let s;if(wi)s=this._runtime.CreateInstanceFromData(containerType,wi.GetLayer(),true,wi.GetX(),wi.GetY(),true);else s=this._runtime.CreateInstanceFromData(containerType,null,true,0,0,true);this._runtime.FlushPendingInstances();
+containerType._UpdateIIDs();inst._AddSibling(s);createdInstances.push(s)}}}}_CreateInitialNonWorldInstances(){for(const instData of this._initialNonWorld){const objectClass=this._runtime.GetObjectClassByIndex(instData[1]);if(!objectClass.IsInContainer())this._runtime.CreateInstanceFromData(instData,null,true)}}_CreateGlobalNonWorlds(){const createdInstances=[];const initialNonWorld=this._initialNonWorld;let k=0;for(let i=0,len=initialNonWorld.length;il.ShouldDraw());for(let i=0,len=layersToDraw.length;i=2||tempRender3dList.length===1&&tempRender3dList[0].HasAnyVisibleSubLayer()){this._Draw3DLayers(renderer,destRenderTarget,tempRender3dList);i+=tempRender3dList.length;C3.clearArray(tempRender3dList);continue}C3.clearArray(tempRender3dList)}layer.Draw(renderer,
+destRenderTarget,canCopyFirstLayer&&i===0);++i}}_DrawLayoutOwnTextureToRenderTarget(renderer,ownRenderTarget){const activeEffectTypes=this._effectList.GetActiveEffectTypes();const runtime=this._runtime;if(activeEffectTypes.length===0){renderer.SetRenderTarget(null);renderer.SetTextureFillMode();renderer.CopyRenderTarget(ownRenderTarget);renderer.InvalidateRenderTarget(ownRenderTarget);runtime.ReleaseAdditionalRenderTarget(ownRenderTarget)}else{tempLayoutRect.set(0,0,runtime.GetViewportWidth(),runtime.GetViewportHeight());
+this.GetEffectChain().Render(renderer,null,{contentObject:this,blendMode:3,devicePixelRatio:this._runtime.GetEffectDevicePixelRatioParam(),layerScale:this._runtime.GetEffectLayerScaleParam()*this.GetScale(),layerAngle:this.GetAngle(),layoutRect:tempLayoutRect,drawSurfaceRect:null,invalidateRenderTargets:true})}}_Draw3DLayers(renderer,renderTarget,layerList){if(!layerList[0].IsTransparent()){tempColor.copyRgb(layerList[0].GetBackgroundColor());tempColor.setA(1);renderer.Clear(tempColor)}const canvasManager=
+this._runtime.GetCanvasManager();renderer.SetDepthEnabled(true);const fullInstanceList=tempInstanceList1;const coplanarInstances=tempInstanceList2;const postRenderInstances=tempInstanceList3;for(const layer of layerList){layer._UpdateZIndices();layer._AppendAllInstancesIncludingSubLayersInDrawOrder(fullInstanceList)}const firstLayer=layerList[0];let layerQuery=null;if(this._runtime.IsGPUProfiling())if(renderer.IsWebGL()){const timingsBuffer=canvasManager.GetLayerTimingsBuffer(firstLayer);if(timingsBuffer){layerQuery=
+timingsBuffer.AddTimeElapsedQuery();renderer.StartQuery(layerQuery)}}else if(renderer.IsWebGPU())renderer.WriteTimestamp((firstLayer.GetIndex()+1)*2);for(let i=0,len=fullInstanceList.length;i0)postRenderInstances.push(inst);const startZ=inst.GetWorldInfo().GetTotalZElevation();coplanarInstances.push(inst);
+let endIndex=i+1;for(;endIndex0)postRenderInstances.push(nextInst);coplanarInstances.push(nextInst)}if(coplanarInstances.length===1&&!coplanarInstances[0].MustMitigateZFighting()){MaybePrepareLayerDraw(wiLayer,
+renderer);wiLayer._DrawInstanceMaybeWithEffects(inst,wi,renderer,renderTarget);for(let j=0,lenj=postRenderInstances.length;j=0;--i){const dld=dynamicLayersData[i];const sid=dld["sid"];const layerName=dld["name"];const parentSid=dld["parentSid"];const siblingIndex=dld["siblingIndex"];const layerData=dld["data"];this._ReindexLayers();if(this.HasLayerByName(layerName)||
+this.GetLayerBySID(sid))continue;let parentLayer;let parentLayerArr;if(parentSid===null){parentLayer=null;parentLayerArr=this._rootLayers}else{parentLayer=this.GetLayerBySID(parentSid);if(!parentLayer)continue;parentLayerArr=parentLayer.GetSubLayers()}const layer=C3.New(C3.Layer,this,parentLayer,{name:layerName,sid,isDynamic:true});parentLayerArr.push(layer);let arr=reorderLayers.get(parentLayerArr);if(!arr){arr=[];reorderLayers.set(parentLayerArr,arr)}arr.push({layer,siblingIndex});layer._LoadFromJson(layerData)}for(const [parentLayerArr,
+reorderArr]of reorderLayers){reorderArr.sort((a,b)=>a.siblingIndex-b.siblingIndex);for(const r of reorderArr){const layer=r.layer;const siblingIndex=r.siblingIndex;let i=parentLayerArr.indexOf(layer);parentLayerArr.splice(i,1);parentLayerArr.splice(siblingIndex,0,layer)}}}this._ReindexAndUpdateAllLayers();this._SetAllLayersProjectionChanged();this._SetAllLayersMVChanged()}GetILayout(){return this._iLayout}UserScriptDispatcher(){return this._userScriptDispatcher}DispatchUserScriptEvent(e){e.layout=
+this.GetILayout();const runtime=this._runtime;const shouldTime=runtime.IsDebug()&&!runtime.GetEventSheetManager().IsInEventEngine();if(shouldTime)C3Debugger.StartMeasuringScriptTime();this._userScriptDispatcher.dispatchEvent(e);if(shouldTime)C3Debugger.AddScriptTime()}DispatchUserScriptEventAsyncWait(e){e.layout=this.GetILayout();return this._userScriptDispatcher.dispatchEventAndWaitAsync(e)}_LogLayerTree(){this._LogLayerList(this._rootLayers)}_LogLayerList(layersArr,indent=0){const layersRev=layersArr.slice(0);
+layersRev.reverse();for(const layer of layersRev){console.log(`${"\t".repeat(indent)}- ${layer.GetName()}`);this._LogLayerList(layer.GetSubLayers(),indent+1)}}};
+
+}
+
+// layouts/layoutManager.js
+{
+'use strict';const C3=self.C3;
+C3.LayoutManager=class LayoutManager extends C3.DefendedBase{constructor(runtime){super();this._runtime=runtime;this._allLayouts=[];this._layoutsByName=new Map;this._layoutsBySid=new Map;this._mainRunningLayout=null;this._runningSubLayouts=[];this._firstLayout=null;this._isEndingLayout=0;this._pendingChangeLayout=null}Release(){this._runtime=null;this._mainRunningLayout=null;this._firstLayout=null;this._pendingChangeLayout=null;C3.clearArray(this._allLayouts);this._layoutsByName.clear();this._layoutsBySid.clear();
+C3.clearArray(this._runningSubLayouts)}Create(layoutData){const layout=C3.New(C3.Layout,this,this._allLayouts.length,layoutData);this._allLayouts.push(layout);this._layoutsByName.set(layout.GetName().toLowerCase(),layout);this._layoutsBySid.set(layout.GetSID(),layout)}GetRuntime(){return this._runtime}SetFirstLayout(layout){this._firstLayout=layout}GetFirstLayout(){if(this._firstLayout)return this._firstLayout;if(this._allLayouts.length)return this._allLayouts[0];throw new Error("no first layout");
+}GetLayoutByName(name){return this._layoutsByName.get(name.toLowerCase())||null}GetLayoutBySID(sid){return this._layoutsBySid.get(sid)||null}GetLayoutByIndex(index){index=C3.clamp(Math.floor(index),0,this._allLayouts.length-1);return this._allLayouts[index]}GetLayout(p){if(typeof p==="number")return this.GetLayoutByIndex(p);else return this.GetLayoutByName(p.toString())}GetAllLayouts(){return this._allLayouts}_SetMainRunningLayout(layout){this._mainRunningLayout=layout}GetMainRunningLayout(){return this._mainRunningLayout}_AddRunningSubLayout(layout){if(this._runningSubLayouts.includes(layout))throw new Error("layout already running");
+this._runningSubLayouts.push(layout)}_RemoveRunningSubLayout(layout){const i=this._runningSubLayouts.indexOf(layout);if(i===-1)throw new Error("layout not running");this._runningSubLayouts.splice(i,1)}*runningLayouts(){if(this._mainRunningLayout)yield this._mainRunningLayout;if(this._runningSubLayouts.length)yield*this._runningSubLayouts}IsLayoutRunning(layout){return this._mainRunningLayout===layout||this._runningSubLayouts.includes(layout)}SetIsEndingLayout(e){if(e)this._isEndingLayout++;else{if(this._isEndingLayout<=
+0)throw new Error("already unset");this._isEndingLayout--}}IsEndingLayout(){return this._isEndingLayout>0}ChangeMainLayout(layout){this._pendingChangeLayout=layout}ClearPendingChangeLayout(){this._pendingChangeLayout=null}IsPendingChangeMainLayout(){return!!this._pendingChangeLayout}GetPendingChangeMainLayout(){return this._pendingChangeLayout}SetAllLayerProjectionChanged(){const runningLayout=this.GetMainRunningLayout();if(!runningLayout)return;runningLayout._SetAllLayersProjectionChanged()}SetAllLayerMVChanged(){const runningLayout=
+this.GetMainRunningLayout();if(!runningLayout)return;runningLayout._SetAllLayersMVChanged()}};
+
+}
+
+// timelines/timelineManager.js
+{
+'use strict';const C3=self.C3;const NAMES_REGEXP=new RegExp("<(.+?)>","g");
+C3.TimelineManager=class TimelineManager extends C3.DefendedBase{constructor(runtime){super();this._runtime=runtime;this._timelineDataManager=C3.New(C3.TimelineDataManager);this._pluginInstance=null;this._timelines=[];this._timelinesByName=new Map;this._objectClassToTimelineMap=new Map;this._timelinesCreatedByTemplate=new Map;this._scheduledTimelines=[];this._playingTimelines=[];this._markedForRemovalTimelines=[];this._hasRuntimeListeners=false;this._changingLayout=false;this._isTickingTimelines=
+false;this._tickFunc=()=>this._OnTick();this._tick2Func=()=>this._OnTick2();this._beforeLayoutChange=()=>this._OnBeforeChangeLayout();this._layoutChange=()=>this._OnAfterChangeLayout();this._instanceDestroy=e=>this._OnInstanceDestroy(e.instance);this._beforeLoad=e=>this._OnBeforeLoad();this._afterLoad=e=>this._OnAfterLoad();this._afterLayoutStart=e=>this._OnAfterLayoutStart();this._destroyedWhileLoadingState=[];this._renderChange=0}Release(){this.RemoveRuntimeListeners();this._tickFunc=null;this._tick2Func=
+null;this._beforeLayoutChange=null;this._layoutChange=null;this._instanceDestroy=null;this._afterLoad=null;for(const timeline of this._timelines){timeline.Stop();timeline.Release()}C3.clearArray(this._timelines);this._timelines=null;this._timelineDataManager.Release();this._timelineDataManager=null;C3.clearArray(this._scheduledTimelines);this._scheduledTimelines=null;C3.clearArray(this._playingTimelines);this._playingTimelines=null;C3.clearArray(this._markedForRemovalTimelines);this._markedForRemovalTimelines=
+null;this._timelinesByName.clear();this._timelinesByName=null;this._objectClassToTimelineMap.clear();this._objectClassToTimelineMap=null;this._timelinesCreatedByTemplate.clear();this._timelinesCreatedByTemplate=null;C3.clearArray(this._destroyedWhileLoadingState);this._destroyedWhileLoadingState=null;this._runtime=null}AddRuntimeListeners(){const dispatcher=this._runtime.Dispatcher();dispatcher.addEventListener("pretick",this._tickFunc);dispatcher.addEventListener("tick2",this._tick2Func);dispatcher.addEventListener("beforelayoutchange",
+this._beforeLayoutChange);dispatcher.addEventListener("layoutchange",this._layoutChange);dispatcher.addEventListener("instancedestroy",this._instanceDestroy);dispatcher.addEventListener("beforeload",this._beforeLoad);dispatcher.addEventListener("afterload",this._afterLoad);dispatcher.addEventListener("afterlayoutstart",this._afterLayoutStart)}RemoveRuntimeListeners(){const dispatcher=this._runtime.Dispatcher();dispatcher.removeEventListener("pretick",this._tickFunc);dispatcher.removeEventListener("tick2",
+this._tick2Func);dispatcher.removeEventListener("beforelayoutchange",this._beforeLayoutChange);dispatcher.removeEventListener("layoutchange",this._layoutChange);dispatcher.removeEventListener("instancedestroy",this._instanceDestroy);dispatcher.removeEventListener("beforeload",this._beforeLoad);dispatcher.removeEventListener("afterload",this._afterLoad);dispatcher.removeEventListener("afterlayoutstart",this._afterLayoutStart)}Create(timelineData){this._timelineDataManager.Add(timelineData);const timeline=
+C3.TimelineState.CreateInitial(timelineData,this);this.Add(timeline);this.SetTimelineObjectClassesToMap(timeline);this._timelinesCreatedByTemplate.set(timeline.GetName(),0)}CreateFromTemplate(template){const timelineDataManager=this.GetTimelineDataManager();const templateName=template.GetTemplateName();const timelineDataItem=timelineDataManager.Get(templateName);const timeline=C3.TimelineState.CreateFromTemplate(`${templateName}:${this._timelinesCreatedByTemplate.get(templateName)}`,timelineDataItem,
+this);this._IncreaseTemplateTimelinesCount(templateName);this.Add(timeline);return timeline}_IncreaseTemplateTimelinesCount(templateName){this._timelinesCreatedByTemplate.set(templateName,this._timelinesCreatedByTemplate.get(templateName)+1)}_SetCreatedTemplateTimelinesCount(){for(const timeline of this._timelines){if(timeline.IsTemplate())continue;const templateName=timeline.GetTemplateName();this._IncreaseTemplateTimelinesCount(templateName)}}_ClearCreatedTemplateTimelinesCount(){for(const templateName of this._timelinesCreatedByTemplate.keys())this._timelinesCreatedByTemplate.set(templateName,
+0)}Add(timeline){this._timelines.push(timeline);this._timelinesByName.set(timeline.GetName().toLowerCase(),timeline)}Remove(timeline){timeline.Removed();if(timeline.IsTemplate())return;C3.arrayFindRemove(this._timelines,timeline);C3.arrayFindRemove(this._scheduledTimelines,timeline);C3.arrayFindRemove(this._playingTimelines,timeline);C3.arrayFindRemove(this._markedForRemovalTimelines,timeline);this._timelinesByName.delete(timeline.GetName().toLowerCase());this.RemoveTimelineFromObjectClassMap(timeline);
+if(!timeline.IsReleased())timeline.Release()}Trigger(method){this._runtime.Trigger(method,this._pluginInstance,null)}GetRuntime(){return this._runtime}GetTimelineDataManager(){return this._timelineDataManager}SetPluginInstance(inst){this._pluginInstance=inst}GetPluginInstance(){return this._pluginInstance}*GetTimelines(){for(const timeline of this._timelines)yield timeline}*GetPlayingTimelines(){for(const timeline of this._playingTimelines)yield timeline}SetTimelineObjectClassToMap(objectClass,timeline){if(!this._objectClassToTimelineMap.has(objectClass))this._objectClassToTimelineMap.set(objectClass,
+new Set);this._objectClassToTimelineMap.get(objectClass).add(timeline)}SetTimelineObjectClassesToMap(timeline){for(const objectClass of timeline.GetObjectClasses())this.SetTimelineObjectClassToMap(objectClass,timeline)}RemoveTimelineFromObjectClassMap(timeline){for(const [objectClass,timelines]of this._objectClassToTimelineMap.entries())if(timelines.has(timeline)){timelines.delete(timeline);if(timelines.size===0)this._objectClassToTimelineMap.delete(objectClass)}}GetTimelinesForObjectClass(objectClass){if(!this._objectClassToTimelineMap.has(objectClass))return;
+return this._objectClassToTimelineMap.get(objectClass)}GetTimelineOfTemplateForInstances(templateTimeline,instancesObject){if(!instancesObject)return;for(const timeline of this._timelines){const found=instancesObject.every(io=>{return timeline.HasTrackInstance(io.instance,io.trackId)});if(found)if(timeline.GetName().includes(templateTimeline.GetName()))return timeline}}GetTimelineByName(name){return this._timelinesByName.get(name.toLowerCase())||null}GetScheduledOrPlayingTimelineByName(name){for(const timeline of this._scheduledTimelines)if(timeline.GetName()===
+name)return timeline;for(const timeline of this._playingTimelines)if(timeline.GetName()===name)return timeline;return null}*GetTimelinesByName(name){if(NAMES_REGEXP.test(name)){NAMES_REGEXP.lastIndex=0;let match;const uniqueNames=new Set;do{match=NAMES_REGEXP.exec(name);if(match){const names=match[1].split(",");for(const name of names)uniqueNames.add(name)}}while(match);for(const name of uniqueNames.values()){const timeline=this.GetTimelineByName(name);if(timeline)yield timeline}uniqueNames.clear()}else{const timeline=
+this.GetTimelineByName(name);if(timeline)yield timeline}}*GetTimelinesByTags(tags){for(const timeline of this._timelines)if(timeline.HasTags(tags))yield timeline}AddScheduledTimeline(timeline){if(!this._scheduledTimelines.includes(timeline))this._scheduledTimelines.push(timeline);this._MaybeEnableRuntimeListeners()}RemovePlayingTimeline(timeline){C3.arrayFindRemove(this._playingTimelines,timeline);this._MaybeDisableRuntimeListeners()}ScheduleTimeline(timeline){if(this._playingTimelines.includes(timeline)){timeline.SetPlaying(true);
+timeline.SetScheduled(false);timeline.SetMarkedForRemoval(false)}else{timeline.SetPlaying(false);timeline.SetScheduled(true);timeline.SetMarkedForRemoval(false);if(!this._scheduledTimelines.includes(timeline))this._scheduledTimelines.push(timeline)}this._MaybeEnableRuntimeListeners()}DeScheduleTimeline(timeline){timeline.SetPlaying(false);timeline.SetScheduled(false);timeline.ResolvePlayPromise();C3.arrayFindRemove(this._scheduledTimelines,timeline);this._MaybeDisableRuntimeListeners()}CompleteTimeline(timeline){timeline.SetPlaying(false);
+timeline.SetScheduled(false);if(this._playingTimelines.includes(timeline)){timeline.SetMarkedForRemoval(true);this._markedForRemovalTimelines.push(timeline);C3.arrayFindRemove(this._playingTimelines,timeline)}}CompleteTimelineBeforeChangeOfLayout(timeline){timeline.SetPlaying(false);timeline.SetScheduled(false);timeline.SetMarkedForRemoval(false);timeline.SetPlaybackRate(1);C3.arrayFindRemove(this._playingTimelines,timeline)}CompleteTimelineAndResolve(timeline){this.CompleteTimeline(timeline);timeline.ResolvePlayPromise()}_OnTick(){if(this.GetRuntime().IsLoadingState())return;
+if(!this._hasRuntimeListeners)return;if(this._changingLayout)return;this._isTickingTimelines=true;while(this._scheduledTimelines.length){const t=this._scheduledTimelines.pop();t.SetInitialState();if(t.GetRenderChange()!==0)this._renderChange=1;this._playingTimelines.push(t)}const dt=this._runtime._GetDtFast();const dt1=this._runtime.GetDt1();const ts=this._runtime.GetTimeScale();for(let i=this._playingTimelines.length-1;i>=0;i--){const t=this._playingTimelines[i];if(t)t.Tick(dt,ts,dt1)}this._isTickingTimelines=
+false;if(this._renderChange!==0)this.GetRuntime().UpdateRender()}_OnTick2(){if(this.GetRuntime().IsLoadingState())return;if(!this._hasRuntimeListeners)return;if(this._changingLayout)return;let timelinesToRemove;for(let i=0,l=this._markedForRemovalTimelines.length;it)){this._MaybeExecuteTimelineFinishTriggers(timeline);this.Remove(timeline)}for(const timeline of this._playingTimelines.map(t=>
+t)){this._MaybeExecuteTimelineFinishTriggers(timeline);this.Remove(timeline)}}_OnAfterLoad(){for(const destroyedInstance of this._destroyedWhileLoadingState)this._OnInstanceDestroy(destroyedInstance);C3.clearArray(this._destroyedWhileLoadingState)}_OnAfterLayoutStart(){const layoutManager=this._runtime.GetLayoutManager();const runningLayout=layoutManager.GetMainRunningLayout();if(!runningLayout)return;for(const timeline of this._timelines){const startOnLayout=timeline.GetStartOnLayout();if(!startOnLayout)continue;
+if(runningLayout.GetName()===startOnLayout)this.ScheduleTimeline(timeline)}}_SaveToJson(){return{"timelinesJson":this._SaveTimelinesToJson(),"scheduledTimelinesJson":this._SaveScheduledTimelinesToJson(),"playingTimelinesJson":this._SavePlayingTimelinesToJson(),"markedForRemovalTimelinesJson":this._SaveMarkedForRemovalTimelinesToJson(),"hasRuntimeListeners":this._hasRuntimeListeners,"changingLayout":this._changingLayout,"isTickingTimelines":this._isTickingTimelines}}_LoadFromJson(o){if(!o)return;this._ClearCreatedTemplateTimelinesCount();
+this._LoadTimelinesFromJson(o["timelinesJson"]);this._LoadScheduledTimelinesFromJson(o["scheduledTimelinesJson"]);this._LoadPlayingTimelinesFromJson(o["playingTimelinesJson"]);this._LoadMarkedForRemovalTimelinesFromJson(o["markedForRemovalTimelinesJson"]);this._hasRuntimeListeners=!o["hasRuntimeListeners"];this._changingLayout=!!o["changingLayout"];this._isTickingTimelines=!!o["isTickingTimelines"];this._SetCreatedTemplateTimelinesCount();this._MaybeEnableRuntimeListeners();this._MaybeDisableRuntimeListeners()}_SaveTimelinesToJson(){return this._timelines.map(timelineState=>
+timelineState._SaveToJson())}_LoadTimelinesFromJson(timelinesJson){for(const timelineJson of timelinesJson){let timeline=this.GetTimelineByName(timelineJson["name"]);if(timeline)timeline._LoadFromJson(timelineJson);else{const templateName=this._GetTemplateNameFromJson(timelineJson);if(!templateName)continue;const templateTimeline=this.GetTimelineByName(templateName);timeline=this.CreateFromTemplate(templateTimeline);timeline._LoadFromJson(timelineJson)}if(!timeline.HasTracks())this.Remove(timeline)}}_GetTemplateNameFromJson(timelineJson){const name=
+timelineJson["name"];const nameParts=name.split(":");if(!nameParts||nameParts.length!==2)return null;return nameParts[0]}_SaveScheduledTimelinesToJson(){return this._SaveTimelines(this._scheduledTimelines)}_LoadScheduledTimelinesFromJson(scheduledTimelinesJson){this._LoadTimelines(scheduledTimelinesJson,this._scheduledTimelines)}_SavePlayingTimelinesToJson(){return this._SaveTimelines(this._playingTimelines)}_LoadPlayingTimelinesFromJson(playingTimelinesJson){this._LoadTimelines(playingTimelinesJson,
+this._playingTimelines)}_SaveMarkedForRemovalTimelinesToJson(){return this._SaveTimelines(this._markedForRemovalTimelines)}_LoadMarkedForRemovalTimelinesFromJson(markedForRemovalTimelinesJson){this._LoadTimelines(markedForRemovalTimelinesJson,this._markedForRemovalTimelines)}_IsTimelineInJson(timeline,json){if(!json)return false;for(const name of json)if(name===timeline.GetName())return true;return false}_SaveTimelines(collection){return collection.map(t=>t.GetName())}_LoadTimelines(timelinesJson,
+collection){const timelinesToRemove=new Set;for(const timeline of collection)if(!this._IsTimelineInJson(timeline,timelinesJson))timelinesToRemove.add(timeline);C3.arrayRemoveAllInSet(collection,timelinesToRemove);if(timelinesJson){const ff=tn=>t=>t.GetName()===tn;for(const name of timelinesJson){const timeline=this.GetTimelineByName(name);if(timeline){const t=collection.find(ff(name));if(!t)collection.push(timeline)}}}}};
+
+}
+
+// timelines/timelineInfo.js
+{
+'use strict';const C3=self.C3;const STEPS=100;const LENGTH_STEP_SIZE=.01;const BEZIER_STEP_SIZE=30;const TANGENT_RESULT=[0,0];const MAP_RESULT=[0,0];const PROJECTION_RESULT=[0,0,0,0,0];
+C3.TimelineInfo=class TimelineInfo{constructor(timeline,trackId){this._initialized=false;this._timeline=timeline;this._segments=[];let trackState=null;if(trackId)trackState=this._timeline.GetTrackById(trackId);else trackState=C3.first(this._timeline.GetTracks());if(!trackState)return;const xTrack=trackState.GetPropertyTrack("offsetX");const yTrack=trackState.GetPropertyTrack("offsetY");if(!xTrack||!yTrack)return;this._xTrack=xTrack;this._yTrack=yTrack;const xPropertyKeyframes=xTrack.GetPropertyKeyframeDataItemArrayIncludingDisabled();
+const yPropertyKeyframes=yTrack.GetPropertyKeyframeDataItemArrayIncludingDisabled();for(let i=1,len=Math.min(xPropertyKeyframes.length,yPropertyKeyframes.length);if[3]-s[3]);return ret[0]}Tangent(t,segmentIndex){return this._segments[segmentIndex].Tangent(t)}TangentAngle(x,y,t,segmentIndex){return this._segments[segmentIndex].TangentAngle(x,y,t)}};
+C3.TimelineCubicBezierSegmentInfo=class TimelineCubicBezierSegmentInfo{constructor(startX,startY,endX,endY,index){this._index=index;const startXAddon=startX.GetAddOn("cubic-bezier");const endXAddon=endX.GetAddOn("cubic-bezier");const startYAddon=startY.GetAddOn("cubic-bezier");const endYAddon=endY.GetAddOn("cubic-bezier");this._aX=startX.GetValueWithResultMode();this._aY=startY.GetValueWithResultMode();this._bX=startX.GetValueWithResultMode()+startXAddon.GetStartAnchor();this._bY=startY.GetValueWithResultMode()+
+startYAddon.GetStartAnchor();this._cX=endX.GetValueWithResultMode()+endXAddon.GetEndAnchor();this._cY=endY.GetValueWithResultMode()+endYAddon.GetEndAnchor();this._dX=endX.GetValueWithResultMode();this._dY=endY.GetValueWithResultMode();this._initialized=false;this._len=STEPS;this._arcLengths=new Array(this._len+1);this._arcLengths[0]=0;this._length=0;this._lut=[];this._CalculateLength()}Release(){C3.clearArray(this._arcLengths);this._arcLengths=null;C3.clearArray(this._lut);this._lut=null}GetType(){return"cubic-bezier"}GetIndex(){return this._index}GetStepCount(){return Math.floor(this._length/
+BEZIER_STEP_SIZE)}GetStepIncrement(){return 1/this.GetStepCount()}SetOrigin(ox,oy){this._originX=ox;this._originY=oy;this._arcLengths=new Array(this._len+1);this._arcLengths[0]=0;this._CalculateLength()}Map(u){if(!this._initialized)return NaN;const mt=this._Map(u);MAP_RESULT[0]=this._X(mt);MAP_RESULT[1]=this._Y(mt);return MAP_RESULT}Project(x,y,tRange){const lut=this._GenerateLUT(STEPS);const i=this._FindClosestFromLUT(x,y,lut,tRange);const p=this._RefineProjection(x,y,lut,i);PROJECTION_RESULT[0]=
+p.x;PROJECTION_RESULT[1]=p.y;PROJECTION_RESULT[2]=p.t;PROJECTION_RESULT[3]=p.distance;return PROJECTION_RESULT}Tangent(t){const mt=1-t;const a=mt*mt;const b=2*mt*t;const c=t*t;const d0x=3*(this._bX+this._originX-(this._aX+this._originX));const d0y=3*(this._bY+this._originY-(this._aY+this._originY));const d1x=3*(this._cX+this._originX-(this._bX+this._originX));const d1y=3*(this._cY+this._originY-(this._bY+this._originY));const d2x=3*(this._dX+this._originX-(this._cX+this._originX));const d2y=3*(this._dY+
+this._originY-(this._cY+this._originY));const dx=a*d0x+b*d1x+c*d2x;const dy=a*d0y+b*d1y+c*d2y;const m=Math.hypot(dx,dy);TANGENT_RESULT[0]=dx/m;TANGENT_RESULT[1]=dy/m;return TANGENT_RESULT}TangentAngle(x,y,t){const tanget=this.Tangent(t);const angle=C3.angleTo(x,y,x+tanget[0],y+tanget[1]);return angle}_Map(u){if(!this._initialized)return;let targetLength=u*this._arcLengths[this._len];let low=0;let high=this._len;let index=0;while(lowtargetLength)index--;const lengthBefore=this._arcLengths[index];if(lengthBefore===targetLength)return index/this._len;else return(index+(targetLength-lengthBefore)/(this._arcLengths[index+1]-lengthBefore))/this._len}_X(t){if(!this._initialized)return NaN;return self.Ease.GetRuntimeEase("cubicbezier")(t,this._aX+this._originX,this._bX+this._originX,this._cX+this._originX,this._dX+this._originX)}_Y(t){if(!this._initialized)return NaN;return self.Ease.GetRuntimeEase("cubicbezier")(t,
+this._aY+this._originY,this._bY+this._originY,this._cY+this._originY,this._dY+this._originY)}_GenerateLUT(steps){steps=steps||STEPS;if(this._lut.length===steps)return this._lut;this._lut=[];steps++;for(let i=0;i{p.t=index/(LUT.length-1);p.distance=C3.distanceTo(x,y,p.x,
+p.y);if(tRange&&C3.IsArray(tRange)&&C3.IsFiniteNumber(tRange[0])&&C3.IsFiniteNumber(tRange[1])){if(p.t>=tRange[0]&&p.t<=tRange[1])if(p.distanceepsilon)q=null;return q}_CalculateLength(){this._initialized=true;let ox=this._X(0);let oy=
+this._Y(0);let clen=0;for(let i=1;i<=this._len;i++){const x=this._X(i*LENGTH_STEP_SIZE);const y=this._Y(i*LENGTH_STEP_SIZE);const dx=ox-x;const dy=oy-y;clen+=Math.hypot(dx,dy);this._arcLengths[i]=clen;ox=x;oy=y}this._length=clen}};
+C3.TimelineLineSegmentInfo=class TimelineLineSegmentInfo{constructor(startX,startY,index){this._index=index;this._targetX=startX.GetValueWithResultMode();this._targetY=startY.GetValueWithResultMode();this._originX=0;this._originY=0}Release(){}GetType(){return"line"}GetIndex(){return this._index}SetOrigin(ox,oy){this._originX=ox;this._originY=oy}GetX(){return this._targetX+this._originX}GetY(){return this._targetY+this._originY}};
+
+}
+
+// timelines/state/timelineState.js
+{
+'use strict';const C3=self.C3;const PING_PONG_BEGIN=0;const PING_PONG_END=1;
+C3.TimelineState=class Timeline extends C3.DefendedBase{constructor(name,timelineDataItem,timelineManager){super();this._runtime=timelineManager.GetRuntime();this._timelineManager=timelineManager;this._timelineDataItem=timelineDataItem;this._name=name;this._tracks=[];this._tracksLength=0;this._beforeAndAfterTracks=null;this._beforeAndAfterTracksLength=0;this.CreateTrackStates();this._playPromise=null;this._playResolve=null;this._playheadTime=0;this._playbackRate=1;this._pingPongState=PING_PONG_BEGIN;
+this._currentRepeatCount=1;this._isPlaying=false;this._isScheduled=false;this._initialStateSet=false;this._complete=true;this._released=false;this._markedForRemoval=false;this._completedTick=-1;this._implicitPause=false;this._isTemplate=false;this._finishedTriggers=false;this._firstTick=false;this._lastDelta=NaN;this._tags=[""];this._stringTags="";this._tagsChanged=false;this._renderChange=0;this._hasNestedContent=0;this._iTimelineState=null}static CreateInitial(timelineDataJson,timelineManager){const timelineDataManager=
+timelineManager.GetTimelineDataManager();const nameId=timelineDataManager.GetNameId();const timelineDataItem=timelineDataManager.Get(timelineDataJson[nameId]);const timeline=C3.New(C3.TimelineState,timelineDataJson[nameId],timelineDataItem,timelineManager);timeline.SetIsTemplate(true);return timeline}static CreateFromTemplate(name,timelineDataItem,timelineManager){return C3.New(C3.TimelineState,name,timelineDataItem,timelineManager)}Release(){if(this.IsReleased())return;const dispatcher=this._runtime.Dispatcher();
+this._timelineManager.DeScheduleTimeline(this);this._timelineManager.CompleteTimelineAndResolve(this);for(const track of this._tracks)track.Release();C3.clearArray(this._tracks);this._tracks=null;this._runtime=null;this._timelineManager=null;this._timelineDataItem=null;this._released=true;this._playPromise=null;this._playResolve=null;this.FireReleaseEvent(dispatcher)}FireReleaseEvent(dispatcher){const event=C3.New(C3.Event,"timelinestatereleased");event.timelineState=this;dispatcher.dispatchEvent(event)}GetType(){return 0}CreateTrackStates(){for(const trackDataItem of this._timelineDataItem.GetTrackData().trackDataItems())this._tracksLength=
+this._tracks.push(C3.TrackState.Create(this,trackDataItem))}GetTimelineManager(){return this._timelineManager}GetRuntime(){return this._runtime}GetTracks(){return this._tracks}GetSimilarPropertyTracks(instance,sourceAdapter,propertyName,propertyTrack){if(!this._hasNestedContent)return;let ret;for(let i=0;i0}GetPlayPromise(){if(this._playPromise)return this._playPromise;this._playPromise=new Promise(resolve=>{this._playResolve=resolve});return this._playPromise}ResolvePlayPromise(){if(!this._playPromise)return;
+this._playResolve();this._playPromise=null;this._playResolve=null}SetTags(tags){this._tags=C3.TimelineState._GetTagArray(tags);this._tagsChanged=true}GetTags(){return this._tags}GetStringTags(){if(this._tagsChanged)this._stringTags=this._tags.join(" ");this._tagsChanged=false;return this._stringTags}HasTags(tags){if(!this._tags)return false;if(!this._tags.length)return false;const t=C3.TimelineState._GetTagArray(tags);if(!t)return false;if(!t.length)return false;return t.every(C3.TimelineState._HasTag,
+this)}OnStarted(){if(!C3.Plugins.Timeline||this.constructor!==C3.TimelineState)return;C3.Plugins.Timeline.Cnds.PushTriggerTimeline(this);this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimelineStarted);this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimelineStartedByName);this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimelineStartedByTags);this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnAnyTimelineStarted);C3.Plugins.Timeline.Cnds.PopTriggerTimeline()}OnCompleted(){this._completedTick=
+this._runtime.GetTickCount()}FinishTriggers(){if(this._finishedTriggers)return;this._finishedTriggers=true;if(!C3.Plugins.Timeline||this.constructor!==C3.TimelineState)return;C3.Plugins.Timeline.Cnds.PushTriggerTimeline(this);this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimelineFinished);this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimelineFinishedByName);this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimelineFinishedByTags);this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnAnyTimelineFinished);
+C3.Plugins.Timeline.Cnds.PopTriggerTimeline()}SetPlaying(p){this._isPlaying=p}IsCompletedTick(){return this._completedTick===this._runtime.GetTickCount()}IsPlaying(playingOnly=false){if(this.IsCompletedTick())return true;if(this.IsScheduled()&&!playingOnly)return true;return this._isPlaying}_IsPlaying(){return this.IsPlaying(true)}IsPaused(){return this._IsPaused()}_IsPaused(){if(this.IsReleased())return false;if(this.IsScheduled())return false;if(this._IsPlaying())return false;if(this.IsComplete())return false;
+return true}SetScheduled(s){this._isScheduled=s}IsScheduled(){return this._isScheduled}SetComplete(c){this._complete=c;const t=this.GetTime();if(t<=0||t>=this.GetTotalTime())this._complete=true}IsComplete(){return this._complete}IsReleased(){return this._released}SetMarkedForRemoval(mfr){this._markedForRemoval=mfr}IsMarkedForRemoval(){return this._markedForRemoval}SetImplicitPause(ip){this._implicitPause=ip}IsImplicitPause(){return this._implicitPause}SetIsTemplate(it){this._isTemplate=!!it}IsTemplate(){return this._isTemplate}InitialStateSet(){return this._initialStateSet}GetTime(){return this._playheadTime}SetTime(time){const lastGlobalTime=
+this.GetTime();this._SetTime(time);this.SetComplete(false);if(!this.IsComplete())this.SetImplicitPause(true);if(!this._IsPlaying()&&!this.IsScheduled()&&this._initialStateSet);else if(!this._IsPlaying()&&!this.IsScheduled()&&!this._initialStateSet)this.SetInitialStateFromSetTime();else if(this._IsPlaying())this.Stop();else if(this.IsScheduled()){this._timelineManager.DeScheduleTimeline(this);this.SetInitialStateFromSetTime()}this._SetUpdateStateBefore();this._Interpolate(this.GetTime(),false,true,
+true,lastGlobalTime);this._SetUpdateStateAfter();if(this._renderChange)this.GetRuntime().UpdateRender();this._OnSetTime()}_SetTime(time){if(!C3.IsFiniteNumber(time))time=this.GetTotalTime();if(time<0)this._playheadTime=0;else if(time>=this.GetTotalTime())this._playheadTime=this.GetTotalTime();else this._playheadTime=time}_SetTimeAndReset(time){if(!C3.IsFiniteNumber(time))time=this.GetTotalTime();if(time<0)this._playheadTime=0;else if(time>=this.GetTotalTime())this._playheadTime=this.GetTotalTime();
+else this._playheadTime=time;for(const track of this._tracks)track.SetResetState()}_OnSetTime(){if(!C3.Plugins.Timeline||this.constructor!==C3.TimelineState)return;C3.Plugins.Timeline.Cnds.PushTriggerTimeline(this);this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimeSet);this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimeSetByName);this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimeSetByTags);C3.Plugins.Timeline.Cnds.PopTriggerTimeline()}_CanResume(){if(this.GetLoop())return true;
+else if(this.GetPingPong()&&this._pingPongState===PING_PONG_END)if(this.IsForwardPlayBack()){if(this.GetTime()>=this.GetTotalTime())return false}else{if(this.GetTime()<=0)return false}else if(!this.GetLoop()&&!this.GetPingPong())if(this.IsForwardPlayBack()){if(this.GetTime()>=this.GetTotalTime())return false}else if(this.GetTime()<=0)return false;return true}Resume(){if(this.IsReleased())return;if(this._CanResume())this.Play(true)}Play(resume=false){if(this.IsReleased())return false;if(this.IsScheduled())return false;
+if(this._IsPlaying()&&this.IsCompletedTick())return this._SchedulePlayingTimeline();if(this._IsPlaying())return false;if(!this.IsComplete()&&!resume&&!this.IsImplicitPause())return false;return this._ScheduleStoppedTimeline()}_SchedulePlayingTimeline(){this.SetImplicitPause(false);this._timelineManager.RemovePlayingTimeline(this);this._timelineManager.ScheduleTimeline(this);this.GetPlayPromise();return true}_ScheduleStoppedTimeline(){this.SetImplicitPause(false);this._timelineManager.ScheduleTimeline(this);
+this.GetPlayPromise();return true}Stop(completed=false){if(this.IsReleased())return;this.SetComplete(completed);this._timelineManager.CompleteTimeline(this);if(this.IsComplete())this.ResolvePlayPromise()}Reset(render=true,beforeChangeLayout=false){if(this.IsReleased())return;if(!this._IsPlaying()&&this.IsScheduled())return this._timelineManager.DeScheduleTimeline(this);if(this.IsComplete())return;this.Stop(true);if(this.IsForwardPlayBack())this._SetTime(0);else this._SetTime(this.GetTotalTime());
+const time=this.GetTime();this._SetUpdateStateBefore();if(beforeChangeLayout)this._InterpolateBeforeChangeLayout(time);else this._Interpolate(time,false,false,true);if(render)this._OnSetTime();this._SetUpdateStateAfter();if(this._renderChange&&render)this.GetRuntime().UpdateRender()}ResetBeforeChangeLayout(){this.Reset(false,true)}_InterpolateBeforeChangeLayout(time){this._Interpolate(time,false,false,true,NaN,false,true)}_OnBeforeChangeLayout(){if(this.IsReleased())return true;if(!this.GetRuntime().IsLoadingState())if(this.HasValidGlobalTracks())return false;
+this._timelineManager.CompleteTimelineBeforeChangeOfLayout(this);if(!this.GetRuntime().IsLoadingState())this.ResetBeforeChangeLayout();return true}SetInitialStateFromSetTime(){this.SetInitialState(true)}SetInitialState(fromSetTime){if(this.IsMarkedForRemoval())return;if(fromSetTime){this._finishedTriggers=false;this._initialStateSet=true;this._firstTick=true;this._SetUpdateStateBefore();for(const track of this._tracks)track.SetInitialState();this._SetUpdateStateAfter()}else{this.SetPlaying(true);
+this.SetScheduled(false);this.OnStarted();if(this.IsComplete()){this._completedTick=-1;if(this._pingPongState!==PING_PONG_BEGIN)this._playbackRate=Math.abs(this._playbackRate);this._pingPongState=PING_PONG_BEGIN;this._currentRepeatCount=1;this._complete=false;this._finishedTriggers=false;this._initialStateSet=true;this._firstTick=true;if(this.IsForwardPlayBack())this._SetTime(0);else this._SetTime(this.GetTotalTime());this._SetUpdateStateBefore();for(const track of this._tracks)track.SetInitialState();
+this._SetUpdateStateAfter()}else{this._firstTick=true;this._finishedTriggers=false;this._SetUpdateStateBefore();for(const track of this._tracks)track.SetResumeState();this._SetUpdateStateAfter()}}}GetRenderChange(){return this._renderChange}_SetUpdateStateBefore(){this._hasNestedContent=0;for(const track of this._tracks)if(track.IsNested())this._hasNestedContent=1}_SetUpdateStateAfter(){this._renderChange=0;for(const track of this._tracks){track._SetUpdateState();if(this._renderChange===0&&track.GetRenderChange()===
+1)this._renderChange=1;if(!this._beforeAndAfterTracks&&track.GetNeedsBeforeAndAfter()===1){if(!this._beforeAndAfterTracks)this._beforeAndAfterTracks=[];this._beforeAndAfterTracksLength=this._beforeAndAfterTracks.push(track)}}}Tick(deltaTime,timeScale,deltaTime1){if(this.GetUseSystemTimescale()){if(deltaTime===0&&this._lastDelta===0)return;this._lastDelta=deltaTime;deltaTime=deltaTime1}else{if(deltaTime1===0&&this._lastDelta===0)return;this._lastDelta=deltaTime1;deltaTime=deltaTime1;timeScale=1}const lastTime=
+this._playheadTime;const newDeltaTime=deltaTime*timeScale*this._playbackRate;const newTime=lastTime+newDeltaTime;const totalTime=this._timelineDataItem._totalTime;if(newTime<0)this._playheadTime=0;else if(newTime>=totalTime)this._playheadTime=totalTime;else this._playheadTime=newTime;let complete=false;let ensureValue=false;const loop=this.GetLoop();const pingPong=this.GetPingPong();if(!loop&&!pingPong)if(this._playbackRate>0){if(this._playheadTime>=totalTime)if(this._currentRepeatCount0){if(this._playheadTime>=totalTime){this._SetTimeAndReset(0);ensureValue=true}}else{if(this._playheadTime<=0){this._SetTimeAndReset(totalTime);ensureValue=true}}else if(!loop&&
+pingPong)if(this._playbackRate>0){if(this._playheadTime>=totalTime){this._SetTime(totalTime);this.SetPlaybackRate(this.GetPlaybackRate()*-1);ensureValue=true;if(this._pingPongState===PING_PONG_END)if(this._currentRepeatCount0){if(this._playheadTime>=totalTime){this._SetTime(totalTime);this.SetPlaybackRate(this.GetPlaybackRate()*-1);ensureValue=true;this._pingPongState++;C3.wrap(this._pingPongState,0,2)}}else if(this._playheadTime<=
+0){this._SetTime(0);this.SetPlaybackRate(this.GetPlaybackRate()*-1);ensureValue=true;this._pingPongState++;C3.wrap(this._pingPongState,0,2)}let i;const l=this._tracksLength;if(complete){for(i=0;i0){if(startOffset<0)this._playheadTime=0;else if(startOffset>=totalTime)this._playheadTime=totalTime;else this._playheadTime=startOffset;track.Interpolate(startOffset,true,false,ensureValue,this._firstTick,false)}else track.Interpolate(this._playheadTime,true,false,ensureValue,this._firstTick,false)}else for(i=0;i0){t=track.GetStartOffset();this._SetTime(t)}}track.Interpolate(t,isTicking,setTime,ensureValue,this._firstTick,ignoreGlobals)}for(const track of this._tracks)track.AfterInterpolate();if(this._firstTick&&onTickCall)this._firstTick=false}AddTrack(){const trackDataItem=this._timelineDataItem.GetTrackData().AddEmptyTrackDataItem();const track=C3.TrackState.Create(this,trackDataItem);this._tracksLength=this._tracks.push(track);return track}Removed(){if(this.IsReleased())return;
+for(const track of this._tracks)track.TimelineRemoved()}CleanCaches(){for(const track of this._tracks)track.CleanCaches()}ClearTrackInstances(){for(const track of this._tracks)track.ClearInstance()}SetTrackInstance(trackId,instance){if(!instance)return;for(const track of this._tracks){if(!track.IsInstanceTrack())continue;if(trackId){if(track.GetId()!==trackId)continue;track.SetInstance(instance);this._timelineManager.SetTimelineObjectClassToMap(instance.GetObjectClass(),this);break}else{if(track.HasInstance())continue;
+track.SetInstance(instance);this._timelineManager.SetTimelineObjectClassToMap(instance.GetObjectClass(),this);break}}}HasTrackInstance(instance,trackId){for(const track of this._tracks){if(!track.IsInstanceTrack())continue;if(trackId){if(trackId===track.GetId()&&instance===track.GetInstance())return true}else if(instance===track.GetInstance())return true}return false}HasValidTracks(){return this._tracks.some(t=>{if(t.IsInstanceTrack())return t.CanInstanceBeValid();else return true})}HasValidGlobalTracks(){return this._tracks.some(t=>
+{if(t.IsInstanceTrack()){if(!t.CanInstanceBeValid())return false;const objectClass=t.GetObjectClass();if(!objectClass)return false;return objectClass.IsGlobal()}else return false})}GetPropertyTrack(propertyName){for(const track of this.GetTracks())for(const propertyTrack of track.GetPropertyTracks())if(propertyTrack.GetPropertyName()===propertyName)return propertyTrack}GetTrackFromInstance(instance){for(const track of this._tracks)if(instance===track.GetInstance())return track;return null}GetKeyframeWithTags(tags){let tagsArray=
+tags?tags.split(" "):[];const tagsSet=new Set(tagsArray.map(t=>t.toLowerCase().trim()));tagsArray=[...tagsSet.values()];for(const track of this.GetTracks())for(const keyframeDataItem of track.GetKeyframeDataItems()){const hasAllTags=tagsArray.every(t=>keyframeDataItem.HasTag(t));if(hasAllTags)return keyframeDataItem}}GetObjectClasses(){const ret=[];for(const track of this.GetTracks())ret.push(track.GetObjectClass());return ret.filter(oc=>oc)}_SaveToJson(){return{"tracksJson":this._SaveTracksToJson(),
+"name":this._name,"playheadTime":this.GetTime(),"playbackRate":this._playbackRate,"pingPongState":this._pingPongState,"currentRepeatCount":this._currentRepeatCount,"isPlaying":this._isPlaying,"isScheduled":this._isScheduled,"initialStateSet":this._initialStateSet,"finishedTriggers":this._finishedTriggers,"complete":this._complete,"released":this._released,"markedForRemoval":this._markedForRemoval,"completedTick":this._completedTick,"implicitPause":this._implicitPause,"isTemplate":this._isTemplate,
+"tags":this._tags.join(" "),"stringTags":this._stringTags,"tagsChanged":this._tagsChanged,"firstTick":this._firstTick}}_LoadFromJson(o){if(!o)return;this._LoadTracksFromJson(o["tracksJson"]);this._name=o["name"];this._playheadTime=o["playheadTime"];this._playbackRate=o["playbackRate"];this._pingPongState=o["pingPongState"];this._currentRepeatCount=o["currentRepeatCount"];this._isPlaying=!!o["isPlaying"];this._isScheduled=!!o["isScheduled"];this._initialStateSet=!!o["initialStateSet"];this._finishedTriggers=
+o.hasOwnProperty("finishedTriggers")?!!o["finishedTriggers"]:false;this._complete=!!o["complete"];this._released=!!o["released"];this._markedForRemoval=!!o["markedForRemoval"];this._completedTick=o["completedTick"];this._implicitPause=!!o["implicitPause"];this._isTemplate=!!o["isTemplate"];this._tags=o["tags"].split(" ");this._stringTags=o["stringTags"];this._tagsChanged=!!o["tagsChanged"];this._firstTick=!!o["firstTick"]}_SaveTracksToJson(){return this._tracks.map(trackState=>trackState._SaveToJson())}_LoadTracksFromJson(tracksJson){this.ClearTrackInstances();
+tracksJson.forEach((trackJson,i)=>{const track=this._tracks[i];track._LoadFromJson(trackJson)});this._tracks.filter(track=>track.CanInstanceBeValid())}static _HasTag(tag){const tags=this.GetTags();if(tag==="")return tags.length===1&&tags[0]==="";return tags.map(t=>t.toLowerCase()).includes(tag.toLowerCase())}static _GetTagArray(tags){if(C3.IsArray(tags))return tags.slice(0);if(C3.IsString(tags))return tags.split(" ");throw new Error("invalid tags");}GetITimelineState(){if(!this._iTimelineState)this._iTimelineState=
+C3.New(self.ITimelineState,this);return this._iTimelineState}};
+
+}
+
+// timelines/state/trackState.js
+{
+'use strict';const C3=self.C3;const INSTANCE_TRACK=0;const VALUE_TRACK=1;const AUDIO_TRACK=2;
+C3.TrackState=class Track extends C3.DefendedBase{constructor(timeline,trackDataItem){super();this._timeline=timeline;this._trackDataItem=trackDataItem;this._trackData=trackDataItem.GetTrackData();this._instanceUid=NaN;this._objectClassIndex=NaN;this._instance=null;this._worldInfo=null;this._isNested=trackDataItem.GetStartOffset()>0;this._initialStateOfNestedSet=false;this._endStateOfNestedSet=false;this._lastKeyframeDataItem=null;this._keyframeDataItems=this._trackDataItem.GetKeyframeData().GetKeyframeDataItemArray();
+this._propertyTracks=[];this.CreatePropertyTrackStates();this._worldInfoChange=0;this._renderChange=0;this._needsBeforeAndAfter=0}static Create(timeline,trackDataItem){return C3.New(C3.TrackState,timeline,trackDataItem)}Release(){this._keyframeDataItems=null;for(const propertyTrack of this._propertyTracks)propertyTrack.Release();C3.clearArray(this._propertyTracks);this._propertyTracks=null;this._timeline=null;this._instance=null;this._worldInfo=null;this._trackDataItem=null;this._lastKeyframeDataItem=
+null}CreatePropertyTrackStates(){for(const propertyTrackDataItem of this._trackDataItem.GetPropertyTrackData().propertyTrackDataItems())this._propertyTracks.push(C3.PropertyTrackState.Create(this,propertyTrackDataItem))}TimelineRemoved(){for(const propertyTrack of this._propertyTracks)propertyTrack.TimelineRemoved()}CleanCaches(){for(const propertyTrack of this._propertyTracks)propertyTrack.CleanCaches();this._instance=null;this._worldInfo=null}GetTimeline(){return this._timeline}GetRuntime(){return this._timeline.GetRuntime()}GetKeyframeDataItems(){if(this._keyframeDataItems)return this._keyframeDataItems;
+this._keyframeDataItems=this._trackDataItem.GetKeyframeData().GetKeyframeDataItemArray();return this._keyframeDataItems}GetPropertyTracks(){return this._propertyTracks}GetPropertyTrack(propertyName){for(let i=0;ipt.GetNeedsBeforeAndAfter());if(nba)this._needsBeforeAndAfter=
+1;this._lastKeyframeDataItem=this._GetLastKeyFrameBeforeTime(time);this._initialStateOfNestedSet=false;this._endStateOfNestedSet=false;this.Interpolate(time);this.OnKeyframeReached(this._GetLastKeyFrameBeforeTime(time))}SetResumeState(){this.MaybeGetInstance();if(!this.IsInstanceValid()&&this.IsInstanceTrack())return;const playbackDirection=this._timeline.IsForwardPlayBack();const time=this._timeline.GetTime()-this.GetStartOffset();this._lastKeyframeDataItem=this._GetLastKeyFrameBeforeTime(time);
+for(const propertyTrack of this._propertyTracks)propertyTrack.SetResumeState(time)}SetEndState(){if(this.GetTimeline().IsComplete())return;this.MaybeGetInstance();if(!this.IsInstanceValid()&&this.IsInstanceTrack())return;if(!this._isNested){const time=this._timeline.GetTime();const totalTime=this.GetStartOffset()+this.GetLocalTotalTime();if(time>=totalTime)this.Interpolate(this.GetLocalTotalTime(),true,false,true,false,false,true);else if(time<=0)this.Interpolate(0,true,false,true,false,false,true)}}_SetUpdateState(){for(let i=
+0,l=this._propertyTracks.length;ithis.GetLocalTotalTime())return;for(const propertyTrack of this._propertyTracks)propertyTrack.SetInitialState();this._initialStateOfNestedSet=true}MaybeSetEndStateOfNestedTrack(time,isTicking){if(!isTicking)return;if(!this._isNested)return;if(this._endStateOfNestedSet)return;const timeline=this.GetTimeline();if(timeline.IsForwardPlayBack()){if(time>=this.GetLocalTotalTime()){for(const propertyTrack of this._propertyTracks)propertyTrack.Interpolate(this.GetLocalTotalTime(),
+false,true);this._endStateOfNestedSet=true}}else if(time<=0){for(const propertyTrack of this._propertyTracks)propertyTrack.Interpolate(0,false,true);this._endStateOfNestedSet=true}}MaybeTriggerKeyframeReachedConditions(time,isTicking,firstTick){if(firstTick)return;if(!isTicking)return;if(!C3.Plugins.Timeline)return;const timeline=this.GetTimeline();const nextKeyframe=this._lastKeyframeDataItem.GetNext();const lastTime=this._lastKeyframeDataItem.GetTime();const nextTime=nextKeyframe?nextKeyframe.GetTime():
+timeline.GetTotalTime();if(time<=lastTime||time>=nextTime){this._lastKeyframeDataItem=this._trackData.GetFirstKeyFrameDataItemLowerOrEqualThan(time,this._trackDataItem);if(timeline.IsForwardPlayBack()){if(nextKeyframe)this.OnKeyframeReached(this._lastKeyframeDataItem)}else{const nextKeyframe=this._lastKeyframeDataItem.GetNext();if(nextKeyframe)this.OnKeyframeReached(nextKeyframe)}}}_GetLastKeyFrameBeforeTime(time){const keyframeDataItem=this._trackData.GetKeyFrameDataItemAtTime(time,this._trackDataItem);
+if(keyframeDataItem)return keyframeDataItem;else return this._trackData.GetFirstKeyFrameDataItemLowerOrEqualThan(time,this._trackDataItem)}OnKeyframeReached(keyframeDataItem){if(!C3.Plugins.Timeline)return;const timeline=this.GetTimeline();const timelineManager=timeline.GetTimelineManager();C3.Plugins.Timeline.Cnds.PushTriggerTimeline(timeline);C3.Plugins.Timeline.Cnds.PushTriggerKeyframe(keyframeDataItem);timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnAnyKeyframeReached);timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnKeyframeReached);
+C3.Plugins.Timeline.Cnds.PopTriggerTimeline(timeline);C3.Plugins.Timeline.Cnds.PopTriggerKeyframe(keyframeDataItem)}AddKeyframe(){const keyframeData=this._trackDataItem.GetKeyframeData();const keyframeDataItem=keyframeData.AddEmptyKeyframeDataItem();return keyframeDataItem}AddPropertyTrack(){const propertyTrackData=this._trackDataItem.GetPropertyTrackData();const propertyTrackDataItem=propertyTrackData.AddEmptyPropertyTrackDataItem();const propertyTrack=C3.PropertyTrackState.Create(this,propertyTrackDataItem);
+this._propertyTracks.push(propertyTrack);return propertyTrack}DeleteKeyframes(match){const keyframeData=this._trackDataItem.GetKeyframeData();keyframeData.DeleteKeyframeDataItems(match)}DeletePropertyKeyframes(match){for(const propertyTrack of this._propertyTracks)propertyTrack.DeletePropertyKeyframes(match)}SaveState(){for(const propertyTrack of this._propertyTracks)propertyTrack.SaveState()}CompareInitialStateWithCurrent(){this.MaybeGetInstance();if(!this.IsInstanceValid()&&this.IsInstanceTrack())return;
+for(const propertyTrack of this._propertyTracks)propertyTrack.CompareInitialStateWithCurrent()}CompareSaveStateWithCurrent(){this.MaybeGetInstance();if(!this.IsInstanceValid()&&this.IsInstanceTrack())return;let difference=false;for(const propertyTrack of this._propertyTracks){const diff=propertyTrack.CompareSaveStateWithCurrent();if(!difference&&diff)difference=true}if(difference){const keyframeDataItem=this.AddKeyframe();keyframeDataItem.SetTime(this.GetTimeline().GetTime());keyframeDataItem.SetEase("noease");
+keyframeDataItem.SetEnable(true);keyframeDataItem.SetTags("")}}_SaveToJson(){const instance=this.GetInstance();const uid=instance?instance.GetUID():this.GetInstanceUID();return{"propertyTracksJson":this._SavePropertyTracksToJson(),"lastKeyframeDataItemJson":this._SaveLastKeyframeDataItemToJson(),"initialStateOfNestedSet":this._initialStateOfNestedSet,"endStateOfNestedSet":this._endStateOfNestedSet,"instanceUid":uid}}_LoadFromJson(o){if(!o)return;this._LoadPropertyTracksFromJson(o["propertyTracksJson"]);
+this._LoadLastKeyframeDataItemFromJson(o["lastKeyframeDataItemJson"]);this._LoadInstanceFromJson(o["instanceUid"]);this._initialStateOfNestedSet=false;if(o.hasOwnProperty["initialStateOfNestedSet"])this._initialStateOfNestedSet=o["initialStateOfNestedSet"];this._endStateOfNestedSet=false;if(o.hasOwnProperty["endStateOfNestedSet"])this._endStateOfNestedSet=o["endStateOfNestedSet"];for(const propertyTrack of this._propertyTracks){if(this._worldInfoChange===0&&propertyTrack.GetWorldInfoChange()===1)this._worldInfoChange=
+1;if(this._renderChange===0&&propertyTrack.GetRenderChange()===1)this._renderChange=1}this._needsBeforeAndAfter=0;if(this._propertyTracks.some(pt=>pt.GetNeedsBeforeAndAfter()))this._needsBeforeAndAfter=1}_SaveLastKeyframeDataItemToJson(){const keyframeData=this._trackDataItem.GetKeyframeData();return keyframeData.GetKeyframeDataItemIndex(this._lastKeyframeDataItem)}_SavePropertyTracksToJson(){return this._propertyTracks.map(propertyTrackState=>propertyTrackState._SaveToJson())}_LoadPropertyTracksFromJson(propertyTracksJson){propertyTracksJson.forEach((propertyTrackJson,
+i)=>{const propertyTrack=this._propertyTracks[i];propertyTrack._LoadFromJson(propertyTrackJson)})}_LoadInstanceFromJson(uid){if(!C3.IsFiniteNumber(uid))return;const instance=this.GetRuntime().GetInstanceByUID(uid);if(!instance)return;const timeline=this.GetTimeline();timeline.SetTrackInstance(this._trackDataItem.GetId(),instance)}_LoadLastKeyframeDataItemFromJson(lastKeyframeDataItemIndex){const keyframeData=this._trackDataItem.GetKeyframeData();this._lastKeyframeDataItem=keyframeData.GetKeyframeDataItemFromIndex(lastKeyframeDataItemIndex)}};
+
+}
+
+// timelines/state/propertyTrackState.js
+{
+'use strict';const C3=self.C3;
+C3.PropertyTrackState=class PropertyTrack extends C3.DefendedBase{constructor(track,propertyTrackDataItem){super();this._track=track;this._propertyTrackDataItem=propertyTrackDataItem;this._propertyTrackData=propertyTrackDataItem.GetPropertyTrackData();this._worldInfoChange=0;this._renderChange=0;this._needsBeforeAndAfter=0;this._sourceAdapter=this.GetSourceAdapter();this._propertyKeyframeDataItems=this._propertyTrackDataItem.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray();this._lastPropertyKeyframeDataItem=
+null;this._absoluteValueObject=null}static Create(track,propertyTrackDataItem){return C3.New(C3.PropertyTrackState,track,propertyTrackDataItem)}Release(){this._track=null;if(this._sourceAdapter){this._sourceAdapter.Release();this._sourceAdapter=null}this._propertyKeyframeDataItems=null;this._propertyTrackDataItem=null;this._propertyTrackData=null}GetWorldInfoChange(){return this._worldInfoChange}GetRenderChange(){return this._renderChange}GetNeedsBeforeAndAfter(){return this._needsBeforeAndAfter}HasAbsoluteValueObject(){return!!this._absoluteValueObject}SetAbsoluteValueObject(avo){this._absoluteValueObject=
+avo}GetAbsoluteValueObject(){return this._absoluteValueObject}GetTrack(){return this._track}GetPropertyTrackDataItem(){return this._propertyTrackDataItem}GetPropertyTrackData(){return this._propertyTrackData}GetTimeline(){return this._track.GetTimeline()}GetRuntime(){return this._track.GetRuntime()}GetInstance(){return this._track.GetInstance()}GetSourceAdapter(){if(this._sourceAdapter)return this._sourceAdapter;const id=this._propertyTrackDataItem.GetSourceAdapterId();let ret;switch(id){case "behavior":ret=
+new C3.PropertyTrackState.BehaviorSourceAdapter(this);break;case "effect":ret=new C3.PropertyTrackState.EffectSourceAdapter(this);this._renderChange=1;break;case "instance-variable":ret=new C3.PropertyTrackState.InstanceVariableSourceAdapter(this);break;case "plugin":ret=new C3.PropertyTrackState.PluginSourceAdapter(this);this._renderChange=1;break;case "world-instance":ret=new C3.PropertyTrackState.PropertySourceAdapter(this);this._renderChange=1;this._worldInfoChange=1;break;case "value":ret=new C3.PropertyTrackState.ValueSourceAdapter(this);
+break;case "audio":ret=new C3.PropertyTrackState.AudioSourceAdapter(this);break}this._sourceAdapter=ret;return this._sourceAdapter}GetSourceAdapterId(){return this._propertyTrackDataItem.GetSourceAdapterId()}SetSourceAdapterId(said){this._propertyTrackDataItem.SetSourceAdapterId(said)}GetSourceAdapterArgs(){return this._propertyTrackDataItem.GetSourceAdapterArguments()}SetSourceAdapterArgs(sargs){this._propertyTrackDataItem.SetSourceAdapterArguments(sargs)}GetSourceAdapterValue(){return this.GetSourceAdapter().GetValue()}GetPropertyName(){return this._propertyTrackDataItem.GetProperty()}SetPropertyName(pn){this._propertyTrackDataItem.SetProperty(pn)}GetPropertyType(){return this._propertyTrackDataItem.GetType()}SetPropertyType(pt){this._propertyTrackDataItem.SetType(pt)}GetPropertyKeyframeType(){return this.GetPropertyTrackData().GetFirstPropertyKeyframeDataItem(this._propertyTrackDataItem).GetType()}GetMin(){return this._propertyTrackDataItem.GetMin()}SetMin(min){this._propertyTrackDataItem.SetMin(min)}GetMax(){return this._propertyTrackDataItem.GetMax()}SetMax(max){this._propertyTrackDataItem.SetMax(max)}GetEnable(){return this._propertyTrackDataItem.GetEnable()}SetEnable(e){this._propertyTrackDataItem.SetEnable(e)}GetInterpolationMode(){return this._propertyTrackDataItem.GetInterpolationMode()}SetInterpolationMode(im){this._propertyTrackDataItem.SetInterpolationMode(im)}GetResultMode(){return this._propertyTrackDataItem.GetResultMode()}SetResultMode(rm){this._propertyTrackDataItem.SetResultMode(rm)}SetEase(e){for(const propertyKeyframeDataItem of this.GetPropertyKeyframeDataItems())propertyKeyframeDataItem.SetEase(e)}CanHavePropertyKeyframes(){return this._propertyTrackDataItem.CanHavePropertyKeyframes()}GetPropertyKeyframeDataItems(){if(this._propertyKeyframeDataItems)return this._propertyKeyframeDataItems;
+this._propertyKeyframeDataItems=this._propertyTrackDataItem.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray();return this._propertyKeyframeDataItems}GetPropertyKeyframeDataItemArrayIncludingDisabled(){return this._propertyTrackDataItem.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArrayIncludingDisabled()}GetPropertyKeyFrameDataItemAtTime(time){return this._propertyTrackData.GetPropertyKeyFrameDataItemAtTime(time,this._propertyTrackDataItem)}GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(time){return this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(time,
+this._propertyTrackDataItem)}GetPropertyKeyframeDataItemPairForTime(time){let start=this._propertyTrackData.GetPropertyKeyFrameDataItemAtTime(time,this._propertyTrackDataItem);let end;if(start)end=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemHigherThan(time,this._propertyTrackDataItem);else{start=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(time,this._propertyTrackDataItem);end=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemHigherOrEqualThan(time,this._propertyTrackDataItem)}return{start,
+end}}*GetPropertyKeyframeValues(){for(const propertyKeyframeDataItem of this.GetPropertyKeyframeDataItems())yield propertyKeyframeDataItem.GetValueWithResultMode()}*GetPropertyKeyframeTimes(){for(const propertyKeyframeDataItem of this.GetPropertyKeyframeDataItems())yield propertyKeyframeDataItem.GetTime()}TimelineRemoved(){this.GetSourceAdapter().TimelineRemoved()}CleanCaches(){this.GetSourceAdapter().CleanCaches()}GetCurrentState(){return this.GetSourceAdapter().GetCurrentState()}SetResetState(){this.GetSourceAdapter().SetResetState()}SetInitialState(time){this.GetSourceAdapter().SetInitialState();
+this._lastPropertyKeyframeDataItem=this._GetLastPropertyKeyFrameBeforeTime(time);this._SetUpdateState()}SetResumeState(time){this.GetSourceAdapter().SetResumeState();this._lastPropertyKeyframeDataItem=this._GetLastPropertyKeyFrameBeforeTime(time)}_SetUpdateState(){const track=this.GetTrack();this._needsBeforeAndAfter=0;if(track.IsInstanceTrack()){const timeline=this.GetTimeline();const instance=track.GetInstance();const sourceAdapter=this.GetSourceAdapter();const propertyName=this.GetPropertyName();
+const mayNeedBeforeAndAfterInterpolate=sourceAdapter.MayNeedBeforeAndAfterInterpolate();if(mayNeedBeforeAndAfterInterpolate){const similarPropertyTracks=timeline.GetSimilarPropertyTracks(instance,sourceAdapter,propertyName,this);if(similarPropertyTracks&&similarPropertyTracks.length)this._needsBeforeAndAfter=1}else this._needsBeforeAndAfter=0}}_GetLastPropertyKeyFrameBeforeTime(time){const timeline=this.GetTimeline();const propertyKeyframeDataItem=this._propertyTrackData.GetPropertyKeyFrameDataItemAtTime(time,
+this._propertyTrackDataItem);if(propertyKeyframeDataItem)return propertyKeyframeDataItem;else if(timeline.IsForwardPlayBack())return this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(time,this._propertyTrackDataItem);else return this._propertyTrackData.GetFirstPropertyKeyFrameDataItemHigherOrEqualThan(time,this._propertyTrackDataItem)}BeforeInterpolate(){this._sourceAdapter.BeforeInterpolate()}Interpolate(time,setTime=false,ensureValue=false,endState=false){let start;let end;
+let propertyKeyframeReached=false;if(setTime)start=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(time,this._propertyTrackDataItem);else{if(this._lastPropertyKeyframeDataItem){const timeline=this.GetTimeline();const nextPropertyKeyframe=this._lastPropertyKeyframeDataItem.GetNext();const lastTime=this._lastPropertyKeyframeDataItem.GetTime();const nextTime=nextPropertyKeyframe?nextPropertyKeyframe.GetTime():timeline.GetTotalTime();if(time<=lastTime||time>=nextTime){this._lastPropertyKeyframeDataItem=
+this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(time,this._propertyTrackDataItem);propertyKeyframeReached=true}}else{this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(time,this._propertyTrackDataItem);propertyKeyframeReached=true}start=this._lastPropertyKeyframeDataItem}if(start)end=start.GetNext();this._sourceAdapter.Interpolate(time,start,end,setTime,ensureValue,endState,propertyKeyframeReached)}GetInterpolatedValue(time){if(this._lastPropertyKeyframeDataItem){const timeline=
+this.GetTimeline();const nextPropertyKeyframe=this._lastPropertyKeyframeDataItem.GetNext();const lastTime=this._lastPropertyKeyframeDataItem.GetTime();const nextTime=nextPropertyKeyframe?nextPropertyKeyframe.GetTime():timeline.GetTotalTime();if(time<=lastTime||time>=nextTime)this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(time,this._propertyTrackDataItem)}else this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(time,
+this._propertyTrackDataItem);const start=this._lastPropertyKeyframeDataItem;const end=start.GetNext();return this._sourceAdapter.GetInterpolatedValue(time,start,end)}GetInterpolatedValueFast(time,start,end){return this._sourceAdapter.GetInterpolatedValue(time,start,end)}AfterInterpolate(){this._sourceAdapter.AfterInterpolate()}static GetStartPropertyKeyframeForTime(time,propertyTrack){const propertyTrackDataItem=propertyTrack.GetPropertyTrackDataItem();const propertyTrackData=propertyTrack._propertyTrackData;
+return propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(time,propertyTrackDataItem)}static GetEndPropertyKeyframeForTime(time,propertyTrack){const propertyTrackDataItem=propertyTrack.GetPropertyTrackDataItem();const propertyTrackData=propertyTrack._propertyTrackData;return propertyTrackData.GetFirstPropertyKeyFrameDataItemHigherOrEqualThan(time,propertyTrackDataItem)}AddPropertyKeyframe(){const propertyKeyframeData=this._propertyTrackDataItem.GetPropertyKeyframeData();const propertyKeyframeDataItem=
+propertyKeyframeData.AddEmptyPropertyKeyframeDataItem();this._lastPropertyKeyframeDataItem=null;return propertyKeyframeDataItem}DeletePropertyKeyframes(match){this._lastPropertyKeyframeDataItem=null;const propertyKeyframeData=this._propertyTrackDataItem.GetPropertyKeyframeData();propertyKeyframeData.DeletePropertyKeyframeDataItems(match)}SaveState(){this.GetSourceAdapter().SaveState()}CompareInitialStateWithCurrent(){const difference=this.GetSourceAdapter().CompareInitialStateWithCurrent();if(difference){const propertyKeyframeDataItem=
+this._propertyTrackData.GetFirstPropertyKeyframeDataItem(this._propertyTrackDataItem);const currentState=this.GetSourceAdapter().GetCurrentState();propertyKeyframeDataItem.SetAbsoluteValue(currentState)}}CompareSaveStateWithCurrent(){const difference=this.GetSourceAdapter().CompareSaveStateWithCurrent();if(difference)this.AddPropertyKeyframeAtCurrentTime();this.GetSourceAdapter().ClearSaveState();return difference}AddPropertyKeyframeAtCurrentTime(){const time=this.GetTimeline().GetTime();const sourceAdapter=
+this.GetSourceAdapter();const startPropertyKeyframe=C3.PropertyTrackState.GetStartPropertyKeyframeForTime(time,this);const propertyKeyframeDataItem=this.AddPropertyKeyframe();propertyKeyframeDataItem.SetType(startPropertyKeyframe.GetType());propertyKeyframeDataItem.SetTime(time);propertyKeyframeDataItem.SetEase(startPropertyKeyframe.GetEase());propertyKeyframeDataItem.SetEnable(true);propertyKeyframeDataItem.SetValue(sourceAdapter.GetValueAtTime());propertyKeyframeDataItem.SetAbsoluteValue(sourceAdapter.GetCurrentState())}_SaveToJson(){return{"sourceAdapterJson":this.GetSourceAdapter()._SaveToJson()}}_LoadFromJson(o){if(!o)return;
+this.GetSourceAdapter()._LoadFromJson(o["sourceAdapterJson"])}};
+
+}
+
+// timelines/state/propertySourceAdapters/propertySourceAdapter.js
+{
+'use strict';const C3=self.C3;const NS=C3.PropertyTrackState;
+NS.PropertySourceAdapter=class PropertySourceAdapter{constructor(propertyTrack){this._propertyTrack=propertyTrack;this._propertyAdapter=null;this.GetPropertyAdapter()}Release(){if(this._propertyAdapter){this._propertyAdapter.Release();this._propertyAdapter=null}this._propertyTrack=null}MayNeedBeforeAndAfterInterpolate(){return this._propertyAdapter.MayNeedBeforeAndAfterInterpolate()}GetPropertyTrack(){return this._propertyTrack}TimelineRemoved(){if(this._propertyAdapter)this._propertyAdapter.TimelineRemoved()}CleanCaches(){if(this._propertyAdapter)this._propertyAdapter.CleanCaches()}GetPropertyAdapter(){if(this._propertyAdapter)return this._propertyAdapter;this._propertyAdapter=
+this._CreatePropertyAdapter();return this._propertyAdapter}GetEditorIndex(){}GetIndex(){return this.GetEditorIndex()}GetTarget(){}SetResetState(){this.GetPropertyAdapter().SetResetState()}SetInitialState(){this.GetPropertyAdapter().SetInitialState()}SetResumeState(){this.GetPropertyAdapter().SetResumeState()}BeforeInterpolate(){this._propertyAdapter.BeforeChangeProperty()}Interpolate(time,start,end,setTime,ensureValue,endState,propertyKeyframeReached){const type=this._propertyTrack.GetPropertyKeyframeType();
+let value;switch(type){case "numeric":{value=NS.NumericTypeAdapter.Interpolate(time,start,end,this._propertyTrack);break}case "angle":{value=NS.AngleTypeAdapter.Interpolate(time,start,end,this._propertyTrack);break}case "boolean":{value=NS.BooleanTypeAdapter.Interpolate(time,start,end,this._propertyTrack);break}case "color":{value=NS.ColorTypeAdapter.Interpolate(time,start,end,this._propertyTrack);break}case "text":{value=NS.TextTypeAdapter.Interpolate(time,start,end,this._propertyTrack);break}}this._propertyAdapter.ChangeProperty(time,
+value,start,end,setTime,ensureValue,endState,propertyKeyframeReached)}GetInterpolatedValue(time,start,end){switch(this._propertyTrack.GetPropertyKeyframeType()){case "numeric":return NS.NumericTypeAdapter.Interpolate(time,start,end,this._propertyTrack);case "angle":return NS.AngleTypeAdapter.Interpolate(time,start,end,this._propertyTrack);case "boolean":return NS.BooleanTypeAdapter.Interpolate(time,start,end,this._propertyTrack);case "color":return NS.ColorTypeAdapter.Interpolate(time,start,end,this._propertyTrack);
+case "text":return NS.TextTypeAdapter.Interpolate(time,start,end,this._propertyTrack)}}AfterInterpolate(){this._propertyAdapter.AfterChangeProperty()}SaveState(){this.GetPropertyAdapter().SetSaveState()}ClearSaveState(){this.GetPropertyAdapter().ClearSaveState()}GetCurrentState(){return this.GetPropertyAdapter().GetCurrentState()}CompareInitialStateWithCurrent(){return this.GetPropertyAdapter().CompareInitialStateWithCurrent()}CompareSaveStateWithCurrent(){return this.GetPropertyAdapter().CompareSaveStateWithCurrent()}GetValueAtTime(){const propertyTrack=
+this._propertyTrack;const track=propertyTrack.GetTrack();const time=track.GetTimeline().GetTime();const start=NS.GetStartPropertyKeyframeForTime(time,propertyTrack);const end=start.GetNext();const type=propertyTrack.GetPropertyKeyframeType();switch(type){case "numeric":{return NS.NumericTypeAdapter.Interpolate(time,start,end,propertyTrack)}case "angle":{return NS.AngleTypeAdapter.Interpolate(time,start,end,propertyTrack)}case "boolean":{return NS.BooleanTypeAdapter.Interpolate(time,start,end,propertyTrack)}case "color":{return NS.ColorTypeAdapter.Interpolate(time,
+start,end,propertyTrack)}case "text":{return NS.TextTypeAdapter.Interpolate(time,start,end,propertyTrack)}}}_CreatePropertyAdapter(){const pt=this._propertyTrack;const type=pt.CanHavePropertyKeyframes()?pt.GetPropertyKeyframeType():"";switch(type){case "combo":case "boolean":case "text":case "string":{return new NS.PropertyInterpolationAdapter.NoInterpolationAdapter(this)}case "numeric":case "number":case "angle":{if(this._propertyTrack.GetPropertyType()==="combo")return new NS.PropertyInterpolationAdapter.NoInterpolationAdapter(this);
+return new NS.PropertyInterpolationAdapter.NumericInterpolationAdapter(this)}case "color":case "offsetColor":{return new NS.PropertyInterpolationAdapter.ColorInterpolationAdapter(this)}default:{return new NS.PropertyInterpolationAdapter.NumericInterpolationAdapter(this)}}}_SaveToJson(){return{"propertyAdapterJson":this.GetPropertyAdapter()._SaveToJson()}}_LoadFromJson(o){if(!o)return;this.GetPropertyAdapter()._LoadFromJson(o["propertyAdapterJson"])}};
+
+}
+
+// timelines/state/propertySourceAdapters/instanceVariableSourceAdapter.js
+{
+'use strict';const C3=self.C3;const INDEX=0;
+class InstanceVariableSourceAdapter extends C3.PropertyTrackState.PropertySourceAdapter{constructor(propertyTrack){super(propertyTrack);this._updatedIndex=NaN}GetEditorIndex(){return this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[INDEX]}GetIndex(){if(this._updatedIndex)return this._updatedIndex;return super.GetIndex()}GetTarget(){return this._propertyTrack.GetTrack().GetInstance()}UpdateInstanceVariableIndex(index){const i=this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[INDEX];if(i===
+index)return;this._updatedIndex=index}Interpolate(time,start,end,setTime,ensureValue,endState,propertyKeyframeReached){if(!this.GetPropertyAdapter().CanChange(start.GetValue()))return;super.Interpolate(time,start,end,setTime,ensureValue,endState,propertyKeyframeReached)}GetInterpolatedValue(time,start,end){if(!this.GetPropertyAdapter().CanChange(start.GetValue()))return;return super.GetInterpolatedValue(time,start,end)}_SaveToJson(){return Object.assign(super._SaveToJson(),{"index":this._updatedIndex})}_LoadFromJson(o){if(!o)return;
+super._LoadFromJson(o);this._updatedIndex=o["index"]}}C3.PropertyTrackState.InstanceVariableSourceAdapter=InstanceVariableSourceAdapter;
+
+}
+
+// timelines/state/propertySourceAdapters/behaviorSourceAdapter.js
+{
+'use strict';const C3=self.C3;const SID=0;const INDEX=1;const NAME=2;
+class BehaviorSourceAdapter extends C3.PropertyTrackState.PropertySourceAdapter{constructor(propertyTrack){super(propertyTrack);this._sid=NaN}GetEditorIndex(){const dataItem=this._propertyTrack.GetPropertyTrackDataItem();return dataItem.GetSourceAdapterArguments()[INDEX]}GetTarget(){const dataItem=this._propertyTrack.GetPropertyTrackDataItem();const track=this._propertyTrack.GetTrack();const sid=this._sid?this._sid:dataItem.GetSourceAdapterArguments()[SID];const instance=track.GetInstance();const index=
+instance.GetBehaviorIndexBySID(sid);const behaviorInstance=instance.GetBehaviorInstances()[index];return behaviorInstance.GetSdkInstance()}GetBehaviorType(objectClass){const dataItem=this._propertyTrack.GetPropertyTrackDataItem();const name=dataItem.GetSourceAdapterArguments()[NAME];return objectClass.GetBehaviorTypeByName(name)}UpdateBehaviorTypeSid(sid){const dataItem=this._propertyTrack.GetPropertyTrackDataItem();if(dataItem.GetSourceAdapterArguments()[SID]===sid)return;this._sid=sid}Interpolate(time,
+start,end,setTime,ensureValue,endState,propertyKeyframeReached){const track=this._propertyTrack.GetTrack();const instance=track.GetInstance();if(!this.GetBehaviorType(instance.GetObjectClass()))return;super.Interpolate(time,start,end,setTime,ensureValue,endState,propertyKeyframeReached)}GetInterpolatedValue(time,start,end){const track=this._propertyTrack.GetTrack();const instance=track.GetInstance();if(!this.GetBehaviorType(instance.GetObjectClass()))return;return super.GetInterpolatedValue(time,
+start,end)}_SaveToJson(){return Object.assign(super._SaveToJson(),{"sid":this._sid})}_LoadFromJson(o){if(!o)return;super._LoadFromJson(o);this._sid=o["sid"]}}C3.PropertyTrackState.BehaviorSourceAdapter=BehaviorSourceAdapter;
+
+}
+
+// timelines/state/propertySourceAdapters/effectSourceAdapter.js
+{
+'use strict';const C3=self.C3;const NAME=0;const INDEX=1;
+class EffectSourceAdapter extends C3.PropertyTrackState.PropertySourceAdapter{constructor(propertyTrack){super(propertyTrack)}GetEditorIndex(){return this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[INDEX]}GetTarget(){const pTrack=this._propertyTrack;const track=pTrack.GetTrack();const worldInfo=track.GetWorldInfo();const instanceEffectList=worldInfo.GetInstanceEffectList();const effectList=instanceEffectList.GetEffectList();const effectType=this.GetEffectType(effectList);
+const effectIndex=effectType.GetIndex();if(instanceEffectList.IsEffectIndexActive(effectIndex))return instanceEffectList.GetEffectParametersForIndex(effectIndex);return null}GetEffectType(effectList){const pTrack=this._propertyTrack;const name=pTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[NAME];return effectList.GetEffectTypeByName(name)}Interpolate(time,start,end,setTime,ensureValue,endState,propertyKeyframeReached){if(!this._IsEffectActive())return;super.Interpolate(time,start,end,
+setTime,ensureValue,endState,propertyKeyframeReached)}GetInterpolatedValue(time,start,end){if(!this._IsEffectActive())return;return super.GetInterpolatedValue(time,start,end)}_IsEffectActive(){const pTrack=this._propertyTrack;const track=pTrack.GetTrack();const worldInfo=track.GetWorldInfo();const instanceEffectList=worldInfo.GetInstanceEffectList();const effectList=instanceEffectList.GetEffectList();const effectType=this.GetEffectType(effectList);if(!effectType)return;const effectIndex=effectType.GetIndex();
+return instanceEffectList.IsEffectIndexActive(effectIndex)}}C3.PropertyTrackState.EffectSourceAdapter=EffectSourceAdapter;
+
+}
+
+// timelines/state/propertySourceAdapters/pluginSourceAdapter.js
+{
+'use strict';const C3=self.C3;const INDEX=0;
+class PluginSourceAdapter extends C3.PropertyTrackState.PropertySourceAdapter{constructor(propertyTrack){super(propertyTrack)}GetEditorIndex(){return this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[INDEX]}GetTarget(){return this._propertyTrack.GetTrack().GetInstance().GetSdkInstance()}Interpolate(time,start,end,setTime,ensureValue,endState,propertyKeyframeReached){const track=this._propertyTrack.GetTrack();const templatePlugin=track.GetObjectClass().GetPlugin();const currentPlugin=
+track.GetInstance().GetObjectClass().GetPlugin();if(templatePlugin!==currentPlugin)return;super.Interpolate(time,start,end,setTime,ensureValue,endState,propertyKeyframeReached)}GetInterpolatedValue(time,start,end){const track=this._propertyTrack.GetTrack();const templatePlugin=track.GetObjectClass().GetPlugin();const currentPlugin=track.GetInstance().GetObjectClass().GetPlugin();if(templatePlugin!==currentPlugin)return;return super.GetInterpolatedValue(time,start,end)}GetOptionalCallbacks(){const track=
+this._propertyTrack.GetTrack();const plugin=track.GetObjectClass().GetPlugin();if(C3.Plugins.Sprite&&plugin instanceof C3.Plugins.Sprite)if(this._propertyTrack.GetPropertyName()==="initial-frame"||this._propertyTrack.GetPropertyName()==="initial-animation")switch(this._propertyTrack.GetResultMode()){case "relative":{return null}case "absolute":{return null}}}}C3.PropertyTrackState.PluginSourceAdapter=PluginSourceAdapter;
+
+}
+
+// timelines/state/propertySourceAdapters/valueSourceAdapter.js
+{
+'use strict';const C3=self.C3;
+class ValueSourceAdapter extends C3.PropertyTrackState.PropertySourceAdapter{constructor(propertyTrack){super(propertyTrack);this._value=0;this._init=false}MayNeedBeforeAndAfterInterpolate(){return false}SetInitialState(){const propertyTrackData=this._propertyTrack.GetPropertyTrackData();let propertyTrackDataItem=this._propertyTrack.GetPropertyTrackDataItem();propertyTrackDataItem=propertyTrackData.GetFirstPropertyKeyframeDataItem(propertyTrackDataItem);this._value=propertyTrackDataItem.GetValueWithResultMode()}SetResumeState(){}GetValue(){if(!this._init)this._propertyTrack.Interpolate(0);return this._value}Interpolate(time,
+start,end,setTime,ensureValue,endState,propertyKeyframeReached){this._value=C3.PropertyTrackState.NumericTypeAdapter.Interpolate(time,start,end,this._propertyTrack);this._init=true}SaveState(){}ClearSaveState(){}GetCurrentState(){return this._value}CompareInitialStateWithCurrent(){return false}CompareSaveStateWithCurrent(){return false}_SaveToJson(){return{"value":this._value,"init":this._init}}_LoadFromJson(o){if(!o)return;this._value=o["value"];this._init=o.hasOwnProperty("init")?o["init"]:true}}
+C3.PropertyTrackState.ValueSourceAdapter=ValueSourceAdapter;
+
+}
+
+// timelines/state/propertySourceAdapters/audioSourceAdapter.js
+{
+'use strict';const C3=self.C3;const PROJECT_FILE=0;const PROJECT_FILE_NAME=0;const PROJECT_FILE_TYPE=1;const START_OFFSET=1;const AUDIO_DURATION=2;const AUDIO_TAG=3;
+class AudioSourceAdapter extends C3.PropertyTrackState.PropertySourceAdapter{constructor(propertyTrack){super(propertyTrack);this._audioPlaybackStarted=false;this._sdkInstance=null;this._actions=null;this._expressions=null;this._timeline=this._propertyTrack.GetTimeline();this._track=this._propertyTrack.GetTrack();this._sourceAdapterArgs=this._propertyTrack.GetSourceAdapterArgs();this._fileArgs=this._sourceAdapterArgs[PROJECT_FILE];this._startOffsetTime=this._sourceAdapterArgs[START_OFFSET];if(this._sourceAdapterArgs[AUDIO_TAG])this._audioTag=
+this._sourceAdapterArgs[AUDIO_TAG];else this._audioTag=Math.random().toString(36).slice(2);this._pauseTime=NaN;this._pauseVolume=NaN;this._volume=NaN;this._audioSource=null;this._Initialize()}Release(){super.Release();this._sdkInstance=null;this._actions=null;this._expressions=null;this._timeline=null;this._track=null;this._sourceAdapterArgs=null;this._fileArgs=null;this._audioSource=null}_Initialize(){if(!self.C3.Plugins.Audio)return;const runtime=this._propertyTrack.GetRuntime();const audioObjectClass=
+runtime.GetSingleGlobalObjectClassByCtor(self.C3.Plugins.Audio);if(audioObjectClass)this._sdkInstance=audioObjectClass.GetSingleGlobalInstance().GetSdkInstance();this._actions=self.C3.Plugins.Audio.Acts;this._expressions=self.C3.Plugins.Audio.Exps}_MaybeSetAudioSource(){if(this._audioSource)return;const track=this._propertyTrack.GetTrack();const audioSourcePropertyTrack=track.GetPropertyTrack("audioSource");if(audioSourcePropertyTrack)this._audioSource=audioSourcePropertyTrack.GetSourceAdapter()}_GetPauseVolume(){const track=
+this._propertyTrack.GetTrack();const volumePropertyTrack=track.GetPropertyTrack("volume");if(volumePropertyTrack)return volumePropertyTrack.GetSourceAdapter()._pauseVolume;else return this._pauseVolume}TimelineRemoved(){super.TimelineRemoved();this._audioPlaybackStarted=false;if(this._sdkInstance){if(this._expressions){this._pauseTime=this._expressions.PlaybackTime.call(this._sdkInstance,this._audioTag);this._pauseVolume=this._expressions.Volume.call(this._sdkInstance,this._audioTag)}if(this._actions)this._actions.Stop.call(this._sdkInstance,
+this._audioTag)}}GetAudioTag(){return this._audioTag}GetVolume(){return this._volume}SetVolume(v){this._volume=v}SetInitialState(){super.SetInitialState();this._pauseTime=NaN;this._audioPlaybackStarted=false}SetResumeState(){super.SetResumeState();const timeline=this._propertyTrack.GetTimeline();const time=timeline.GetTime();this._pauseTime=time-this._startOffsetTime;switch(this._propertyTrack.GetPropertyName()){case "audioSource":{break}case "volume":{this._pauseVolume=this._propertyTrack.GetInterpolatedValue(time);
+break}}this._audioPlaybackStarted=false}Interpolate(time,start,end,setTime,ensureValue,endState,propertyKeyframeReached){if(!this._sdkInstance)return;switch(this._propertyTrack.GetPropertyName()){case "audioSource":{if(!this._timeline.IsForwardPlayBack())return;if(setTime){if(this._actions)this._actions.Stop.call(this._sdkInstance,this._audioTag);return}if(time{const propertyTrackDataItem=
+this._propertyTrack.GetPropertyTrackDataItem();const propertyTrackData=this._propertyTrack.GetPropertyTrackData();return propertyTrackData.GetFirstPropertyKeyframeDataItem(propertyTrackDataItem)},()=>{const propertyTrackDataItem=this._propertyTrack.GetPropertyTrackDataItem();const propertyTrackData=this._propertyTrack.GetPropertyTrackData();return propertyTrackData.GetLastPropertyKeyframeDataItem(propertyTrackDataItem)});return propertyKeyframeDataItem.GetAbsoluteValue()}_CurrentKeyframeGetter(){const timeline=
+this._propertyTrack.GetTimeline();const time=timeline.GetTime()-this._propertyTrack.GetTrack().GetStartOffset();const propertyKeyframe=this._PickTimelinePlaybackMode(()=>{const propertyTrackDataItem=this._propertyTrack.GetPropertyTrackDataItem();const propertyTrackData=this._propertyTrack.GetPropertyTrackData();return propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(time,propertyTrackDataItem)},()=>{const propertyTrackDataItem=this._propertyTrack.GetPropertyTrackDataItem();const propertyTrackData=
+this._propertyTrack.GetPropertyTrackData();const ret=propertyTrackData.GetFirstPropertyKeyFrameDataItemHigherOrEqualThan(time,propertyTrackDataItem);if(!ret)return propertyTrackData.GetLastPropertyKeyframeDataItem(propertyTrackDataItem);return ret});return propertyKeyframe.GetAbsoluteValue()}_PickTimelinePlaybackMode(forwardFunc,backwardFunc){const timeline=this._propertyTrack.GetTimeline();return timeline.IsForwardPlayBack()?forwardFunc():backwardFunc()}_PickResultMode(relativeFunc,absoluteFunc){const resultMode=
+this._propertyTrack.GetResultMode();return resultMode==="relative"?relativeFunc():absoluteFunc()}_PickFirstAbsoluteUpdate(firstFunc,otherFunc){if(this.GetFirstAbsoluteUpdate()){this.SetFirstAbsoluteUpdate(false);return firstFunc()}else return otherFunc()}_GetAbsoluteInitialValue(keyframeValue){}_GetIndex(){return this._sourceAdapter.GetIndex()}_GetTarget(){if(this._target)return this._target;this._target=this._sourceAdapter.GetTarget();return this._target}_PickSource(bFunc,eFunc,ivFunc,pFunc,wiFunc,
+aFunc){const id=this._propertyTrack.GetSourceAdapterId();switch(id){case "behavior":return bFunc();case "effect":return eFunc();case "instance-variable":return ivFunc();case "plugin":return pFunc();case "world-instance":return wiFunc();case "audio":return aFunc()}}_SaveToJson(){return{"firstAbsoluteUpdate":this._firstAbsoluteUpdate,"saveState":this._saveState}}_LoadFromJson(o){if(!o)return;this._firstAbsoluteUpdate=o["firstAbsoluteUpdate"];this._saveState=o["saveState"]}_GetPropertyKeyframeStubs(propertyTracks,
+firstOnly=false){const ret=[];for(const propertyTrack of propertyTracks){const startOffset=propertyTrack.GetTrack().GetStartOffset();for(const propertyKeyframeDataItem of propertyTrack.GetPropertyKeyframeDataItems())if(firstOnly&&propertyKeyframeDataItem.GetTime()===0)ret.push({time:startOffset+propertyKeyframeDataItem.GetTime(),value:propertyKeyframeDataItem.GetAbsoluteValue()});else if(!firstOnly)ret.push({time:startOffset+propertyKeyframeDataItem.GetTime(),value:propertyKeyframeDataItem.GetAbsoluteValue()})}return ret.sort((f,
+s)=>f.time-s.time)}_GetLastPropertyKeyframeStub(timeline,time,propertyKeyframeStubs){return this._GetPropertyKeyframeStubLowerThanPlayhead(time,propertyKeyframeStubs)}_GetPropertyKeyframeStubLowerThanPlayhead(time,propertyKeyframeStubs){for(let i=propertyKeyframeStubs.length-1;i>=0;i--){const stubTime=propertyKeyframeStubs[i].time;if(stubTime<=time)return propertyKeyframeStubs[i]}return null}};
+
+}
+
+// timelines/state/propertyInterpolationAdapters/colorInterpolationAdapter.js
+{
+'use strict';const C3=self.C3;const TMP_COLORS_MAP=new Map;const TMP_COLOR=[0,0,0];
+class ColorInterpolationAdapter extends C3.PropertyTrackState.PropertyInterpolationAdapter{constructor(sourceAdapter){super(sourceAdapter)}SetResetState(){}SetInitialState(){}SetResumeState(){}GetCurrentState(){const id=this._propertyTrack.GetSourceAdapterId();const target=this._GetTarget();const index=this._GetIndex();switch(id){case "behavior":return this._ToColorArray(target.GetPropertyValueByIndex(index));case "effect":return this._ToColorArray(target[index]);case "plugin":return this._ToColorArray(target.GetPropertyValueByIndex(index));
+case "world-instance":return this._ToColorArray(this._Getter())}}CompareInitialStateWithCurrent(){const firstKeyframeColor=this._FirstKeyframeGetter();return!this._CompareColors(firstKeyframeColor,this._Getter())}CompareSaveStateWithCurrent(){if(C3.IsNullOrUndefined(this._saveState))return false;return!this._CompareColors(this._saveState,this._Getter())}_CompareColors(fColor,sColor){fColor=this._GetColorFromArray(fColor);sColor=this._GetColorFromArray(sColor);return fColor.equalsIgnoringAlpha(sColor)}_FirstKeyframeGetter(){const color=
+super._FirstKeyframeGetter();return this._GetColorFromArray(color)}_CurrentKeyframeGetter(){const color=super._CurrentKeyframeGetter();return this._GetColorFromArray(color)}_GetAbsoluteInitialValue(value){}_ToColorArray(color){if(C3.IsInstanceOf(color,C3.Color))return color.toArray().slice(0,3);return color.slice(0,3)}_GetColorFromArray(color){if(C3.IsInstanceOf(color,C3.Color))return color;return new C3.Color(color[0],color[1],color[2],1)}CanChange(value){return true}MayNeedBeforeAndAfterInterpolate(){return true}BeforeChangeProperty(){const timeline=
+this._propertyTrack.GetTimeline();const instance=this._propertyTrack.GetInstance();const sourceAdapter=this._propertyTrack.GetSourceAdapter();const propertyTracks=timeline.GetSimilarPropertyTracks(instance,sourceAdapter,this._property,this._propertyTrack);if(propertyTracks&&propertyTracks.length>1){if(!TMP_COLORS_MAP.has(instance))TMP_COLORS_MAP.set(instance,new Map);const instanceMap=TMP_COLORS_MAP.get(instance);const id=this._propertyTrack.GetSourceAdapterId();if(!instanceMap.has(id))instanceMap.set(id,
+new Map);const sourceMap=instanceMap.get(id);if(!sourceMap.has(this._property))sourceMap.set(this._property,{used:false,color:new C3.Color(0,0,0,1)})}}_GetTmpColor(instance,sourceId,propertyName){const tmpColorObj=TMP_COLORS_MAP.get(instance).get(sourceId).get(propertyName);tmpColorObj.used=true;return tmpColorObj.color}ChangeProperty(time,value,start,end,setTime,ensureValue,endState,propertyKeyframeReached){const timeline=this._propertyTrack.GetTimeline();const track=this._propertyTrack.GetTrack();
+const instance=this._propertyTrack.GetInstance();const sourceAdapter=this._propertyTrack.GetSourceAdapter();const sourceAdapterId=this._propertyTrack.GetSourceAdapterId();const property=this._property;const propertyTracks=timeline.GetSimilarPropertyTracks(instance,sourceAdapter,property,this._propertyTrack);if(propertyTracks&&propertyTracks.length>1){const propertyKeyframeStubs=this._GetPropertyKeyframeStubs(propertyTracks,true);const stub=this._GetLastPropertyKeyframeStub(timeline,timeline.GetTime(),
+propertyKeyframeStubs);if(stub){const startOffset=track.GetStartOffset();const t=stub.time-startOffset;if(t===0)this._GetTmpColor(instance,sourceAdapterId,this._property).addRgb(value[0],value[1],value[2]);else{if(t<0)return;const r=value[0];const g=value[1];const b=value[2];const v=this._propertyTrack.Interpolate(t,false,true);const dr=C3.Color.DiffChannel(r,v[0]);const dg=C3.Color.DiffChannel(g,v[1]);const db=C3.Color.DiffChannel(b,v[2]);this._GetTmpColor(instance,sourceAdapterId,this._property).addRgb(dr,
+dg,db)}}}else this._Setter(value[0],value[1],value[2])}AfterChangeProperty(){const instance=this._propertyTrack.GetInstance();if(!TMP_COLORS_MAP.has(instance))return;const instanceMap=TMP_COLORS_MAP.get(instance);const id=this._propertyTrack.GetSourceAdapterId();if(!instanceMap.has(id))return;const sourceMap=instanceMap.get(id);if(!sourceMap.has(this._property))return;const tmpColorObj=sourceMap.get(this._property);const used=tmpColorObj.used;const color=tmpColorObj.color;if(used)this._Setter(color.getR(),
+color.getG(),color.getB());if(sourceMap.size===0)instanceMap.delete(id);if(instanceMap.size===0)TMP_COLORS_MAP.delete(instance)}_Getter(){const id=this._propertyTrack.GetSourceAdapterId();const target=this._GetTarget();const index=this._GetIndex();switch(id){case "behavior":return this._GetColorFromArray(target.GetPropertyValueByIndex(index));case "effect":return target[index].clone();case "plugin":return this._GetColorFromArray(target.GetPropertyValueByIndex(index));case "world-instance":return this.GetWorldInfo().GetUnpremultipliedColor().clone()}}_Setter(r,
+g,b){const id=this._propertyTrack.GetSourceAdapterId();const target=this._GetTarget();const index=this._GetIndex();switch(id){case "behavior":TMP_COLOR[0]=r;TMP_COLOR[1]=g;TMP_COLOR[2]=b;target.SetPropertyValueByIndex(index,TMP_COLOR);break;case "effect":target[index].setRgb(r,g,b);break;case "plugin":TMP_COLOR[0]=r;TMP_COLOR[1]=g;TMP_COLOR[2]=b;target.SetPropertyValueByIndex(index,TMP_COLOR);break;case "world-instance":this.GetWorldInfo().SetUnpremultipliedColorRGB(r,g,b);break}}_SaveToJson(){}_LoadFromJson(o){}}
+C3.PropertyTrackState.PropertyInterpolationAdapter.ColorInterpolationAdapter=ColorInterpolationAdapter;
+
+}
+
+// timelines/state/propertyInterpolationAdapters/noInterpolationAdapter.js
+{
+'use strict';const C3=self.C3;const NS=C3.PropertyTrackState;
+class NoInterpolationAdapter extends C3.PropertyTrackState.PropertyInterpolationAdapter{constructor(sourceAdapter){super(sourceAdapter)}SetResetState(){}SetInitialState(){}SetResumeState(){}GetCurrentState(){return this._Getter()}CompareInitialStateWithCurrent(){const firstKeyframeValue=this._FirstKeyframeGetter();return firstKeyframeValue!==this.GetCurrentState()}CompareSaveStateWithCurrent(){if(C3.IsNullOrUndefined(this._saveState))return false;return this._saveState!==this.GetCurrentState()}MayNeedBeforeAndAfterInterpolate(){return false}ChangeProperty(time,
+value,start,end,setTime,ensureValue,endState,propertyKeyframeReached){const propertyTrack=this._propertyTrack;const track=propertyTrack.GetTrack();const id=propertyTrack.GetSourceAdapterId();const timeline=propertyTrack.GetTimeline();const instance=track.GetInstance();const sourceAdapter=propertyTrack.GetSourceAdapter();const property=this._property;const propertyTracks=timeline.GetSimilarPropertyTracks(instance,sourceAdapter,property,propertyTrack);if(propertyTracks&&propertyTracks.length>1){const propertyKeyframeStubs=
+this._GetPropertyKeyframeStubs(propertyTracks);const t=time+track.GetStartOffset();const stub=this._GetLastPropertyKeyframeStub(timeline,t,propertyKeyframeStubs);if(stub)value=stub.value}const type=propertyTrack.GetPropertyKeyframeType();switch(type){case "numeric":{if(!NS.NumericTypeAdapter.WillChange(this._GetIndex(),this._GetTarget(),value,id))return;break}case "angle":{if(!NS.AngleTypeAdapter.WillChange(this._GetIndex(),this._GetTarget(),value,id))return;break}case "boolean":{if(!NS.BooleanTypeAdapter.WillChange(this._GetIndex(),
+this._GetTarget(),value,id))return;break}case "color":{if(!NS.ColorTypeAdapter.WillChange(this._GetIndex(),this._GetTarget(),value,id))return;break}case "text":{if(!NS.TextTypeAdapter.WillChange(this._GetIndex(),this._GetTarget(),value,id))return;break}}this._Setter(value)}_Getter(){const id=this._propertyTrack.GetSourceAdapterId();const target=this._GetTarget();const index=this._GetIndex();switch(id){case "behavior":return target.GetPropertyValueByIndex(index);case "effect":return target[index];
+case "instance-variable":return target.GetInstanceVariableValue(index);case "plugin":return target.GetPropertyValueByIndex(index)}}_Setter(value){const id=this._propertyTrack.GetSourceAdapterId();const target=this._GetTarget();const index=this._GetIndex();switch(id){case "behavior":target.SetPropertyValueByIndex(index,value);break;case "effect":target[index]=value;break;case "instance-variable":target.SetInstanceVariableValue(index,value);break;case "plugin":target.SetPropertyValueByIndex(index,value);
+break}}}C3.PropertyTrackState.PropertyInterpolationAdapter.NoInterpolationAdapter=NoInterpolationAdapter;
+
+}
+
+// timelines/state/propertyInterpolationAdapters/numericInterpolationAdapter.js
+{
+'use strict';const C3=self.C3;const NS=C3.PropertyTrackState.PropertyInterpolationAdapter;const INSTANCE_FUNC_MAP=new Map;const add=(prop,setter,absolute_setter,getter,round,fRound=false,init=null,reset=null)=>{INSTANCE_FUNC_MAP.set(prop,{setter,absolute_setter,getter,round,fRound,init,reset})};add("offsetX",(wi,v,t,a)=>{if(a._propertyTrack.GetResultMode()==="relative")wi.OffsetX(v,t.GetTimeline().GetTransformWithSceneGraph());else wi.OffsetX(v)},(wi,v)=>wi.SetX(v),wi=>wi.GetX(),true);
+add("offsetY",(wi,v,t,a)=>{if(a._propertyTrack.GetResultMode()==="relative")wi.OffsetY(v,t.GetTimeline().GetTransformWithSceneGraph());else wi.OffsetY(v)},(wi,v)=>wi.SetY(v),wi=>wi.GetY(),true);
+add("offsetWidth",(wi,v,t,a,noChanges)=>{if(v===0)return;const isRelative=a._propertyTrack.GetResultMode()==="relative";const isTween=a._typeAdapter.GetType()===1;if((isRelative||isTween)&&wi.HasParent()&&wi.GetTransformWithParentWidth()){if(isNaN(a._absoluteToFactor)){const parents=[];let parent=wi.GetParent();while(parent){parents.push(parent);parent=parent.GetParent()}parents.reverse();const get_track=(wi,t)=>{return t.GetTimeline().GetTrackFromInstance(wi.GetInstance())};const get_original_size=
+(wi,t)=>{const track=get_track(wi,t);if(track)return track.GetOriginalWidth();const sdki=wi.GetInstance().GetSdkInstance();if(sdki.IsOriginalSizeKnown())return sdki.GetOriginalWidth();return wi._GetSceneGraphInfo()._GetStartWidth()};const get_last_property_keyframe_value=(wi,t,propertyName,defaultValue=0)=>{const track=get_track(wi,t);if(!track)return defaultValue;const propertyTrack=track.GetPropertyTrack(propertyName);if(!propertyTrack)return defaultValue;const parentPropertyKeyframeData=propertyTrack.GetPropertyTrackDataItem().GetPropertyKeyframeData();
+if(!parentPropertyKeyframeData)return defaultValue;const parentLastPropertyKeyframeDataItem=parentPropertyKeyframeData.GetLastPropertyKeyframeDataItem();if(!parentLastPropertyKeyframeDataItem)return defaultValue;return parentLastPropertyKeyframeDataItem.GetValue()};let absoluteToFactor;if(isTween){let p=parents[parents.length-1];absoluteToFactor=p.GetWidth()}else{let p=parents[0];const ownStartSize=p._GetSceneGraphInfo()._GetStartWidth();const ownStartScale=p._GetSceneGraphInfo().GetStartScaleX();
+absoluteToFactor=ownStartSize*ownStartScale;absoluteToFactor+=get_last_property_keyframe_value(p,t,"offsetWidth");absoluteToFactor+=get_original_size(p,t)*get_last_property_keyframe_value(p,t,"offsetScaleX");for(let i=1;iwi.SetWidth(v),wi=>wi.GetWidth(),true);
+add("offsetHeight",(wi,v,t,a,noChanges)=>{if(v===0)return;const isRelative=a._propertyTrack.GetResultMode()==="relative";const isTween=a._typeAdapter.GetType()===1;if((isRelative||isTween)&&wi.HasParent()&&wi.GetTransformWithParentHeight()){if(isNaN(a._absoluteToFactor)){const parents=[];let parent=wi.GetParent();while(parent){parents.push(parent);parent=parent.GetParent()}parents.reverse();const get_track=(wi,t)=>{return t.GetTimeline().GetTrackFromInstance(wi.GetInstance())};const get_original_size=
+(wi,t)=>{const track=get_track(wi,t);if(track)return track.GetOriginalHeight();const sdki=wi.GetInstance().GetSdkInstance();if(sdki.IsOriginalSizeKnown())return sdki.GetOriginalHeight();return wi._GetSceneGraphInfo()._GetStartHeight()};const get_last_property_keyframe_value=(wi,t,propertyName,defaultValue=0)=>{const track=t.GetTimeline().GetTrackFromInstance(wi.GetInstance());if(!track)return defaultValue;const propertyTrack=track.GetPropertyTrack(propertyName);if(!propertyTrack)return defaultValue;
+const parentPropertyKeyframeData=propertyTrack.GetPropertyTrackDataItem().GetPropertyKeyframeData();if(!parentPropertyKeyframeData)return defaultValue;const parentLastPropertyKeyframeDataItem=parentPropertyKeyframeData.GetLastPropertyKeyframeDataItem();if(!parentLastPropertyKeyframeDataItem)return defaultValue;return parentLastPropertyKeyframeDataItem.GetValue()};let absoluteToFactor;if(isTween){let p=parents[parents.length-1];absoluteToFactor=p.GetHeight()}else{let p=parents[0];const ownStartSize=
+p._GetSceneGraphInfo()._GetStartHeight();const ownStartScale=p._GetSceneGraphInfo().GetStartScaleY();absoluteToFactor=ownStartSize*ownStartScale;absoluteToFactor+=get_last_property_keyframe_value(p,t,"offsetHeight");absoluteToFactor+=get_original_size(p,t)*get_last_property_keyframe_value(p,t,"offsetScaleY");for(let i=1;iwi.SetHeight(v),wi=>wi.GetHeight(),true);add("offsetAngle",(wi,v)=>wi.OffsetAngle(v),(wi,v)=>wi.SetAngle(v),wi=>wi.GetAngle(),false,true);
+add("offsetOpacity",(wi,v,t,a,noChanges)=>{const opacityFactor=a._opacityFactor?a._opacityFactor:1;v/=opacityFactor;const o=wi.GetOpacity();const nv=o+v;const min=0;const max=1;if(a._clampAccumulator===0){if(nv>max)a._clampAccumulator+=nv-max;else if(nv0&&a._clampAccumulator>0){if(nv>max)a._clampAccumulator+=nv-max}else if(v>0&&a._clampAccumulator<0){a._clampAccumulator+=v;if(a._clampAccumulator>0)a._clampAccumulator=
+0}else if(v<0&&a._clampAccumulator>0){a._clampAccumulator+=v;if(a._clampAccumulator<0)a._clampAccumulator=0}else if(v<0&&a._clampAccumulator<0)if(nv{wi.SetOpacity(v)},wi=>{return wi.GetOpacity()},false,true,(a,wi,t)=>{a._clampAccumulator=0;switch(a._propertyTrack.GetResultMode()){case "relative":{const propertyTrackData=a._propertyTrack.GetPropertyTrackData();const propertyTrackDataItem=a._propertyTrack.GetPropertyTrackDataItem();const propertyKeyframeData=propertyTrackDataItem.GetPropertyKeyframeData();
+const propertyKeyframeDataItems=propertyKeyframeData.GetPropertyKeyframeDataItemArray();let startingAbsoluteOpacity=a.GetWorldInfo().GetOpacity();let currentAbsoluteOpacity=startingAbsoluteOpacity;for(const propertyKeyframeDataItem of propertyKeyframeDataItems){const time=propertyKeyframeDataItem.GetTime();const currentRelativeOpacity=a._propertyTrack.GetInterpolatedValue(time);currentAbsoluteOpacity=startingAbsoluteOpacity+currentRelativeOpacity;currentAbsoluteOpacity=C3.clamp(currentAbsoluteOpacity,
+0,1)}a._totalForewardOpacityDelta=startingAbsoluteOpacity-currentAbsoluteOpacity;a._totalForewardOpacityDelta=Math.round((a._totalForewardOpacityDelta+Number.EPSILON)*100)/100;currentAbsoluteOpacity=startingAbsoluteOpacity;for(let i=propertyKeyframeDataItems.length-1;i>=0;i--){const time=propertyKeyframeDataItems[i].GetTime();const currentRelativeOpacity=a._propertyTrack.GetInterpolatedValue(time);currentAbsoluteOpacity-=currentRelativeOpacity;currentAbsoluteOpacity=C3.clamp(currentAbsoluteOpacity,
+0,1)}a._totalBackwardOpacityDelta=currentAbsoluteOpacity;a._totalBackwardOpacityDelta=Math.round((a._totalBackwardOpacityDelta+Number.EPSILON)*100)/100;break}case "absolute":{break}}const isRelative=a._propertyTrack.GetResultMode()==="relative";const isTween=a._typeAdapter.GetType()===1;if((isRelative||isTween)&&wi.HasParent()&&wi.GetTransformWithParentOpacity()){const parents=[];let parent=wi.GetParent();while(parent){parents.push(parent);parent=parent.GetParent()}parents.reverse();const get_last_property_keyframe_value=
+(wi,t,propertyName)=>{const track=t.GetTimeline().GetTrackFromInstance(wi.GetInstance());if(!track)return 0;const propertyTrack=track.GetPropertyTrack(propertyName);if(!propertyTrack)return 0;const parentPropertyKeyframeData=propertyTrack.GetPropertyTrackDataItem().GetPropertyKeyframeData();if(!parentPropertyKeyframeData)return 0;const parentLastPropertyKeyframeDataItem=parentPropertyKeyframeData.GetLastPropertyKeyframeDataItem();if(!parentLastPropertyKeyframeDataItem)return 0;return parentLastPropertyKeyframeDataItem.GetValue()};
+let opacityFactor=parents[0]._GetSceneGraphInfo().GetStartOpacity();opacityFactor+=get_last_property_keyframe_value(parents[0],t,"offsetOpacity");for(let i=1;i{switch(a._propertyTrack.GetResultMode()){case "relative":{a._clampAccumulator=0;const wi=a.GetWorldInfo();let currentOpacity=wi.GetOpacity();currentOpacity=Math.round((currentOpacity+Number.EPSILON)*
+100)/100;if(a._propertyTrack.GetTimeline().IsForwardPlayBack()){wi.SetOpacity(currentOpacity+a._totalForewardOpacityDelta);a._lastValue=0}else{wi.SetOpacity(currentOpacity-a._totalBackwardOpacityDelta);a._lastValue=a.GetSourceAdapter().GetValueAtTime()}break}case "absolute":{break}}});add("offsetOriginX",(wi,v)=>wi.OffsetOriginX(v),(wi,v)=>wi.SetOriginX(v),wi=>wi.GetOriginX(),false);add("offsetOriginY",(wi,v)=>wi.OffsetOriginY(v),(wi,v)=>wi.SetOriginY(v),wi=>wi.GetOriginY(),false);
+add("offsetZElevation",(wi,v)=>wi.OffsetZElevation(v),(wi,v)=>wi.SetZElevation(v),wi=>wi.GetZElevation(),true);
+add("offsetScaleX",(wi,v,t,a)=>{if(v===0)return;const mirrorFactor=wi.GetWidth()<0?-1:1;if(a._propertyTrack.GetResultMode()==="relative"&&wi.HasParent()&&wi.GetTransformWithParentWidth()){const value=t.GetOriginalWidth()*mirrorFactor*v;if(isNaN(a._absoluteToFactor))INSTANCE_FUNC_MAP.get("offsetWidth").setter(wi,1,t,a,true);wi.OffsetWidth(value/a._absoluteToFactor,true)}else wi.OffsetWidth(t.GetOriginalWidth()*mirrorFactor*v)},(wi,v,t)=>{wi.SetWidth(t.GetOriginalWidth()*v)},(wi,t)=>{const mirrorFactor=
+wi.GetWidth()<0?-1:1;if(wi.GetTransformWithParentWidth()){const parentWi=wi.GetParent();const parentTrack=t.GetTimeline().GetTrackFromInstance(parentWi.GetInstance());let parentScale=NaN;if(parentTrack)parentScale=parentWi.GetWidth()/parentTrack.GetOriginalWidth();else{const sdki=parentWi.GetInstance().GetSdkInstance();if(sdki.IsOriginalSizeKnown())parentScale=parentWi.GetWidth()/sdki.GetOriginalWidth();else parentScale=1}return wi.GetWidth()*mirrorFactor/(t.GetOriginalWidth()*parentScale)}else return wi.GetWidth()*
+mirrorFactor/t.GetOriginalWidth()},false);
+add("offsetScaleY",(wi,v,t,a)=>{if(v===0)return;const flipFactor=wi.GetHeight()<0?-1:1;if(a._propertyTrack.GetResultMode()==="relative"&&wi.HasParent()&&wi.GetTransformWithParentHeight()){const value=t.GetOriginalHeight()*flipFactor*v;if(isNaN(a._absoluteToFactor))INSTANCE_FUNC_MAP.get("offsetHeight").setter(wi,1,t,a,true);wi.OffsetHeight(value/a._absoluteToFactor,true)}else wi.OffsetHeight(t.GetOriginalHeight()*flipFactor*v)},(wi,v,t)=>{wi.SetHeight(t.GetOriginalHeight()*v)},(wi,t)=>{const flipFactor=
+wi.GetHeight()<0?-1:1;if(wi.GetTransformWithParentHeight()){const parentWi=wi.GetParent();const parentTrack=t.GetTimeline().GetTrackFromInstance(parentWi.GetInstance());let parentScale=NaN;if(parentTrack)parentScale=parentWi.GetHeight()/parentTrack.GetOriginalHeight();else{const sdki=parentWi.GetInstance().GetSdkInstance();if(sdki.IsOriginalSizeKnown())parentScale=parentWi.GetHeight()/sdki.GetOriginalHeight();else parentScale=1}return wi.GetHeight()*flipFactor/(t.GetOriginalHeight()*parentScale)}else return wi.GetHeight()*
+flipFactor/t.GetOriginalHeight()},false);
+class NumericInterpolationAdapter extends C3.PropertyTrackState.PropertyInterpolationAdapter{constructor(sourceAdapter){super(sourceAdapter);this._lastValue=0;this._clampAccumulator=0;this._totalForewardOpacityDelta=0;this._totalBackwardOpacityDelta=0;this._opacityFactor=NaN;this._absoluteToFactor=NaN;this._instance_getter=null;this._instance_setter=null;this._instance_absolute_setter=null;this._reset_action=null;this._init_action=null;this._source_adapter_getter=null;this._source_adapter_setter=
+null;this._source_adapter_absolute_setter=null;this._round=false;this._fRound=false;if(C3.IsInstanceOf(this._propertyTrack.GetTimeline(),C3.TweenState))this._typeAdapter=new C3.PropertyTrackState.PropertyInterpolationAdapter.NumericInterpolationAdapterForTween(this);else this._typeAdapter=new C3.PropertyTrackState.PropertyInterpolationAdapter.NumericInterpolationAdapterForTimeline(this);const property=this._propertyTrack.GetPropertyName();switch(this._propertyTrack.GetSourceAdapterId()){case "world-instance":{const p=
+INSTANCE_FUNC_MAP.get(property);this._instance_getter=p.getter;this._instance_setter=p.setter;this._instance_absolute_setter=p.absolute_setter;this._round=p.round;this._fRound=p.fRound;this._init_action=p.init;this._reset_action=p.reset;break}case "audio":{this._source_adapter_getter=sourceAdapter.Getter;this._source_adapter_setter=sourceAdapter.Setter;this._source_adapter_absolute_setter=sourceAdapter.AbsoluteSetter;this._round=!!sourceAdapter.DoesRounding();this._fRound=false;break}}}Release(){this._typeAdapter=
+null;this._instance_getter=null;this._instance_setter=null;this._instance_absolute_setter=null;this._absoluteToFactor=NaN;super.Release()}MayNeedBeforeAndAfterInterpolate(){return this._typeAdapter.MayNeedBeforeAndAfterInterpolate()}GetLastValue(){return this._lastValue}SetLastValue(v){this._lastValue=v}SetResetState(){if(this._reset_action)this._reset_action(this)}SetInitialState(){const initValue=this._typeAdapter.SetInitialState();if(typeof initValue==="number")this._lastValue=initValue;if(this._init_action){const wi=
+this.GetWorldInfo();const track=this._propertyTrack.GetTrack();this._init_action(this,wi,track)}}SetResumeState(){const resumeValue=this._typeAdapter.SetResumeState();if(typeof resumeValue==="number")this._lastValue=resumeValue}GetCurrentState(){return this._Getter()}CompareInitialStateWithCurrent(){const firstKeyframeValue=this._FirstKeyframeGetter();return firstKeyframeValue!==this.GetCurrentState()}CompareSaveStateWithCurrent(){if(C3.IsNullOrUndefined(this._saveState))return false;return this._saveState!==
+this.GetCurrentState()}BeforeChangeProperty(){this._typeAdapter.BeforeChangeProperty()}ChangeProperty(time,value,start,end,setTime,ensureValue,endState,propertyKeyframeReached){return this._typeAdapter.ChangeProperty(time,value,start,end,setTime,ensureValue,endState,propertyKeyframeReached)}AfterChangeProperty(){this._typeAdapter.AfterChangeProperty()}_Getter(){const target=this._GetTarget();const index=this._GetIndex();const wi=this.GetWorldInfo();const track=this._propertyTrack.GetTrack();const id=
+this._propertyTrack.GetSourceAdapterId();switch(id){case "behavior":return target.GetPropertyValueByIndex(index);case "effect":return target[index];case "instance-variable":return target.GetInstanceVariableValue(index);case "plugin":return target.GetPropertyValueByIndex(index);case "world-instance":return this._instance_getter(wi,track);case "audio":return this._source_adapter_getter.call(this.GetSourceAdapter(),wi,track)}}_Setter(value,start,end){const target=this._GetTarget();const index=this._GetIndex();
+const wi=this.GetWorldInfo();const track=this._propertyTrack.GetTrack();const id=this._propertyTrack.GetSourceAdapterId();switch(id){case "behavior":target.OffsetPropertyValueByIndex(index,value);break;case "effect":target[index]+=value;break;case "instance-variable":target.SetInstanceVariableOffset(index,value);break;case "plugin":target.OffsetPropertyValueByIndex(index,value,this.GetSourceAdapter().GetOptionalCallbacks());break;case "world-instance":this._instance_setter(wi,value,track,this);break;
+case "audio":this._source_adapter_setter.call(this.GetSourceAdapter(),wi,value,track,this);break}}_SetterAbsolute(value,propertyKeyframeReached,endState){let mode=this._propertyTrack.GetInterpolationMode();mode=mode==="default"?"continuous":mode;if(mode==="discrete"&&!propertyKeyframeReached)return;if(mode==="discrete"&&endState){const timeline=this._propertyTrack.GetTimeline();const time=timeline.GetTime();const propertyKeyframeDataItem=this._propertyTrack.GetPropertyKeyFrameDataItemAtTime(time);
+if(!propertyKeyframeDataItem)return}const target=this._GetTarget();const index=this._GetIndex();const wi=this.GetWorldInfo();const track=this._propertyTrack.GetTrack();const id=this._propertyTrack.GetSourceAdapterId();switch(id){case "behavior":target.SetPropertyValueByIndex(index,value);break;case "effect":target[index]=value;break;case "instance-variable":target.SetInstanceVariableValue(index,value);break;case "plugin":target.SetPropertyValueByIndex(index,value,this.GetSourceAdapter().GetOptionalCallbacks());
+break;case "world-instance":this._instance_absolute_setter(wi,value,track);break;case "audio":this._source_adapter_absolute_setter.call(this.GetSourceAdapter(),wi,value,track);break}}_MaybeEnsureValue(time,start,end,setTime,lastValue,currentValue,forceEndValue,endState){this._typeAdapter._MaybeEnsureValue(time,start,end,setTime,lastValue,currentValue,forceEndValue,endState)}_AddDelta(value,start,end,forceEndValue,endState){switch(this._propertyTrack.GetPropertyType()){case "angle":{value=C3.toDegrees(value);
+break}default:{value=value;break}}const stringValue=value.toString();const decimalsString=stringValue.split(".")[1]||"";const decimalPlaces=decimalsString.length;const v=this._Getter();let rv;if(decimalPlaces===0)if(this._round)rv=Math.round(v);else if(this._fRound)switch(this._propertyTrack.GetPropertyType()){case "angle":{rv=C3.toRadians(Math.round(C3.toDegrees(v)));break}default:{rv=Math.round((v+Number.EPSILON)*100)/100;break}}else rv=v;else if(this._round)rv=Number(C3.toFixed(v,decimalPlaces));
+else if(this._fRound)rv=v;else rv=v;this._Setter(rv-v,start,end)}_SaveToJson(){return Object.assign(super._SaveToJson(),{"v":this._lastValue,"a":this._clampAccumulator,"fod":this._totalForewardOpacityDelta,"bod":this._totalBackwardOpacityDelta})}_LoadFromJson(o){if(!o)return;super._LoadFromJson(o);this._lastValue=o["v"];this._clampAccumulator=o["a"];this._totalForewardOpacityDelta=C3.IsFiniteNumber(o["fod"])?o["fod"]:0;this._totalBackwardOpacityDelta=C3.IsFiniteNumber(o["bod"])?o["bod"]:0}}
+C3.PropertyTrackState.PropertyInterpolationAdapter.NumericInterpolationAdapter=NumericInterpolationAdapter;
+
+}
+
+// timelines/state/propertyInterpolationAdapters/numericInterpolationAdapterForTimeline.js
+{
+'use strict';const C3=self.C3;
+class AbsoluteValueObject{constructor(propertyTracks){this._used=false;this._value=0;this._propertyKeyframeReached=false;this._endState=false;this._propertyTracks=propertyTracks;for(let i=0,l=this._propertyTracks.length;i{return adapter._PickTimelinePlaybackMode(()=>0,()=>adapter.GetSourceAdapter().GetValueAtTime())},()=>{})}SetResumeState(){}MayNeedBeforeAndAfterInterpolate(){const adapter=
+this._numericInterpolationAdapter;const propertyTrack=this._numericInterpolationAdapter.GetPropertyTrack();switch(propertyTrack.GetResultMode()){case "relative":{return false}case "absolute":{return true}}}BeforeChangeProperty(){const adapter=this._numericInterpolationAdapter;const propertyTrack=this._numericInterpolationAdapter.GetPropertyTrack();const property=propertyTrack.GetPropertyName();switch(propertyTrack.GetResultMode()){case "relative":{break}case "absolute":{if(propertyTrack.HasAbsoluteValueObject()){const valueObj=
+propertyTrack.GetAbsoluteValueObject();valueObj.Reset()}else{const timeline=propertyTrack.GetTimeline();const instance=propertyTrack.GetInstance();const sourceAdapter=propertyTrack.GetSourceAdapter();const similarPropertyTracks=timeline.GetSimilarPropertyTracks(instance,sourceAdapter,property,propertyTrack);if(similarPropertyTracks&&similarPropertyTracks.length>1)new AbsoluteValueObject(similarPropertyTracks)}break}}}ChangeProperty(time,value,start,end,setTime,ensureValue,endState,propertyKeyframeReached){const adapter=
+this._numericInterpolationAdapter;const propertyTrack=this._numericInterpolationAdapter.GetPropertyTrack();switch(propertyTrack.GetResultMode()){case "relative":{const lastValue=adapter.GetLastValue();adapter._Setter(value-lastValue,start,end);if(ensureValue)this._MaybeEnsureValue(time,start,end,setTime,lastValue,value);adapter.SetLastValue(value);break}case "absolute":{const timeline=propertyTrack.GetTimeline();const track=propertyTrack.GetTrack();const instance=propertyTrack.GetInstance();const sourceAdapter=
+propertyTrack.GetSourceAdapter();if(propertyTrack.HasAbsoluteValueObject()){const absoluteValueObject=propertyTrack.GetAbsoluteValueObject();const similarpropertyTracks=absoluteValueObject.GetPropertyTracks();const propertyKeyframeStubs=adapter._GetPropertyKeyframeStubs(similarpropertyTracks,true);const stub=adapter._GetLastPropertyKeyframeStub(timeline,timeline.GetTime(),propertyKeyframeStubs);if(stub){const startOffset=track.GetStartOffset();const t=stub.time-startOffset;if(t===0){absoluteValueObject.SetEndState(endState);
+absoluteValueObject.SetPropertyKeyframeReached(propertyKeyframeReached);absoluteValueObject.SetUsed();absoluteValueObject.SetValue(absoluteValueObject.GetValue()+value)}else{if(t<0)return;const v=propertyTrack.GetInterpolatedValue(t);absoluteValueObject.SetEndState(endState);absoluteValueObject.SetPropertyKeyframeReached(propertyKeyframeReached);absoluteValueObject.SetUsed();absoluteValueObject.SetValue(absoluteValueObject.GetValue()+(value-v))}}}else adapter._SetterAbsolute(value,propertyKeyframeReached,
+endState);break}}}AfterChangeProperty(){const adapter=this._numericInterpolationAdapter;const propertyTrack=this._numericInterpolationAdapter.GetPropertyTrack();switch(propertyTrack.GetResultMode()){case "relative":{break}case "absolute":{if(propertyTrack.HasAbsoluteValueObject()){const absoluteValueObject=propertyTrack.GetAbsoluteValueObject();if(absoluteValueObject.GetUsed())adapter._SetterAbsolute(absoluteValueObject.GetValue(),absoluteValueObject.GetPropertyKeyframeReached(),absoluteValueObject.GetEndState())}break}}}_MaybeEnsureValue(time,
+start,end,setTime,lastValue,currentValue){const adapter=this._numericInterpolationAdapter;if(setTime)return;if(start&&time===start.GetTime())adapter._AddDelta(start.GetValueWithResultMode(),start,end);else if(end&&time===end.GetTime())adapter._AddDelta(end.GetValueWithResultMode(),start,end);else if(currentValue-lastValue===0)adapter._AddDelta(start.GetValueWithResultMode(),start,end)}}C3.PropertyTrackState.PropertyInterpolationAdapter.NumericInterpolationAdapterForTimeline=NumericInterpolationAdapterForTimeline;
+
+}
+
+// timelines/state/propertyInterpolationAdapters/numericInterpolationAdapterForTween.js
+{
+'use strict';const C3=self.C3;
+class NumericInterpolationAdapterForTween{constructor(numericInterpolationAdapter){this._numericInterpolationAdapter=numericInterpolationAdapter}Release(){this._numericInterpolationAdapter=null}GetType(){return 1}SetInitialState(){const adapter=this._numericInterpolationAdapter;adapter.SetFirstAbsoluteUpdate(true);return this._GetAbsoluteInitialValue(adapter._FirstKeyframeGetter())}SetResumeState(){const adapter=this._numericInterpolationAdapter;if(adapter._FirstKeyframeGetter()===adapter._CurrentKeyframeGetter())return;
+adapter.SetFirstAbsoluteUpdate(true);return this._GetAbsoluteInitialValue(adapter._CurrentKeyframeGetter())}MayNeedBeforeAndAfterInterpolate(){return false}BeforeChangeProperty(){}ChangeProperty(time,value,start,end,setTime,ensureValue,endState,propertyKeyframeReached){const adapter=this._numericInterpolationAdapter;const lastValue=adapter.GetLastValue();switch(adapter.GetPropertyTrack().GetResultMode()){case "relative":{adapter._Setter(value-lastValue,start,end);if(ensureValue)this._MaybeEnsureValue(time,
+start,end,setTime,lastValue,value,false,endState);break}case "absolute":{if(adapter.GetFirstAbsoluteUpdate()){adapter.SetFirstAbsoluteUpdate(false);adapter._Setter(lastValue,start,end)}else if(time===0&&adapter.GetPropertyTrack().GetTimeline().GetTotalTime()===0)adapter._SetterAbsolute(value,true,false);else{adapter._Setter(value-lastValue,start,end);if(ensureValue)this._MaybeEnsureValue(time,start,end,setTime,lastValue,value,this._ForceEndValue(),endState)}break}}adapter.SetLastValue(value)}AfterChangeProperty(){}_GetAbsoluteInitialValue(keyframeValue){const adapter=
+this._numericInterpolationAdapter;return keyframeValue-adapter.GetCurrentState()}_ForceEndValue(){const adapter=this._numericInterpolationAdapter;const inst=adapter.GetWorldInfo().GetInstance();const runtime=adapter.GetPropertyTrack().GetRuntime();const timelineManager=runtime.GetTimelineManager();let activeTimelineCount=0;for(const timeline of timelineManager.GetPlayingTimelines())if(timeline.GetType()===0){if(timeline.HasTrackInstance(inst))activeTimelineCount++}else if(timeline.GetType()===1)if(timeline.GetInstance()===
+inst)activeTimelineCount++;return activeTimelineCount<=1}_MaybeEnsureValue(time,start,end,setTime,lastValue,currentValue,forceEndValue,endState){const adapter=this._numericInterpolationAdapter;if(setTime)if(start&&time===start.GetTime())adapter._AddDelta(start.GetValueWithResultMode(),start,end,forceEndValue,endState);else if(end&&time===end.GetTime())adapter._AddDelta(end.GetValueWithResultMode(),start,end,forceEndValue,endState);else{if(!end)adapter._AddDelta(start.GetValueWithResultMode(),start,
+end,forceEndValue,endState)}else if(start&&time===start.GetTime())adapter._AddDelta(start.GetValueWithResultMode(),start,end,forceEndValue,endState);else if(end&&time===end.GetTime())adapter._AddDelta(end.GetValueWithResultMode(),start,end,forceEndValue,endState);else if(currentValue-lastValue===0)adapter._AddDelta(start.GetValueWithResultMode(),start,end,forceEndValue,endState)}}C3.PropertyTrackState.PropertyInterpolationAdapter.NumericInterpolationAdapterForTween=NumericInterpolationAdapterForTween;
+
+}
+
+// timelines/state/propertyTypeAdapters/numericTypeAdapter.js
+{
+'use strict';const C3=self.C3;const Ease=self.Ease;
+C3.PropertyTrackState.NumericTypeAdapter=class NumericTypeAdapter{constructor(){}static WillChange(index,source,newValue,type){let oldValue;switch(type){case "behavior":oldValue=source.GetPropertyValueByIndex(index);break;case "effect":oldValue=source[index];break;case "instance-variable":oldValue=source.GetInstanceVariableValue(index);break;case "plugin":oldValue=source.GetPropertyValueByIndex(index);break}if(oldValue===newValue)return false;return true}static Interpolate(time,start,end,propertyTrack){if(!end){let propertyTrackDataItem=
+propertyTrack.GetPropertyTrackDataItem();const propertyTrackData=propertyTrack.GetPropertyTrackData();propertyTrackDataItem=propertyTrackData.GetLastPropertyKeyframeDataItem(propertyTrackDataItem);return propertyTrackDataItem.GetValueWithResultMode()}let mode=propertyTrack.GetInterpolationMode();if(mode==="default")mode="continuous";if(propertyTrack.GetPropertyType()==="combo")mode="discrete";if(mode==="discrete")return start.GetValueWithResultMode();else if(mode==="continuous"||mode==="step"){const step=
+propertyTrack.GetTimeline().GetStep();if(mode==="step"&&step!==0){const s=1/step;time=Math.floor(time*s)/s}const sv=start.GetValueWithResultMode();const ev=end.GetValueWithResultMode();const startAddon=start.GetAddOn("cubic-bezier");const endAddon=end.GetAddOn("cubic-bezier");const doCubicBezier=startAddon&&startAddon.GetStartEnable()&&endAddon&&endAddon.GetEndEnable();if(!doCubicBezier&&sv===ev)return sv;const st=start.GetTime();const et=end.GetTime();if(mode==="step"&&step!==0)time=C3.clamp(time,
+st,et);const n=C3.normalize(time,st,et);const e=start.GetEase();let ret;if(doCubicBezier){const dt=et-st;ret=Ease.GetRuntimeEase(e)(dt*n,0,1,dt);ret=Ease.GetRuntimeEase("cubicbezier")(ret,sv,sv+startAddon.GetStartAnchor(),ev+endAddon.GetEndAnchor(),ev)}else ret=Ease.GetRuntimeEase(e)((et-st)*n,sv,ev-sv,et-st);if(propertyTrack.GetPropertyType()==="integer")return Math.floor(ret);return ret}}};
+
+}
+
+// timelines/state/propertyTypeAdapters/angleTypeAdapter.js
+{
+'use strict';const C3=self.C3;
+C3.PropertyTrackState.AngleTypeAdapter=class AngleTypeAdapter{constructor(){}static WillChange(index,source,newValue,type){let oldValue;switch(type){case "behavior":oldValue=source.GetPropertyValueByIndex(index);break;case "effect":oldValue=source[index];break;case "instance-variable":oldValue=source.GetInstanceVariableValue(index);break;case "plugin":oldValue=source.GetPropertyValueByIndex(index);break}if(oldValue===newValue)return false;return true}static Interpolate(time,start,end,propertyTrack){if(!end){let propertyTrackDataItem=
+propertyTrack.GetPropertyTrackDataItem();const propertyTrackData=propertyTrack.GetPropertyTrackData();propertyTrackDataItem=propertyTrackData.GetLastPropertyKeyframeDataItem(propertyTrackDataItem);return propertyTrackDataItem.GetValueWithResultMode()}let mode=propertyTrack.GetInterpolationMode();if(mode==="default")mode="continuous";if(propertyTrack.GetPropertyType()==="combo")mode="discrete";if(mode==="discrete")return start.GetValueWithResultMode();else if(mode==="continuous"||mode==="step"){const step=
+propertyTrack.GetTimeline().GetStep();if(mode==="step"&&step!==0){const s=1/step;time=Math.floor(time*s)/s}const st=start.GetTime();const et=end.GetTime();const sv=start.GetValueWithResultMode();const ev=end.GetValueWithResultMode();if(mode==="step"&&step!==0)time=C3.clamp(time,st,et);const angleAddon=start.GetAddOn("angle");if(angleAddon){const revolutions=angleAddon.GetRevolutions();if(sv===ev&&revolutions===0)return sv;const n=C3.normalize(time,st,et);const easeFunc=self.Ease.GetRuntimeEase(start.GetEase());
+const easeRes=easeFunc(n,0,1,1);switch(angleAddon.GetDirection()){case "closest":return C3.angleLerp(sv,ev,easeRes,revolutions);case "clockwise":return C3.angleLerpClockwise(sv,ev,easeRes,revolutions);case "anti-clockwise":return C3.angleLerpAntiClockwise(sv,ev,easeRes,revolutions)}}else{if(sv===ev)return sv;const n=C3.normalize(time,st,et);const easeFunc=self.Ease.GetRuntimeEase(start.GetEase());return C3.angleLerp(sv,ev,easeFunc(n,0,1,1))}}}};
+
+}
+
+// timelines/state/propertyTypeAdapters/booleanTypeAdapter.js
+{
+'use strict';const C3=self.C3;
+C3.PropertyTrackState.BooleanTypeAdapter=class BooleanTypeAdapter{constructor(){}static WillChange(index,source,newValue,type){let oldValue;switch(type){case "behavior":oldValue=source.GetPropertyValueByIndex(index);break;case "effect":oldValue=source[index];break;case "instance-variable":oldValue=source.GetInstanceVariableValue(index);break;case "plugin":oldValue=source.GetPropertyValueByIndex(index);break}if(!!oldValue===!!newValue)return false;return true}static Interpolate(time,start,end,propertyTrack){if(!end){let propertyTrackDataItem=
+propertyTrack.GetPropertyTrackDataItem();const propertyTrackData=propertyTrack.GetPropertyTrackData();propertyTrackDataItem=propertyTrackData.GetLastPropertyKeyframeDataItem(propertyTrackDataItem);return propertyTrackDataItem.GetValueWithResultMode()?1:0}return start.GetValueWithResultMode()?1:0}};
+
+}
+
+// timelines/state/propertyTypeAdapters/colorTypeAdapter.js
+{
+'use strict';const C3=self.C3;const TEMP_COLOR_ARRAY=[0,0,0];const TEMP_COLOR_ARRAY_2=[0,0,0];const TEMP_COLOR_ARRAY_3=[0,0,0];
+C3.PropertyTrackState.ColorTypeAdapter=class ColorTypeAdapter{constructor(){}static WillChange(index,source,newValue,type){let oldValue;switch(type){case "behavior":oldValue=source.GetPropertyValueByIndex(index);break;case "effect":oldValue=source[index];break;case "instance-variable":oldValue=source.GetInstanceVariableValue(index);break;case "plugin":oldValue=source.GetPropertyValueByIndex(index);break}if(Array.isArray(newValue)){TEMP_COLOR_ARRAY[0]=newValue[0];TEMP_COLOR_ARRAY[1]=newValue[1];TEMP_COLOR_ARRAY[2]=
+newValue[2]}else{TEMP_COLOR_ARRAY_3.parseCommaSeparatedRgb(newValue);TEMP_COLOR_ARRAY[0]=Math.floor(TEMP_COLOR_ARRAY_3.getR()*255);TEMP_COLOR_ARRAY[1]=Math.floor(TEMP_COLOR_ARRAY_3.getG()*255);TEMP_COLOR_ARRAY[2]=Math.floor(TEMP_COLOR_ARRAY_3.getB()*255)}if(Array.isArray(oldValue)){TEMP_COLOR_ARRAY_2[0]=oldValue[0];TEMP_COLOR_ARRAY_2[1]=oldValue[1];TEMP_COLOR_ARRAY_2[2]=oldValue[2]}else{TEMP_COLOR_ARRAY_3.parseCommaSeparatedRgb(oldValue);TEMP_COLOR_ARRAY_2[0]=Math.floor(TEMP_COLOR_ARRAY_3.getR()*
+255);TEMP_COLOR_ARRAY_2[1]=Math.floor(TEMP_COLOR_ARRAY_3.getG()*255);TEMP_COLOR_ARRAY_2[2]=Math.floor(TEMP_COLOR_ARRAY_3.getB()*255)}if(TEMP_COLOR_ARRAY[0]!==TEMP_COLOR_ARRAY_2[0])return true;if(TEMP_COLOR_ARRAY[1]!==TEMP_COLOR_ARRAY_2[1])return true;if(TEMP_COLOR_ARRAY[2]!==TEMP_COLOR_ARRAY_2[2])return true;return false}static Interpolate(time,start,end,propertyTrack){if(!end){let propertyTrackDataItem=propertyTrack.GetPropertyTrackDataItem();const propertyTrackData=propertyTrack.GetPropertyTrackData();
+propertyTrackDataItem=propertyTrackData.GetLastPropertyKeyframeDataItem(propertyTrackDataItem);const color=propertyTrackDataItem.GetValueWithResultMode();TEMP_COLOR_ARRAY[0]=color[0];TEMP_COLOR_ARRAY[1]=color[1];TEMP_COLOR_ARRAY[2]=color[2];return TEMP_COLOR_ARRAY}let mode=propertyTrack.GetInterpolationMode();if(mode==="default")mode="continuous";if(mode==="discrete"){const color=start.GetValueWithResultMode();TEMP_COLOR_ARRAY[0]=color[0];TEMP_COLOR_ARRAY[1]=color[1];TEMP_COLOR_ARRAY[2]=color[2];
+return TEMP_COLOR_ARRAY}else if(mode==="continuous"||mode==="step"){const step=propertyTrack.GetTimeline().GetStep();if(mode==="step"&&step!==0){const s=1/step;time=Math.floor(time*s)/s}const st=start.GetTime();const et=end.GetTime();const sv=start.GetValueWithResultMode();const ev=end.GetValueWithResultMode();if(mode==="step"&&step!==0)time=C3.clamp(time,st,et);const n=C3.normalize(time,st,et);const e=start.GetEase();const sr=sv[0];const sg=sv[1];const sb=sv[2];const er=ev[0];const eg=ev[1];const eb=
+ev[2];const easeFunc=self.Ease.GetRuntimeEase(e);const d=et-st;const dn=d*n;if(sr===er)TEMP_COLOR_ARRAY[0]=sr;else TEMP_COLOR_ARRAY[0]=easeFunc(dn,sr,er-sr,d);if(sg===eg)TEMP_COLOR_ARRAY[1]=sg;else TEMP_COLOR_ARRAY[1]=easeFunc(dn,sg,eg-sg,d);if(sb===eb)TEMP_COLOR_ARRAY[2]=sb;else TEMP_COLOR_ARRAY[2]=easeFunc(dn,sb,eb-sb,d);return TEMP_COLOR_ARRAY}}};
+
+}
+
+// timelines/state/propertyTypeAdapters/textTypeAdapter.js
+{
+'use strict';const C3=self.C3;
+C3.PropertyTrackState.TextTypeAdapter=class TextTypeAdapter{constructor(){}static WillChange(index,source,newValue,type){let oldValue;switch(type){case "behavior":oldValue=source.GetPropertyValueByIndex(index);break;case "effect":oldValue=source[index];break;case "instance-variable":oldValue=source.GetInstanceVariableValue(index);break;case "plugin":oldValue=source.GetPropertyValueByIndex(index);break}if(oldValue===newValue)return false;return true}static Interpolate(time,start,end,propertyTrack){if(!end){let propertyTrackDataItem=
+propertyTrack.GetPropertyTrackDataItem();const propertyTrackData=propertyTrack.GetPropertyTrackData();propertyTrackDataItem=propertyTrackData.GetLastPropertyKeyframeDataItem(propertyTrackDataItem);return propertyTrackDataItem.GetValueWithResultMode()}return start.GetValueWithResultMode()}};
+
+}
+
+// timelines/data/timelineDataManager.js
+{
+'use strict';const C3=self.C3;
+C3.TimelineDataManager=class TimelineDataManager{constructor(){this._timelineDataItems=new Map}Release(){for(const timelineDataItem of this._timelineDataItems.values())timelineDataItem.Release();this._timelineDataItems.clear();this._timelineDataItems=null}Add(data){const timelineDataItem=new C3.TimelineDataItem(data);const name=timelineDataItem.GetName();this._timelineDataItems.set(name,timelineDataItem)}Get(name){return this._timelineDataItems.get(name)}GetNameId(){return 0}static _CreateDataItems(items,jsonItems,
+dataItemConstructor,dataContainer){if(!jsonItems)return;for(const jsonItem of jsonItems)C3.TimelineDataManager._CreateDataItem("create",jsonItem,items,dataItemConstructor,dataContainer)}static _CreateDataItemsIncludingDisabled(items,jsonItems,dataItemConstructor,dataContainer){if(!jsonItems)return;for(const jsonItem of jsonItems)C3.TimelineDataManager._CreateDataItem("create-including-disabled",jsonItem,items,dataItemConstructor,dataContainer)}static _LoadDataItemsFromJson(items,jsonItems,dataItemConstructor,
+dataContainer){if(items.length)jsonItems.forEach((jsonItem,index)=>{items[index]._LoadFromJson(jsonItem)});else jsonItems.forEach(jsonItem=>{C3.TimelineDataManager._CreateDataItem("load",jsonItem,items,dataItemConstructor,dataContainer)})}static _CreateDataItem(mode,json,items,dataItemConstructor,dataContainer){let dataItem;if(typeof dataItemConstructor==="function")switch(mode){case "load":dataItem=new dataItemConstructor(null,dataContainer);break;case "create":dataItem=new dataItemConstructor(json,
+dataContainer);break;case "create-including-disabled":dataItem=new dataItemConstructor(json,dataContainer);break}else if(typeof dataItemConstructor==="object"){const prop=dataItemConstructor.prop;const value=json[prop];const cnstrctr=dataItemConstructor.map.get(value);switch(mode){case "load":dataItem=new cnstrctr(null,dataContainer);break;case "create":dataItem=new cnstrctr(json,dataContainer);break;case "create-including-disabled":dataItem=new cnstrctr(json,dataContainer);break}}switch(mode){case "load":dataItem._LoadFromJson(json);
+items.push(dataItem);break;case "create":if(typeof dataItem.GetEnable==="function"&&!dataItem.GetEnable())return dataItem.Release();items.push(dataItem);break;case "create-including-disabled":items.push(dataItem);break}}};
+
+}
+
+// timelines/data/timelineData.js
+{
+'use strict';const C3=self.C3;const NAME=0;const TOTAL_TIME=1;const STEP=2;const INTERPOLATION_MODE=3;const RESULT_MODE=4;const TRACKS=5;const LOOP=6;const PING_PONG=7;const REPEAT_COUNT=8;const START_ON_LAYOUT=9;const TRANSFORM_WITH_SCENE_GRAPH=10;const USE_SYSTEM_TIMESCALE=11;
+C3.TimelineDataItem=class TimelineDataItem{constructor(timelineDataJson){this._name="";this._totalTime=NaN;this._step=0;this._interpolationMode="default";this._resultMode="default";this._loop=false;this._pingPong=false;this._repeatCount=1;this._trackData=null;this._startOnLayout="";this._transformWithSceneGraph=false;this._useSystemTimescale=true;if(!timelineDataJson)return;this._name=timelineDataJson[NAME];this._totalTime=timelineDataJson[TOTAL_TIME];this._step=timelineDataJson[STEP];this._interpolationMode=
+timelineDataJson[INTERPOLATION_MODE];this._resultMode=timelineDataJson[RESULT_MODE];this._loop=!!timelineDataJson[LOOP];this._pingPong=!!timelineDataJson[PING_PONG];this._repeatCount=timelineDataJson[REPEAT_COUNT];this._startOnLayout=timelineDataJson[START_ON_LAYOUT];this._transformWithSceneGraph=!!timelineDataJson[TRANSFORM_WITH_SCENE_GRAPH];this._useSystemTimescale=!!timelineDataJson[USE_SYSTEM_TIMESCALE];this._trackData=new C3.TrackData(timelineDataJson[TRACKS],this)}Release(){this._trackData.Release();
+this._trackData=null}GetTrackData(){if(!this._trackData)this._trackData=new C3.TrackData(null,this);return this._trackData}GetName(){return this._name}SetName(n){this._name=n}GetTotalTime(){return this._totalTime}SetTotalTime(tt){this._totalTime=tt}GetStep(){return this._step}SetStep(s){this._step=s}GetInterpolationMode(){return this._interpolationMode}SetInterpolationMode(im){this._interpolationMode=im}GetResultMode(){return this._resultMode}SetResultMode(rm){this._resultMode=rm}GetLoop(){return this._loop}SetLoop(l){this._loop=
+l}GetPingPong(){return this._pingPong}SetPingPong(p){this._pingPong=p}GetRepeatCount(){return this._repeatCount}SetRepeatCount(rc){this._repeatCount=rc}GetStartOnLayout(){return this._startOnLayout}GetTransformWithSceneGraph(){return this._transformWithSceneGraph}GetUseSystemTimescale(){return this._useSystemTimescale}_SaveToJson(){return{"trackDataJson":this._trackData._SaveToJson(),"name":this._name,"totalTime":this._totalTime,"step":this._step,"interpolationMode":this._interpolationMode,"resultMode":this._resultMode,
+"loop":this._loop,"pingPong":this._pingPong,"repeatCount":this._repeatCount,"startOnLayout":this._startOnLayout,"transformWithSceneGraph":!!this._transformWithSceneGraph,"useSystemTimescale":this._useSystemTimescale}}_LoadFromJson(o){if(!o)return;this.GetTrackData()._LoadFromJson(o["trackDataJson"]);this._name=o["name"];this._totalTime=o["totalTime"];this._step=o["step"];this._interpolationMode=o["interpolationMode"];this._resultMode=o["resultMode"];this._loop=o["loop"];this._pingPong=o["pingPong"];
+this._repeatCount=o["repeatCount"];this._startOnLayout=o["startOnLayout"];this._transformWithSceneGraph=!!o["transformWithSceneGraph"];this._useSystemTimescale=!!o["useSystemTimescale"]}};
+
+}
+
+// timelines/data/trackData.js
+{
+'use strict';const C3=self.C3;const WI_DATA=0;const OC_INDEX=1;const WI_UID=2;const INTERPOLATION_MODE=1;const RESULT_MODE=2;const ENABLED=3;const KEYFRAMES=4;const PROPERTY_TRACKS=5;const ID=6;const NESTED_DATA=7;const START_OFFSET=0;const LOCAL_TOTAL_TIME=1;const WI_ADDITIONAL_DATA=8;const ORIGINAL_WIDTH=0;const ORIGINAL_HEIGHT=1;const TRACK_TYPE=9;const TRACK_NAME=10;
+class TrackDataItem{constructor(trackDataJson,trackData){this._trackData=trackData;this._instanceData=null;this._additionalInstanceData=null;this._instanceUid=NaN;this._objectClassIndex=NaN;this._interpolationMode="default";this._resultMode="default";this._enabled=false;this._keyframeData=null;this._propertyTrackData=null;this._id="";this._nestedData=null;this._startOffset=0;this._localTotalTime=this._trackData.GetTimelineDataItem().GetTotalTime();this._type=0;this._name="";if(!trackDataJson)return;
+if(trackDataJson[WI_DATA]){this._instanceData=trackDataJson[WI_DATA];this._instanceUid=trackDataJson[WI_DATA][WI_UID];this._objectClassIndex=trackDataJson[WI_DATA][OC_INDEX]}this._interpolationMode=trackDataJson[INTERPOLATION_MODE];this._resultMode=trackDataJson[RESULT_MODE];this._enabled=!!trackDataJson[ENABLED];if(trackDataJson[ID])this._id=trackDataJson[ID];if(trackDataJson[NESTED_DATA]){this._nestedData=trackDataJson[NESTED_DATA];this._startOffset=trackDataJson[NESTED_DATA][START_OFFSET];this._localTotalTime=
+trackDataJson[NESTED_DATA][LOCAL_TOTAL_TIME]}if(trackDataJson[WI_ADDITIONAL_DATA])this._additionalInstanceData=trackDataJson[WI_ADDITIONAL_DATA];if(trackDataJson[WI_ADDITIONAL_DATA])this._additionalInstanceData=trackDataJson[WI_ADDITIONAL_DATA];if(trackDataJson[TRACK_TYPE])this._type=trackDataJson[TRACK_TYPE];if(trackDataJson[TRACK_NAME])this._name=trackDataJson[TRACK_NAME];this._keyframeData=new C3.KeyframeData(trackDataJson[KEYFRAMES],this);this._propertyTrackData=new C3.PropertyTrackData(trackDataJson[PROPERTY_TRACKS],
+this)}Release(){this._instanceData=null;this._trackData=null;if(this._keyframeData){this._keyframeData.Release();this._keyframeData=null}if(this._propertyTrackData){this._propertyTrackData.Release();this._propertyTrackData=null}this._nestedData=null}GetTrackData(){return this._trackData}GetKeyframeData(){if(!this._keyframeData)this._keyframeData=new C3.KeyframeData(null,this);return this._keyframeData}GetPropertyTrackData(){if(!this._propertyTrackData)this._propertyTrackData=new C3.PropertyTrackData(null,
+this);return this._propertyTrackData}GetInstanceData(){return this._instanceData}GetObjectClassIndex(){return this._objectClassIndex}SetObjectClassIndex(index){this._objectClassIndex=index}GetInstanceUID(){return this._instanceUid}SetInstanceUID(uid){this._instanceUid=uid}GetInterpolationMode(){return this._interpolationMode}SetInterpolationMode(im){this._interpolationMode=im}GetResultMode(){return this._resultMode}SetResultMode(rm){this._resultMode=rm}GetEnable(){return this._enabled}SetEnable(e){this._enabled=
+!!e}GetId(){return this._id}GetStartOffset(){return this._startOffset}GetLocalTotalTime(){return this._localTotalTime}SetLocalTotalTime(t){this._localTotalTime=t}GetOriginalWidth(){return this._additionalInstanceData[ORIGINAL_WIDTH]}SetOriginalWidth(w){if(!this._additionalInstanceData)this._additionalInstanceData=[];this._additionalInstanceData[ORIGINAL_WIDTH]=w}GetOriginalHeight(){if(!this._additionalInstanceData)this._additionalInstanceData=[];return this._additionalInstanceData[ORIGINAL_HEIGHT]}SetOriginalHeight(h){if(!this._additionalInstanceData)this._additionalInstanceData=
+[];this._additionalInstanceData[ORIGINAL_HEIGHT]=h}GetType(){return this._type}GetName(){return this._name}_SaveToJson(){return{"keyframeDataJson":this._keyframeData._SaveToJson(),"propertyTrackDataJson":this._propertyTrackData._SaveToJson(),"instanceData":this._instanceData,"additionalInstanceData":this._additionalInstanceData,"instanceUid":this._instanceUid,"objectClassIndex":this._objectClassIndex,"interpolationMode":this._interpolationMode,"resultMode":this._resultMode,"enabled":this._enabled,
+"id":this._id,"nestedData":this._nestedData,"type":this._type,"name":this._name}}_LoadFromJson(o){if(!o)return;this._instanceData=o["instanceData"];this._instanceUid=o["instanceUid"];this._objectClassIndex=o["objectClassIndex"];this._interpolationMode=o["interpolationMode"];this._resultMode=o["resultMode"];this._enabled=o["enabled"];this._id=o["id"];this._type=o["type"]?o["type"]:0;this._name=o["name"]?o["name"]:"";this._localTotalTime=this._trackData.GetTimelineDataItem().GetTotalTime();if(o["nestedData"]){this._nestedData=
+o["nestedData"];this._startOffset=this._nestedData[START_OFFSET];this._localTotalTime=this._nestedData[LOCAL_TOTAL_TIME]}if(o["additionalInstanceData"])this._additionalInstanceData=o["additionalInstanceData"];this.GetKeyframeData()._LoadFromJson(o["keyframeDataJson"]);this.GetPropertyTrackData()._LoadFromJson(o["propertyTrackDataJson"])}}
+C3.TrackData=class TrackData{constructor(tracksDataJson,timelineDataItem){this._timelineDataItem=timelineDataItem;this._trackDataItems=[];C3.TimelineDataManager._CreateDataItems(this._trackDataItems,tracksDataJson,TrackDataItem,this)}Release(){this._timelineDataItem=null;for(const trackDataItem of this._trackDataItems)trackDataItem.Release();C3.clearArray(this._trackDataItems);this._trackDataItems=null}GetTimelineDataItem(){return this._timelineDataItem}AddEmptyTrackDataItem(){const trackDataItem=
+new TrackDataItem(null,this);this._trackDataItems.push(trackDataItem);return trackDataItem}GetFirstKeyframeDataItem(trackDataItem){return trackDataItem.GetKeyframeData().GetKeyframeDataItemArray()[0]}GetLastKeyframeDataItem(trackDataItem){const keyframeDataItems=trackDataItem.GetKeyframeData().GetKeyframeDataItemArray();return keyframeDataItems.at(-1)}GetKeyFrameDataItemAtTime(time,trackDataItem){const keyframeDataItems=trackDataItem.GetKeyframeData().GetKeyframeDataItemArray();const l=keyframeDataItems.length;
+for(let i=0;itime)return keyframeDataItem}}GetFirstKeyFrameDataItemHigherOrEqualThan(time,trackDataItem){const keyframeDataItems=
+trackDataItem.GetKeyframeData().GetKeyframeDataItemArray();const l=keyframeDataItems.length;for(let i=0;i=time)return keyframeDataItem}}GetFirstKeyFrameDataItemLowerOrEqualThan(time,trackDataItem){const keyframeDataItems=trackDataItem.GetKeyframeData().GetKeyframeDataItemArray();for(let i=keyframeDataItems.length-1;i>=0;i--){const keyframeDataItem=keyframeDataItems[i];if(keyframeDataItem.GetTime()<=time)return keyframeDataItem}}*trackDataItems(){for(const trackDataItem of this._trackDataItems)yield trackDataItem}_SaveToJson(){return{"trackDataItemsJson":this._trackDataItems.map(trackDataItem=>
+trackDataItem._SaveToJson())}}_LoadFromJson(o){if(!o)return;C3.TimelineDataManager._LoadDataItemsFromJson(this._trackDataItems,o["trackDataItemsJson"],TrackDataItem,this)}};
+
+}
+
+// timelines/data/propertyTrackData.js
+{
+'use strict';const C3=self.C3;const SOURCE_DATA=0;const SOURCE=0;const PROPERTY=1;const TYPE=2;const MIN=3;const MAX=4;const INTERPOLATION_MODE=5;const RESULT_MODE=6;const ENABLED=7;const PROPERTY_KEYFRAMES=8;const CAN_HAVE_PROPERTY_KEYFRAMES=9;
+class PropertyTrackDataItem{constructor(propertyTrackDataJson,propertyTrackData){this._propertyTrackData=propertyTrackData;this._sourceAdapterId="";this._sourceAdapterArguments=null;this._property=null;this._type=null;this._min=NaN;this._max=NaN;this._interpolationMode="default";this._resultMode="default";this._enabled=false;this._propertyKeyframeData=null;this._canHavePropertyKeyframes=true;if(!propertyTrackDataJson)return;this._sourceAdapterId=propertyTrackDataJson[SOURCE_DATA][SOURCE];this._sourceAdapterArguments=
+propertyTrackDataJson[SOURCE_DATA].slice(1);this._property=propertyTrackDataJson[PROPERTY];this._type=propertyTrackDataJson[TYPE];this._min=propertyTrackDataJson[MIN];this._max=propertyTrackDataJson[MAX];this._interpolationMode=propertyTrackDataJson[INTERPOLATION_MODE];this._resultMode=propertyTrackDataJson[RESULT_MODE];this._enabled=!!propertyTrackDataJson[ENABLED];this._propertyKeyframeData=new C3.PropertyKeyframeData(propertyTrackDataJson[PROPERTY_KEYFRAMES],this);this._canHavePropertyKeyframes=
+propertyTrackDataJson[CAN_HAVE_PROPERTY_KEYFRAMES]}Release(){this._propertyKeyframeData.Release();this._propertyKeyframeData=null;this._propertyTrackData=null;this._sourceAdapterArguments=null}GetPropertyTrackData(){return this._propertyTrackData}GetPropertyKeyframeData(){if(!this._propertyKeyframeData)this._propertyKeyframeData=new C3.PropertyKeyframeData(null,this);return this._propertyKeyframeData}GetSourceAdapterId(){return this._sourceAdapterId}SetSourceAdapterId(said){this._sourceAdapterId=
+said}GetSourceAdapterArguments(){return this._sourceAdapterArguments}SetSourceAdapterArguments(sargs){this._sourceAdapterArguments=sargs}GetProperty(){return this._property}SetProperty(p){this._property=p}GetType(){return this._type}SetType(t){this._type=t}GetMin(){return this._min}SetMin(min){this._min=min}GetMax(){return this._max}SetMax(max){this._max=max}GetInterpolationMode(){return this._interpolationMode}SetInterpolationMode(im){this._interpolationMode=im}GetResultMode(){return this._resultMode}SetResultMode(rm){this._resultMode=
+rm}GetEnable(){return this._enabled}SetEnable(e){this._enabled=!!e}CanHavePropertyKeyframes(){return!!this._canHavePropertyKeyframes}_SaveToJson(){return{"propertyKeyframeDataJson":this._propertyKeyframeData._SaveToJson(),"sourceAdapterId":this._sourceAdapterId,"sourceAdapterArguments":this._sourceAdapterArguments,"property":this._property,"type":this._type,"min":this._min,"max":this._max,"interpolationMode":this._interpolationMode,"resultMode":this._resultMode,"enabled":this._enabled,"canHavePropertyKeyframes":this._canHavePropertyKeyframes}}_LoadFromJson(o){if(!o)return;
+this._sourceAdapterId=o["sourceAdapterId"];this._sourceAdapterArguments=o["sourceAdapterArguments"];this._property=o["property"];this._type=o["type"];this._min=o["min"];this._max=o["max"];this._interpolationMode=o["interpolationMode"];this._resultMode=o["resultMode"];this._enabled=o["enabled"];this._canHavePropertyKeyframes=o["canHavePropertyKeyframes"];this.GetPropertyKeyframeData()._LoadFromJson(o["propertyKeyframeDataJson"])}}
+C3.PropertyTrackData=class PropertyTrackData{constructor(propertyTracksDataJson,trackDataItem){this._trackDataItem=trackDataItem;this._propertyTrackDataItems=[];C3.TimelineDataManager._CreateDataItems(this._propertyTrackDataItems,propertyTracksDataJson,PropertyTrackDataItem,this)}Release(){this._trackDataItem=null;for(const propertyTrackDataItem of this._propertyTrackDataItems)propertyTrackDataItem.Release();C3.clearArray(this._propertyTrackDataItems);this._propertyTrackDataItems=null}GetTrackDataItem(){return this._trackDataItem}AddEmptyPropertyTrackDataItem(){const propertyTrackDataItem=
+new PropertyTrackDataItem(null,this);this._propertyTrackDataItems.push(propertyTrackDataItem);return propertyTrackDataItem}GetFirstPropertyKeyframeDataItem(propertyTrackDataItem){const propertyKeyframeData=propertyTrackDataItem.GetPropertyKeyframeData();return propertyKeyframeData.GetPropertyKeyframeDataItemArray()[0]}GetLastPropertyKeyframeDataItem(propertyTrackDataItem){const propertyKeyframeData=propertyTrackDataItem.GetPropertyKeyframeData();const propertyKeyframeDataItems=propertyKeyframeData.GetPropertyKeyframeDataItemArray();
+return propertyKeyframeDataItems.at(-1)}GetPropertyKeyFrameDataItemAtTime(time,propertyTrackDataItem){const propertyKeyframeData=propertyTrackDataItem.GetPropertyKeyframeData();const propertyKeyframeDataItems=propertyKeyframeData.GetPropertyKeyframeDataItemArray();const l=propertyKeyframeDataItems.length;for(let i=0;itime)return propertyKeyframeDataItem}}GetFirstPropertyKeyFrameDataItemHigherOrEqualThan(time,propertyTrackDataItem){const propertyKeyframeData=propertyTrackDataItem.GetPropertyKeyframeData();
+const propertyKeyframeDataItems=propertyKeyframeData.GetPropertyKeyframeDataItemArray();const l=propertyKeyframeDataItems.length;for(let i=0;i=time)return propertyKeyframeDataItem}}GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(time,propertyTrackDataItem){const propertyKeyframeData=propertyTrackDataItem.GetPropertyKeyframeData();const propertyKeyframeDataItems=propertyKeyframeData.GetPropertyKeyframeDataItemArray();
+for(let i=propertyKeyframeDataItems.length-1;i>=0;i--){const propertyKeyframeDataItem=propertyKeyframeDataItems[i];if(propertyKeyframeDataItem.GetTime()<=time)return propertyKeyframeDataItem}}*propertyTrackDataItems(){for(const propertyTrackDataItem of this._propertyTrackDataItems)yield propertyTrackDataItem}_SaveToJson(){return{"propertyTrackDataItemsJson":this._propertyTrackDataItems.map(propertyTrackDataItem=>propertyTrackDataItem._SaveToJson())}}_LoadFromJson(o){if(!o)return;C3.TimelineDataManager._LoadDataItemsFromJson(this._propertyTrackDataItems,
+o["propertyTrackDataItemsJson"],PropertyTrackDataItem,this)}};
+
+}
+
+// timelines/data/keyframeData.js
+{
+'use strict';const C3=self.C3;const TIME=0;const EASE=1;const ENABLE=2;const TAGS=3;
+class KeyframeDataItem{constructor(keyframeDataJson,keyframeData){this._keyframeData=keyframeData;this._time=-1;this._ease="noease";this._enable=false;this._tags=null;this._lowerTags=null;if(!keyframeDataJson)return;this._time=keyframeDataJson[TIME];this._ease=keyframeDataJson[EASE];this._enable=!!keyframeDataJson[ENABLE];const tagStr=keyframeDataJson[TAGS];this._tags=tagStr?tagStr.split(" "):[];this._lowerTags=new Set(this._tags.map(t=>t.toLowerCase()));this._next=null}Release(){this._keyframeData=
+null;C3.clearArray(this._tags);this._tags=null;this._lowerTags.clear();this._lowerTags=null;this._next=null}GetKeyframeData(){return this._keyframeData}GetNext(){return this._next}SetNext(next){this._next=next}GetTime(){return this._time}SetTime(t){this._time=t;this._keyframeData._LinkKeyframeDataItems()}GetEase(){return this._ease}SetEase(e){this._ease=e}GetEnable(){return this._enable}SetEnable(e){this._enable=!!e}GetTags(){return this._tags}SetTags(t){this._tags=t?t.split(" "):[];this._lowerTags=
+new Set(this._tags.map(t=>t.toLowerCase()))}GetLowerTags(){return this._lowerTags}HasTag(tag){return this._lowerTags.has(tag.toLowerCase())}_SaveToJson(){return{"time":this._time,"ease":this._ease,"enable":this._enable,"tags":this._tags}}_LoadFromJson(o){if(!o)return;this._time=o["time"];this._ease=o["ease"];this._enable=o["enable"];this._tags=o["tags"];this._lowerTags=new Set(this._tags.map(t=>t.toLowerCase()))}}
+C3.KeyframeData=class KeyframeData{constructor(keyframesDataJson,trackDataItem){this._trackDataItem=trackDataItem;this._keyframeDataItems=[];C3.TimelineDataManager._CreateDataItems(this._keyframeDataItems,keyframesDataJson,KeyframeDataItem,this);this._LinkKeyframeDataItems()}Release(){this._trackDataItem=null;for(const keyframeDataItem of this._keyframeDataItems)keyframeDataItem.Release();C3.clearArray(this._keyframeDataItems);this._keyframeDataItems=null}_LinkKeyframeDataItems(){this._keyframeDataItems.sort((first,
+second)=>first.GetTime()-second.GetTime());for(let i=0;ia.GetTime()-b.GetTime())}GetKeyframeDataItemIndex(keyframeDataItem){return this._keyframeDataItems.indexOf(keyframeDataItem)}GetKeyframeDataItemFromIndex(index){return this._keyframeDataItems[index]}*keyframeDataItems(){for(const keyframeDataItem of this._keyframeDataItems)yield keyframeDataItem}*keyframeDataItemsReverse(){for(let i=
+this._keyframeDataItems.length-1;i>=0;i--)yield this._keyframeDataItems[i]}_SaveToJson(){return{"keyframeDataItemsJson":this._keyframeDataItems.map(keyframeDataItem=>keyframeDataItem._SaveToJson())}}_LoadFromJson(o){if(!o)return;C3.TimelineDataManager._LoadDataItemsFromJson(this._keyframeDataItems,o["keyframeDataItemsJson"],KeyframeDataItem,this);this._LinkKeyframeDataItems()}};
+
+}
+
+// timelines/data/propertyKeyframeData.js
+{
+'use strict';const C3=self.C3;const VALUE_DATA=0;const VALUE_DATA_VALUE=0;const VALUE_DATA_ABSOLUTE_VALUE=1;const VALUE_DATA_TYPE=2;const TIME=1;const EASE=2;const ENABLE=3;const ADDONS=4;const PATH_MODE=5;
+class PropertyKeyframeDataItem{constructor(propertyKeyframeDataJson,propertyKeyframeData){this._propertyKeyframeData=propertyKeyframeData;this._value=null;this._aValue=null;this._type="";this._time=NaN;this._ease="noease";this._enable=false;this._addonData=null;this._addonInstance=undefined;this._pathMode="line";if(!propertyKeyframeDataJson)return;this._value=propertyKeyframeDataJson[VALUE_DATA][VALUE_DATA_VALUE];this._aValue=propertyKeyframeDataJson[VALUE_DATA][VALUE_DATA_ABSOLUTE_VALUE];this._type=
+propertyKeyframeDataJson[VALUE_DATA][VALUE_DATA_TYPE];this._time=propertyKeyframeDataJson[TIME];this._ease=propertyKeyframeDataJson[EASE];this._enable=!!propertyKeyframeDataJson[ENABLE];this._pathMode=propertyKeyframeDataJson[PATH_MODE];this._addonData=null;if(!!propertyKeyframeDataJson[ADDONS])this._addonData=new C3.AddonData(propertyKeyframeDataJson[ADDONS],this);this._next=null;this._prev=null}Release(){this._propertyKeyframeData=null;if(this._addonData){this._addonData.Release();this._addonData=
+null}this._next=null;this._prev=null}GetAddonData(){return this._addonData}SetNext(next){this._next=next}GetNext(){return this._next}SetPrevious(prev){this._prev=prev}GetPrevious(){return this._prev}GetValue(){return this._value}SetValue(value){if(this._type==="color"&&C3.IsFiniteNumber(value)){this._value[0]=C3.GetRValue(value);this._value[1]=C3.GetGValue(value);this._value[2]=C3.GetBValue(value)}else this._value=value}GetAbsoluteValue(){return this._aValue}SetAbsoluteValue(aValue){if(this._type===
+"color"&&C3.IsFiniteNumber(aValue)){this._aValue[0]=C3.GetRValue(aValue);this._aValue[1]=C3.GetGValue(aValue);this._aValue[2]=C3.GetBValue(aValue)}else this._aValue=aValue}GetValueWithResultMode(){const rm=this._propertyKeyframeData.GetPropertyTrackDataItem().GetResultMode();if(rm==="relative")return this.GetValue();else if(rm==="absolute")return this.GetAbsoluteValue()}GetType(){return this._type}SetType(t){this._type=t}GetTime(){return this._time}SetTime(t){this._time=t;this._propertyKeyframeData._LinkPropertyKeyframeDataItems()}GetEase(){return this._ease}SetEase(e){this._ease=
+e}GetEnable(){return this._enable}SetEnable(e){this._enable=!!e}GetPathMode(){return this._pathMode}GetAddOn(id){if(!this._addonData)return;if(this._addonInstance||this._addonInstance===null)return this._addonInstance;const addonArray=this._addonData.GetAddDataItemArray();if(!addonArray){this._addonInstance=null;return this._addonInstance}const len=addonArray.length;for(let i=0;ifirst.GetTime()-second.GetTime());for(let i=0;i=0)current.SetPrevious(dataItems[i-1])}dataItems=this._propertyKeyframeDataItemsIncludingDisabled;dataItems.sort((first,second)=>first.GetTime()-second.GetTime());for(let i=0;i=0)current.SetPrevious(dataItems[i-1])}}AddEmptyPropertyKeyframeDataItem(){const propertyKeyframeDataItem=new PropertyKeyframeDataItem(null,this);this._propertyKeyframeDataItems.push(propertyKeyframeDataItem);this._LinkPropertyKeyframeDataItems();return propertyKeyframeDataItem}DeletePropertyKeyframeDataItems(match){for(const propertyKeyframeDataItem of this._propertyKeyframeDataItems){if(!match(propertyKeyframeDataItem))continue;const index=
+this._propertyKeyframeDataItems.indexOf(propertyKeyframeDataItem);if(index===-1)continue;propertyKeyframeDataItem.Release();this._propertyKeyframeDataItems.splice(index,1)}this.SortPropertyKeyFrameDataItems();this._LinkPropertyKeyframeDataItems()}SortPropertyKeyFrameDataItems(){this._propertyKeyframeDataItems.sort((a,b)=>a.GetTime()-b.GetTime())}GetPropertyTrackDataItem(){return this._propertyTrackDataItem}GetPropertyKeyframeDataItemCount(){return this._propertyKeyframeDataItems.length}GetLastPropertyKeyframeDataItem(){return this._propertyKeyframeDataItems[this._propertyKeyframeDataItems.length-
+1]}GetPropertyKeyframeDataItemArray(){return this._propertyKeyframeDataItems}GetPropertyKeyframeDataItemArrayIncludingDisabled(){return this._propertyKeyframeDataItemsIncludingDisabled}*propertyKeyframeDataItems(){for(const propertyKeyframeDataItem of this._propertyKeyframeDataItems)yield propertyKeyframeDataItem}*propertyKeyframeDataItemsReverse(){for(let i=this._propertyKeyframeDataItems.length-1;i>=0;i--)yield this._propertyKeyframeDataItems[i]}_SaveToJson(){const propertyKeyframeDataItems=this._propertyKeyframeDataItems;
+const propertyKeyframeDataItemsIncludingDisabled=this._propertyKeyframeDataItemsIncludingDisabled;return{"propertyKeyframeDataItemsJson":propertyKeyframeDataItems.map(propertyTrackDataItem=>{return propertyTrackDataItem._SaveToJson()}),"propertyKeyframeDataItemsIncludingDisabledJson":propertyKeyframeDataItemsIncludingDisabled.map(propertyTrackDataItem=>{return propertyTrackDataItem._SaveToJson()})}}_LoadFromJson(o){if(!o)return;C3.TimelineDataManager._LoadDataItemsFromJson(this._propertyKeyframeDataItems,
+o["propertyKeyframeDataItemsJson"],PropertyKeyframeDataItem,this);C3.TimelineDataManager._LoadDataItemsFromJson(this._propertyKeyframeDataItemsIncludingDisabled,o["propertyKeyframeDataItemsIncludingDisabledJson"],PropertyKeyframeDataItem,this);this._LinkPropertyKeyframeDataItems()}};
+
+}
+
+// timelines/data/propertyKeyframeAddonData.js
+{
+'use strict';const C3=self.C3;const ADDON_ID=0;const ADDON_DATA=1;class AddonDataItem{constructor(addonDataJson,addonData){this._addonData=addonData;this._id=addonDataJson[ADDON_ID];this._data=addonDataJson[ADDON_DATA]}Release(){this._addonData=null;this._data=null}GetAddonData(){return this._addonData}GetId(){return this._id}_SaveToJson(){return{"id":this._id,"data":this._data}}_LoadFromJson(o){if(!o)return;this._id=o["id"];this._data=o["data"]}}const START_ANCHOR=0;const START_ENABLE=1;
+const END_ANCHOR=2;const END_ENABLE=3;
+class AddonDataCubicBezierItem extends AddonDataItem{constructor(addonDataJson,addonData){super(addonDataJson,addonData);this._startAnchor=this._data[START_ANCHOR];this._startEnable=!!this._data[START_ENABLE];this._endAnchor=this._data[END_ANCHOR];this._endEnable=!!this._data[END_ENABLE]}Release(){super.Release()}GetStartAnchor(){return this._startAnchor}GetStartEnable(){return this._startEnable}GetEndAnchor(){return this._endAnchor}GetEndEnable(){return this._endEnable}_SaveToJson(){return Object.assign(super._SaveToJson(),{"startAnchor":this._startAnchor,
+"startEnable":!!this._startEnable,"endAnchor":this._endAnchor,"endEnable":!!this._endEnable})}_LoadFromJson(o){if(!o)return;super._LoadFromJson(o);this._startAnchor=o["startAnchor"];this._startEnable=!!o["startEnable"];this._endAnchor=o["endAnchor"];this._endEnable=!!o["endEnable"]}}const DIRECTION=0;const REVOLUTIONS=1;
+class AddonDataAngleItem extends AddonDataItem{constructor(addonDataJson,addonData){super(addonDataJson,addonData);this._direction=this._data[DIRECTION];this._revolutions=this._data[REVOLUTIONS]}Release(){super.Release()}GetDirection(){return this._direction}GetRevolutions(){return this._revolutions}_SaveToJson(){return Object.assign(super._SaveToJson(),{"direction":this._direction,"revolutions":this._revolutions})}_LoadFromJson(o){if(!o)return;super._LoadFromJson(o);this._direction=o["direction"];
+this._revolutions=o["revolutions"]}}
+C3.AddonData=class AddonData{constructor(addonsDataJson,propertyKeyframeDataItem){this._propertyKeyframeDataItem=propertyKeyframeDataItem;this._addonDataItems=[];C3.TimelineDataManager._CreateDataItems(this._addonDataItems,addonsDataJson,{prop:0,map:new Map([["cubic-bezier",AddonDataCubicBezierItem],["angle",AddonDataAngleItem]])},this)}Release(){this._propertyKeyframeDataItem=null;for(const addonDataItem of this._addonDataItems)addonDataItem.Release();C3.clearArray(this._addonDataItems);this._addonDataItems=
+null}GetPropertyKeyframeDataItem(){return this._propertyKeyframeDataItem}GetAddDataItemArray(){return this._addonDataItems}*addonDataItems(){for(const addonDataItem of this._addonDataItems)yield addonDataItem}_SaveToJson(){return{"addonDataItemsJson":this._addonDataItems.map(addonDataItem=>addonDataItem._SaveToJson())}}_LoadFromJson(o){if(!o)return;C3.TimelineDataManager._LoadDataItemsFromJson(this._addonDataItems,o["addonDataItemsJson"],{prop:"id",map:new Map([["cubic-bezier",AddonDataCubicBezierItem],
+["angle",AddonDataAngleItem]])},this)}};
+
+}
+
+// timelines/tweens/tweenState.js
+{
+'use strict';const C3=self.C3;const INITIAL_VALUE_MODE_START_VALUE="start-value";const INITIAL_VALUE_MODE_CURRENT_STATE="current-state";const PING_PONG_BEGIN=0;const PING_PONG_END=1;let createdTweens=0;
+C3.TweenState=class Tween extends C3.TimelineState{constructor(tweenDataItem,timelineManager){super(`tween-${createdTweens++}`,tweenDataItem,timelineManager);this._id="";this._destroyInstanceOnComplete=false;this._initialValueMode=INITIAL_VALUE_MODE_START_VALUE;this._instance=null;this._on_completed_callbacks=null;this._on_started_callbacks=null;this._track=null;this._iTweenState=null}FireReleaseEvent(dispatcher){const event=C3.New(C3.Event,"tweenstatereleased");event.tweenState=this;dispatcher.dispatchEvent(event)}GetType(){return 1}CreateTrackStates(){for(const trackDataItem of this._timelineDataItem.GetTrackData().trackDataItems())this._tracks.push(C3.TweenTrackState.Create(this,
+trackDataItem));this._track=this._tracks[0]}AddTrack(){const trackDataItem=this._timelineDataItem.GetTrackData().AddEmptyTrackDataItem();const track=C3.TweenTrackState.Create(this,trackDataItem);this._tracks.push(track);this._track=this._tracks[0];return track}GetPropertyTrack(propertyName){return this._track.GetPropertyTracks()[0]}SetPropertyType(type){this._propertyType=type}GetInstance(){const tracks=this.GetTracks();if(!tracks||!tracks.length)return;const track=tracks[0];this._track=track;if(!track)return;
+const instance=track.GetInstance();return track.IsInstanceValid()?instance:undefined}AddStartedCallback(c){if(!this._on_started_callbacks)this._on_started_callbacks=[];this._on_started_callbacks.push(c)}AddCompletedCallback(c){if(!this._on_completed_callbacks)this._on_completed_callbacks=[];this._on_completed_callbacks.push(c)}RemoveStartedCallback(c){if(!this._on_started_callbacks)return;const index=this._on_started_callbacks.indexOf(c);if(index!==-1)this._on_started_callbacks.splice(index,1)}RemoveCompletedCallback(c){if(!this._on_completed_callbacks)return;
+const index=this._on_completed_callbacks.indexOf(c);if(index!==-1)this._on_completed_callbacks.splice(index,1)}SetStartValue(startValue,propertyName){for(const track of this._tracks)for(const propertyTrack of track._propertyTracks){if(propertyTrack.GetPropertyName()!==propertyName)continue;const propertyTrackData=propertyTrack.GetPropertyTrackData();const propertyTrackDataItem=propertyTrack.GetPropertyTrackDataItem();const propertyKeyframeDataItem=propertyTrackData.GetFirstPropertyKeyframeDataItem(propertyTrackDataItem);
+propertyKeyframeDataItem.SetValue(startValue);propertyKeyframeDataItem.SetAbsoluteValue(startValue)}}_GetPropertyTrackState(propertyName){for(const track of this._tracks)for(const propertyTrack of track._propertyTracks)if(propertyTrack.GetPropertyName()===propertyName)return propertyTrack}BeforeSetEndValues(properties){for(const propertyName of properties){const propertyTrackState=this._GetPropertyTrackState(propertyName);this.SetStartValue(propertyTrackState.GetCurrentState(),propertyName)}if(this.IsForwardPlayBack()){const newTotalTime=
+this.GetTotalTime()-this.GetTime();this.SetTotalTime(newTotalTime);for(const track of this._tracks)track.SetLocalTotalTime(newTotalTime);this._SetTime(0)}else{const newTotalTime=this.GetTime();this.SetTotalTime(newTotalTime);for(const track of this._tracks)track.SetLocalTotalTime(newTotalTime);this._SetTime(newTotalTime)}this.SetInitialStateFromSetTime()}SetEndValue(endValue,propertyName){const propertyTrackState=this._GetPropertyTrackState(propertyName);const propertyTrackData=propertyTrackState.GetPropertyTrackData();
+const propertyTrackDataItem=propertyTrackState.GetPropertyTrackDataItem();const propertyKeyframeDataItem=propertyTrackData.GetLastPropertyKeyframeDataItem(propertyTrackDataItem);propertyKeyframeDataItem.SetTime(this.GetTotalTime());propertyKeyframeDataItem.SetValue(endValue);propertyKeyframeDataItem.SetAbsoluteValue(endValue)}SetId(id){this._id=id}GetId(){return this._id}SetInitialValueMode(initialValueMode){this._initialValueMode=initialValueMode}GetInitialValueMode(){return this._initialValueMode}SetDestroyInstanceOnComplete(releaseOnComplete){this._destroyInstanceOnComplete=
+releaseOnComplete}GetDestroyInstanceOnComplete(){return this._destroyInstanceOnComplete}OnStarted(){if(this._on_started_callbacks)for(const c of this._on_started_callbacks)c(this);if(this.IsComplete())return;for(const track of this._tracks)track.CompareSaveStateWithCurrent()}OnCompleted(){this._completedTick=this._runtime.GetTickCount()}FinishTriggers(){if(this._finishedTriggers)return;this._finishedTriggers=true;if(this._on_completed_callbacks)for(const c of this._on_completed_callbacks)c(this)}SetTime(time){this._DeleteIntermediateKeyframes();
+super.SetTime(time)}_SetTimeAndReset(time){if(!C3.IsFiniteNumber(time))time=this.GetTotalTime();if(time<0)this._playheadTime=0;else if(time>=this.GetTotalTime())this._playheadTime=this.GetTotalTime();else this._playheadTime=time;this._track.SetResetState()}SetInitialState(fromSetTime){if(!this.InitialStateSet()&&this.GetInitialValueMode()===INITIAL_VALUE_MODE_CURRENT_STATE)for(const track of this._tracks)track.CompareInitialStateWithCurrent();super.SetInitialState(fromSetTime)}Stop(completed=false){super.Stop(completed);
+if(this.IsComplete())return;for(const track of this._tracks)track.SaveState()}Reset(render=true,beforeChangeLayout=false){this._DeleteIntermediateKeyframes();super.Reset(render,beforeChangeLayout)}_DeleteIntermediateKeyframes(){for(const track of this._tracks){const del=kf=>{const time=kf.GetTime();const totalTime=this.GetTotalTime();return time!==0&&time!==totalTime};track.DeleteKeyframes(del);track.DeletePropertyKeyframes(del)}}_OnBeforeChangeLayout(){if(this.IsReleased())return true;const instance=
+this.GetInstance();if(instance&&instance.GetObjectClass().IsGlobal())return false;this._timelineManager.CompleteTimelineBeforeChangeOfLayout(this);this.ResetBeforeChangeLayout();return true}Tick(deltaTime,timeScale,deltaTime1){if(!this._instance)this._instance=this.GetInstance();if(!this._instance||this._instance.IsDestroyed()){this.Stop(true);this.OnCompleted();return}const instanceTimeScale=this._instance.GetTimeScale();if(instanceTimeScale!==-1)deltaTime=deltaTime1*instanceTimeScale;if(deltaTime===
+0&&this._lastDelta===0)return;this._lastDelta=deltaTime;const lastTime=this._playheadTime;const newDeltaTime=deltaTime*this._playbackRate;const newTime=lastTime+newDeltaTime;const totalTime=this._timelineDataItem._totalTime;if(newTime<0)this._playheadTime=0;else if(newTime>=totalTime)this._playheadTime=totalTime;else this._playheadTime=newTime;let complete=false;let ensureValue=false;const loop=this.GetLoop();const pingPong=this.GetPingPong();if(!loop&&!pingPong)if(this._playbackRate>0){if(this._playheadTime>=
+totalTime)if(this._currentRepeatCount0){if(this._playheadTime>=totalTime){this._SetTimeAndReset(0);ensureValue=true}}else{if(this._playheadTime<=
+0){this._SetTimeAndReset(totalTime);ensureValue=true}}else if(!loop&&pingPong)if(this._playbackRate>0){if(this._playheadTime>=totalTime){this._SetTime(totalTime);this.SetPlaybackRate(this.GetPlaybackRate()*-1);ensureValue=true;if(this._pingPongState===PING_PONG_END)if(this._currentRepeatCount0){if(this._playheadTime>=totalTime){this._SetTime(totalTime);this.SetPlaybackRate(this.GetPlaybackRate()*-1);ensureValue=
+true;this._pingPongState++;C3.wrap(this._pingPongState,0,2)}}else if(this._playheadTime<=0){this._SetTime(0);this.SetPlaybackRate(this.GetPlaybackRate()*-1);ensureValue=true;this._pingPongState++;C3.wrap(this._pingPongState,0,2)}if(complete){this._track.SetEndState();this.Stop(true);this.OnCompleted();return}this._track.Interpolate(this._playheadTime,true,false,ensureValue,this._firstTick,false);if(this._firstTick)this._firstTick=false}_SaveToJson(){const ret=super._SaveToJson();const tweenDataItem=
+this.GetTimelineDataItem();return Object.assign(ret,{"tweenDataItemJson":tweenDataItem._SaveToJson(),"id":this._id,"destroyInstanceOnComplete":this._destroyInstanceOnComplete,"initialValueMode":this._initialValueMode})}_LoadFromJson(o){if(!o)return;const tweenDataItem=this.GetTimelineDataItem();tweenDataItem._LoadFromJson(o["tweenDataItemJson"]);super._LoadFromJson(o);this._id=o["id"];this._destroyInstanceOnComplete=o["destroyInstanceOnComplete"];this._initialValueMode=o["initialValueMode"]}static IsPlaying(tween){return tween.IsPlaying()}static IsPaused(tween){return tween.IsPaused()}static Build(config){const timelineManager=
+config.runtime.GetTimelineManager();const tweenDataItem=new C3.TimelineDataItem;if(config.json){tweenDataItem._LoadFromJson(config.json["tweenDataItemJson"]);const tween=new C3.TweenState(tweenDataItem,timelineManager);tween._LoadFromJson(config.json);return tween}else{const tween=new C3.TweenState(tweenDataItem,timelineManager);if(!C3.IsArray(config.propertyTracksConfig))config.propertyTracksConfig=[config.propertyTracksConfig];tween.SetId(config.id);tween.SetTags(config.tags);tween.SetInitialValueMode(config.initialValueMode);
+tween.SetDestroyInstanceOnComplete(config.releaseOnComplete);tween.SetLoop(config.loop);tween.SetPingPong(config.pingPong);tween.SetTotalTime(config.time);tween.SetStep(0);tween.SetInterpolationMode("default");tween.SetResultMode(config.propertyTracksConfig[0].resultMode);tween.SetRepeatCount(config.repeatCount);const track=tween.AddTrack();track.SetInstanceUID(config.instance.GetUID());track.SetInterpolationMode("default");track.SetResultMode(config.propertyTracksConfig[0].resultMode);track.SetEnable(true);
+track.SetObjectClassIndex(config.instance.GetObjectClass().GetIndex());const sdkIntance=config.instance.GetSdkInstance();const w=sdkIntance.IsOriginalSizeKnown()?sdkIntance.GetOriginalWidth():config.instance.GetWorldInfo().GetWidth();const h=sdkIntance.IsOriginalSizeKnown()?sdkIntance.GetOriginalHeight():config.instance.GetWorldInfo().GetHeight();track.SetOriginalWidth(w);track.SetOriginalHeight(h);const startKeyframeDataItem=track.AddKeyframe();startKeyframeDataItem.SetTime(0);startKeyframeDataItem.SetEase("noease");
+startKeyframeDataItem.SetEnable(true);startKeyframeDataItem.SetTags("");const endKeyframeDataItem=track.AddKeyframe();endKeyframeDataItem.SetTime(config.time);endKeyframeDataItem.SetEase("noease");endKeyframeDataItem.SetEnable(true);endKeyframeDataItem.SetTags("");for(const propertyTrackConfig of config.propertyTracksConfig){const propertyTrack=track.AddPropertyTrack();propertyTrack.SetSourceAdapterId(propertyTrackConfig.sourceId);propertyTrack.SetSourceAdapterArgs(propertyTrackConfig.sourceArgs);
+propertyTrack.SetPropertyName(propertyTrackConfig.property);propertyTrack.SetPropertyType(propertyTrackConfig.type);propertyTrack.SetMin(NaN);propertyTrack.SetMax(NaN);propertyTrack.SetInterpolationMode("default");propertyTrack.SetResultMode(propertyTrackConfig.resultMode);propertyTrack.SetEnable(true);const startPropertyKeyframeDataItem=propertyTrack.AddPropertyKeyframe();startPropertyKeyframeDataItem.SetType(propertyTrackConfig.valueType);startPropertyKeyframeDataItem.SetTime(0);startPropertyKeyframeDataItem.SetEase(propertyTrackConfig.ease);
+startPropertyKeyframeDataItem.SetEnable(true);startPropertyKeyframeDataItem.SetValue(propertyTrackConfig.startValue);startPropertyKeyframeDataItem.SetAbsoluteValue(propertyTrackConfig.startValue);const endPropertyKeyframeDataItem=propertyTrack.AddPropertyKeyframe();endPropertyKeyframeDataItem.SetType(propertyTrackConfig.valueType);endPropertyKeyframeDataItem.SetTime(config.time);endPropertyKeyframeDataItem.SetEase(propertyTrackConfig.ease);endPropertyKeyframeDataItem.SetEnable(true);endPropertyKeyframeDataItem.SetValue(propertyTrackConfig.endValue);
+endPropertyKeyframeDataItem.SetAbsoluteValue(propertyTrackConfig.endValue);propertyTrack.GetSourceAdapter()}return tween}}GetITweenState(behInst,opts){if(!this._iTweenState)this._iTweenState=C3.New(self.ITweenState,this,behInst,opts);return this._iTweenState}};
+
+}
+
+// timelines/tweens/tweenTrackState.js
+{
+'use strict';const C3=self.C3;
+C3.TweenTrackState=class TweenTrack extends C3.TrackState{constructor(timeline,trackDataItem){super(timeline,trackDataItem);this._firstPropertyTrack=null;this._secondPropertyTrack=null}static Create(timeline,trackDataItem){return C3.New(C3.TweenTrackState,timeline,trackDataItem)}_CachePropertyTracks(){if(this._propertyTracks.length===1)this._firstPropertyTrack=this._propertyTracks[0];else{this._firstPropertyTrack=this._propertyTracks[0];this._secondPropertyTrack=this._propertyTracks[1]}}CreatePropertyTrackStates(){for(const propertyTrackDataItem of this._trackDataItem.GetPropertyTrackData().propertyTrackDataItems())this._propertyTracks.push(C3.TweenPropertyTrackState.Create(this,propertyTrackDataItem));
+this._CachePropertyTracks()}AddPropertyTrack(){const propertyTrackData=this._trackDataItem.GetPropertyTrackData();const propertyTrackDataItem=propertyTrackData.AddEmptyPropertyTrackDataItem();const propertyTrack=C3.TweenPropertyTrackState.Create(this,propertyTrackDataItem);this._propertyTracks.push(propertyTrack);this._CachePropertyTracks();return propertyTrack}SetInitialState(){this.MaybeGetInstance();if(!this.IsInstanceValid()&&this.IsInstanceTrack())return;const timeline=this.GetTimeline();const isForwardPlayBack=
+timeline.IsForwardPlayBack();const time=isForwardPlayBack?0:this.GetLocalTotalTime();for(const propertyTrack of this._propertyTracks){propertyTrack.SetInitialState(time);if(this._worldInfoChange===0&&propertyTrack.GetWorldInfoChange()===1)this._worldInfoChange=1;if(this._renderChange===0&&propertyTrack.GetRenderChange()===1)this._renderChange=1}this._needsBeforeAndAfter=0;const nba=this._propertyTracks.some(pt=>pt.GetNeedsBeforeAndAfter());if(nba)this._needsBeforeAndAfter=1;this._lastKeyframeDataItem=
+this._GetLastKeyFrameBeforeTime(time);this._initialStateOfNestedSet=false;this._endStateOfNestedSet=false;this.Interpolate(time)}BeforeInterpolate(){}Interpolate(time,isTicking=false,setTime=false,ensureValue=false,firstTick=false,ignoreGlobals=false,endState=false){if(!this._instance)this.GetInstance();if(!this._instance)return;const instanceValid=!this._instance.IsDestroyed();if(!instanceValid)return false;if(ignoreGlobals&&this.GetObjectClass().IsGlobal())return false;if(this._secondPropertyTrack){this._firstPropertyTrack.Interpolate(time,
+setTime,ensureValue,endState);this._secondPropertyTrack.Interpolate(time,setTime,ensureValue,endState)}else this._firstPropertyTrack.Interpolate(time,setTime,ensureValue,endState);if(this._firstPropertyTrack.GetWorldInfoChange()!==0){if(!this._worldInfo)this._worldInfo=this._instance.GetWorldInfo();if(this._worldInfo)this._worldInfo.SetBboxChanged()}}AfterInterpolate(){}_LoadFromJson(o){super._LoadFromJson(o);this._CachePropertyTracks()}};
+
+}
+
+// timelines/tweens/tweenPropertyTrackState.js
+{
+'use strict';const C3=self.C3;
+C3.TweenPropertyTrackState=class TweenPropertyTrackState extends C3.PropertyTrackState{constructor(track,propertyTrackDataItem){super(track,propertyTrackDataItem);this._basic=false}static Create(track,propertyTrackDataItem){return C3.New(C3.TweenPropertyTrackState,track,propertyTrackDataItem)}Interpolate(time,setTime=false,ensureValue=false,endState=false){let start;let end;if(this._basic){start=this._propertyKeyframeDataItems[0];end=this._propertyKeyframeDataItems[1]}else if(setTime){start=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(time,
+this._propertyTrackDataItem);end=start.GetNext()}else{if(this._lastPropertyKeyframeDataItem){const timeline=this.GetTimeline();const nextPropertyKeyframe=this._lastPropertyKeyframeDataItem.GetNext();const lastTime=this._lastPropertyKeyframeDataItem.GetTime();const nextTime=nextPropertyKeyframe?nextPropertyKeyframe.GetTime():timeline.GetTotalTime();if(time<=lastTime||time>=nextTime)this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(time,this._propertyTrackDataItem)}else this._lastPropertyKeyframeDataItem=
+this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(time,this._propertyTrackDataItem);start=this._lastPropertyKeyframeDataItem;end=start.GetNext()}this._sourceAdapter.Interpolate(time,start,end,setTime,ensureValue,endState)}AddPropertyKeyframe(){const propertyKeyframeData=this._propertyTrackDataItem.GetPropertyKeyframeData();const propertyKeyframeDataItem=propertyKeyframeData.AddEmptyPropertyKeyframeDataItem();this._lastPropertyKeyframeDataItem=null;this._basic=this.GetPropertyKeyframeDataItems().length<=
+2;return propertyKeyframeDataItem}DeletePropertyKeyframes(match){this._lastPropertyKeyframeDataItem=null;const propertyKeyframeData=this._propertyTrackDataItem.GetPropertyKeyframeData();propertyKeyframeData.DeletePropertyKeyframeDataItems(match);this._basic=this.GetPropertyKeyframeDataItems().length<=2}_SaveToJson(){return{"sourceAdapterJson":this.GetSourceAdapter()._SaveToJson(),"basic":this._basic}}_LoadFromJson(o){if(!o)return;this.GetSourceAdapter()._LoadFromJson(o["sourceAdapterJson"]);this._basic=
+o["basic"]}};
+
+}
+
+// timelines/transitions/transition.js
+{
+'use strict';const C3=self.C3;const Ease=self.Ease;const NAME=0;const TRANSITION_KEYFRAMES=1;
+C3.Transition=class Transition extends C3.DefendedBase{constructor(data,addCustomEase=true){super();this._name=data[NAME];this._linear=false;this._transitionKeyframes=[];for(const transitionKeyframeData of data[TRANSITION_KEYFRAMES]){const transitionKeyframe=C3.TransitionKeyframe.Create(this,transitionKeyframeData);this._transitionKeyframes.push(transitionKeyframe)}for(let i=0;ithis.Interpolate(t,sv,dv,tt))}static Create(data){return C3.New(C3.Transition,data)}Release(){for(const transitionKeyframe of this._transitionKeyframes)transitionKeyframe.Release();C3.clearArray(this._transitionKeyframes);this._transitionKeyframes=null;this._precalculatedSamples.clear();this._precalculatedSamples=null;this._transitionKeyframeCache.clear();
+this._transitionKeyframeCache=null}MakeLinear(linear){this._linear=!!linear}GetTransitionKeyFrameAt(x){const transitionKeyframe=this._transitionKeyframeCache.get(x);if(transitionKeyframe)return transitionKeyframe;for(const transitionKeyframe of this._transitionKeyframes)if(transitionKeyframe.GetValueX()===x){this._transitionKeyframeCache.set(x,transitionKeyframe);return transitionKeyframe}}GetFirstTransitionKeyFrameHigherThan(x){for(const transitionKeyframe of this._transitionKeyframes)if(transitionKeyframe.GetValueX()>
+x)return transitionKeyframe}GetFirstTransitionKeyFrameHigherOrEqualThan(x){for(const transitionKeyframe of this._transitionKeyframes)if(transitionKeyframe.GetValueX()>=x)return transitionKeyframe}GetFirstTransitionKeyFrameLowerThan(x){for(let i=this._transitionKeyframes.length-1;i>=0;i--){const transitionKeyframe=this._transitionKeyframes[i];if(transitionKeyframe.GetValueX()=
+0;i--){const transitionKeyframe=this._transitionKeyframes[i];if(transitionKeyframe.GetValueX()<=x)return transitionKeyframe}}Interpolate(time,startValue,deltaValue,totalTime){let n=time/totalTime;if(this._linear){if(totalTime===0)return startValue+deltaValue;return Ease.NoEase(time,startValue,deltaValue,totalTime)}if(totalTime===0)n=1;let start=this.GetFirstTransitionKeyFrameLowerOrEqualThan(n);let end=start.GetNext();if(!end){start=this.GetFirstTransitionKeyFrameLowerThan(n);end=start.GetNext()}const delta=
+end.GetValueX()-start.GetValueX();const nn=C3.mapToRange(n,start.GetValueX(),end.GetValueX(),0,delta);const startX=start.GetValueX();const startY=start.GetValueY();const anchor1X=start.GetValueX()+start.GetStartAnchorX();const anchor1Y=start.GetValueY()+start.GetStartAnchorY();const anchor2X=end.GetValueX()+end.GetEndAnchorX();const anchor2Y=end.GetValueY()+end.GetEndAnchorY();const endX=end.GetValueX();const endY=end.GetValueY();let ret=Ease.GetRuntimeEase("spline")(nn,startX,startY,anchor1X,anchor1Y,
+anchor2X,anchor2Y,endX,endY,this._precalculatedSamples.get(start));ret+=start.GetValueY();return(1-ret)*startValue+ret*(startValue+deltaValue)}_PreCalcSamples(){this._precalculatedSamples.clear();for(let i=0;ithis._OnInstanceDestroy(e.instance)}Release(){this.RemoveRuntimeListeners();if(this._templateDataMap){for(const objectClassTemplatesMap of this._templateDataMap.values())objectClassTemplatesMap.clear();this._templateDataMap.clear()}this._templateDataMap=null;this._runtime=null}Create(templateInstanceData){if(!this._templateDataMap)this._templateDataMap=
+new Map;if(!templateInstanceData)return;const templateData=templateInstanceData[0][16];const templateName=templateData[0];const objectClassIndex=templateInstanceData[1];if(!this._templateDataMap.has(objectClassIndex))this._templateDataMap.set(objectClassIndex,new Map);const objectClassTemplatesMap=this._templateDataMap.get(objectClassIndex);objectClassTemplatesMap.set(templateName,templateInstanceData)}AddRuntimeListeners(){const dispatcher=this._runtime.Dispatcher();if(dispatcher)dispatcher.addEventListener("instancedestroy",
+this._instanceDestroy)}RemoveRuntimeListeners(){const dispatcher=this._runtime.Dispatcher();if(dispatcher)dispatcher.removeEventListener("instancedestroy",this._instanceDestroy)}HasTemplates(){if(!this._templateDataMap)return false;return this._templateDataMap.size!==0}GetTemplateData(objectClass_or_index,templateName){let index=0;if(objectClass_or_index instanceof C3.ObjectClass)index=objectClass_or_index.GetIndex();else index=objectClass_or_index;if(!this._templateDataMap.has(index))return;const ret=
+this._templateDataMap.get(index).get(templateName);if(ret)return JSON.parse(JSON.stringify(ret));return undefined}MapInstanceToTemplateName(inst,templateName){if(!this._instanceToTemplateNameMap)this._instanceToTemplateNameMap=new WeakMap;if(this._instanceToTemplateNameMap.has(inst))return;this._instanceToTemplateNameMap.set(inst,templateName)}GetInstanceTemplateName(inst){if(!this._instanceToTemplateNameMap)return"";const ret=this._instanceToTemplateNameMap.get(inst);if(ret)return ret;return""}_OnInstanceDestroy(inst){if(!this._instanceToTemplateNameMap)return;
+if(!this._instanceToTemplateNameMap.has(inst))return;this._instanceToTemplateNameMap.delete(inst)}};
+
+}
+
+// flowcharts/flowchartManager.js
+{
+'use strict';const C3=self.C3;
+C3.FlowchartManager=class FlowchartManager{constructor(runtime){this._runtime=runtime;this._flowchartDataManager=new C3.FlowchartDataManager;this._flowchartStates=new Map;this._currentFlowchartState=null;this._flowchartStateStack=[]}Release(){this._flowchartDataManager.Release();this._flowchartDataManager=null;C3.clearArray(this._flowchartStateStack);this._flowchartStateStack=null;this._flowchartStates.clear();this._flowchartStates=null;this._currentFlowchartState=null;this._runtime=null}GetRuntime(){return this._runtime}Create(flowchartData){this._flowchartDataManager.Add(flowchartData)}GetFlowchartDataItemByName(flowchartName){return this._flowchartDataManager.Get(flowchartName)}HasFlowcharts(){return this._flowchartDataManager.HasFlowcharts()}AddFlowchartState(flowchartName,
+startNodeTag,flowchartTag,pluginInstance,setAsCurrent,pluginUID){const flowchartDataItem=this._flowchartDataManager.Get(flowchartName);if(!flowchartDataItem){console.warn(`[Flowcharts] no flowchart found with name '${flowchartName}'`);return}if(this._flowchartStates.has(flowchartTag)){console.warn(`[Flowcharts] there already is a flowchart with the tag '${flowchartTag}'`);return}const flowchartState=new C3.FlowchartState(flowchartName,flowchartTag,startNodeTag,flowchartDataItem,this,pluginInstance,
+pluginUID);this._flowchartStates.set(flowchartTag,flowchartState);if(setAsCurrent)this.SetCurrentFlowchartState(flowchartState,true);return flowchartState}RemoveFlowchartState(flowchartState){flowchartState.MarkForRelease();if(flowchartState.IsInTriggerState())return;const flowchartTag=flowchartState.GetTag();this._flowchartStates.delete(flowchartTag);flowchartState.Release();if(this._currentFlowchartState===flowchartState)this._currentFlowchartState=null}ResetFlowchartState(flowchartState){flowchartState.Reset()}GetFlowchartState(flowchartTag){return this._flowchartStates.get(flowchartTag)}PushFlowchartState(flowchartState){this._flowchartStateStack.push(flowchartState)}PopFlowchartState(){this._flowchartStateStack.pop()}SetCurrentFlowchartState(flowchartState,
+triggerNodeChange=false){if(flowchartState===this._currentFlowchartState)return;this._TriggerBeforeFlowchartChange();this._TriggerAfterFlowchartChange(flowchartState,triggerNodeChange)}GetCurrentFlowchartState(tag){if(typeof tag==="string")return this.GetFlowchartState(tag);else if(this._flowchartStateStack.length)return this._flowchartStateStack[this._flowchartStateStack.length-1];else return this._currentFlowchartState}_TriggerBeforeFlowchartChange(){if(!this._currentFlowchartState)return;if(this._currentFlowchartState.WasReleased())return;
+const inst=this._currentFlowchartState.GetPluginInstance().GetInstance();this._currentFlowchartState.PushIsTriggerState();this.PushFlowchartState(this._currentFlowchartState);this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnBeforeFlowchartChange,inst);this.PopFlowchartState();this._currentFlowchartState.PopIsTriggerState()}_TriggerAfterFlowchartChange(flowchartState,triggerNodeChange=false){this._currentFlowchartState=flowchartState;if(!this._currentFlowchartState)return;if(this._currentFlowchartState.WasReleased())return;
+const inst=this._currentFlowchartState.GetPluginInstance().GetInstance();this._currentFlowchartState.PushIsTriggerState();this.PushFlowchartState(this._currentFlowchartState);this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnFlowchartChange,inst);if(triggerNodeChange){this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnAnyNodeChange,inst);this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnTaggedNodeChange,inst)}this.PopFlowchartState();this._currentFlowchartState.PopIsTriggerState()}_SaveToJson(){return{"flowchartJsonObjects":[...this._flowchartStates.values()].map(fs=>
+fs._SaveToJson()),"currentFlowchartTag":this._currentFlowchartState?this._currentFlowchartState.GetTag():null}}_LoadFromJson(o){if(!o)return;const newFlowchartStates=new Map;for(const flowchartJsonObject of o["flowchartJsonObjects"]){const flowchartTag=flowchartJsonObject["flowchartTag"];if(this._flowchartStates.has(flowchartTag)){const flowchartState=this._flowchartStates.get(flowchartTag);flowchartState._LoadFromJson(flowchartJsonObject);newFlowchartStates.set(flowchartTag,flowchartState)}else{const flowchartState=
+this.AddFlowchartState(flowchartJsonObject["flowchartName"],flowchartJsonObject["startNodeTag"],flowchartJsonObject["flowchartTag"],null,false,flowchartJsonObject["pluginUID"]);newFlowchartStates.set(flowchartJsonObject["flowchartTag"],flowchartState)}}for(const [tag,state]of this._flowchartStates.entries()){if(newFlowchartStates.has(tag))continue;state.Release()}this._flowchartStates.clear();this._flowchartStates=newFlowchartStates;const currentFlowchartTag=this._flowchartStates.get(o["currentFlowchartTag"]);
+if(currentFlowchartTag)this.SetCurrentFlowchartState(currentFlowchartTag,true)}};
+
+}
+
+// flowcharts/state/flowchartState.js
+{
+'use strict';const C3=self.C3;
+C3.FlowchartState=class Flowchart{constructor(flowchartName,tag,startNodeTag,flowchartDataItem,flowchartManager,pluginInstance,pluginUID){this._runtime=flowchartManager.GetRuntime();this._flowchartManager=flowchartManager;this._flowchartName=flowchartName;this._startNodeTag=startNodeTag;this._flowchartDataItem=flowchartDataItem;this._tag=tag;this._pluginInstance=pluginInstance;this._pluginUID=pluginUID?pluginUID:pluginInstance.GetInstance().GetUID();this._SetStartFlowchartNode();this._currentFlowchartNodeId=
+this._startFlowchartNode.GetFlowchartId();this._previousFlowchartNodeIds=[];this._triggerCount=0;this._markForRelease=false;this._released=false}Release(){if(this._released)return;C3.clearArray(this._previousFlowchartNodeIds);this._previousFlowchartNodeIds=null;this._runtime=null;this._flowchartManager=null;this._flowchartDataItem=null;this._pluginInstance=null;this._released=true}WasReleased(){return this._released}GetFlowchartManager(){return this._flowchartManager}GetRuntime(){return this._runtime}GetFlowchartDataItem(){return this._flowchartDataItem}GetTag(){return this._tag}GetPluginInstance(){if(!this._pluginInstance)this._pluginInstance=
+this._runtime.GetInstanceByUID(this._pluginUID).GetPlugin();return this._pluginInstance}GetCurrentNode(){return this.GetFlowchartElementById(this._currentFlowchartNodeId)}GetCurrentNodeTag(){const currentFlowchartNode=this.GetCurrentNode();if(!currentFlowchartNode)return"";return currentFlowchartNode.GetTag()}GetCurrentNodeParent(indexOrTag){const currentFlowchartNode=this.GetCurrentNode();if(C3.IsFiniteNumber(indexOrTag)){const parentFlowchartIds=currentFlowchartNode.GetParentFlowchartIds();const newFlowchartNodeId=
+parentFlowchartIds?parentFlowchartIds[indexOrTag]:undefined;if(C3.IsFiniteNumber(newFlowchartNodeId))return this.GetFlowchartElementById(newFlowchartNodeId)}if(typeof indexOrTag==="string")for(const parentFlowchartId of currentFlowchartNode.GetParentFlowchartIds()){const parentFlowchartNode=this.GetFlowchartElementById(parentFlowchartId);if(parentFlowchartNode.GetTag()===indexOrTag)return this.GetFlowchartElementById(parentFlowchartNode.GetFlowchartId())}}GetCurrentNodeParentTag(index){const currentParentFlowchartNode=
+this.GetCurrentNodeParent(index);if(!currentParentFlowchartNode)return"";return currentParentFlowchartNode.GetTag()}GetCurrentNodeParentIndex(tag){const currentParentFlowchartNode=this.GetCurrentNodeParent(tag);if(!currentParentFlowchartNode)return-1;const parentFlowchartIds=currentParentFlowchartNode.GetParentFlowchartIds();if(!parentFlowchartIds)return-1;return parentFlowchartIds.indexOf(currentParentFlowchartNode.GetFlowchartId())}GetFlowchartElementById(flowchartElementId){return this._flowchartDataItem.GetFlowchartElementById(flowchartElementId)}Reset(){this._previousFlowchartNodeIds=
+[];const startFlowchartId=this._startFlowchartNode.GetFlowchartId();if(startFlowchartId!==this._currentFlowchartNodeId)this._GotoFlowchartNode(startFlowchartId)}GetCurrentNodeOutputCount(){const flowchartNodeDataItem=this._flowchartDataItem.GetFlowchartElementById(this._currentFlowchartNodeId);return flowchartNodeDataItem.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDataItemCount()}GetCurrentNodeOutputNameAt(index){const flowchartNodeOutputDataItem=this._GetFlowchartNodeOutputAt(index);if(!flowchartNodeOutputDataItem)return"";
+return flowchartNodeOutputDataItem.GetName()}GetCurrentNodeOutputValueAt(indexOrName){let flowchartNodeOutputDataItem;if(C3.IsFiniteNumber(indexOrName))flowchartNodeOutputDataItem=this._GetFlowchartNodeOutputAt(indexOrName);if(typeof indexOrName==="string")flowchartNodeOutputDataItem=this._GetFlowchartNodeOutputByName(indexOrName);if(typeof indexOrName!=="number"&&typeof indexOrName!=="string")console.warn("[Flowcharts] unexpected argument type in GetCurrentNodeOutputValueAt expression");if(!flowchartNodeOutputDataItem)return"";
+return flowchartNodeOutputDataItem.GetValue()}GotoNextFlowchartNode(indexOrName){let flowchartNodeOutputDataItem;if(C3.IsFiniteNumber(indexOrName))flowchartNodeOutputDataItem=this._GetFlowchartNodeOutputAt(indexOrName);if(typeof indexOrName==="string")flowchartNodeOutputDataItem=this._GetFlowchartNodeOutputByName(indexOrName);const newFlowchartNodeId=flowchartNodeOutputDataItem.GetConnectedFlowchartNodeFlowchartId();if(!C3.IsFiniteNumber(newFlowchartNodeId))return;this._previousFlowchartNodeIds.push(this._currentFlowchartNodeId);
+this._GotoFlowchartNode(newFlowchartNodeId)}GotoAnyFlowchartNode(nodeTag){const flowchartNodeDataItem=this._flowchartDataItem.GetFlowchartNodeByTag(nodeTag);if(!flowchartNodeDataItem)return;const newFlowchartNodeDataItem=this._flowchartDataItem.GetFlowchartElementById(flowchartNodeDataItem.GetFlowchartId());if(!newFlowchartNodeDataItem)return;this._previousFlowchartNodeIds.push(this._currentFlowchartNodeId);this._GotoFlowchartNode(newFlowchartNodeDataItem.GetFlowchartId())}GotoPreviousFlowchartNode(){const previousFlowchartNodeId=
+this._previousFlowchartNodeIds.pop(this._currentFlowchartNodeId);if(C3.IsFiniteNumber(previousFlowchartNodeId))this._GotoFlowchartNode(previousFlowchartNodeId)}GotoParentFlowchartNode(indexOrTag){const currentFlowchartNode=this.GetCurrentNode();const flowchartNodeId=currentFlowchartNode.GetFlowchartId();const parentFlowchartNode=this.GetCurrentNodeParent(indexOrTag);if(parentFlowchartNode){this._previousFlowchartNodeIds.push(this._currentFlowchartNodeId);this._GotoFlowchartNode(parentFlowchartNode.GetFlowchartId())}}HasOutput(outputIndexOrName){if(C3.IsFiniteNumber(outputIndexOrName)){const flowchartNodeDataItem=
+this._flowchartDataItem.GetFlowchartElementById(this._currentFlowchartNodeId);const flowchartNodeOutputDataItems=flowchartNodeDataItem.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDataItems();return!!flowchartNodeOutputDataItems[outputIndexOrName]}if(typeof outputIndexOrName==="string"){const flowchartNodeDataItem=this._flowchartDataItem.GetFlowchartElementById(this._currentFlowchartNodeId);const flowchartNodeOutputDataItems=flowchartNodeDataItem.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDataItems();
+for(let i=0;i0}PushIsTriggerState(){this._triggerCount++}PopIsTriggerState(){this._triggerCount--;if(this._triggerCount===0&&this._markForRelease)this._flowchartManager.RemoveFlowchartState(this)}_GotoFlowchartNode(newFlowchartNodeId){const inst=this.GetPluginInstance().GetInstance();
+this.PushIsTriggerState();this._flowchartManager.PushFlowchartState(this);this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnBeforeAnyNodeChange,inst);this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnBeforeTaggedNodeChange,inst);this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnBeforeAnyNodeChangeInFlowchart,inst);this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnBeforeTaggedNodeChangeInFlowchart,inst);this._currentFlowchartNodeId=newFlowchartNodeId;this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnAnyNodeChange,
+inst);this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnTaggedNodeChange,inst);this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnAnyNodeChangeInFlowchart,inst);this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnTaggedNodeChangeInFlowchart,inst);this._flowchartManager.PopFlowchartState();this.PopIsTriggerState()}_GetFlowchartNodeOutputAt(index){const flowchartNodeDataItem=this._flowchartDataItem.GetFlowchartElementById(this._currentFlowchartNodeId);if(!flowchartNodeDataItem)return null;const flowchartNodeOutputDataItems=
+flowchartNodeDataItem.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDataItems();if(!flowchartNodeOutputDataItems)return null;const flowchartNodeOutputDataItem=flowchartNodeOutputDataItems[index];if(!flowchartNodeOutputDataItem)return null;return flowchartNodeOutputDataItem}_GetFlowchartNodeOutputByName(outputName){const flowchartNodeDataItem=this._flowchartDataItem.GetFlowchartElementById(this._currentFlowchartNodeId);if(!flowchartNodeDataItem)return null;const flowchartNodeOutputDataItem=flowchartNodeDataItem.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDataItemByName(outputName);
+if(!flowchartNodeOutputDataItem)return null;return flowchartNodeOutputDataItem}_SetStartFlowchartNode(){let startFlowchartNode=this._flowchartDataItem.GetFlowchartNodeByTag(this._startNodeTag);if(!startFlowchartNode)startFlowchartNode=this._flowchartDataItem.GetFlowchartStartNode();this._startFlowchartNode=startFlowchartNode}_SaveToJson(){if(this._markForRelease)return null;return{"flowchartName":this._flowchartName,"flowchartTag":this._tag,"startNodeTag":this._startNodeTag,"currentNodeId":this._currentFlowchartNodeId,
+"previousNodeIds":this._previousFlowchartNodeIds,"pluginUID":this._pluginInstance.GetInstance().GetUID()}}_LoadFromJson(o){if(!o)return;this._flowchartName=o["flowchartName"];this._tag=o["flowchartTag"];this._startNodeTag=o["startNodeTag"];this._currentFlowchartNodeId=o["currentNodeId"];this._previousFlowchartNodeIds=o["previousNodeIds"];this._pluginUID=o["pluginUID"];this._SetStartFlowchartNode()}};
+
+}
+
+// flowcharts/data/flowchartDataManager.js
+{
+'use strict';const C3=self.C3;
+C3.FlowchartDataManager=class FlowchartDataManager{constructor(){this._flowchartDataItems=new Map}Release(){for(const flowchartDataItem of this._flowchartDataItems.values())flowchartDataItem.Release();this._flowchartDataItems.clear();this._flowchartDataItems=null}Add(data){const flowchartDataItem=new C3.FlowchartDataItem(data);const name=flowchartDataItem.GetName();this._flowchartDataItems.set(name,flowchartDataItem)}Get(name){return this._flowchartDataItems.get(name)}HasFlowcharts(){return!!this._flowchartDataItems.size}static CreateDataItems(items,jsonItems,
+dataItemConstructor,dataContainer){if(!jsonItems)return;for(const jsonItem of jsonItems){const dataItem=new dataItemConstructor(jsonItem,dataContainer);items.push(dataItem)}}};
+
+}
+
+// flowcharts/data/flowchartData.js
+{
+'use strict';const C3=self.C3;const NAME=0;const NODES=1;C3.FlowchartDataItem=class FlowchartDataItem{constructor(flowchartDataJson){this._name=flowchartDataJson[NAME];this._flowchartNodeData=new C3.FlowchartNodeData(flowchartDataJson[NODES],this)}Release(){this._flowchartNodeData.Release();this._flowchartNodeData=null}GetFlowchartNodeData(){return this._flowchartNodeData}GetFlowchartElementById(id){return this._flowchartNodeData.GetFlowchartElementById(id)}GetFlowchartNodeByTag(tag){return this._flowchartNodeData.GetFlowchartNodeByTag(tag)}GetFlowchartStartNode(){return this._flowchartNodeData.GetFlowchartStartNode()}GetName(){return this._name}};
+
+}
+
+// flowcharts/data/flowchartNodeData.js
+{
+'use strict';const C3=self.C3;const FLOWCHART_ID=0;const TAG=1;const PARENT_FLOWCHART_IDS=2;const PARENT_OUTPUT_FLOWCHART_IDS=3;const CHILDREN_FLOWCHART_IDS=4;const OUTPUTS=5;const IS_START=6;
+class FlowchartNodeDataItem{constructor(flowchartNodeJson,flowchartNodeData){this._flowchartNodeData=flowchartNodeData;this._flowchartId=flowchartNodeJson[FLOWCHART_ID];this._tag=flowchartNodeJson[TAG];this._parentFlowchartIds=flowchartNodeJson[PARENT_FLOWCHART_IDS];this._parentOutputFlowchartIds=flowchartNodeJson[PARENT_OUTPUT_FLOWCHART_IDS];this._childrenFlowchartIds=flowchartNodeJson[CHILDREN_FLOWCHART_IDS];this._isStart=flowchartNodeJson[IS_START];this._flowchartNodeOutputData=new C3.FlowchartNodeOutputData(flowchartNodeJson[OUTPUTS],
+this)}Release(){this._flowchartNodeData=null}GetFlowchartNodeData(){return this._flowchartNodeData}GetFlowchartNodeOutputData(){return this._flowchartNodeOutputData}GetFlowchartId(){return this._flowchartId}GetTag(){return this._tag}GetIsStart(){return this._isStart}GetParentFlowchartIds(){return this._parentFlowchartIds}GetParentOutputFlowchartIds(){return this._parentOutputFlowchartIds}GetChildrenFlowchartIds(){return this._childrenFlowchartIds}}
+C3.FlowchartNodeData=class FlowchartNodeData{constructor(flowchartNodesDataJson,flowchartDataItem){this._flowchartDataItem=flowchartDataItem;this._flowchartNodeItems=[];this._flowchartNodeItemsIdMap=new Map;this._flowchartNodeItemsTagMap=new Map;this._flowchartNodeStartItem=null;C3.FlowchartDataManager.CreateDataItems(this._flowchartNodeItems,flowchartNodesDataJson,FlowchartNodeDataItem,this);for(const flowchartNodeItem of this._flowchartNodeItems){const flowchartId=flowchartNodeItem.GetFlowchartId();
+const tag=flowchartNodeItem.GetTag();const isStart=flowchartNodeItem.GetIsStart();this._flowchartNodeItemsIdMap.set(flowchartId,flowchartNodeItem);if(tag)this._flowchartNodeItemsTagMap.set(tag,flowchartNodeItem);if(isStart)this._flowchartNodeStartItem=flowchartNodeItem;const flowchartNodeOutputData=flowchartNodeItem.GetFlowchartNodeOutputData();for(const flowchartNodeOutputDataItem of flowchartNodeOutputData.flowchartNodeOutputDataItems()){const flowchartId=flowchartNodeOutputDataItem.GetFlowchartId();
+this._flowchartNodeItemsIdMap.set(flowchartId,flowchartNodeOutputDataItem)}}}Release(){this._flowchartDataItem=null;for(const flowchartNodeDataItem of this._flowchartNodeItems)flowchartNodeDataItem.Release();C3.clearArray(this._flowchartNodeItems);this._flowchartNodeItems=null}GetFlowchartDataItem(){return this._flowchartDataItem}GetFlowchartElementById(id){return this._flowchartNodeItemsIdMap.get(id)}GetFlowchartNodeByTag(tag){return this._flowchartNodeItemsTagMap.get(tag)}GetFlowchartStartNode(){return this._flowchartNodeStartItem}*flowchartNodeDataItems(){for(const flowchartNodeDataItem of this._flowchartNodeItems)yield flowchartNodeDataItem}};
+
+}
+
+// flowcharts/data/flowchartNodeOutputData.js
+{
+'use strict';const C3=self.C3;const FLOWCHART_ID=0;const NAME=1;const VALUE=2;const CONNECTED_FLOWCHART_NODE_FLOWCHART_ID=3;
+class FlowchartNodeDataOutputItem{constructor(flowchartNodeOutputJson,flowchartNodeOutputData){this._flowchartNodeOutputData=flowchartNodeOutputData;this._flowchartId=flowchartNodeOutputJson[FLOWCHART_ID];this._name=flowchartNodeOutputJson[NAME];this._value=flowchartNodeOutputJson[VALUE];this._connectedFlowchartNodeFlowchartId=flowchartNodeOutputJson[CONNECTED_FLOWCHART_NODE_FLOWCHART_ID]}Release(){this._flowchartNodeOutputData=null}GetFlowchartNodeOutputData(){return this._flowchartNodeOutputData}GetFlowchartId(){return this._flowchartId}GetName(){return this._name}GetValue(){return this._value}GetConnectedFlowchartNodeFlowchartId(){return this._connectedFlowchartNodeFlowchartId}}
+C3.FlowchartNodeOutputData=class FlowchartNodeOutputData{constructor(flowchartNodeOuputsDataJson,flowchartDataNodeItem){this._flowchartDataNodeItem=flowchartDataNodeItem;this._flowchartNodeOutputItems=[];this._flowchartNodeOutputItemsNameMap=new Map;C3.FlowchartDataManager.CreateDataItems(this._flowchartNodeOutputItems,flowchartNodeOuputsDataJson,FlowchartNodeDataOutputItem,this);for(const flowchartNodeOutputItem of this._flowchartNodeOutputItems)this._flowchartNodeOutputItemsNameMap.set(flowchartNodeOutputItem.GetName(),
+flowchartNodeOutputItem)}Release(){this._flowchartDataNodeItem=null;for(const flowchartNodeDataItem of this._flowchartNodeOutputItems)flowchartNodeDataItem.Release();C3.clearArray(this._flowchartNodeOutputItems);this._flowchartNodeOutputItems=null}GetFlowchartNodeDataItem(){return this._flowchartDataNodeItem}GetFlowchartNodeOutputDataItemCount(){return this._flowchartNodeOutputItems.length}GetFlowchartNodeOutputDataItems(){return this._flowchartNodeOutputItems}GetFlowchartNodeOutputDataItemByName(outputName){return this._flowchartNodeOutputItemsNameMap.get(outputName)}*flowchartNodeOutputDataItems(){for(const flowchartNodeDataItem of this._flowchartNodeOutputItems)yield flowchartNodeDataItem}};
+
+}
+
+// events/stacks/solStack.js
+{
+'use strict';const C3=self.C3;
+C3.SolStack=class SolStack extends C3.DefendedBase{constructor(objectClass){super();this._objectClass=objectClass;this._stack=[];this._stack.push(C3.New(C3.Sol,this));this._index=0;this._current=this._stack[0]}Release(){for(const s of this._stack)s.Release();C3.clearArray(this._stack);this._current=null;this._objectClass=null}GetObjectClass(){return this._objectClass}GetCurrentSol(){return this._current}GetOneBelowCurrentSol(){return this._stack[this._index-1]}Clear(){this.GetCurrentSol().Clear()}PushClean(){const stack=this._stack;
+const index=++this._index;if(index===stack.length){const sol=C3.New(C3.Sol,this);stack.push(sol);this._current=sol}else{const sol=stack[index];sol.Reset();this._current=sol}}PushCopy(){const stack=this._stack;const index=++this._index;if(index===stack.length)stack.push(C3.New(C3.Sol,this));const sol=stack[index];sol.Copy(stack[index-1]);this._current=sol}Pop(){this._current=this._stack[--this._index]}RemoveInstances(s){const stack=this._stack;for(let i=0,len=stack.length;i=0}GetCurrent(){return this._stack[this._index]}Push(){++this._index;if(this._index===
+this._stack.length){const ret=C3.New(C3.Loop,this);this._stack.push(ret);return ret}else{const ret=this._stack[this._index];ret.Reset();return ret}}Pop(){--this._index}FindByName(name){const stack=this._stack;for(let i=this._index;i>=0;--i){const loop=stack[i];if(loop.GetName()===name)return loop}return null}_GetStack(){return this._stack.slice(0,this._index+1)}};
+
+}
+
+// events/stacks/loop.js
+{
+'use strict';const C3=self.C3;C3.Loop=class Loop extends C3.DefendedBase{constructor(loopStack){super();this._loopStack=loopStack;this._name="";this._index=0;this._isStopped=false;this._end=NaN}Reset(){this._name="";this._index=0;this._isStopped=false;this._end=NaN}SetName(name){this._name=name}GetName(){return this._name}SetIndex(i){this._index=i}GetIndex(){return this._index}Stop(){this._isStopped=true}IsStopped(){return this._isStopped}SetEnd(e){this._end=e}GetEnd(){return this._end}};
+
+}
+
+// events/stacks/arrayStack.js
+{
+'use strict';const C3=self.C3;C3.ArrayStack=class ArrayStack extends C3.DefendedBase{constructor(){super();this._stack=[];this._index=-1}Release(){C3.clearArray(this._stack)}GetCurrent(){return this._stack[this._index]}Push(){++this._index;if(this._index===this._stack.length){const ret=[];this._stack.push(ret);return ret}else return this._stack[this._index]}Pop(){--this._index}};
+
+}
+
+// events/eventSheetManager.js
+{
+'use strict';const C3=self.C3;const assert=self.assert;function SortSolArray(a,b){return a.GetIndex()-b.GetIndex()}function IsSolArrayIdentical(a,b){for(let i=0,len=a.length;ithis._InvokeFunctionFromJS(name,params)}Release(){this.ClearAllScheduledWaits();this._eventStack.Release();
+this._eventStack=null;this._localVarStack.Release();this._localVarStack=null;C3.clearArray(this._queuedTriggers);C3.clearArray(this._queuedDebugTriggers);this._runtime=null;C3.clearArray(this._allSheets);this._sheetsByName.clear()}Create(eventSheetData){const eventSheet=C3.New(C3.EventSheet,this,eventSheetData);this._allSheets.push(eventSheet);this._sheetsByName.set(eventSheet.GetName().toLowerCase(),eventSheet)}_AddTriggerToPostInit(trig){this._triggersToPostInit.push(trig)}_PostInit(){for(const customActionBlock of this._customActionBlocksMap.values())customActionBlock._CheckOverrideState();
+for(const functionBlock of this._functionBlocksByName.values())functionBlock._PostInit();for(const customActionBlock of this._customActionBlocksMap.values())customActionBlock._PostInit();for(const sheet of this._allSheets)sheet._PostInit();for(const sheet of this._allSheets)sheet._UpdateDeepIncludes();for(const trig of this._triggersToPostInit)trig._PostInit(false);C3.clearArray(this._triggersToPostInit);this._localVarStack._SetInitialValues(this._localVarInitialValues)}GetRuntime(){return this._runtime}GetEventSheetByName(name){return this._sheetsByName.get(name.toLowerCase())||
+null}_RegisterGroup(group){this._allGroups.push(group);this._groupsByName.set(group.GetGroupName(),group)}_RegisterEventBlock(eventBlock){this._blocksBySid.set(eventBlock.GetSID(),eventBlock)}_RegisterCondition(condition){this._cndsBySid.set(condition.GetSID(),condition)}_RegisterAction(action){this._actsBySid.set(action.GetSID(),action)}_RegisterFunctionBlock(functionBlock){switch(functionBlock.GetFunctionType()){case 0:this._functionBlocksByName.set(functionBlock.GetFunctionName().toLowerCase(),
+functionBlock);break;case 1:this._customActionBlocksMap.set(functionBlock.GetFunctionName().toLowerCase(),functionBlock);break;default:}}_RegisterEventVariable(ev){this._eventVarsBySid.set(ev.GetSID(),ev);if(ev.IsGlobal())this._allGlobalVars.push(ev);else this._allLocalVars.push(ev)}_DeduplicateSolModifierList(arr){if(arr.length>=2)arr.sort(SortSolArray);let candidateList=this._allUniqueSolModifiers.get(arr.length);if(!candidateList){candidateList=[];this._allUniqueSolModifiers.set(arr.length,candidateList)}for(let i=
+0,len=candidateList.length;iresolve=r);this._queuedDebugTriggers.push([method,inst,behaviorType,resolve]);return ret}*_RunQueuedDebugTriggersGen(){if(this._runtime.HitBreakpoint())throw new Error("should not be in breakpoint");const layoutManager=this._runtime.GetLayoutManager();while(this._queuedDebugTriggers.length){const [method,inst,behaviorType,resolve]=this._queuedDebugTriggers.shift();const ret=yield*this._DebugTrigger(layoutManager,method,inst,behaviorType);resolve(ret)}}async RunQueuedDebugTriggersAsync(){for(const breakEventObject of this._RunQueuedDebugTriggersGen())await this._runtime.DebugBreak(breakEventObject)}_FastTrigger(layoutManager,
+method,inst,value){let ret=false;const layout=layoutManager.GetMainRunningLayout();const eventSheet=layout.GetEventSheet();if(!eventSheet)return;this._executingTriggerDepth++;this._runtime.PushCurrentLayout(layout);const deepIncludes=eventSheet.deepIncludes();for(let i=0,len=deepIncludes.length;i0}_IncTriggerDepth(){return++this._executingTriggerDepth}_DecTriggerDepth(){--this._executingTriggerDepth}IsRunningEvents(){return this._runningEventsDepth>0}IsInEventEngine(){return this.IsRunningEvents()||this.IsInTrigger()}_RunQueuedTriggers(layoutManager){for(const [method,inst,behaviorType]of this._queuedTriggers)this._Trigger(layoutManager,
+method,inst,behaviorType);C3.clearArray(this._queuedTriggers)}BlockFlushingInstances(e){if(e)this._blockFlushingDepth++;else this._blockFlushingDepth--}IsFlushingBlocked(){return this._blockFlushingDepth>0}ClearSol(solModifiers){for(let i=0,len=solModifiers.length;i0){for(const t of pushSet)t.GetSolStack().PushClean();return[...pushSet]}else return null}AddScheduledWait(){const w=C3.New(C3.ScheduledWait,this);this._scheduledWaits.push(w);return w}scheduledWaits(){return this._scheduledWaits}RunScheduledWaits(){if(!this._scheduledWaits.length)return;const frame=this.GetCurrentEventStackFrame();let didAnyRun=false;this._runningEventsDepth++;for(let i=0,
+len=this._scheduledWaits.length;iw.ShouldRelease());for(const w of toRelease)w.Release()}ClearAllScheduledWaits(){for(const w of this._scheduledWaits)w.Release();C3.clearArray(this._scheduledWaits)}RemoveInstancesFromScheduledWaits(s){for(const w of this._scheduledWaits)w.RemoveInstances(s)}AddAsyncActionPromise(p){this._asyncActionPromises.push(p)}ClearAsyncActionPromises(){C3.clearArray(this._asyncActionPromises)}GetPromiseForAllAsyncActions(){const ret=
+Promise.all(this._asyncActionPromises);this._asyncActionPromises=[];return ret}_SaveToJson(){return{"groups":this._SaveGroupsToJson(),"cnds":this._SaveCndsToJson(),"acts":this._SaveActsToJson(),"vars":this._SaveVarsToJson(),"waits":this._SaveScheduledWaitsToJson()}}_LoadFromJson(o){this._LoadGroupsFromJson(o["groups"]);this._LoadCndsFromJson(o["cnds"]);this._LoadActsFromJson(o["acts"]);this._LoadVarsFromJson(o["vars"]);this._LoadScheduledWaitsFromJson(o["waits"])}_SaveGroupsToJson(){const o={};for(const group of this.GetAllGroups())o[group.GetSID().toString()]=
+group.IsGroupActive();return o}_LoadGroupsFromJson(o){for(const [sidStr,data]of Object.entries(o)){const sid=parseInt(sidStr,10);const group=this.GetEventGroupBySID(sid);if(group)group.SetGroupActive(data)}}_SaveCndsToJson(){const o={};for(const [sid,cnd]of this._cndsBySid){const data=cnd._SaveToJson();if(data)o[sid.toString()]=data}return o}_LoadCndsFromJson(o){const map=new Map;for(const [sidStr,data]of Object.entries(o))map.set(parseInt(sidStr,10),data);for(const [sid,cnd]of this._cndsBySid)cnd._LoadFromJson(map.get(sid)||
+null)}_SaveActsToJson(){const o={};for(const [sid,act]of this._actsBySid){const data=act._SaveToJson();if(data)o[sid.toString()]=data}return o}_LoadActsFromJson(o){const map=new Map;for(const [sidStr,data]of Object.entries(o))map.set(parseInt(sidStr,10),data);for(const [sid,act]of this._actsBySid)act._LoadFromJson(map.get(sid)||null)}_SaveVarsToJson(){const o={};for(const [sid,eventVar]of this._eventVarsBySid)if(!eventVar.IsConstant()&&(eventVar.IsGlobal()||eventVar.IsStatic()))o[sid.toString()]=
+eventVar.GetValue();return o}_LoadVarsFromJson(o){for(const [sidStr,data]of Object.entries(o)){const sid=parseInt(sidStr,10);const eventVar=this.GetEventVariableBySID(sid);if(eventVar)eventVar.SetValue(data)}}_SaveScheduledWaitsToJson(){return this._scheduledWaits.filter(w=>!w.IsPromise()).map(w=>w._SaveToJson())}_LoadScheduledWaitsFromJson(arr){this.ClearAllScheduledWaits();for(const data of arr){const sw=C3.ScheduledWait._CreateFromJson(this,data);if(sw)this._scheduledWaits.push(sw)}}_GetPerfRecords(){return[...this._runtime.GetLayoutManager().runningLayouts()].map(l=>
+l.GetEventSheet()).filter(eventSheet=>eventSheet).map(e=>e._GetPerfRecord())}FindFirstFunctionBlockParent(parent){while(parent){const scopeParent=parent.GetScopeParent();if(scopeParent instanceof C3.FunctionBlock)return scopeParent;parent=scopeParent}return null}_InvokeFunctionFromJS(name,params){if(!Array.isArray(params))params=[];const functionBlock=this.GetFunctionBlockByName(name.toLowerCase());if(!functionBlock)return null;if(!functionBlock.IsEnabled())return functionBlock.GetDefaultReturnValue();
+const functionParameters=functionBlock.GetFunctionParameters();if(params.length1;if(isRecursive)eventSheetManager.GetLocalVarStack().Push();const frame=eventStack.Push(trigger);if(inst){const objectClass=trigger.GetConditions()[index].GetObjectClass();const sol=objectClass.GetCurrentSol();sol.SetSinglePicked(inst);if(inst.IsInContainer())inst.SetSiblingsSinglePicked()}let okToRun=true;if(trigger.GetParent()){const parents=trigger.GetTriggerParents();for(let i=0,len=parents.length;i<
+len;++i)if(!parents[i].RunPreTrigger(frame)){okToRun=false;break}}if(okToRun){if(trigger.IsOrBlock())trigger.RunOrBlockTrigger(frame,index);else trigger.Run(frame);ret=frame.GetLastEventTrue()}eventStack.Pop();if(isRecursive)eventSheetManager.GetLocalVarStack().Pop();eventSheetManager.PopSol(trigger.GetSolModifiersIncludingParents());if(currentEvent)eventSheetManager.PopSol(currentEvent.GetSolModifiersIncludingParents());if(!currentEvent&&triggerDepth===1){eventSheetManager.ClearAsyncActionPromises();
+if(!eventSheetManager.IsFlushingBlocked())runtime.FlushPendingInstances()}return ret}*_DebugExecuteTrigger(inst,trigger,index){const runtime=this._runtime;const eventSheetManager=this._eventSheetManager;const currentEvent=eventSheetManager.GetCurrentEvent();const eventStack=eventSheetManager.GetEventStack();const triggerDepth=eventSheetManager.GetTriggerDepth();let ret=false;if(currentEvent)eventSheetManager.PushCleanSol(currentEvent.GetSolModifiersIncludingParents());eventSheetManager.PushCleanSol(trigger.GetSolModifiersIncludingParents());
+const isRecursive=triggerDepth>1;if(isRecursive)eventSheetManager.GetLocalVarStack().Push();const frame=eventStack.Push(trigger);if(inst){const objectClass=trigger.GetConditions()[index].GetObjectClass();const sol=objectClass.GetCurrentSol();sol.SetSinglePicked(inst);if(inst.IsInContainer())inst.SetSiblingsSinglePicked()}let okToRun=true;if(trigger.GetParent()){const parents=trigger.GetTriggerParents();for(let i=0,len=parents.length;i0){let hasAnyActionWithReturnType=false;for(const a of this._actions){a._PostInit();if(a.HasReturnType())hasAnyActionWithReturnType=true}if(hasAnyActionWithReturnType){this._RunActions=this._RunActions_ReturnValue;
+this._DebugRunActions=this._DebugRunActions_ReturnValue}else{this._RunActions=this._RunActions_Fast;this._DebugRunActions=this._DebugRunActions_Fast}}const subEvents=this._subEvents;for(let i=0,len=subEvents.length;ic.DebugCanRunFast());dd.canRunAllActionsFast=this._actions.every(a=>a.DebugCanRunFast());dd.canRunAllSubEventsFast=this._subEvents.every(s=>s.DebugCanRunFast());dd.canRunSelfFast=dd.canRunAllConditionsFast&&dd.canRunAllActionsFast&&dd.canRunAllSubEventsFast}_UpdateCanRunFastRecursive(){let e=this;do{e._UpdateCanRunFast();
+e=e.GetParent()}while(e)}_IdentifyTopLevelGroup(){if(!this.IsGroup())return;let p=this.GetParent();this._isTopLevelGroup=true;while(p){if(!p.IsGroup()){this._isTopLevelGroup=false;break}p=p.GetParent()}}_IdentifySolModifiersIncludingParents(){const allObjectClasses=this._runtime.GetAllObjectClasses();if(this._solModifiers===allObjectClasses)this._solModifiersIncludingParents=allObjectClasses;else{this._solModifiersIncludingParents=C3.cloneArray(this._solModifiers);let p=this.GetParent();while(p){for(const o of p._solModifiers)this._AddParentSolModifier(o);
+p=p.GetParent()}const eventSheetManager=this.GetEventSheetManager();this._solModifiers=eventSheetManager._DeduplicateSolModifierList(this._solModifiers);this._solModifiersIncludingParents=eventSheetManager._DeduplicateSolModifierList(this._solModifiersIncludingParents)}}_IdentifyTriggerParents(){if(!this.HasAnyTriggeredCondition())return;this._triggerParents=[];let p=this.GetParent();while(p){this._triggerParents.push(p);p=p.GetParent()}this._triggerParents.reverse()}SetSolWriterAfterCnds(){this._isSolWriterAfterCnds=
+true;if(this._parent)this._parent.SetSolWriterAfterCnds()}IsSolWriterAfterCnds(){return this._isSolWriterAfterCnds}GetSolModifiers(){return this._solModifiers}GetSolModifiersIncludingParents(){if(!this._hasGotSolModifiersIncludingParents){this._hasGotSolModifiersIncludingParents=true;this._IdentifySolModifiersIncludingParents()}return this._solModifiersIncludingParents}HasSolModifier(objectClass){return this._solModifiers.includes(objectClass)}GetTriggerParents(){return this._triggerParents}GetEventSheet(){return this._eventSheet}GetEventSheetManager(){return this._eventSheet.GetEventSheetManager()}GetRuntime(){return this._runtime}GetParent(){return this._parent}_SetScopeParent(p){this._scopeParent=
+p}GetScopeParent(){return this._scopeParent||this._parent}GetDisplayNumber(){return this._displayNumber}IsDebugBreakable(){return this._debugData&&this._debugData.isBreakable}IsDebugBreakpoint(){return this.IsDebugBreakable()&&this._debugData.isBreakpoint}_SetDebugBreakpoint(b){this._debugData.isBreakpoint=!!b;this._UpdateCanRunFastRecursive()}IsGroup(){return this._isGroup}IsTopLevelGroup(){return this._isTopLevelGroup}IsElseBlock(){return this._isElseBlock}HasElseBlock(){return this._hasElseBlock}GetGroupName(){return this._groupName}IsGroupActive(){return this._isGroupActive}ResetInitialActivation(){this.SetGroupActive(this._isInitiallyActive)}SetGroupActive(a){a=
+!!a;if(!this._isGroup)throw new Error("not a group");if(this._isGroupActive===a)return;this._isGroupActive=a;for(const include of this._containedIncludes)include.UpdateActive();if(this._containedIncludes.length){const currentLayout=this._runtime.GetCurrentLayout();const mainEventSheet=currentLayout.GetEventSheet();if(mainEventSheet)mainEventSheet._UpdateDeepIncludes()}}GetSID(){return this._sid}IsOrBlock(){return this._isOrBlock}IsTrigger(){return this._conditions.length&&this._conditions[0].IsTrigger()}IsForFunctionBlock(){return this._scopeParent&&
+this._scopeParent instanceof C3.FunctionBlock}HasAnyTriggeredCondition(){return this.IsForFunctionBlock()||this._conditions.some(c=>c.IsTrigger())}GetConditions(){return this._conditions}GetConditionCount(){return this._conditions.length}GetConditionAt(i){i=Math.floor(i);if(i<0||i>=this._conditions.length)throw new RangeError("invalid condition index");return this._conditions[i]}GetConditionByDebugIndex(i){return this.GetConditionAt(i)}IsFirstConditionOfType(cnd){let i=cnd.GetIndex();if(i===0)return true;
+--i;const cndObjectClass=cnd.GetObjectClass();for(;i>=0;--i){const c=this._conditions[i];if(c.GetObjectClass()===cndObjectClass||c.IsSystemCondition()&&c.GetFirstObjectParameterObjectClass()===cndObjectClass)return false}return true}GetActions(){return this._actions}GetActionCount(){return this._actions.length}GetActionAt(i){i=Math.floor(i);if(i<0||i>=this._actions.length)throw new RangeError("invalid action index");return this._actions[i]}GetActionByDebugIndex(i){i=Math.floor(i);const ret=this._actions.find(a=>
+a.GetDebugIndex()===i);if(!ret)throw new RangeError("invalid action debug index");return ret}_HasActionIndex(i){i=Math.floor(i);return i>=0&&ie instanceof C3.EventVariable)}RunPreTrigger(frame){frame.SetCurrentEvent(this);const conditions=this._conditions;let isAnyTrue=conditions.length===0;for(let i=0,len=conditions.length;i
+0)if(isRecursive){const paramResults=parameters.map(p=>p.Get(0));eventSheetManager.GetLocalVarStack().Push();this._scopeParent.SetFunctionParameters(paramResults)}else this._scopeParent.EvaluateFunctionParameters(parameters);else if(isRecursive)eventSheetManager.GetLocalVarStack().Push()}RunAsFunctionCall(combinedSolModifiers,parameters,isCopyPicked,pickInfo){let ret;let asyncId;const hasAnySolModifiers=combinedSolModifiers.length>0;let extraPopSolModifiers=null;const runtime=this._runtime;const eventStack=
+this._eventStack;const eventSheetManager=runtime.GetEventSheetManager();const triggerDepth=eventSheetManager._IncTriggerDepth();const isRecursive=triggerDepth>1;this._EvaluateFunctionCallParameters(eventSheetManager,parameters,isRecursive);if(hasAnySolModifiers)if(isCopyPicked)eventSheetManager.PushCopySol(combinedSolModifiers);else eventSheetManager.PushCleanSol(combinedSolModifiers);if(pickInfo!==null){if(pickInfo.copyFromObjectClass){const copyFromSol=isCopyPicked?pickInfo.copyFromObjectClass.GetCurrentSol():
+pickInfo.copyFromObjectClass.GetSolStack().GetOneBelowCurrentSol();const copyToSol=pickInfo.copyToObjectClass.GetCurrentSol();copyToSol.SetArrayPicked(copyFromSol.GetInstances());copyToSol.ClearElseInstances();if(!isCopyPicked)pickInfo.copyToObjectClass.ApplySolToContainer()}else if(pickInfo.pickObjectClass){const objectClassSol=pickInfo.pickObjectClass.GetCurrentSol();objectClassSol.SetArrayPicked(pickInfo.pickInstances);objectClassSol.ClearElseInstances()}if(pickInfo.pushCleanSolDynamic)extraPopSolModifiers=
+eventSheetManager.PushCleanSolDynamic(combinedSolModifiers)}const frame=eventStack.Push(this);if(isCopyPicked)frame.SetDynamicSolModifiers(combinedSolModifiers);if(this._CheckParentsOKToRun(frame)){frame.SetCurrentEvent(this);const isAsync=this._scopeParent.IsAsync();if(isAsync)[asyncId,ret]=this._scopeParent.StartAsyncFunctionCall();this._RunAndBlock(frame);if(isAsync)this._scopeParent.MaybeFinishAsyncFunctionCall(asyncId)}eventStack.Pop();if(isRecursive)eventSheetManager.GetLocalVarStack().Pop();
+if(extraPopSolModifiers!==null)eventSheetManager.PopSol(extraPopSolModifiers);if(hasAnySolModifiers)eventSheetManager.PopSol(combinedSolModifiers);eventSheetManager._DecTriggerDepth();return ret}*DebugRunAsFunctionCall(combinedSolModifiers,parameters,isCopyPicked,pickInfo){let ret;let asyncId;if(this.IsDebugBreakpoint()||this._runtime.DebugBreakNext())yield this;const hasAnySolModifiers=combinedSolModifiers.length>0;let extraPopSolModifiers=null;const runtime=this._runtime;const eventStack=this._eventStack;
+const eventSheetManager=runtime.GetEventSheetManager();const triggerDepth=eventSheetManager._IncTriggerDepth();const isRecursive=triggerDepth>1;this._EvaluateFunctionCallParameters(eventSheetManager,parameters,isRecursive);if(hasAnySolModifiers)if(isCopyPicked)eventSheetManager.PushCopySol(combinedSolModifiers);else eventSheetManager.PushCleanSol(combinedSolModifiers);if(pickInfo!==null){if(pickInfo.copyFromObjectClass){const copyFromSol=isCopyPicked?pickInfo.copyFromObjectClass.GetCurrentSol():pickInfo.copyFromObjectClass.GetSolStack().GetOneBelowCurrentSol();
+const copyToSol=pickInfo.copyToObjectClass.GetCurrentSol();copyToSol.SetArrayPicked(copyFromSol.GetInstances());copyToSol.ClearElseInstances();if(!isCopyPicked)pickInfo.copyToObjectClass.ApplySolToContainer()}else if(pickInfo.pickObjectClass){const objectClassSol=pickInfo.pickObjectClass.GetCurrentSol();objectClassSol.SetArrayPicked(pickInfo.pickInstances);objectClassSol.ClearElseInstances()}if(pickInfo.pushCleanSolDynamic)extraPopSolModifiers=eventSheetManager.PushCleanSolDynamic(combinedSolModifiers)}const frame=
+eventStack.Push(this);if(isCopyPicked)frame.SetDynamicSolModifiers(combinedSolModifiers);if(yield*this._DebugCheckParentsOKToRun(frame)){frame.SetCurrentEvent(this);const isAsync=this._scopeParent.IsAsync();if(isAsync)[asyncId,ret]=this._scopeParent.StartAsyncFunctionCall();yield*this._DebugRunAndBlock(frame);if(isAsync)this._scopeParent.MaybeFinishAsyncFunctionCall(asyncId)}eventStack.Pop();if(isRecursive)eventSheetManager.GetLocalVarStack().Pop();if(extraPopSolModifiers!==null)eventSheetManager.PopSol(extraPopSolModifiers);
+if(hasAnySolModifiers)eventSheetManager.PopSol(combinedSolModifiers);eventSheetManager._DecTriggerDepth();return ret}RunAsMappedFunctionCall(paramResults,isCopyPicked){const solModifiers=this.GetSolModifiersIncludingParents();const hasAnySolModifiers=solModifiers.length>0;const runtime=this._runtime;const eventStack=this._eventStack;const eventSheetManager=runtime.GetEventSheetManager();const triggerDepth=eventSheetManager._IncTriggerDepth();const isRecursive=triggerDepth>1;if(isRecursive)eventSheetManager.GetLocalVarStack().Push();
+this._scopeParent.SetFunctionParameters(paramResults);if(hasAnySolModifiers)if(isCopyPicked)eventSheetManager.PushCopySol(solModifiers);else eventSheetManager.PushCleanSol(solModifiers);const frame=eventStack.Push(this);if(this._CheckParentsOKToRun(frame)){frame.SetCurrentEvent(this);this._RunAndBlock(frame)}eventStack.Pop();if(isRecursive)eventSheetManager.GetLocalVarStack().Pop();if(hasAnySolModifiers)eventSheetManager.PopSol(solModifiers);eventSheetManager._DecTriggerDepth()}*DebugRunAsMappedFunctionCall(paramResults,
+isCopyPicked){if(this.IsDebugBreakpoint()||this._runtime.DebugBreakNext())yield this;const solModifiers=this.GetSolModifiersIncludingParents();const hasAnySolModifiers=solModifiers.length>0;const runtime=this._runtime;const eventStack=this._eventStack;const eventSheetManager=runtime.GetEventSheetManager();const triggerDepth=eventSheetManager._IncTriggerDepth();const isRecursive=triggerDepth>1;if(isRecursive)eventSheetManager.GetLocalVarStack().Push();this._scopeParent.SetFunctionParameters(paramResults);
+if(hasAnySolModifiers)if(isCopyPicked)eventSheetManager.PushCopySol(solModifiers);else eventSheetManager.PushCleanSol(solModifiers);const frame=eventStack.Push(this);if(yield*this._DebugCheckParentsOKToRun(frame)){frame.SetCurrentEvent(this);yield*this._DebugRunAndBlock(frame)}eventStack.Pop();if(isRecursive)eventSheetManager.GetLocalVarStack().Pop();if(hasAnySolModifiers)eventSheetManager.PopSol(solModifiers);eventSheetManager._DecTriggerDepth()}RunAsExpressionFunctionCall(combinedSolModifiers,isCopyPicked,
+returnType,defaultReturnValue,...paramResults){let ret;let asyncId;const hasAnySolModifiers=combinedSolModifiers.length>0;const runtime=this._runtime;const eventStack=this._eventStack;const eventSheetManager=runtime.GetEventSheetManager();const triggerDepth=eventSheetManager._IncTriggerDepth();const isRecursive=triggerDepth>1;if(isRecursive)eventSheetManager.GetLocalVarStack().Push();if(paramResults.length>0)this._scopeParent.SetFunctionParameters(paramResults);if(hasAnySolModifiers)if(isCopyPicked)eventSheetManager.PushCopySol(combinedSolModifiers);
+else eventSheetManager.PushCleanSol(combinedSolModifiers);const frame=eventStack.Push(this);frame.InitCallFunctionExpression(returnType,defaultReturnValue);eventStack.PushExpFunc(frame);runtime.SetDebuggingEnabled(false);if(this._CheckParentsOKToRun(frame)){frame.SetCurrentEvent(this);const isAsync=this._scopeParent.IsAsync();if(isAsync)[asyncId,ret]=this._scopeParent.StartAsyncFunctionCall();this._RunAndBlock(frame);if(isAsync)this._scopeParent.MaybeFinishAsyncFunctionCall(asyncId)}runtime.SetDebuggingEnabled(true);
+eventStack.Pop();eventStack.PopExpFunc();if(isRecursive)eventSheetManager.GetLocalVarStack().Pop();if(hasAnySolModifiers)eventSheetManager.PopSol(combinedSolModifiers);eventSheetManager._DecTriggerDepth();return ret||frame.GetFunctionReturnValue()}};
+
+}
+
+// events/eventScript.js
+{
+'use strict';const C3=self.C3;const EMPTY_SOL_MODIFIERS=[];let hadUserScriptException=false;
+C3.EventScript=class EventScript extends C3.DefendedBase{constructor(eventSheet,parent,data){super();const runtime=eventSheet.GetRuntime();const eventSheetManager=eventSheet.GetEventSheetManager();this._eventSheet=eventSheet;this._eventSheetManager=eventSheetManager;this._runtime=eventSheet.GetRuntime();this._parent=parent;const userMethod=runtime.GetObjectReference(data[1]);this._func=userMethod;this._displayNumber=data[2];this._eventSheet._RegisterEventByDisplayNumber(this,this._displayNumber);
+this._debugData=runtime.IsDebug()?{isBreakpoint:data[3][0],isBreakable:data[3][1]}:null}static Create(eventSheet,parent,data){return C3.New(C3.EventScript,eventSheet,parent,data)}_PostInit(){const userMethod=this._func;const localVars=this._runtime.GetEventSheetManager()._GetLocalVariablesScriptInterface(this);this._func=userMethod.bind(null,this._runtime.GetIRuntime(),localVars)}GetParent(){return this._parent}GetScopeParent(){return this._parent}GetEventSheet(){return this._eventSheet}GetDisplayNumber(){return this._displayNumber}IsDebugBreakable(){return this._debugData&&
+this._debugData.isBreakable}IsDebugBreakpoint(){return this.IsDebugBreakable()&&this._debugData.isBreakpoint}_SetDebugBreakpoint(b){this._debugData.isBreakpoint=!!b}IsElseBlock(){return false}GetSolModifiers(){return EMPTY_SOL_MODIFIERS}GetSolModifiersIncludingParents(){if(this._parent)return this._parent.GetSolModifiersIncludingParents();else return EMPTY_SOL_MODIFIERS}Run(frame){frame.SetCurrentEvent(this);this._eventSheetManager.AddAsyncActionPromise(this._RunUserScript())}async _RunUserScript(){try{await this._func()}catch(err){console.error(`Unhandled exception running script %c${this.GetEventSheet().GetName()}, event ${this.GetDisplayNumber()}:`,
+"font-size: 1.2em; font-weight: bold;",err);if(self.C3Debugger)self.C3Debugger._SetLastErrorScript(this);if(!hadUserScriptException){console.info(`%cTip:%c run this to highlight in Construct the last script that had an error: %cgoToLastErrorScript()`,"font-weight: bold; text-decoration: underline","","font-weight: bold");hadUserScriptException=true}}}*DebugRun(frame){frame.SetCurrentEvent(this);if(this.IsDebugBreakpoint()||this._runtime.DebugBreakNext())yield this;this.Run(frame)}DebugCanRunFast(){return!this.IsDebugBreakpoint()&&
+!this._runtime.DebugBreakNext()}static HadUserScriptException(){return hadUserScriptException}static SetHadUserScriptException(){hadUserScriptException=true}};
+
+}
+
+// events/functionBlock.js
+{
+'use strict';const C3=self.C3;const assert=self.assert;
+C3.FunctionBlock=class FunctionBlock extends C3.DefendedBase{constructor(eventSheet,parent,data){super();this._eventSheet=eventSheet;this._runtime=eventSheet.GetRuntime();this._parent=parent;this._functionType=0;this._functionName="";this._returnType=0;this._functionParameters=[];this._isEnabled=true;this._aceName="";this._objectClass=null;this._hasOverrides=false;this._innerLocalVariables=[];this._isCopyPicked=false;this._isAsync=false;this._nextAsyncId=0;this._currentAsyncId=-1;this._asyncMap=new Map;
+this._eventBlock=C3.EventBlock.Create(eventSheet,parent,data);this._eventBlock._SetScopeParent(this)}InitFunctionBlock(funcData){this._functionType=0;this._functionName=funcData[0];this._returnType=funcData[1];this._functionParameters=funcData[2].map(paramData=>C3.EventVariable.Create(this._eventSheet,this,paramData));this._isEnabled=funcData[3];this._isAsync=funcData[4];this._isCopyPicked=funcData[5]}InitCustomACEBlock(funcData){this._functionType=1;this._aceName=funcData[1];this._objectClass=this._runtime.GetObjectClassByIndex(funcData[2]);
+this._eventBlock._AddSolModifier(this._objectClass);this._functionName=this._objectClass.GetName()+"."+this._aceName;this._returnType=funcData[3];this._functionParameters=funcData[4].map(paramData=>C3.EventVariable.Create(this._eventSheet,this,paramData));this._isEnabled=funcData[5];this._isAsync=funcData[6];this._isCopyPicked=funcData[7];this._objectClass.AddCustomAction(this)}static CreateFunctionBlock(eventSheet,parent,data){const ret=C3.New(C3.FunctionBlock,eventSheet,parent,data);const funcData=
+data[1];ret.InitFunctionBlock(funcData);return ret}static CreateCustomACEBlock(eventSheet,parent,data){const ret=C3.New(C3.FunctionBlock,eventSheet,parent,data);const funcData=data[1];ret.InitCustomACEBlock(funcData);return ret}_CheckOverrideState(){if(this._objectClass&&this._objectClass.IsFamily())for(const objectType of this._objectClass.GetFamilyMembers())if(objectType.HasOwnCustomActionByName(this._aceName)){this._hasOverrides=true;break}}_PostInit(){for(const fp of this._functionParameters)fp._PostInit();
+this._eventBlock._PostInit(false)}GetFunctionType(){return this._functionType}_GetAllLocalVariablesInScope(){return this._functionParameters}GetFunctionParameters(){return this._functionParameters}GetFunctionParameterCount(){return this._functionParameters.length}_RegisterLocalVariable(localVariable){this._innerLocalVariables.push(localVariable)}_GetAllInnerLocalVariables(){return this._innerLocalVariables}EvaluateFunctionParameters(parameters){const functionParameters=this._functionParameters;for(let i=
+0,len=functionParameters.length;ip.GetValue())}GetParent(){return this._parent}GetScopeParent(){return this._parent}GetFunctionName(){return this._functionName}GetACEName(){return this._aceName}HasCustomACEOverrides(){return this._hasOverrides}GetReturnType(){return this._returnType}GetObjectClass(){return this._objectClass}IsEnabled(){return this._isEnabled}GetDefaultReturnValue(){switch(this._returnType){case 0:return null;
+case 2:return"";default:return 0}}GetEventBlock(){return this._eventBlock}IsCopyPicked(){return this._isCopyPicked}IsAsync(){return this._isAsync}StartAsyncFunctionCall(){const asyncId=this._nextAsyncId++;this._currentAsyncId=asyncId;let resolve;const promise=new Promise(r=>resolve=r);this._asyncMap.set(asyncId,{resolve,pauseCount:0});return[asyncId,promise]}MaybeFinishAsyncFunctionCall(asyncId){const info=this._asyncMap.get(asyncId);if(info.pauseCount===0){info.resolve();this._asyncMap.delete(asyncId)}this._currentAsyncId=
+-1}PauseCurrentAsyncFunction(){const info=this._asyncMap.get(this._currentAsyncId);info.pauseCount++;return this._currentAsyncId}ResumeAsyncFunction(asyncId){this._currentAsyncId=asyncId;const info=this._asyncMap.get(asyncId);info.pauseCount--}RunAsFamilyCustomActionWithOverrides(combinedSolModifiers,parameters){const objectTypeMap=new Map;const familyInstances=[];for(const inst of this._objectClass.GetCurrentSol().GetInstances()){const objectType=inst.GetObjectClass();if(objectType.HasOwnCustomActionByName(this._aceName)){const arr=
+objectTypeMap.get(objectType);if(Array.isArray(arr))arr.push(inst);else objectTypeMap.set(objectType,[inst])}else familyInstances.push(inst)}if(familyInstances.length>0)this._eventBlock.RunAsFunctionCall(combinedSolModifiers,parameters,this._isCopyPicked,{pickObjectClass:this._objectClass,pickInstances:familyInstances});if(objectTypeMap.size>0)for(const [objectType,arr]of objectTypeMap){const eventBlock=objectType.GetOwnCustomActionByName(this._aceName).GetEventBlock();const allCombinedSolModifiers=
+[...(new Set([...combinedSolModifiers,...eventBlock.GetSolModifiers()]))];eventBlock.RunAsFunctionCall(allCombinedSolModifiers,parameters,this._isCopyPicked,{pickObjectClass:objectType,pickInstances:arr})}}*DebugRunAsFamilyCustomActionWithOverrides(combinedSolModifiers,parameters){const objectTypeMap=new Map;const familyInstances=[];for(const inst of this._objectClass.GetCurrentSol().GetInstances()){const objectType=inst.GetObjectClass();if(objectType.HasOwnCustomActionByName(this._aceName)){const arr=
+objectTypeMap.get(objectType);if(Array.isArray(arr))arr.push(inst);else objectTypeMap.set(objectType,[inst])}else familyInstances.push(inst)}if(familyInstances.length>0)yield*this._eventBlock.DebugRunAsFunctionCall(combinedSolModifiers,parameters,this._isCopyPicked,{pickObjectClass:this._objectClass,pickInstances:familyInstances});if(objectTypeMap.size>0)for(const [objectType,arr]of objectTypeMap){const eventBlock=objectType.GetOwnCustomActionByName(this._aceName).GetEventBlock();const allCombinedSolModifiers=
+[...(new Set([...combinedSolModifiers,...eventBlock.GetSolModifiers()]))];yield*eventBlock.DebugRunAsFunctionCall(allCombinedSolModifiers,parameters,this._isCopyPicked,{pickObjectClass:objectType,pickInstances:arr})}}};
+
+}
+
+// events/eventVariable.js
+{
+'use strict';const C3=self.C3;const EMPTY_SOL_MODIFIERS=[];
+C3.EventVariable=class EventVariable extends C3.DefendedBase{constructor(eventSheet,parent,data){super();const eventSheetManager=eventSheet.GetEventSheetManager();this._eventSheet=eventSheet;this._eventSheetManager=eventSheetManager;this._runtime=eventSheet.GetRuntime();this._parent=parent;this._localVarStack=eventSheetManager.GetLocalVarStack();this._name=data[1];this._type=data[2];this._initialValue=data[3];this._isStatic=!!data[4];this._isConstant=!!data[5];this._isFunctionParameter=parent instanceof
+C3.FunctionBlock;this._sid=data[6];this._jsPropName=this._runtime.GetJsPropName(data[8]);this._scriptSetter=v=>this.SetValue(v);this._scriptGetter=()=>this.GetValue();this._hasSingleValue=!this._parent||this._isStatic||this._isConstant;this._value=this._initialValue;this._localIndex=-1;if(this.IsBoolean())this._value=this._value?1:0;if(this.IsLocal()&&!this.IsStatic()&&!this.IsConstant())this._localIndex=eventSheetManager._GetNextLocalVarIndex(this);eventSheetManager._RegisterEventVariable(this)}static Create(eventSheet,
+parent,data){return C3.New(C3.EventVariable,eventSheet,parent,data)}_PostInit(){if(this.IsLocal()&&!this.IsStatic()&&!this.IsConstant()&&!this.IsFunctionParameter()){const functionBlock=this._eventSheetManager.FindFirstFunctionBlockParent(this);if(functionBlock)functionBlock._RegisterLocalVariable(this)}}GetName(){return this._name}GetJsPropName(){return this._jsPropName}GetParent(){return this._parent}GetScopeParent(){return this.GetParent()}IsGlobal(){return!this.GetParent()}IsLocal(){return!this.IsGlobal()}IsFunctionParameter(){return this._isFunctionParameter}IsStatic(){return this._isStatic}IsConstant(){return this._isConstant}IsNumber(){return this._type===
+0}IsString(){return this._type===1}IsBoolean(){return this._type===2}IsElseBlock(){return false}GetSID(){return this._sid}GetInitialValue(){return this._initialValue}GetSolModifiers(){return EMPTY_SOL_MODIFIERS}Run(frame){if(this.IsLocal()&&!this.IsStatic()&&!this.IsConstant())this.SetValue(this.GetInitialValue())}DebugCanRunFast(){return true}*DebugRun(frame){this.Run(frame)}SetValue(v){if(this.IsNumber()){if(typeof v!=="number")v=parseFloat(v)}else if(this.IsString()){if(typeof v!=="string")v=v.toString()}else if(this.IsBoolean())v=
+v?1:0;if(this._hasSingleValue)this._value=v;else this._localVarStack.GetCurrent()[this._localIndex]=v}GetValue(){return this._hasSingleValue?this._value:this._localVarStack.GetCurrent()[this._localIndex]}GetTypedValue(){let ret=this.GetValue();if(this.IsBoolean())ret=!!ret;return ret}ResetToInitialValue(){this._value=this._initialValue}_GetScriptInterfaceDescriptor(){return{configurable:false,enumerable:true,get:this._scriptGetter,set:this._scriptSetter}}};
+
+}
+
+// events/eventInclude.js
+{
+'use strict';const C3=self.C3;const assert=self.assert;const EMPTY_SOL_MODIFIERS=[];
+C3.EventInclude=class EventInclude extends C3.DefendedBase{constructor(eventSheet,parent,data){super();const eventSheetManager=eventSheet.GetEventSheetManager();this._eventSheet=eventSheet;this._eventSheetManager=eventSheetManager;this._runtime=eventSheet.GetRuntime();this._parent=parent;this._includeSheet=null;this._includeSheetName=data[1];this._isActive=true}static Create(eventSheet,parent,data){return C3.New(C3.EventInclude,eventSheet,parent,data)}_PostInit(){this._includeSheet=this._eventSheetManager.GetEventSheetByName(this._includeSheetName);
+this._eventSheet._AddShallowInclude(this);let p=this.GetParent();while(p){if(p instanceof C3.EventBlock&&p.IsGroup())p._AddContainedInclude(this);p=p.GetParent()}this.UpdateActive();if(this._runtime.IsDebug())this._eventSheet._GetPerfRecord().children.push(this._includeSheet._GetPerfRecord())}GetParent(){return this._parent}GetSolModifiers(){return EMPTY_SOL_MODIFIERS}GetIncludeSheet(){return this._includeSheet}Run(frame){const pushSol=!!this.GetParent();const allObjectClasses=this._runtime.GetAllObjectClasses();
+if(pushSol)this._eventSheetManager.PushCleanSol(allObjectClasses);this._includeSheet.Run();if(pushSol)this._eventSheetManager.PopSol(allObjectClasses)}*DebugRun(frame){const pushSol=!!this.GetParent();const allObjectClasses=this._runtime.GetAllObjectClasses();if(pushSol)this._eventSheetManager.PushCleanSol(allObjectClasses);yield*this._includeSheet.DebugRun();if(pushSol)this._eventSheetManager.PopSol(allObjectClasses)}DebugCanRunFast(){return false}IsActive(){return this._isActive}UpdateActive(){let p=
+this.GetParent();while(p){if(p instanceof C3.EventBlock&&p.IsGroup()&&!p.IsGroupActive()){this._isActive=false;return}p=p.GetParent()}this._isActive=true}};
+
+}
+
+// events/expNode.js
+{
+'use strict';const C3=self.C3;const assert=self.assert;C3.ExpNode=class ExpNode extends C3.DefendedBase{constructor(owner){super();this._owner=owner;this._runtime=owner.GetRuntime()}_PostInit(){}static CreateNode(owner,data){const type=data[0];const Classes=[BehaviorExpressionNode,ObjectExpressionNode,InstVarExpressionNode,EventVarExpNode,SystemExpressionExpNode,CallFunctionExpressionExpNode];return C3.New(Classes[type],owner,data)}};
+class SystemExpressionExpNode extends C3.ExpNode{constructor(owner,data){super(owner);this._systemPlugin=this._runtime.GetSystemPlugin();this._func=this._runtime.GetObjectReference(data[1]);if(this._func===C3.Plugins.System.Exps.random||this._func===C3.Plugins.System.Exps.choose)this._owner.SetVariesPerInstance()}GetBoundMethod(){return this._systemPlugin._GetBoundACEMethod(this._func,this._systemPlugin)}}
+class CallFunctionExpressionExpNode extends C3.ExpNode{constructor(owner,data){super(owner);this._functionBlock=null;this._functionName=data[1];this._owner.SetVariesPerInstance()}_PostInit(){const eventSheetManager=this._runtime.GetEventSheetManager();this._functionBlock=eventSheetManager.GetFunctionBlockByName(this._functionName);this._functionName=null;const myEventBlock=this._owner.GetEventBlock();const callEventBlock=this._functionBlock.GetEventBlock();this._combinedSolModifiers=[...(new Set([...myEventBlock.GetSolModifiersIncludingParents(),
+...callEventBlock.GetSolModifiersIncludingParents()]))];this._combinedSolModifiers=eventSheetManager._DeduplicateSolModifierList(this._combinedSolModifiers)}GetBoundMethod(){const functionBlock=this._functionBlock;if(functionBlock.IsEnabled()){const callEventBlock=functionBlock.GetEventBlock();return C3.EventBlock.prototype.RunAsExpressionFunctionCall.bind(callEventBlock,this._combinedSolModifiers,functionBlock.IsCopyPicked(),functionBlock.GetReturnType(),functionBlock.GetDefaultReturnValue())}else{const defaultReturnValue=
+functionBlock.GetDefaultReturnValue();return()=>defaultReturnValue}}}function WrapIndex(index,len){if(index>=len)return index%len;else if(index<0){if(index<=-len)index%=len;if(index<0)index+=len;return index}else return index}
+class ObjectExpressionNode extends C3.ExpNode{constructor(owner,data){super(owner);this._objectClass=this._runtime.GetObjectClassByIndex(data[1]);this._func=this._runtime.GetObjectReference(data[2]);this._returnsString=!!data[3];this._eventStack=this._runtime.GetEventSheetManager().GetEventStack();this._owner._MaybeVaryFor(this._objectClass)}GetBoundMethod(){return this._objectClass.GetPlugin()._GetBoundACEMethod(this._func,this._objectClass.GetSingleGlobalInstance().GetSdkInstance())}ExpObject(...args){const objectClass=
+this._objectClass;const instances=objectClass.GetCurrentSol().GetExpressionInstances();const len=instances.length;if(len===0)return this._returnsString?"":0;const index=WrapIndex(this._owner.GetSolIndex(),len);this._eventStack.GetCurrentStackFrame().SetExpressionObjectClass(objectClass);return this._func.apply(instances[index].GetSdkInstance(),args)}ExpObject_InstExpr(instIndex,...args){const objectClass=this._objectClass;const instances=objectClass.GetInstances();const len=instances.length;if(len===
+0)return this._returnsString?"":0;const index=WrapIndex(instIndex,len);this._eventStack.GetCurrentStackFrame().SetExpressionObjectClass(objectClass);return this._func.apply(instances[index].GetSdkInstance(),args)}}
+class InstVarExpressionNode extends C3.ExpNode{constructor(owner,data){super(owner);this._objectClass=this._runtime.GetObjectClassByIndex(data[1]);this._varIndex=data[3];this._returnsString=!!data[2];this._owner._MaybeVaryFor(this._objectClass)}ExpInstVar(){const instances=this._objectClass.GetCurrentSol().GetExpressionInstances();const len=instances.length;if(len===0)return this._returnsString?"":0;const index=WrapIndex(this._owner.GetSolIndex(),len);return instances[index]._GetInstanceVariableValueUnchecked(this._varIndex)}ExpInstVar_Family(){const objectClass=
+this._objectClass;const instances=objectClass.GetCurrentSol().GetExpressionInstances();const len=instances.length;if(len===0)return this._returnsString?"":0;const index=WrapIndex(this._owner.GetSolIndex(),len);const inst=instances[index];const offset=inst.GetObjectClass().GetFamilyInstanceVariableOffset(objectClass.GetFamilyIndex());return inst._GetInstanceVariableValueUnchecked(this._varIndex+offset)}ExpInstVar_InstExpr(instIndex){const objectClass=this._objectClass;const instances=objectClass.GetInstances();
+const len=instances.length;if(len===0)return this._returnsString?"":0;const index=WrapIndex(instIndex,len);const inst=instances[index];let offset=0;if(objectClass.IsFamily())offset=inst.GetObjectClass().GetFamilyInstanceVariableOffset(objectClass.GetFamilyIndex());return inst._GetInstanceVariableValueUnchecked(this._varIndex+offset)}}
+class BehaviorExpressionNode extends C3.ExpNode{constructor(owner,data){super(owner);this._objectClass=this._runtime.GetObjectClassByIndex(data[1]);this._behaviorType=this._objectClass.GetBehaviorTypeByName(data[2]);this._behaviorIndex=this._objectClass.GetBehaviorIndexByName(data[2]);this._func=this._runtime.GetObjectReference(data[3]);this._returnsString=!!data[4];this._eventStack=this._runtime.GetEventSheetManager().GetEventStack();this._owner._MaybeVaryFor(this._objectClass)}ExpBehavior(...args){const objectClass=
+this._objectClass;const instances=objectClass.GetCurrentSol().GetExpressionInstances();const len=instances.length;if(len===0)return this._returnsString?"":0;const index=WrapIndex(this._owner.GetSolIndex(),len);this._eventStack.GetCurrentStackFrame().SetExpressionObjectClass(objectClass);const inst=instances[index];let offset=0;if(objectClass.IsFamily())offset=inst.GetObjectClass().GetFamilyBehaviorOffset(objectClass.GetFamilyIndex());return this._func.apply(inst.GetBehaviorInstances()[this._behaviorIndex+
+offset].GetSdkInstance(),args)}ExpBehavior_InstExpr(instIndex,...args){const objectClass=this._objectClass;const instances=objectClass.GetInstances();const len=instances.length;if(len===0)return this._returnsString?"":0;const index=WrapIndex(instIndex,len);this._eventStack.GetCurrentStackFrame().SetExpressionObjectClass(objectClass);const inst=instances[index];let offset=0;if(objectClass.IsFamily())offset=inst.GetObjectClass().GetFamilyBehaviorOffset(objectClass.GetFamilyIndex());return this._func.apply(inst.GetBehaviorInstances()[this._behaviorIndex+
+offset].GetSdkInstance(),args)}}class EventVarExpNode extends C3.ExpNode{constructor(owner,data){super(owner);this._eventVar=null;this._eventVarSid=data[1]}_PostInit(){this._eventVar=this._runtime.GetEventSheetManager().GetEventVariableBySID(this._eventVarSid)}GetVar(){return this._eventVar}};
+
+}
+
+// events/parameter.js
+{
+'use strict';const C3=self.C3;const assert=self.assert;
+C3.Parameter=class Parameter extends C3.DefendedBase{constructor(owner,type,index){super();this._owner=owner;this._index=index;this._type=type;this.Get=null;this._variesPerInstance=false;this._isConstant=false}static Create(owner,data,index){const type=data[0];const Classes=[ExpressionParameter,StringExpressionParameter,FileParameter,ComboParameter,ObjectParameter,LayerExpressionParameter,LayoutParameter,ExpressionParameter,ComboParameter,ComboParameter,InstVarParameter,EventVarParameter,FileParameter,
+VariadicParameter,StringExpressionParameter,TimelineParameter,BooleanParameter,FunctionParameter,EaseParameter,TilemapBrushParameter,TemplateExpressionParameter,FlowchartParameter];return C3.New(Classes[type],owner,type,index,data)}_PostInit(){}SetVariesPerInstance(){this._variesPerInstance=true}_MaybeVaryFor(objectClass){if(this._variesPerInstance)return;if(!objectClass)return;if(!objectClass.GetPlugin().IsSingleGlobal())this._variesPerInstance=true}VariesPerInstance(){return this._variesPerInstance}GetIndex(){return this._index}GetRuntime(){return this._owner.GetRuntime()}GetEventBlock(){return this._owner.GetEventBlock()}IsConstant(){return this._isConstant}IsObjectParameter(){return this._type===
+4}};function GetExpressionFunc(number){const ret=self.C3_ExpressionFuncs[number];if(!ret)throw new Error("invalid expression number");return ret}
+class ExpressionParameter extends C3.Parameter{constructor(owner,type,index,data){super(owner,type,index);this._solIndex=0;const expData=data[1];this._expressionNumber=expData[0];this._numberedNodes=[];this._expressionFunc=null;for(let i=1,len=expData.length;i=this._numberedNodes.length)throw new RangeError("invalid numbered node");
+return this._numberedNodes[i]}_PostInit(){for(const node of this._numberedNodes)node._PostInit();const func=GetExpressionFunc(this._expressionNumber);if(this._numberedNodes.length)this._expressionFunc=func(this);else this._expressionFunc=func}GetSolIndex(){return this._solIndex}GetExpression(solIndex){this._solIndex=solIndex;return this._expressionFunc()}}
+class StringExpressionParameter extends ExpressionParameter{constructor(owner,type,index,data){super(owner,type,index,data);this.Get=this.GetStringExpression;if(type===14){this.GetEventBlock().SetAllSolModifiers();if(this._owner instanceof C3.Action)this.GetEventBlock().SetSolWriterAfterCnds()}}GetStringExpression(solIndex){this._solIndex=solIndex;const ret=this._expressionFunc();if(typeof ret==="string")return ret;else return""}_GetFastTriggerValue(){return GetExpressionFunc(this._expressionNumber)()}}
+class LayerExpressionParameter extends ExpressionParameter{constructor(owner,type,index,data){super(owner,type,index,data);this.Get=this.GetLayer;this._isConstant=false}GetLayer(solIndex){this._solIndex=solIndex;const ret=this._expressionFunc();const layout=this.GetRuntime().GetCurrentLayout();return layout.GetLayer(ret)}}
+class ComboParameter extends C3.Parameter{constructor(owner,type,index,data){super(owner,type,index);this._combo=data[1];this.Get=this.GetCombo;this._isConstant=true}GetCombo(){return this._combo}}class BooleanParameter extends C3.Parameter{constructor(owner,type,index,data){super(owner,type,index);this._bool=data[1];this.Get=this.GetBoolean;this._isConstant=true}GetBoolean(){return this._bool}}
+class ObjectParameter extends C3.Parameter{constructor(owner,type,index,data){super(owner,type,index);this._objectClass=this.GetRuntime().GetObjectClassByIndex(data[1]);this.Get=this.GetObjectClass;const eventBlock=this.GetEventBlock();eventBlock._AddSolModifier(this._objectClass);if(this._owner instanceof C3.Action)eventBlock.SetSolWriterAfterCnds();else if(eventBlock.GetParent())eventBlock.GetParent().SetSolWriterAfterCnds();this._isConstant=true}GetObjectClass(){return this._objectClass}}
+class LayoutParameter extends C3.Parameter{constructor(owner,type,index,data){super(owner,type,index);this._layout=this.GetRuntime().GetLayoutManager().GetLayoutByName(data[1]);this.Get=this.GetLayout;this._isConstant=true}GetLayout(){return this._layout}}
+class TimelineParameter extends C3.Parameter{constructor(owner,type,index,data){super(owner,type,index);this._timeline=this.GetRuntime().GetTimelineManager().GetTimelineByName(data[1]);this.Get=this.GetTimeline;this._isConstant=true}GetTimeline(){return this._timeline}}class FileParameter extends C3.Parameter{constructor(owner,type,index,data){super(owner,type,index);this._fileInfo=data[1];this.Get=this.GetFile;this._isConstant=true}GetFile(){return this._fileInfo}}
+class InstVarParameter extends C3.Parameter{constructor(owner,type,index,data){super(owner,type,index);this._instVarIndex=data[1];const ownerObjectClass=this._owner.GetObjectClass();if(this._owner instanceof C3.Condition&&this._owner.IsStatic()){this.Get=this.GetInstanceVariable;this._isConstant=true}else if(ownerObjectClass&&ownerObjectClass.IsFamily()){this.Get=this.GetFamilyInstanceVariable;this.SetVariesPerInstance()}else{this.Get=this.GetInstanceVariable;this._isConstant=true}}GetInstanceVariable(){return this._instVarIndex}GetFamilyInstanceVariable(solIndex){solIndex=
+solIndex||0;const familyType=this._owner.GetObjectClass();const sol=familyType.GetCurrentSol();const instances=sol.GetInstances();let realType=null;if(instances.length)realType=instances[solIndex%instances.length].GetObjectClass();else if(sol.HasAnyElseInstances()){const elseInstances=sol.GetElseInstances();realType=elseInstances[solIndex%elseInstances.length].GetObjectClass()}else if(familyType.GetInstanceCount()>0){const familyInstances=familyType.GetInstances();realType=familyInstances[solIndex%
+familyInstances.length].GetObjectClass()}else return 0;return this._instVarIndex+realType.GetFamilyInstanceVariableOffset(familyType.GetFamilyIndex())}}
+class EventVarParameter extends C3.Parameter{constructor(owner,type,index,data){super(owner,type,index);this._eventVarSid=data[1];this._eventVar=null;this.Get=this.GetEventVariable;this._isConstant=true}_PostInit(){this._eventVar=this.GetRuntime().GetEventSheetManager().GetEventVariableBySID(this._eventVarSid)}GetEventVariable(){return this._eventVar}}
+class FunctionParameter extends C3.Parameter{constructor(owner,type,index,data){super(owner,type,index);this._functionBlockName=data[1];this._functionBlock=null;this.Get=this.GetFunction;this._isConstant=true}_PostInit(){this._functionBlock=this.GetRuntime().GetEventSheetManager().GetFunctionBlockByName(this._functionBlockName);this._functionBlockName=null}GetFunction(){return this._functionBlock}}
+class VariadicParameter extends C3.Parameter{constructor(owner,type,index,data){super(owner,type,index);this._subParams=[];this._variadicRet=[];this._isConstant=true;for(let i=1,len=data.length;i0;this._isFastTrigger=data[3]===2;this._isLooping=!!data[4];this._isInverted=!!data[5];this._isStatic=!!data[6];this._sid=data[7];this._isInOrBlock=this._eventBlock.IsOrBlock();this._objectClass=null;this._behaviorType=null;this._behaviorIndex=
+-1;this._systemPlugin=null;this.Run=noop;this.DebugRun=noop;this._parameters=[];this._results=[];this._anyParamVariesPerInstance=false;this._savedData=null;this._unsavedData=null;this._debugData=this._runtime.IsDebug()?{isBreakpoint:data[8][0],canDebug:data[8][1]}:null;if(data[0]===-1)this._systemPlugin=this._runtime.GetSystemPlugin();else{this._objectClass=this._runtime.GetObjectClassByIndex(data[0]);if(data[2]){this._behaviorType=this._objectClass.GetBehaviorTypeByName(data[2]);this._behaviorIndex=
+this._objectClass.GetBehaviorIndexByName(data[2])}if(this._eventBlock.GetParent())this._eventBlock.GetParent().SetSolWriterAfterCnds()}if(data.length===10){let paramData=data[9];for(let data of paramData){this._parameters.push(C3.Parameter.Create(this,data,this._parameters.length));this._results.push(0)}}if(this._parameters.length===0){this._parameters=EMPTY_PARAMS_ARRAY;this._results=EMPTY_PARAMS_ARRAY}this._eventBlock.GetEventSheetManager()._RegisterCondition(this)}static Create(eventBlock,data,
+index){return C3.New(C3.Condition,eventBlock,data,index)}_PostInit(){for(const param of this._parameters){param._PostInit();if(param.VariesPerInstance())this._anyParamVariesPerInstance=true}if(this._isFastTrigger){this.Run=this._RunFastTrigger;this.DebugRun=this._DebugRunFastTrigger}else if(this._systemPlugin){this._SetSystemRunMethod();this.DebugRun=this._DebugRunSystem}else if(this._objectClass.GetPlugin().IsSingleGlobal()){this._SetSingleGlobalRunMethod();this.DebugRun=this._DebugRunSingleGlobal}else if(this._isStatic){this.Run=
+this._RunStatic;this.DebugRun=this._DebugRunStatic}else{this.Run=this._RunObject;this.DebugRun=this._DebugRunObject}}_SetSystemRunMethod(){const plugin=this._systemPlugin;const bindThis=this._systemPlugin;this._SetRunMethodForBoundFunc(plugin,bindThis,this._RunSystem)}_SetSingleGlobalRunMethod(){const plugin=this._objectClass.GetPlugin();const bindThis=this._objectClass.GetSingleGlobalInstance().GetSdkInstance();this._SetRunMethodForBoundFunc(plugin,bindThis,this._RunSingleGlobal)}_SetRunMethodForBoundFunc(plugin,
+bindThis,fallbackMethod){const func=this._func;const isInverted=this._isInverted;const parameters=this._parameters;if(parameters.length===0){const boundFunc=plugin._GetBoundACEMethod(func,bindThis);if(isInverted)this.Run=function RunSingleCnd_0param(){return C3.xor(boundFunc(),isInverted)};else this.Run=boundFunc}else if(parameters.length===1){const param0=parameters[0];if(!isInverted&¶m0.IsConstant())this.Run=plugin._GetBoundACEMethod_1param(func,bindThis,param0.Get(0));else{const boundFunc=
+plugin._GetBoundACEMethod(func,bindThis);this.Run=function RunSingleCnd_1param(){return C3.xor(boundFunc(param0.Get(0)),isInverted)}}}else if(parameters.length===2){const param0=parameters[0];const param1=parameters[1];if(!isInverted&¶m0.IsConstant()&¶m1.IsConstant())this.Run=plugin._GetBoundACEMethod_2params(func,bindThis,param0.Get(0),param1.Get(0));else{const boundFunc=plugin._GetBoundACEMethod(func,bindThis);this.Run=function RunSingleCnd_2params(){return C3.xor(boundFunc(param0.Get(0),
+param1.Get(0)),isInverted)}}}else if(parameters.length===3){const param0=parameters[0];const param1=parameters[1];const param2=parameters[2];if(!isInverted&¶m0.IsConstant()&¶m1.IsConstant()&¶m2.IsConstant())this.Run=plugin._GetBoundACEMethod_3params(func,bindThis,param0.Get(0),param1.Get(0),param2.Get(0));else{const boundFunc=plugin._GetBoundACEMethod(func,bindThis);this.Run=function RunSingleCnd_3params(){return C3.xor(boundFunc(param0.Get(0),param1.Get(0),param2.Get(0)),isInverted)}}}else this.Run=
+fallbackMethod}GetSID(){return this._sid}_GetFunc(){return this._func}GetObjectClass(){return this._objectClass}GetBehaviorType(){return this._behaviorType}GetEventBlock(){return this._eventBlock}GetRuntime(){return this._runtime}GetIndex(){return this._index}GetDebugIndex(){return this.GetIndex()}IsTrigger(){return this._isTrigger}IsFastTrigger(){return this._isFastTrigger}IsInverted(){return this._isInverted}IsLooping(){return this._isLooping}IsStatic(){return this._isStatic}IsBreakpoint(){return this._debugData.isBreakpoint}IsSystemCondition(){return!!this._systemPlugin}GetFirstObjectParameterObjectClass(){for(const p of this._parameters)if(p.IsObjectParameter())return p.GetObjectClass();
+return null}_SetBreakpoint(b){this._debugData.isBreakpoint=!!b;this._eventBlock._UpdateCanRunFastRecursive()}_DebugReturnsGenerator(){return this._debugData.canDebug}DebugCanRunFast(){return!this.IsBreakpoint()&&!this._runtime.DebugBreakNext()&&!this._DebugReturnsGenerator()}GetSavedDataMap(){if(!this._savedData)this._savedData=new Map;return this._savedData}GetUnsavedDataMap(){if(!this._unsavedData)this._unsavedData=new Map;return this._unsavedData}_RunSystem(){const results=this._results;EvalParams(this._parameters,
+results);return C3.xor(this._func.apply(this._systemPlugin,results),this._isInverted)}*_DebugRunSystem(){if(this.IsBreakpoint()||this._runtime.DebugBreakNext())yield this;if(this._DebugReturnsGenerator()){const results=this._results;EvalParams(this._parameters,results);let ret=this._func.apply(this._systemPlugin,results);if(C3.IsIterator(ret))ret=yield*ret;return C3.xor(ret,this._isInverted)}else return this.Run()}_RunSingleGlobal(){const results=this._results;EvalParams(this._parameters,results);
+const inst=this._objectClass.GetSingleGlobalInstance().GetSdkInstance();return C3.xor(this._func.apply(inst,results),this._isInverted)}*_DebugRunSingleGlobal(){if(this.IsBreakpoint()||this._runtime.DebugBreakNext())yield this;if(this._DebugReturnsGenerator()){const results=this._results;EvalParams(this._parameters,results);const inst=this._objectClass.GetSingleGlobalInstance().GetSdkInstance();let ret=this._func.apply(inst,results);if(C3.IsIterator(ret))ret=yield*ret;return C3.xor(ret,this._isInverted)}else return this.Run()}_RunFastTrigger(){return true}*_DebugRunFastTrigger(){if(this.IsBreakpoint()||
+this._runtime.DebugBreakNext())yield this;return true}_RunStatic(){const results=this._results;EvalParams(this._parameters,results);const ret=this._func.apply(this._behaviorType||this._objectClass,results);this._objectClass.ApplySolToContainer();return ret}*_DebugRunStatic(){if(this.IsBreakpoint()||this._runtime.DebugBreakNext())yield this;if(this._DebugReturnsGenerator()){const results=this._results;EvalParams(this._parameters,results);let ret=this._func.apply(this._behaviorType||this._objectClass,
+results);if(C3.IsIterator(ret))ret=yield*ret;this._objectClass.ApplySolToContainer();return ret}else return this.Run()}_RunObject(){const parameters=this._parameters;const results=this._results;const sol=this._objectClass.GetCurrentSol();for(let i=0,len=parameters.length;i=0;const allInstances=objectClass.GetInstances();
+const paramsVary=this._anyParamVariesPerInstance;const results=this._results;const func=this._func;const isInverted=this._isInverted;const isInOrBlock=this._isInOrBlock&&!this._isTrigger;sol.ClearArrays();for(let i=0,len=allInstances.length;i=0;const paramsVary=this._anyParamVariesPerInstance;const results=this._results;const func=this._func;const isInverted=this._isInverted;const isInOrBlock=this._isInOrBlock&&!this._isTrigger;const solInstances=sol._GetOwnInstances();const solElseInstances=sol._GetOwnElseInstances();const isUsingElseInstances=isInOrBlock&&!this._eventBlock.IsFirstConditionOfType(this);const arr=isUsingElseInstances?solElseInstances:solInstances;let k=0;let isAnyTrue=false;for(let i=0,
+len=arr.length;i=0;const results=this._results;const func=this._func;const isInverted=this._isInverted;for(let i=0,len=solInstances.length;i[arr[0].GetUID(),arr[1].GetUID(),arr[2]]);ex[k]=saveVal}return{"ex":ex}}_LoadFromJson(o){if(this._savedData){this._savedData.clear();this._savedData=null}if(!o)return;const runtime=this._runtime;const ex=o["ex"];if(ex){const map=this.GetSavedDataMap();map.clear();
+for(const [k,v]of Object.entries(ex)){let loadVal=v;if(k==="collmemory")loadVal=C3.New(C3.PairMap,v.map(arr=>[runtime.GetInstanceByUID(arr[0]),runtime.GetInstanceByUID(arr[1]),arr[2]]).filter(arr=>arr[0]&&arr[1]));map.set(k,loadVal)}}}};
+
+}
+
+// events/action.js
+{
+'use strict';const C3=self.C3;const assert=self.assert;function EvalParams(parameters,results){for(let i=0,len=parameters.length;i=4?data[3]:-1;this._actionType=data.length>=5?data[4]&255:0;this._flags=data.length>=5?data[4]>>8:0;this._func=null;this._objectClass=null;this._behaviorType=null;this._behaviorIndex=-1;this._systemPlugin=null;this._callFunctionName="";this._callCustomAceObjectClass=null;this._callEventBlock=
+null;this.Run=noop;this.DebugRun=noop;this._parameters=[];this._results=[];this._anyParamVariesPerInstance=false;this._savedData=null;this._unsavedData=null;const isScript=data[0]===-3;const debugInfo=isScript?data[2]:data[5];this._debugData=runtime.IsDebug()||isScript?{isBreakpoint:debugInfo[0],canDebug:debugInfo[1],index:debugInfo[2]}:null;if(data[0]===-1){this._systemPlugin=runtime.GetSystemPlugin();this._func=runtime.GetObjectReference(data[1])}else if(data[0]===-2)this._callFunctionName=data[1];
+else if(isScript){const userMethod=runtime.GetObjectReference(data[1]);this._func=userMethod;this.Run=this.RunUserScript;this.DebugRun=this.DebugRunUserScript;this._actionType=1}else{this._objectClass=runtime.GetObjectClassByIndex(data[0]);if(this._flags&FLAG_CUSTOM_ACE){this._callFunctionName=data[1];this._callCustomAceObjectClass=runtime.GetObjectClassByIndex(data[2])}else{if(data[2]){this._behaviorType=this._objectClass.GetBehaviorTypeByName(data[2]);this._behaviorIndex=this._objectClass.GetBehaviorIndexByName(data[2])}this._func=
+runtime.GetObjectReference(data[1])}}if(data.length===7){const paramData=data[6];for(const data of paramData){this._parameters.push(C3.Parameter.Create(this,data,this._parameters.length));this._results.push(0)}}if(this._parameters.length===0){this._parameters=EMPTY_PARAMS_ARRAY;this._results=EMPTY_PARAMS_ARRAY}if(this.CanPickAnyObjectClass()){this._eventBlock.SetAllSolModifiers();this._eventBlock.SetSolWriterAfterCnds()}this._eventBlock.GetEventSheetManager()._RegisterAction(this)}static Create(eventBlock,
+data,index){return C3.New(C3.Action,eventBlock,data,index)}_PostInit(){for(const param of this._parameters){param._PostInit();if(param.VariesPerInstance())this._anyParamVariesPerInstance=true}if(this._systemPlugin){this._SetSystemRunMethod();this.DebugRun=this._DebugRunSystem}else if(this._callFunctionName){if(this._flags&FLAG_CUSTOM_ACE)this._SetCallCustomActionRunMethod();else this._SetCallFunctionRunMethod();this._callFunctionName="";this._callCustomAceObjectClass=null}else if(this.Run===this.RunUserScript){const userMethod=
+this._func;const localVars=this._runtime.GetEventSheetManager()._GetLocalVariablesScriptInterface(this._eventBlock);this._func=userMethod.bind(null,this._runtime.GetIRuntime(),localVars)}else if(this._behaviorType)if(this.IsAsync()){this.Run=this._RunBehavior_Async;this.DebugRun=this._DebugRunBehavior_Async}else{this.Run=this._RunBehavior;this.DebugRun=this._DebugRunBehavior}else if(this._objectClass.GetPlugin().IsSingleGlobal()){this._SetSingleGlobalRunMethod();this.DebugRun=this._DebugRunSingleGlobal}else if(this.IsAsync()){this.Run=
+this._RunObject_Async;this.DebugRun=this._DebugRunObject_Async}else if(this.CallBeforeAfterHooks()){this.Run=this._RunObject_BeforeAfterHooks;this.DebugRun=this._DebugRunObject_BeforeAfterHooks}else if(!this._parameters.length){this.Run=this._RunObject_ParamsConst;this.DebugRun=this._DebugRunObject_ParamsConst}else if(this._parameters.every(p=>p.VariesPerInstance())){this.Run=this._RunObject_AllParamsVary;this.DebugRun=this._DebugRunObject_AllParamsVary}else if(this._anyParamVariesPerInstance){this.Run=
+this._RunObject_SomeParamsVary;this.DebugRun=this._DebugRunObject_SomeParamsVary}else if(this._parameters.every(p=>p.IsConstant())){EvalParams(this._parameters,this._results);this.Run=this._RunObject_ParamsConst;this.DebugRun=this._DebugRunObject_ParamsConst}else{this.Run=this._RunObject_ParamsDontVary;this.DebugRun=this._DebugRunObject_ParamsDontVary}}_SetSystemRunMethod(){const plugin=this._systemPlugin;const bindThis=this._systemPlugin;this._SetRunMethodForBoundFunc(plugin,bindThis,this._RunSystem)}_SetSingleGlobalRunMethod(){const plugin=
+this._objectClass.GetPlugin();const bindThis=this._objectClass.GetSingleGlobalInstance().GetSdkInstance();this._SetRunMethodForBoundFunc(plugin,bindThis,this._RunSingleGlobal)}_SetCallFunctionRunMethod(){const eventSheetManager=this._eventBlock.GetEventSheetManager();const functionBlock=eventSheetManager.GetFunctionBlockByName(this._callFunctionName);if(functionBlock.IsEnabled()){const isCopyPicked=(this._flags&FLAG_COPYPICKED)!==0;this._callEventBlock=functionBlock.GetEventBlock();let combinedSolModifiers=
+[...(new Set([...this._eventBlock.GetSolModifiersIncludingParents(),...this._callEventBlock.GetSolModifiersIncludingParents()]))];combinedSolModifiers=eventSheetManager._DeduplicateSolModifierList(combinedSolModifiers);const pickInfo=!functionBlock.IsCopyPicked()&&this._HasCopyPickedParent()?{pushCleanSolDynamic:true}:null;this.Run=C3.EventBlock.prototype.RunAsFunctionCall.bind(this._callEventBlock,combinedSolModifiers,this._parameters,isCopyPicked,pickInfo);if(this._runtime.IsDebug()){const thiz=
+this;this.DebugRun=function*DebugRunCallFunction(){if(thiz.IsBreakpoint()||thiz._runtime.DebugBreakNext())yield thiz;const ret=yield*thiz._callEventBlock.DebugRunAsFunctionCall(combinedSolModifiers,thiz._parameters,isCopyPicked,pickInfo);return ret}}else this.DebugRun=noopGenerator}else{this.Run=noop;this.DebugRun=noopGenerator}}_SetCallCustomActionRunMethod(){const eventSheetManager=this._eventBlock.GetEventSheetManager();const customAceBlock=eventSheetManager.GetCustomActionBlockByName(this._callCustomAceObjectClass,
+this._callFunctionName);if(customAceBlock.IsEnabled()){const isCopyPicked=(this._flags&FLAG_COPYPICKED)!==0;this._callEventBlock=customAceBlock.GetEventBlock();let combinedSolModifiers=[...(new Set([...this._eventBlock.GetSolModifiersIncludingParents(),...this._callEventBlock.GetSolModifiersIncludingParents(),this._objectClass,customAceBlock.GetObjectClass()]))];combinedSolModifiers=eventSheetManager._DeduplicateSolModifierList(combinedSolModifiers);const isOTtoOT=!this._objectClass.IsFamily()&&!customAceBlock.GetObjectClass().IsFamily();
+const isOTtoFamily=!this._objectClass.IsFamily()&&customAceBlock.GetObjectClass().IsFamily();const isFamilyToFamily=this._objectClass.IsFamily();let pickInfo=null;if(!customAceBlock.IsCopyPicked()&&this._HasCopyPickedParent()){pickInfo=pickInfo||{};pickInfo.pushCleanSolDynamic=true}if(isOTtoFamily||!isCopyPicked){pickInfo=pickInfo||{};pickInfo.copyFromObjectClass=this._objectClass;pickInfo.copyToObjectClass=customAceBlock.GetObjectClass()}if(isOTtoOT||isOTtoFamily||isFamilyToFamily&&!customAceBlock.HasCustomACEOverrides())this.Run=
+C3.EventBlock.prototype.RunAsFunctionCall.bind(this._callEventBlock,combinedSolModifiers,this._parameters,isCopyPicked,pickInfo);else if(isFamilyToFamily)this.Run=C3.FunctionBlock.prototype.RunAsFamilyCustomActionWithOverrides.bind(customAceBlock,combinedSolModifiers,this._parameters);else;if(this._runtime.IsDebug()){const thiz=this;if(isOTtoOT||isOTtoFamily||isFamilyToFamily&&!customAceBlock.HasCustomACEOverrides())this.DebugRun=function*DebugRunCustomAction(){if(thiz.IsBreakpoint()||thiz._runtime.DebugBreakNext())yield thiz;
+const ret=yield*thiz._callEventBlock.DebugRunAsFunctionCall(combinedSolModifiers,thiz._parameters,isCopyPicked,pickInfo);return ret};else if(isFamilyToFamily)this.DebugRun=function*DebugRunCustomAction(){if(thiz.IsBreakpoint()||thiz._runtime.DebugBreakNext())yield thiz;const ret=yield*customAceBlock.DebugRunAsFamilyCustomActionWithOverrides(combinedSolModifiers,thiz._parameters);return ret}}else this.DebugRun=noopGenerator}else{this.Run=noop;this.DebugRun=noopGenerator}}_SetRunMethodForBoundFunc(plugin,
+bindThis,fallbackMethod){const func=this._func;const parameters=this._parameters;if(parameters.length===0)this.Run=plugin._GetBoundACEMethod(func,bindThis);else if(parameters.length===1){const param0=parameters[0];if(param0.IsConstant())this.Run=plugin._GetBoundACEMethod_1param(func,bindThis,param0.Get(0));else{const boundFunc=plugin._GetBoundACEMethod(func,bindThis);this.Run=function RunSingleAct_1param(){return boundFunc(param0.Get(0))}}}else if(parameters.length===2){const param0=parameters[0];
+const param1=parameters[1];if(param0.IsConstant()&¶m1.IsConstant())this.Run=plugin._GetBoundACEMethod_2params(func,bindThis,param0.Get(0),param1.Get(0));else{const boundFunc=plugin._GetBoundACEMethod(func,bindThis);this.Run=function RunSingleAct_2params(){return boundFunc(param0.Get(0),param1.Get(0))}}}else if(parameters.length===3){const param0=parameters[0];const param1=parameters[1];const param2=parameters[2];if(param0.IsConstant()&¶m1.IsConstant()&¶m2.IsConstant())this.Run=plugin._GetBoundACEMethod_3params(func,
+bindThis,param0.Get(0),param1.Get(0),param2.Get(0));else{const boundFunc=plugin._GetBoundACEMethod(func,bindThis);this.Run=function RunSingleAct_3params(){return boundFunc(param0.Get(0),param1.Get(0),param2.Get(0))}}}else this.Run=fallbackMethod}GetSID(){return this._sid}IsAsync(){return this._actionType===1}CanBailOut(){return this._actionType===2}CallBeforeAfterHooks(){return this._actionType===3}CanPickAnyObjectClass(){return(this._flags&FLAG_CANPICKANYOBJECTCLASS)!==0}HasReturnType(){return this.IsAsync()||
+this.CanBailOut()}GetObjectClass(){return this._objectClass}GetEventBlock(){return this._eventBlock}_HasCopyPickedParent(){let parent=this._eventBlock;do{if(parent instanceof C3.FunctionBlock&&parent.IsCopyPicked())return true;parent=parent.GetScopeParent()}while(parent);return false}GetRuntime(){return this._runtime}GetIndex(){return this._index}GetDebugIndex(){return this._debugData.index}IsBreakpoint(){return this._debugData.isBreakpoint}_SetBreakpoint(b){this._debugData.isBreakpoint=!!b;this._eventBlock._UpdateCanRunFastRecursive()}_DebugReturnsGenerator(){return this._debugData.canDebug}DebugCanRunFast(){return!this.IsBreakpoint()&&
+!this._runtime.DebugBreakNext()&&!this._DebugReturnsGenerator()}GetSavedDataMap(){if(!this._savedData)this._savedData=new Map;return this._savedData}GetUnsavedDataMap(){if(!this._unsavedData)this._unsavedData=new Map;return this._unsavedData}_RunSystem(){const results=this._results;EvalParams(this._parameters,results);return this._func.apply(this._systemPlugin,results)}*_DebugRunSystem(){if(this.IsBreakpoint()||this._runtime.DebugBreakNext())yield this;if(this._DebugReturnsGenerator()){const results=
+this._results;EvalParams(this._parameters,results);const ret=yield*this._func.apply(this._systemPlugin,results);return ret}else return this.Run()}_RunSingleGlobal(){const results=this._results;EvalParams(this._parameters,results);return this._func.apply(this._objectClass.GetSingleGlobalInstance().GetSdkInstance(),results)}*_DebugRunSingleGlobal(){if(this.IsBreakpoint()||this._runtime.DebugBreakNext())yield this;if(this._DebugReturnsGenerator()){const results=this._results;EvalParams(this._parameters,
+results);const ret=yield*this._func.apply(this._objectClass.GetSingleGlobalInstance().GetSdkInstance(),results);return ret}else return this.Run()}_RunObject_ParamsConst(){const results=this._results;const instances=this._objectClass.GetCurrentSol().GetInstances();for(let i=0,len=instances.length;ilayout.GetWidth()||bbox.getTop()>layout.GetHeight()}
+function PickDistance(which,x,y){const sol=this.GetCurrentSol();const instances=sol.GetInstances();if(!instances.length)return false;let inst=instances[0];let wi=inst.GetWorldInfo();let pickme=inst;let dist2=C3.distanceSquared(wi.GetX(),wi.GetY(),x,y);for(let i=1,len=instances.length;idist2){dist2=d2;pickme=inst}}sol.PickOne(pickme);return true}
+function SetX(x){const wi=this.GetWorldInfo();if(wi.GetX()===x)return;wi.SetX(x);wi.SetBboxChanged()}function SetY(y){const wi=this.GetWorldInfo();if(wi.GetY()===y)return;wi.SetY(y);wi.SetBboxChanged()}function SetPos(x,y){const wi=this.GetWorldInfo();if(wi.EqualsXY(x,y))return;wi.SetXY(x,y);wi.SetBboxChanged()}
+function SetPosToObject(objectClass,imgPt){if(!objectClass)return;const inst=objectClass.GetPairedInstance(this._inst);if(!inst)return;const [x,y]=inst.GetImagePoint(imgPt);const wi=this.GetWorldInfo();if(wi.GetX()===x&&wi.GetY()===y)return;wi.SetXY(x,y);wi.SetBboxChanged()}function MoveForward(dist){if(dist===0)return;const wi=this.GetWorldInfo();wi.OffsetXY(wi.GetCosAngle()*dist,wi.GetSinAngle()*dist);wi.SetBboxChanged()}
+function MoveAtAngle(a,dist){if(dist===0)return;const wi=this.GetWorldInfo();a=C3.toRadians(a);wi.OffsetXY(Math.cos(a)*dist,Math.sin(a)*dist);wi.SetBboxChanged()}function GetX(){return this.GetWorldInfo().GetX()}function GetY(){return this.GetWorldInfo().GetY()}function GetDt(){return this._runtime.GetDt(this._inst)}function CompareWidth(cmp,w){return C3.compare(this.GetWorldInfo().GetWidth(),cmp,w)}function CompareHeight(cmp,h){return C3.compare(this.GetWorldInfo().GetHeight(),cmp,h)}
+function SetWidth(w){const wi=this.GetWorldInfo();if(wi.GetWidth()===w)return;wi.SetWidth(w);wi.SetBboxChanged()}function SetHeight(h){const wi=this.GetWorldInfo();if(wi.GetHeight()===h)return;wi.SetHeight(h);wi.SetBboxChanged()}function SetSize(w,h){const wi=this.GetWorldInfo();if(wi.GetWidth()===w&&wi.GetHeight()===h)return;wi.SetSize(w,h);wi.SetBboxChanged()}function GetWidth(){return this.GetWorldInfo().GetWidth()}function GetHeight(){return this.GetWorldInfo().GetHeight()}
+function GetBboxLeft(){return this.GetWorldInfo().GetBoundingBox().getLeft()}function GetBboxTop(){return this.GetWorldInfo().GetBoundingBox().getTop()}function GetBboxRight(){return this.GetWorldInfo().GetBoundingBox().getRight()}function GetBboxBottom(){return this.GetWorldInfo().GetBoundingBox().getBottom()}function GetBboxMidX(){const bbox=this.GetWorldInfo().GetBoundingBox();return(bbox.getLeft()+bbox.getRight())/2}
+function GetBboxMidY(){const bbox=this.GetWorldInfo().GetBoundingBox();return(bbox.getTop()+bbox.getBottom())/2}function IsAngleWithin(within,a){return C3.angleDiff(this.GetWorldInfo().GetAngle(),C3.toRadians(a))<=C3.toRadians(within)}function IsAngleClockwiseFrom(a){return C3.angleClockwise(this.GetWorldInfo().GetAngle(),C3.toRadians(a))}
+function IsBetweenAngles(a,b){const lower=C3.toRadians(a);const upper=C3.toRadians(b);const angle=this.GetWorldInfo().GetAngle();const obtuse=!C3.angleClockwise(upper,lower);if(obtuse)return!(!C3.angleClockwise(angle,lower)&&C3.angleClockwise(angle,upper));else return C3.angleClockwise(angle,lower)&&!C3.angleClockwise(angle,upper)}
+function SetAngle(a){const wi=this.GetWorldInfo();const newAngle=C3.clampAngle(C3.toRadians(a));if(isNaN(newAngle)||wi.GetAngle()===newAngle)return;wi.SetAngle(newAngle);wi.SetBboxChanged()}function RotateClockwise(a){if(isNaN(a)||a===0)return;const wi=this.GetWorldInfo();wi.SetAngle(wi.GetAngle()+C3.toRadians(a));wi.SetBboxChanged()}function RotateCounterclockwise(a){if(isNaN(a)||a===0)return;const wi=this.GetWorldInfo();wi.SetAngle(wi.GetAngle()-C3.toRadians(a));wi.SetBboxChanged()}
+function RotateTowardAngle(amt,target){const wi=this.GetWorldInfo();const a=wi.GetAngle();const newAngle=C3.angleRotate(a,C3.toRadians(target),C3.toRadians(amt));if(isNaN(newAngle)||a===newAngle)return;wi.SetAngle(newAngle);wi.SetBboxChanged()}
+function RotateTowardPosition(amt,x,y){const wi=this.GetWorldInfo();const a=wi.GetAngle();const dx=x-wi.GetX();const dy=y-wi.GetY();const target=Math.atan2(dy,dx);const newAngle=C3.angleRotate(a,target,C3.toRadians(amt));if(isNaN(newAngle)||a===newAngle)return;wi.SetAngle(newAngle);wi.SetBboxChanged()}
+function SetTowardPosition(x,y){const wi=this.GetWorldInfo();const a=wi.GetAngle();const dx=x-wi.GetX();const dy=y-wi.GetY();const newAngle=Math.atan2(dy,dx);if(isNaN(newAngle)||a===newAngle)return;wi.SetAngle(newAngle);wi.SetBboxChanged()}function GetAngle(){return C3.toDegrees(this.GetWorldInfo().GetAngle())}function CompareOpacity(cmp,x){return C3.compare(C3.roundToDp(this.GetWorldInfo().GetOpacity()*100,6),cmp,x)}function IsVisible(){return this.GetWorldInfo().IsVisible()}
+function SetVisible(v){const wi=this.GetWorldInfo();if(v===2)v=!wi.IsVisible();else v=v!==0;if(wi.IsVisible()===v)return;wi.SetVisible(v);this._runtime.UpdateRender()}function SetOpacity(o){const newOpacity=C3.clamp(o/100,0,1);const wi=this.GetWorldInfo();if(wi.GetTransformWithParentOpacity()){if(wi._GetSceneGraphInfo().GetOwnOpacity()===newOpacity)return}else if(wi.GetOpacity()===newOpacity)return;wi.SetOpacity(newOpacity);this._runtime.UpdateRender()}
+function SetDefaultColor(rgb){tempColor.setFromRgbValue(rgb);const wi=this.GetWorldInfo();if(wi.GetUnpremultipliedColor().equalsIgnoringAlpha(tempColor))return;wi.SetUnpremultipliedColor(tempColor);this._runtime.UpdateRender()}function GetColor(){const c=this.GetWorldInfo().GetUnpremultipliedColor();return C3.PackRGBAEx(c.getR(),c.getG(),c.getB(),c.getA())}function GetOpacity(){return C3.roundToDp(this.GetWorldInfo().GetOpacity()*100,6)}
+function IsOnLayer(layer){if(!layer)return false;return this.GetWorldInfo().GetLayer()===layer}
+function PickTopBottom(which){const sol=this.GetCurrentSol();const instances=sol.GetInstances();if(!instances.length)return false;let inst=instances[0];let pickme=inst;for(let i=1,len=instances.length;ipickmeLayerIndex||instLayerIndex===pickmeLayerIndex&&instWi.GetZIndex()>
+pickmeWi.GetZIndex())pickme=inst}else if(instLayerIndexCollMemory_RemoveInstance(collMemory,e.instance))}const lsol=
+ltype.GetCurrentSol();const rsol=rtype.GetCurrentSol();const linstances=lsol.GetInstances();let rinstances=null;for(let l=0;lCollMemory_RemoveInstance(collMemory,e.instance))}const lsol=ltype.GetCurrentSol();const rsol=rtype.GetCurrentSol();
+const linstances=lsol.GetInstances();let rinstances=null;for(let l=0;l0)parentInstances=parentInstances.concat(parentInstsPendingCreate)}if(parentInstances.length===
+0)return false;const parentInstancesSet=new Set(parentInstances);const pickParents=new Set;for(let i=0,len=myInstances.length;i0)childInstances=childInstances.concat(childInstsPendingCreate)}if(childInstances.length===
+0)return false;const childInstancesSet=new Set(childInstances);const pickChildren=new Set;for(let i=0,len=myInstances.length;i0)childInstances=childInstances.concat(childInstsPendingCreate)}if(childInstances.length===
+0)return false;const childInstancesSet=new Set(childInstances);const pickChildren=[];for(let i=0,len=myInstances.length;ibestVal){bestVal=v;pickInst=inst}}sol.PickOne(pickInst);
+return true}function PickByUID(uid){if(this._runtime.GetCurrentCondition().IsInverted())return PickByUID_Inverted(this,uid);else return PickByUID_Normal(this,uid)}
+function PickByUID_Normal(objectClass,uid){const inst=objectClass.GetRuntime().GetInstanceByUID(uid);if(!inst)return false;const sol=objectClass.GetCurrentSol();if(!sol.IsSelectAll()&&!sol._GetOwnInstances().includes(inst))return false;if(objectClass.IsFamily()){if(inst.GetObjectClass().BelongsToFamily(objectClass)){sol.PickOne(inst);objectClass.ApplySolToContainer();return true}}else if(inst.GetObjectClass()===objectClass){sol.PickOne(inst);objectClass.ApplySolToContainer();return true}return false}
+function PickByUID_Inverted(objectClass,uid){const sol=objectClass.GetCurrentSol();if(sol.IsSelectAll()){sol._SetSelectAll(false);sol.ClearArrays();const instances=objectClass.GetInstances();for(let i=0,len=instances.length;iv.GetValue());if(functionBlock.IsAsync())this._asyncId=functionBlock.PauseCurrentAsyncFunction()}for(const objectClass of allObjectClasses){const sol=
+objectClass.GetCurrentSol();if(sol.IsSelectAll()&&!this._event.HasSolModifier(objectClass))continue;this._solModifiers.push(objectClass);this._sols.set(objectClass,C3.New(C3.SolState,sol))}const dynamicSolModifiersSet=eventSheetManager.GetDynamicSolModifiersSet();this._dynamicSolModifiers=dynamicSolModifiersSet.size>0?dynamicSolModifiersSet:null}InitTimer(seconds){this._type="timer";this._Init();this._time=this._eventSheetManager.GetRuntime().GetGameTime()+seconds}InitSignal(tag){this._type="signal";
+this._Init();this._signalTag=tag.toLowerCase()}InitPromise(p){this._type="promise";this._Init();p.then(()=>this.SetSignalled()).catch(err=>{console.warn("[C3 runtime] Promise rejected in 'Wait for previous actions to complete': ",err);this.SetSignalled()})}IsTimer(){return this._type==="timer"}IsSignal(){return this._type==="signal"}IsPromise(){return this._type==="promise"}GetSignalTag(){return this._signalTag}IsSignalled(){return this._isSignalled}SetSignalled(){this._isSignalled=true}_ShouldRun(){if(this.IsTimer())return this._time<=
+this._eventSheetManager.GetRuntime().GetGameTime();else return this.IsSignalled()}_RestoreState(frame){frame._Restore(this._event,this._actIndex);for(const [objectClass,solState]of this._sols.entries()){const sol=objectClass.GetCurrentSol();solState._Restore(sol)}if(this._dynamicSolModifiers)frame.SetDynamicSolModifiers([...this._dynamicSolModifiers]);const callingFunctionBlock=this._callingFunctionBlock;if(callingFunctionBlock){callingFunctionBlock.SetFunctionParameters(this._functionParameters);
+callingFunctionBlock._GetAllInnerLocalVariables().map((v,index)=>v.SetValue(this._functionInnerLocalVars[index]));if(callingFunctionBlock.IsAsync())callingFunctionBlock.ResumeAsyncFunction(this._asyncId)}}_Run(frame){this._RestoreState(frame);this._event._ResumeActionsAndSubEvents(frame);if(this._callingFunctionBlock&&this._callingFunctionBlock.IsAsync())this._callingFunctionBlock.MaybeFinishAsyncFunctionCall(this._asyncId);this._eventSheetManager.ClearSol(this._solModifiers);this._shouldRelease=
+true}async _DebugRun(frame){this._RestoreState(frame);for(const breakEventObject of this._event._DebugResumeActionsAndSubEvents(frame))await this._eventSheetManager.GetRuntime().DebugBreak(breakEventObject);if(this._callingFunctionBlock&&this._callingFunctionBlock.IsAsync())this._callingFunctionBlock.MaybeFinishAsyncFunctionCall(this._asyncId);this._eventSheetManager.ClearSol(this._solModifiers);this._shouldRelease=true}ShouldRelease(){return this._shouldRelease}RemoveInstances(s){for(const solState of this._sols.values())solState.RemoveInstances(s)}_SaveToJson(){const sols=
+{};const o={"t":this._time,"st":this._signalTag,"s":this._isSignalled,"ev":this._event.GetSID(),"sm":this._solModifiers.map(oc=>oc.GetSID()),"dsm":this._dynamicSolModifiers?[...this._dynamicSolModifiers].map(oc=>oc.GetSID()):null,"sols":sols};if(this._event._HasActionIndex(this._actIndex))o["act"]=this._event.GetActionAt(this._actIndex).GetSID();for(const [objectClass,solState]of this._sols)sols[objectClass.GetSID().toString()]=solState._SaveToJson();return o}static _CreateFromJson(eventSheetManager,
+o){const runtime=eventSheetManager.GetRuntime();const event=eventSheetManager.GetEventBlockBySID(o["ev"]);if(!event)return null;let actIndex=0;if(o.hasOwnProperty("act")){const act=eventSheetManager.GetActionBySID(o["act"]);if(!act)return null;actIndex=act.GetIndex()}const sw=C3.New(C3.ScheduledWait,eventSheetManager);sw._time=o["t"];sw._type=sw._time===-1?"signal":"timer";sw._signalTag=o["st"];sw._isSignalled=o["s"];sw._event=event;sw._actIndex=actIndex;for(const sid of o["sm"]){const objectClass=
+runtime.GetObjectClassBySID(sid);if(objectClass)sw._solModifiers.push(objectClass)}if(Array.isArray(o["dsm"]))for(const sid of o["dsm"]){const objectClass=runtime.GetObjectClassBySID(sid);if(objectClass){if(!sw._dynamicSolModifiers)sw._dynamicSolModifiers=new Set;sw._dynamicSolModifiers.add(objectClass)}}for(const [sidStr,solData]of Object.entries(o["sols"])){const sid=parseInt(sidStr,10);const objectClass=runtime.GetObjectClassBySID(sid);if(!objectClass)continue;const solState=C3.New(C3.SolState,
+null);solState._LoadFromJson(eventSheetManager,solData);sw._sols.set(objectClass,solState)}return sw}};
+
+}
+
+// events/solState.js
+{
+'use strict';const C3=self.C3;
+C3.SolState=class SolState extends C3.DefendedBase{constructor(sol){super();this._objectClass=null;this._isSelectAll=true;this._instances=[];if(sol){this._objectClass=sol.GetObjectClass();this._isSelectAll=sol.IsSelectAll();C3.shallowAssignArray(this._instances,sol._GetOwnInstances())}}Release(){this._objectClass=null;C3.clearArray(this._instances)}_Restore(sol){sol._SetSelectAll(this._isSelectAll);C3.shallowAssignArray(sol._GetOwnInstances(),this._instances)}RemoveInstances(s){C3.arrayRemoveAllInSet(this._instances,s)}_SaveToJson(){return{"sa":this._isSelectAll,
+"insts":this._instances.map(inst=>inst.GetUID())}}_LoadFromJson(eventSheetManager,o){const runtime=eventSheetManager.GetRuntime();this._isSelectAll=!!o["sa"];C3.clearArray(this._instances);for(const uid of o["insts"]){const inst=runtime.GetInstanceByUID(uid);if(inst)this._instances.push(inst)}}};
+
+}
+
+// sdk/sdkPluginBase.js
+{
+'use strict';const C3=self.C3;function GetNextParamMap(paramMap,param){let nextParamMap=paramMap.get(param);if(!nextParamMap){nextParamMap=new Map;paramMap.set(param,nextParamMap)}return nextParamMap}
+C3.SDKPluginBase=class SDKPluginBase extends C3.DefendedBase{constructor(opts){super();this._runtime=opts.runtime;this._isSingleGlobal=!!opts.isSingleGlobal;this._isWorldType=!!opts.isWorld;this._isRotatable=!!opts.isRotatable;this._mustPredraw=!!opts.mustPredraw;this._hasEffects=!!opts.hasEffects;this._supportsSceneGraph=!!opts.supportsSceneGraph;this._supportsMesh=!!opts.supportsMesh;this._isHTMLElementType=!!opts.isHTMLElementType;this._singleGlobalObjectClass=null;this._boundACEMethodCache=new Map;
+this._boundACEMethodCache_1param=new Map;this._boundACEMethodCache_2params=new Map;this._boundACEMethodCache_3params=new Map}Release(){this._runtime=null}GetRuntime(){return this._runtime}OnCreate(){}IsSingleGlobal(){return this._isSingleGlobal}IsWorldType(){return this._isWorldType}IsHTMLElementType(){return this._isHTMLElementType}IsRotatable(){return this._isRotatable}MustPreDraw(){return this._mustPredraw}HasEffects(){return this._hasEffects}SupportsSceneGraph(){return this._supportsSceneGraph}SupportsMesh(){return this._supportsMesh}_GetBoundACEMethod(func,
+bindThis){if(!bindThis)throw new Error("missing 'this' binding");let ret=this._boundACEMethodCache.get(func);if(ret)return ret;ret=func.bind(bindThis);this._boundACEMethodCache.set(func,ret);return ret}_GetBoundACEMethod_1param(func,bindThis,param0){if(!bindThis)throw new Error("missing 'this' binding");const param0map=GetNextParamMap(this._boundACEMethodCache_1param,func);let ret=param0map.get(param0);if(ret)return ret;ret=func.bind(bindThis,param0);param0map.set(param0,ret);return ret}_GetBoundACEMethod_2params(func,
+bindThis,param0,param1){if(!bindThis)throw new Error("missing 'this' binding");const param0map=GetNextParamMap(this._boundACEMethodCache_2params,func);const param1map=GetNextParamMap(param0map,param0);let ret=param1map.get(param1);if(ret)return ret;ret=func.bind(bindThis,param0,param1);param1map.set(param1,ret);return ret}_GetBoundACEMethod_3params(func,bindThis,param0,param1,param2){if(!bindThis)throw new Error("missing 'this' binding");const param0map=GetNextParamMap(this._boundACEMethodCache_3params,
+func);const param1map=GetNextParamMap(param0map,param0);const param2map=GetNextParamMap(param1map,param1);let ret=param2map.get(param2);if(ret)return ret;ret=func.bind(bindThis,param0,param1,param2);param2map.set(param2,ret);return ret}_SetSingleGlobalObjectClass(objectClass){if(!this.IsSingleGlobal())throw new Error("must be single-global plugin");this._singleGlobalObjectClass=objectClass}GetSingleGlobalObjectClass(){if(!this.IsSingleGlobal())throw new Error("must be single-global plugin");return this._singleGlobalObjectClass}GetSingleGlobalInstance(){if(!this.IsSingleGlobal())throw new Error("must be single-global plugin");
+return this._singleGlobalObjectClass.GetSingleGlobalInstance()}};
+
+}
+
+// sdk/sdkDOMPluginBase.js
+{
+'use strict';const C3=self.C3;
+C3.SDKDOMPluginBase=class SDKDOMPluginBase extends C3.SDKPluginBase{constructor(opts,DOM_COMPONENT_ID){super(opts);this._domComponentId=DOM_COMPONENT_ID;this._nextElementId=0;this._instMap=new Map;this.AddElementMessageHandler("elem-focused",sdkInst=>sdkInst._OnElemFocused());this.AddElementMessageHandler("elem-blurred",sdkInst=>{if(sdkInst)sdkInst._OnElemBlurred()})}Release(){super.Release()}_AddElement(sdkInst){const elementId=this._nextElementId++;this._instMap.set(elementId,sdkInst);return elementId}_RemoveElement(elementId){this._instMap.delete(elementId)}AddElementMessageHandler(handler,
+func){this._runtime.AddDOMComponentMessageHandler(this._domComponentId,handler,e=>{const sdkInst=this._instMap.get(e["elementId"]);func(sdkInst,e)})}};
+
+}
+
+// sdk/sdkTypeBase.js
+{
+'use strict';const C3=self.C3;
+C3.SDKTypeBase=class SDKTypeBase extends C3.DefendedBase{constructor(objectClass){super();this._objectClass=objectClass;this._runtime=objectClass.GetRuntime();this._plugin=objectClass.GetPlugin()}Release(){this._objectClass=null;this._runtime=null;this._plugin=null}GetObjectClass(){return this._objectClass}GetRuntime(){return this._runtime}GetPlugin(){return this._plugin}GetImageInfo(){return this._objectClass.GetImageInfo()}OnCreate(){}FinishCondition(f){}BeforeRunAction(method){}AfterRunAction(method){}LoadTextures(renderer){}ReleaseTextures(){}OnDynamicTextureLoadComplete(){}PreloadTexturesWithInstances(renderer){}LoadTilemapData(){}GetScriptInterfaceClass(){return null}DispatchScriptEvent(name,cancelable,
+additionalProperties){const e=C3.New(C3.Event,name,cancelable);e.objectClass=this;if(additionalProperties)Object.assign(e,additionalProperties);this.GetObjectClass().DispatchUserScriptEvent(e)}};
+
+}
+
+// sdk/sdkInstanceBase.js
+{
+'use strict';const C3=self.C3;
+C3.SDKInstanceBase=class SDKInstanceBase extends C3.DefendedBase{constructor(inst,domComponentId){super();this._inst=inst;this._domComponentId=domComponentId;this._wrapperComponentId=null;this._runtime=inst.GetRuntime();this._objectClass=this._inst.GetObjectClass();this._sdkType=this._objectClass.GetSdkType();this._tickFunc=null;this._tick2Func=null;this._isTicking=false;this._isTicking2=false;this._disposables=null;this._wasReleased=false}Release(){this._wasReleased=true;this._StopTicking();this._StopTicking2();
+this._tickFunc=null;this._tick2Func=null;if(this._disposables){this._disposables.Release();this._disposables=null}this._inst=null;this._runtime=null;this._objectClass=null;this._sdkType=null}WasReleased(){return this._wasReleased}GetInstance(){return this._inst}GetRuntime(){return this._runtime}GetObjectClass(){return this._objectClass}GetPlugin(){return this._sdkType.GetPlugin()}GetSdkType(){return this._sdkType}GetScriptInterface(){return this._inst.GetInterfaceClass()}Trigger(method){return this._runtime.Trigger(method,
+this._inst,null)}DebugTrigger(method){return this._runtime.DebugTrigger(method,this._inst,null)}TriggerAsync(method){return this._runtime.TriggerAsync(method,this._inst,null)}FastTrigger(method,value){return this._runtime.FastTrigger(method,this._inst,value)}DebugFastTrigger(method,value){return this._runtime.DebugFastTrigger(method,this._inst,value)}ScheduleTriggers(f){return this._runtime.ScheduleTriggers(f)}AddDOMMessageHandler(handler,func){this._runtime.AddDOMComponentMessageHandler(this._domComponentId,
+handler,func)}AddDOMMessageHandlers(list){for(const [handler,func]of list)this.AddDOMMessageHandler(handler,func)}PostToDOM(handler,data){this._runtime.PostComponentMessageToDOM(this._domComponentId,handler,data)}PostToDOMAsync(handler,data){return this._runtime.PostComponentMessageToDOMAsync(this._domComponentId,handler,data)}_PostToDOMMaybeSync(handler,data){if(this._runtime.IsInWorker())this.PostToDOM(handler,data);else return window["c3_runtimeInterface"]["_OnMessageFromRuntime"]({"type":"event",
+"component":this._domComponentId,"handler":handler,"data":data,"responseId":null})}SetWrapperExtensionComponentId(componentId){if(!componentId)throw new Error("cannot set empty component id");this._wrapperComponentId=componentId}IsWrapperExtensionAvailable(){if(!this._wrapperComponentId)throw new Error("wrapper extension component id not set");return this._runtime.HasWrapperComponentId(this._wrapperComponentId)}AddWrapperExtensionMessageHandler(handler,func){if(!this._wrapperComponentId)throw new Error("wrapper extension component id not set");
+this._runtime.AddWrapperExtensionMessageHandler(this._wrapperComponentId,handler,func)}AddWrapperExtensionMessageHandlers(list){for(const [handler,func]of list)this.AddWrapperExtensionMessageHandler(handler,func)}SendWrapperExtensionMessage(messageId,params){if(!this._wrapperComponentId)throw new Error("wrapper extension component id not set");this._runtime.SendWrapperExtensionMessage(this._wrapperComponentId,messageId,params)}SendWrapperExtensionMessageAsync(messageId,params){if(!this._wrapperComponentId)throw new Error("wrapper extension component id not set");
+return this._runtime.SendWrapperExtensionMessageAsync(this._wrapperComponentId,messageId,params)}Tick(){}Tick2(){}_StartTicking(){if(this._isTicking)return;if(!this._tickFunc)this._tickFunc=()=>this.Tick();this._runtime.Dispatcher().addEventListener("tick",this._tickFunc);this._isTicking=true}_StopTicking(){if(!this._isTicking)return;this._runtime.Dispatcher().removeEventListener("tick",this._tickFunc);this._isTicking=false}IsTicking(){return this._isTicking}_StartTicking2(){if(this._isTicking2)return;
+if(!this._tick2Func)this._tick2Func=()=>this.Tick2();this._runtime.Dispatcher().addEventListener("tick2",this._tick2Func);this._isTicking2=true}_StopTicking2(){if(!this._isTicking2)return;this._runtime.Dispatcher().removeEventListener("tick2",this._tick2Func);this._isTicking2=false}IsTicking2(){return this._isTicking2}GetDebuggerProperties(){return[]}SaveToJson(){return null}LoadFromJson(o){}GetPropertyValueByIndex(index){}SetPropertyValueByIndex(index,value){}OffsetPropertyValueByIndex(index,offset,
+opts){if(offset===0)return;const value=this.GetPropertyValueByIndex(index);if(typeof value!=="number")throw new Error("expected number");this.SetPropertyValueByIndex(index,value+offset,opts)}SetPropertyColorOffsetValueByIndex(offset,r,g,b){}CallAction(actMethod,...args){actMethod.call(this,...args)}CallExpression(expMethod,...args){return expMethod.call(this,...args)}GetScriptInterfaceClass(){return null}DispatchScriptEvent(name,cancelable,additionalProperties){if(!this._inst.HasScriptInterface())return;
+const scriptInterface=this.GetScriptInterface();const e=C3.New(C3.Event,name,cancelable);e.instance=scriptInterface;if(additionalProperties)Object.assign(e,additionalProperties);scriptInterface.dispatchEvent(e)}};
+
+}
+
+// sdk/sdkWorldInstanceBase.js
+{
+'use strict';const C3=self.C3;
+C3.SDKWorldInstanceBase=class SDKWorldInstanceBase extends C3.SDKInstanceBase{constructor(inst,domComponentId){super(inst,domComponentId);this._worldInfo=inst.GetWorldInfo();this._renderercontextlost_handler=null;this._renderercontextrestored_handler=null}Release(){if(this._renderercontextlost_handler){const dispatcher=this._runtime.Dispatcher();dispatcher.removeEventListener("renderercontextlost",this._renderercontextlost_handler);dispatcher.removeEventListener("renderercontextrestored",this._renderercontextrestored_handler);
+this._renderercontextlost_handler=null;this._renderercontextrestored_handler=null}this._worldInfo=null;super.Release()}HandleWebGLContextLoss(){this.HandleRendererContextLoss()}OnWebGLContextLost(){}OnWebGLContextRestored(){}HandleRendererContextLoss(){if(this._renderercontextlost_handler)return;this._renderercontextlost_handler=()=>this.OnRendererContextLost();this._renderercontextrestored_handler=()=>this.OnRendererContextRestored();const dispatcher=this._runtime.Dispatcher();dispatcher.addEventListener("renderercontextlost",
+this._renderercontextlost_handler);dispatcher.addEventListener("renderercontextrestored",this._renderercontextrestored_handler)}OnRendererContextLost(){this.OnWebGLContextLost()}OnRendererContextRestored(){this.OnWebGLContextRestored()}GetWorldInfo(){return this._worldInfo}IsOriginalSizeKnown(){return false}GetOriginalWidth(){if(!this.IsOriginalSizeKnown())throw new Error("original size not known");const imageInfo=this.GetCurrentImageInfo();if(imageInfo)return imageInfo.GetWidth();else;}GetOriginalHeight(){if(!this.IsOriginalSizeKnown())throw new Error("original size not known");
+const imageInfo=this.GetCurrentImageInfo();if(imageInfo)return imageInfo.GetHeight();else;}GetCurrentImageInfo(){return null}GetCurrentSurfaceSize(){const imageInfo=this.GetCurrentImageInfo();if(imageInfo){const texture=imageInfo.GetTexture();if(texture)return[texture.GetWidth(),texture.GetHeight()]}return[100,100]}GetCurrentTexRect(){const imageInfo=this.GetCurrentImageInfo();return imageInfo?imageInfo.GetTexRect():null}GetCurrentTexQuad(){const imageInfo=this.GetCurrentImageInfo();return imageInfo?
+imageInfo.GetTexQuad():null}IsCurrentTexRotated(){const imageInfo=this.GetCurrentImageInfo();return imageInfo?imageInfo.IsRotated():false}GetImagePoint(nameOrIndex){const wi=this._inst.GetWorldInfo();return[wi.GetX(),wi.GetY(),wi.GetTotalZElevation()]}LoadTilemapData(data,mapWidth,mapHeight){}TestPointOverlapTile(x,y){}RendersToOwnZPlane(){return true}};
+
+}
+
+// sdk/sdkDOMInstanceBase.js
+{
+'use strict';const C3=self.C3;const tempRect=C3.New(C3.Rect);
+C3.SDKDOMInstanceBase=class SDKDOMInstanceBase extends C3.SDKWorldInstanceBase{constructor(inst,domComponentId){super(inst,domComponentId);this._elementId=this.GetPlugin()._AddElement(this);this._isElementShowing=true;this._elemHasFocus=false;this._autoFontSize=false;this._autoFontSizeOffset=-.2;this._lastRect=C3.New(C3.Rect,0,0,-1,-1);const canvasManager=this._runtime.GetCanvasManager();this._lastWindowWidth=canvasManager.GetLastWidth();this._lastWindowHeight=canvasManager.GetLastHeight();this._lastHTMLIndex=
+-1;this._lastHTMLZIndex=-1;this._isPendingUpdateState=false;this._StartTicking()}Release(){this.GetPlugin()._RemoveElement(this._elementId);this.PostToDOMElement("destroy");this._elementId=-1;super.Release()}_GetElementInDOMMode(){if(this._runtime.IsInWorker())throw new Error("not valid in worker mode");return this._PostToDOMElementMaybeSync("get-element")}PostToDOMElement(handler,data){if(!data)data={};data["elementId"]=this._elementId;this.PostToDOM(handler,data)}_PostToDOMElementMaybeSync(handler,
+data){if(!data)data={};data["elementId"]=this._elementId;return this._PostToDOMMaybeSync(handler,data)}PostToDOMElementAsync(handler,data){if(!data)data={};data["elementId"]=this._elementId;return this.PostToDOMAsync(handler,data)}CreateElement(data){if(!data)data={};const wi=this.GetWorldInfo();data["elementId"]=this._elementId;data["isVisible"]=wi.IsVisible();data["htmlIndex"]=wi.GetLayer().GetHTMLIndex();data["htmlZIndex"]=wi.GetHTMLZIndex();Object.assign(data,this.GetElementState());this._isElementShowing=
+!!data["isVisible"];this._PostToDOMMaybeSync("create",data);this._UpdatePosition(true)}SetElementVisible(v){v=!!v;if(this._isElementShowing===v)return;this._isElementShowing=v;this.PostToDOMElement("set-visible",{"isVisible":v})}Tick(){this._UpdatePosition(false)}_ShouldPreserveElement(){const fullscreenMode=this._runtime.GetCanvasManager().GetFullscreenMode();return C3.Platform.OS==="Android"&&(fullscreenMode==="scale-inner"||fullscreenMode==="scale-outer"||fullscreenMode==="crop")}_UpdatePosition(first){if(this.GetInstance().IsDestroyed())return;
+const wi=this.GetWorldInfo();const layer=wi.GetLayer();const bbox=wi.GetBoundingBox();let [cleft,ctop]=layer.LayerToCanvasCss(bbox.getLeft(),bbox.getTop());let [cright,cbottom]=layer.LayerToCanvasCss(bbox.getRight(),bbox.getBottom());const canvasManager=this._runtime.GetCanvasManager();const rightEdge=canvasManager.GetCssWidth();const bottomEdge=canvasManager.GetCssHeight();if(!wi.IsVisible()||!layer.IsVisible()){this.SetElementVisible(false);return}if(!this._ShouldPreserveElement())if(cright<=0||
+cbottom<=0||cleft>=rightEdge||ctop>=bottomEdge){this.SetElementVisible(false);return}tempRect.set(cleft,ctop,cright,cbottom);const curWinWidth=canvasManager.GetLastWidth();const curWinHeight=canvasManager.GetLastHeight();const curHTMLIndex=layer.GetHTMLIndex();const curHTMLZIndex=wi.GetHTMLZIndex();if(!first&&tempRect.equals(this._lastRect)&&this._lastWindowWidth===curWinWidth&&this._lastWindowHeight===curWinHeight&&this._lastHTMLIndex===curHTMLIndex&&this._lastHTMLZIndex===curHTMLZIndex){this.SetElementVisible(true);
+return}this._lastRect.copy(tempRect);this._lastWindowWidth=curWinWidth;this._lastWindowHeight=curWinHeight;this._lastHTMLIndex=curHTMLIndex;this._lastHTMLZIndex=curHTMLZIndex;this.SetElementVisible(true);let fontSize=null;if(this._autoFontSize)fontSize=layer.GetDisplayScale()+this._autoFontSizeOffset;this.PostToDOMElement("update-position",{"left":Math.round(this._lastRect.getLeft()),"top":Math.round(this._lastRect.getTop()),"width":Math.round(this._lastRect.width()),"height":Math.round(this._lastRect.height()),
+"htmlIndex":curHTMLIndex,"htmlZIndex":curHTMLZIndex,"fontSize":fontSize})}FocusElement(){this._PostToDOMElementMaybeSync("focus",{"focus":true})}BlurElement(){this._PostToDOMElementMaybeSync("focus",{"focus":false})}_OnElemFocused(){this._elemHasFocus=true}_OnElemBlurred(){this._elemHasFocus=false}IsElementFocused(){return this._elemHasFocus}SetElementCSSStyle(prop,val){this.PostToDOMElement("set-css-style",{"prop":C3.CSSToCamelCase(prop),"val":val})}SetElementAttribute(attribName,value){this.PostToDOMElement("set-attribute",
+{"name":attribName,"val":value})}RemoveElementAttribute(attribName){this.PostToDOMElement("remove-attribute",{"name":attribName})}UpdateElementState(){if(this._isPendingUpdateState)return;this._isPendingUpdateState=true;Promise.resolve().then(()=>{this._isPendingUpdateState=false;this.PostToDOMElement("update-state",this.GetElementState())})}GetElementState(){}GetElementId(){return this._elementId}};
+
+}
+
+// sdk/sdkBehaviorBase.js
+{
+'use strict';const C3=self.C3;const IBehavior=self.IBehavior;
+C3.SDKBehaviorBase=class SDKBehaviorBase extends C3.DefendedBase{constructor(opts){super();this._runtime=opts.runtime;this._myObjectClasses=C3.New(C3.ArraySet);this._myInstances=C3.New(C3.ArraySet);this._iBehavior=null;this._scriptInterfaceClass=opts.scriptInterfaceClass||null}Release(){this._myInstances.Release();this._myObjectClasses.Release();this._runtime=null}GetRuntime(){return this._runtime}OnCreate(){}_AddObjectClass(objectClass){this._myObjectClasses.Add(objectClass)}GetObjectClasses(){return this._myObjectClasses.GetArray()}_AddInstance(inst){this._myInstances.Add(inst)}_RemoveInstance(inst){this._myInstances.Delete(inst)}GetInstances(){return this._myInstances.GetArray()}GetIBehavior(){if(this._iBehavior===null){const CustomScriptClass=
+this._scriptInterfaceClass;if(CustomScriptClass){this._iBehavior=new CustomScriptClass(this);if(!(this._iBehavior instanceof IBehavior))throw new TypeError("script interface class must derive from IBehavior");}else this._iBehavior=new IBehavior(this)}return this._iBehavior}};
+
+}
+
+// sdk/sdkBehaviorTypeBase.js
+{
+'use strict';const C3=self.C3;C3.SDKBehaviorTypeBase=class SDKBehaviorTypeBase extends C3.DefendedBase{constructor(behaviorType){super();this._runtime=behaviorType.GetRuntime();this._behaviorType=behaviorType;this._objectClass=behaviorType.GetObjectClass();this._behavior=behaviorType.GetBehavior();this._behavior._AddObjectClass(this._objectClass)}Release(){this._runtime=null;this._behaviorType=null;this._objectClass=null;this._behavior=null}OnCreate(){}GetBehaviorType(){return this._behaviorType}GetObjectClass(){return this._objectClass}GetRuntime(){return this._runtime}GetBehavior(){return this._behavior}};
+
+}
+
+// sdk/sdkBehaviorInstanceBase.js
+{
+'use strict';const C3=self.C3;
+C3.SDKBehaviorInstanceBase=class SDKBehaviorInstanceBase extends C3.DefendedBase{constructor(behInst,domComponentId){super();this._behInst=behInst;this._domComponentId=domComponentId;this._inst=behInst.GetObjectInstance();this._runtime=behInst.GetRuntime();this._behaviorType=behInst.GetBehaviorType();this._sdkType=this._behaviorType.GetSdkType();this._isTicking=false;this._isTicking2=false;this._isPostTicking=false;this._disposables=null}Release(){this._StopTicking();this._StopTicking2();this._StopPostTicking();
+if(this._disposables){this._disposables.Release();this._disposables=null}this._behInst=null;this._inst=null;this._runtime=null;this._behaviorType=null;this._sdkType=null}GetBehavior(){return this._behaviorType.GetBehavior()}GetBehaviorInstance(){return this._behInst}GetObjectInstance(){return this._inst}GetObjectClass(){return this._inst.GetObjectClass()}GetWorldInfo(){return this._inst.GetWorldInfo()}GetRuntime(){return this._runtime}GetBehaviorType(){return this._behaviorType}GetSdkType(){return this._sdkType}GetScriptInterface(){return this._behInst.GetScriptInterface()}Trigger(method){return this._runtime.Trigger(method,
+this._inst,this._behaviorType)}DebugTrigger(method){return this._runtime.DebugTrigger(method,this._inst,this._behaviorType)}TriggerAsync(method){return this._runtime.TriggerAsync(method,this._inst,this._behaviorType)}PostCreate(){}Tick(){}Tick2(){}PostTick(){}_StartTicking(){if(this._isTicking)return;this._runtime._AddBehInstToTick(this);this._isTicking=true}_StopTicking(){if(!this._isTicking)return;this._runtime._RemoveBehInstToTick(this);this._isTicking=false}IsTicking(){return this._isTicking}_StartTicking2(){if(this._isTicking2)return;
+this._runtime._AddBehInstToTick2(this);this._isTicking2=true}_StopTicking2(){if(!this._isTicking2)return;this._runtime._RemoveBehInstToTick2(this);this._isTicking2=false}IsTicking2(){return this._isTicking2}_StartPostTicking(){if(this._isPostTicking)return;this._runtime._AddBehInstToPostTick(this);this._isPostTicking=true}_StopPostTicking(){if(!this._isPostTicking)return;this._runtime._RemoveBehInstToPostTick(this);this._isPostTicking=false}IsPostTicking(){return this._isPostTicking}GetDebuggerProperties(){return[]}AddDOMMessageHandler(handler,
+func){this._runtime.AddDOMComponentMessageHandler(this._domComponentId,handler,func)}OnSpriteFrameChanged(prevFrame,nextFrame){}SaveToJson(){return null}LoadFromJson(o){}GetPropertyValueByIndex(index){}SetPropertyValueByIndex(index,value){}OffsetPropertyValueByIndex(index,offset){if(offset===0)return;const value=this.GetPropertyValueByIndex(index);if(typeof value!=="number")throw new Error("expected number");this.SetPropertyValueByIndex(index,value+offset)}SetPropertyColorOffsetValueByIndex(index,
+offsetR,offsetG,offsetB){}CallAction(actMethod,...args){actMethod.call(this,...args)}CallExpression(expMethod,...args){return expMethod.call(this,...args)}GetScriptInterfaceClass(){return null}DispatchScriptEvent(name,cancelable,additionalProperties){if(!this._behInst.HasScriptInterface())return;const scriptInterface=this.GetScriptInterface();const e=C3.New(C3.Event,name,cancelable);e.behaviorInstance=scriptInterface;e.instance=scriptInterface.instance;if(additionalProperties)Object.assign(e,additionalProperties);
+scriptInterface.dispatchEvent(e)}};
+
+}
+
+// objects/pluginManager.js
+{
+'use strict';const C3=self.C3;C3.Plugins={};C3.Behaviors={};
+C3.PluginManager=class PluginManager extends C3.DefendedBase{constructor(runtime,wrapperComponentIds){super();this._runtime=runtime;this._allPlugins=[];this._pluginsByCtor=new Map;this._systemPlugin=null;this._allBehaviors=[];this._behaviorsByCtor=new Map;this._solidBehavior=null;this._jumpthruBehavior=null;this._wrapperComponentIds=new Set(wrapperComponentIds)}CreatePlugin(pluginData){const Ctor=this._runtime.GetObjectReference(pluginData[0]);if(!Ctor)throw new Error("missing plugin");C3.AddCommonACEs(pluginData,
+Ctor);const plugin=C3.New(Ctor,{runtime:this._runtime,isSingleGlobal:pluginData[1],isWorld:pluginData[2],isRotatable:pluginData[5],hasEffects:pluginData[8],mustPredraw:pluginData[9],supportsSceneGraph:pluginData[13],supportsMesh:pluginData[14],isHTMLElementType:pluginData[17]});plugin.OnCreate();this._allPlugins.push(plugin);this._pluginsByCtor.set(Ctor,plugin)}CreateSystemPlugin(){this._systemPlugin=C3.New(C3.Plugins.System,{runtime:this._runtime,isSingleGlobal:true});this._systemPlugin.OnCreate()}CreateBehavior(behaviorData){const Ctor=
+this._runtime.GetObjectReference(behaviorData[1]);if(!Ctor)throw new Error("missing behavior");const behavior=C3.New(Ctor,{runtime:this._runtime});behavior.OnCreate();this._allBehaviors.push(behavior);this._behaviorsByCtor.set(Ctor,behavior);if(!this._solidBehavior&&C3.Behaviors.solid&&behavior instanceof C3.Behaviors.solid)this._solidBehavior=behavior;else if(!this._jumpthruBehavior&&C3.Behaviors.jumpthru&&behavior instanceof C3.Behaviors.jumpthru)this._jumpthruBehavior=behavior}GetPluginByConstructorFunction(ctor){return this._pluginsByCtor.get(ctor)||
+null}HasBehaviorByConstructorFunction(ctor){return this._behaviorsByCtor.has(ctor)}GetBehaviorByConstructorFunction(ctor){return this._behaviorsByCtor.get(ctor)||null}GetSystemPlugin(){return this._systemPlugin}GetSolidBehavior(){return this._solidBehavior}GetJumpthruBehavior(){return this._jumpthruBehavior}HasWrapperComponentId(id){return this._wrapperComponentIds.has(id)}};
+
+}
+
+// objects/imageInfo.js
+{
+'use strict';const C3=self.C3;const allImageInfos=new Set;
+C3.ImageInfo=class ImageInfo extends C3.DefendedBase{constructor(){super();this._generation=0;this._url="";this._size=0;this._offsetX=0;this._offsetY=0;this._width=0;this._height=0;this._isRotated=false;this._hasMetaData=false;this._imageAsset=null;this._textureState="";this._rcTex=C3.New(C3.Rect);this._quadTex=C3.New(C3.Quad);this._blobUrl="";this._iImageInfo=new self.IImageInfo(this);allImageInfos.add(this)}Release(){this.ReleaseTexture();this._imageAsset=null;allImageInfos.delete(this);this.ReleaseBlobURL()}static OnRendererContextLost(){for(const imageInfo of allImageInfos){imageInfo._textureState=
+"";imageInfo._rcTex.set(0,0,0,0);imageInfo._quadTex.setFromRect(imageInfo._rcTex)}}LoadData(imageData){this._url=imageData[0];this._size=imageData[1];this._offsetX=imageData[2];this._offsetY=imageData[3];this._width=imageData[4];this._height=imageData[5];this._isRotated=imageData[6];this._hasMetaData=true}LoadDynamicAsset(runtime,url){if(this._imageAsset)throw new Error("already loaded asset");this._url=url;const opts={};if(C3.IsAbsoluteURL(url))opts.loadPolicy="remote";this.LoadAsset(runtime,opts);
+return this._imageAsset.Load()}async LoadDynamicBlobAsset(runtime,blob){if(this._imageAsset)throw new Error("already loaded asset");this._url="";this._size=blob.size;this._imageAsset=C3.New(C3.ImageAsset,runtime.GetAssetManager(),{blob,size:this._size,loadPolicy:"local"})}ReplaceWith(otherImageInfo){if(otherImageInfo===this)throw new Error("cannot replace with self");this._generation++;this.ReleaseTexture();this._url=otherImageInfo._url;this._size=otherImageInfo._size;this._offsetX=otherImageInfo._offsetX;
+this._offsetY=otherImageInfo._offsetY;this._width=otherImageInfo._width;this._height=otherImageInfo._height;this._isRotated=otherImageInfo._isRotated;this._hasMetaData=otherImageInfo._hasMetaData;this._imageAsset=otherImageInfo._imageAsset;this._textureState=otherImageInfo._textureState;this._rcTex=otherImageInfo._rcTex;this._quadTex=otherImageInfo._quadTex;this.ReleaseBlobURL()}GetURL(){return this._url}GetSize(){return this._size}GetOffsetX(){return this._offsetX}GetOffsetY(){return this._offsetY}IsRotated(){return this._isRotated}GetWidth(){return this._width}GetHeight(){return this._height}GetSheetWidth(){return this._imageAsset.GetWidth()}GetSheetHeight(){return this._imageAsset.GetHeight()}LoadAsset(runtime,
+opts){if(this._imageAsset)throw new Error("already got asset");opts=Object.assign({},opts,{url:this.GetURL(),size:this.GetSize()});this._imageAsset=runtime.LoadImage(opts)}IsLoaded(){return this._imageAsset&&this._imageAsset.IsLoaded()}async LoadStaticTexture(renderer,opts){if(!this._imageAsset)throw new Error("no asset");if(this._textureState)throw new Error("already loaded texture");const startGeneration=this._generation;this._textureState="loading";const texture=await this._imageAsset.LoadStaticTexture(renderer,
+opts);if(this._generation!==startGeneration)return null;if(!texture){this._textureState="";return null}this._textureState="loaded";if(!this._hasMetaData){this._width=texture.GetWidth();this._height=texture.GetHeight();this._hasMetaData=true}const wr=this._isRotated?this._height:this._width;const hr=this._isRotated?this._width:this._height;this._rcTex.set(this._offsetX,this._offsetY,this._offsetX+wr,this._offsetY+hr);this._rcTex.divide(texture.GetWidth(),texture.GetHeight());this._quadTex.setFromRect(this._rcTex);
+if(this._isRotated)this._quadTex.rotatePointsAnticlockwise();return texture}ReleaseTexture(){if(!this._textureState)return;if(this._imageAsset)this._imageAsset.ReleaseTexture();this._textureState="";this._rcTex.set(0,0,0,0);this._quadTex.setFromRect(this._rcTex)}GetTexture(){return this._imageAsset&&this._textureState==="loaded"?this._imageAsset.GetTexture():null}GetTexRect(){return this._rcTex}GetTexQuad(){return this._quadTex}GetIImageInfo(){return this._iImageInfo}GetImageAsset(){return this._imageAsset}async ExtractImageToCanvas(drawable){if(!drawable)drawable=
+await this._imageAsset.LoadToDrawable();const canvas=C3.CreateCanvas(this._width,this._height);const ctx=canvas.getContext("2d");if(this._isRotated){ctx.rotate(Math.PI/-2);ctx.translate(-this._height,0);ctx.drawImage(drawable,this._offsetX,this._offsetY,this._height,this._width,0,0,this._height,this._width)}else ctx.drawImage(drawable,this._offsetX,this._offsetY,this._width,this._height,0,0,this._width,this._height);return canvas}async ExtractImageToBlobURL(drawable){if(this._blobUrl)return this._blobUrl;
+const canvas=await this.ExtractImageToCanvas(drawable);const blob=await C3.CanvasToBlob(canvas);this._blobUrl=URL.createObjectURL(blob);return this._blobUrl}ReleaseBlobURL(){if(this._blobUrl){URL.revokeObjectURL(this._blobUrl);this._blobUrl=""}}};
+
+}
+
+// objects/animationInfo.js
+{
+'use strict';const C3=self.C3;
+C3.AnimationInfo=class AnimationInfo extends C3.DefendedBase{constructor(animData){super();this._name=animData[0];this._speed=animData[1];this._isLooping=!!animData[2];this._repeatCount=animData[3];this._repeatTo=animData[4];this._isPingPong=!!animData[5];this._sid=animData[6];this._frames=animData[7].map(frameData=>C3.New(C3.AnimationFrameInfo,frameData));this._iAnimation=new self.IAnimation(this)}Release(){for(const f of this._frames)f.Release();C3.clearArray(this._frames)}LoadAllAssets(runtime){for(const f of this._frames)f.GetImageInfo().LoadAsset(runtime)}LoadAllTextures(renderer,opts){return Promise.all(this._frames.map(f=>
+f.GetImageInfo().LoadStaticTexture(renderer,opts)))}ReleaseAllTextures(){for(const f of this._frames)f.GetImageInfo().ReleaseTexture()}GetName(){return this._name}GetSID(){return this._sid}GetFrameCount(){return this._frames.length}GetFrames(){return this._frames}GetFrameAt(i){i=Math.floor(i);if(i<0||i>=this._frames.length)throw new RangeError("invalid frame");return this._frames[i]}GetFrameIndexByTag(tag){for(let i=0,len=this._frames.length;iC3.New(C3.ImagePoint,this,data));this._imagePointsByName=new Map;for(const ip of this._imagePoints)this._imagePointsByName.set(ip.GetName().toLowerCase(),ip);this._collisionPoly=null;const polyPoints=
+frameData[11];if(polyPoints.length>=6)this._collisionPoly=C3.New(C3.CollisionPoly,polyPoints);this._tag=frameData[12]?frameData[12]:"";this._iAnimationFrame=new self.IAnimationFrame(this)}Release(){if(this._collisionPoly){this._collisionPoly.Release();this._collisionPoly=null}this._imageInfo.Release();this._imageInfo=null}GetImageInfo(){return this._imageInfo}GetDuration(){return this._duration}GetOriginX(){return this._origin.getX()}GetOriginY(){return this._origin.getY()}GetCollisionPoly(){return this._collisionPoly}GetImagePointByName(name){return this._imagePointsByName.get(name.toLowerCase())||
+null}GetImagePointByIndex(index){index=Math.floor(index);if(index<0||index>=this._imagePoints.length)return null;return this._imagePoints[index]}GetImagePointCount(){return this._imagePoints.length}GetTag(){return this._tag}GetIAnimationFrame(){return this._iAnimationFrame}};
+
+}
+
+// objects/imagePoint.js
+{
+'use strict';const C3=self.C3;C3.ImagePoint=class ImagePoint extends C3.DefendedBase{constructor(afi,data){super();this._afi=afi;this._name=data[0];this._pos=C3.New(C3.Vector2,data[1],data[2])}Release(){}GetName(){return this._name}GetX(){return this._pos.getX()}GetY(){return this._pos.getY()}GetVec2(){return this._pos}};
+
+}
+
+// objects/objectClass.js
+{
+'use strict';const C3=self.C3;const C3Debugger=self.C3Debugger;const IObjectClass=self.IObjectClass;const assert=self.assert;
+C3.ObjectClass=class ObjectClass extends C3.DefendedBase{constructor(runtime,index,data){super();const PluginCtor=runtime.GetObjectReference(data[1]);this._runtime=runtime;this._plugin=runtime.GetPluginManager().GetPluginByConstructorFunction(PluginCtor);this._sdkType=null;this._instSdkCtor=PluginCtor.Instance;this._index=index;this._sid=data[11];this._name=data[0];this._jsPropName=this._runtime.GetJsPropName(data[14]);this._isGlobal=!!data[9];this._isFamily=!!data[2];this._isOnLoaderLayout=!!data[10];
+this._instVars=data[3].map(arr=>({sid:arr[0],type:arr[1],name:arr[2],jsPropName:runtime.GetJsPropName(arr[3])}));this._behaviorsCount=data[4];this._effectsCount=data[5];this._isWorldType=this._plugin.IsWorldType();this._dispatcher=C3.New(C3.Event.Dispatcher);this._effectList=null;const [collisionCellWidth,collisionCellHeight]=runtime.GetCollisionEngine().GetCollisionCellSize();this._collisionGrid=C3.New(C3.SparseGrid,collisionCellWidth,collisionCellHeight);this._anyCollisionCellChanged=true;this._anyInstanceParallaxed=
+false;this._familyMembers=null;this._familyMembersSet=null;this._familyIndex=-1;this._families=null;this._familiesSet=null;this._familyInstVarMap=null;this._familyBehaviorMap=null;this._familyEffectMap=null;this._isInContainer=false;this._container=null;this._behaviorTypes=data[8].map(behaviorTypeData=>C3.BehaviorType.Create(this,behaviorTypeData));this._behaviorTypesIncludingInherited=[];this._behaviorsByName=new Map;this._behaviorNameToIndex=new Map;this._usedBehaviorCtors=new Set;this._customActionMap=
+new Map;this._solStack=C3.New(C3.SolStack,this);this._defaultInstanceData=null;this._defaultLayerIndex=0;this._isContained=false;this._container=null;this._imageInfo=null;this._animations=null;this._animationsByName=null;this._animationsBySid=null;this._textureRefCount=0;this._savedData=new Map;this._unsavedData=new Map;this._instances=[];this._iidsStale=true;if(this._plugin.HasEffects())this._effectList=C3.New(C3.EffectList,this,data[12]);if(data[6]){this._imageInfo=C3.New(C3.ImageInfo);this._imageInfo.LoadData(data[6])}if(data[7]){this._animations=
+data[7].map(animData=>C3.New(C3.AnimationInfo,animData));this._animationsByName=new Map;this._animationsBySid=new Map;for(const anim of this._animations){this._animationsByName.set(anim.GetName().toLowerCase(),anim);this._animationsBySid.set(anim.GetSID(),anim)}}if(this._isFamily){this._familyMembers=[];this._familyMembersSet=new Set;this._familyIndex=this._runtime._GetNextFamilyIndex()}else{this._families=[];this._familiesSet=new Set;this._familyInstVarMap=[];this._familyBehaviorMap=[];this._familyEffectMap=
+[]}this._sdkType=C3.New(PluginCtor.Type,this,data[15]);this._iObjectClass=null;this._instanceUserScriptClass=null;this._userScriptDispatcher=C3.New(C3.Event.Dispatcher);const CustomScriptClass=this._sdkType.GetScriptInterfaceClass();if(CustomScriptClass){this._iObjectClass=new CustomScriptClass(this);if(!(this._iObjectClass instanceof IObjectClass))throw new TypeError("script interface class must derive from IObjectClass");}else this._iObjectClass=new IObjectClass(this);if(data[13]){const tilemapData=
+data[13];if(tilemapData){const tilePolyData=tilemapData[0];const maxTileIndex=tilemapData[1];const brushData=tilemapData[2];this._sdkType.LoadTilemapData(tilePolyData,maxTileIndex,brushData)}}if(!this._runtime.UsesLoaderLayout()||this._isFamily||this._isOnLoaderLayout||!this._isWorldType)this.OnCreate();if(this._plugin.IsSingleGlobal()){this._plugin._SetSingleGlobalObjectClass(this);this._CreateSingleGlobalInstance(data)}this._loadInstancesJson=null}static Create(runtime,index,objectClassData){return C3.New(C3.ObjectClass,
+runtime,index,objectClassData)}Release(){this._dispatcher.Release();this._dispatcher=null;if(this._imageInfo){this._imageInfo.Release();this._imageInfo=null}if(this._animations){for(const a of this._animations)a.Release();C3.clearArray(this._animations);this._animationsByName.clear();this._animationsBySid.clear()}this._loadInstancesJson=null;this._solStack.Release();this._solStack=null;this._savedData.clear();this._unsavedData.clear();this._container=null;this._runtime=null}_LoadFamily(familyData){for(let i=
+1,len=familyData.length;i0}LoadTextures(renderer){if(this._isFamily)return Promise.resolve();this._textureRefCount++;if(this._textureRefCount===1)return this._sdkType.LoadTextures(renderer)||
+Promise.resolve();else return Promise.resolve()}ReleaseTextures(){if(this._isFamily)return;this._textureRefCount--;if(this._textureRefCount<0)throw new Error("released textures too many times");if(this._textureRefCount===0)this._sdkType.ReleaseTextures()}OnDynamicTextureLoadComplete(){if(this._isFamily)throw new Error("not applicable to family");this._sdkType.OnDynamicTextureLoadComplete()}PreloadTexturesWithInstances(renderer){if(this._isFamily)return Promise.resolve();return this._sdkType.PreloadTexturesWithInstances(renderer)}GetRuntime(){return this._runtime}GetPlugin(){return this._plugin}GetInstanceSdkCtor(){return this._instSdkCtor}GetName(){return this._name}GetJsPropName(){return this._jsPropName}GetIndex(){return this._index}GetSID(){return this._sid}IsFamily(){return this._isFamily}IsGlobal(){return this._isGlobal}IsWorldType(){return this._isWorldType}GetFamilyIndex(){return this._familyIndex}GetBehaviorTypes(){return this._behaviorTypes}GetBehaviorTypesCount(){return this._behaviorsCount}UsesBehaviorByCtor(Ctor){return Ctor&&
+this._usedBehaviorCtors.has(Ctor)}GetInstanceVariablesCount(){return this._instVars.length}GetInstanceVariableSIDs(){return this._instVars.map(iv=>iv.sid)}GetInstanceVariableIndexBySID(sid){return this._instVars.findIndex(iv=>iv.sid===sid)}GetInstanceVariableIndexByName(name){return this._instVars.findIndex(iv=>iv.name===name)}_GetAllInstanceVariableNames(){return this._instVars.map(iv=>iv.name)}_GetAllInstanceVariableJsPropNames(){return this._instVars.map(iv=>iv.jsPropName)}GetInstanceVariableType(i){i=
+Math.floor(i);if(i<0||i>=this._instVars.length)throw new RangeError("invalid instance variable index");return this._instVars[i].type}GetInstanceVariableName(i){i=Math.floor(i);if(i<0||i>=this._instVars.length)throw new RangeError("invalid instance variable index");return this._instVars[i].name}GetEffectTypesCount(){return this._effectsCount}GetBehaviorTypesIncludingInherited(){return this._behaviorTypesIncludingInherited}GetBehaviorTypeByName(name){return this._behaviorsByName.get(name.toLowerCase())||
+null}GetBehaviorIndexByName(name){const ret=this._behaviorNameToIndex.get(name.toLowerCase());if(typeof ret==="undefined")return-1;else return ret}GetEffectList(){return this._effectList}HasEffects(){return this._plugin.HasEffects()}UsesEffects(){return this._effectList&&this._effectList.HasAnyEffectType()}GetSolStack(){return this._solStack}GetCurrentSol(){return this._solStack.GetCurrentSol()}GetImageInfo(){return this._imageInfo}SetDefaultInstanceData(d){this._defaultInstanceData=d}GetDefaultInstanceData(){return this._defaultInstanceData}_SetDefaultLayerIndex(i){this._defaultLayerIndex=
+i}GetDefaultLayerIndex(){return this._defaultLayerIndex}GetAnimations(){return this._animations}GetAnimationCount(){return this._animations.length}GetFamilies(){return this._families}BelongsToFamily(family){return this._familiesSet.has(family)}GetFamilyMembers(){return this._familyMembers}FamilyHasMember(objectType){return this._familyMembersSet.has(objectType)}GetFamilyBehaviorOffset(familyIndex){return this._familyBehaviorMap[familyIndex]}GetFamilyInstanceVariableOffset(familyIndex){return this._familyInstVarMap[familyIndex]}AddCustomAction(customAceBlock){this._customActionMap.set(customAceBlock.GetACEName().toLowerCase(),
+customAceBlock)}HasOwnCustomActionByName(name){return!!this.GetOwnCustomActionByName(name)}GetOwnCustomActionByName(name){const ret=this._customActionMap.get(name.toLowerCase());return ret&&ret.IsEnabled()?ret:null}GetAnimationByName(name){if(!this._animations)throw new Error("no animations");return this._animationsByName.get(name.toLowerCase())||null}GetAnimationBySID(sid){if(!this._animations)throw new Error("no animations");return this._animationsBySid.get(sid)||null}GetFirstAnimationFrame(){if(!this._animations)throw new Error("no animations");
+return this._animations[0].GetFrameAt(0)}GetDefaultInstanceSize(){if(this._animations){const firstFrameInfo=this.GetFirstAnimationFrame().GetImageInfo();return[firstFrameInfo.GetWidth(),firstFrameInfo.GetHeight()]}else if(this._imageInfo)return[this._imageInfo.GetWidth(),this._imageInfo.GetHeight()];else return[100,100]}GetSingleGlobalInstance(){if(!this._plugin.IsSingleGlobal())throw new Error("not a single-global plugin");return this._instances[0]}GetInstances(){return this._instances}*instances(){yield*this._instances}*instancesIncludingPendingCreate(){yield*this._instances;
+yield*this._runtime.instancesPendingCreateForObjectClass(this)}GetInstanceCount(){return this._instances.length}_AddInstance(inst){this._instances.push(inst)}_SetIIDsStale(){this._iidsStale=true}_UpdateIIDs(){if(!this._iidsStale||this._isFamily)return;const instances=this._instances;let i=0;for(let len=instances.length;i0)return instances[inst.GetIID()%instances.length];else return null}*allCorrespondingInstances(inst,objectClass){const myInstances=this.GetCurrentSol().GetInstances();const myInstanceCount=myInstances.length;const otherSol=objectClass.GetCurrentSol();const otherInstances=objectClass.GetCurrentSol().GetInstances();
+const otherInstanceCount=otherInstances.length;let index=inst.GetIID();if(objectClass.IsFamily()||!otherSol.IsSelectAll())index=otherInstances.indexOf(inst);const divisor=Math.ceil(myInstanceCount/otherInstanceCount);const remainder=myInstanceCount%otherInstanceCount;let startIndex=0;let correspondCount=0;if(remainder===0||indexinst.SaveToJson())};if(this._savedData&&this._savedData.size)o["ex"]=C3.ToSuperJSON(this._savedData);return o}_LoadFromJson(o){if(this._savedData){this._savedData.clear();this._savedData=null}const ex=o["ex"];if(ex)this._savedData=C3.FromSuperJSON(ex);const existingInstances=this._instances;const loadInstances=o["instances"];for(let i=0,len=Math.min(existingInstances.length,loadInstances.length);io.IsWorldType())}};
+
+}
+
+// objects/instance.js
+{
+'use strict';const C3=self.C3;const C3Debugger=self.C3Debugger;const IInstance=self.IInstance;const EMPTY_ARRAY=[];let nextPuid=0;const savedDataMaps=new WeakMap;const unsavedDataMaps=new WeakMap;const FLAG_DESTROYED=1<<0;const FLAG_TILEMAP=1<<1;const FLAG_MUST_PREDRAW=1<<2;const FLAG_SOLID_ENABLED=1<<3;const FLAG_JUMPTHRU_ENABLED=1<<4;const FLAG_MUST_MITIGATE_Z_FIGHTING=1<<5;const FLAG_IS_DRAWING_WITH_EFFECTS=1<<6;
+C3.Instance=class Instance extends C3.DefendedBase{constructor(opts){super();this._runtime=opts.runtime;this._objectType=opts.objectType;this._worldInfo=null;this._sdkInst=null;this._iScriptInterface=null;this._iid=0;this._uid=opts.uid;this._puid=nextPuid++;this._flags=0;this._instVarValues=EMPTY_ARRAY;this._behaviorInstances=EMPTY_ARRAY;const behaviorTypes=this._objectType.GetBehaviorTypesIncludingInherited();if(behaviorTypes.length>0)this._behaviorInstances=behaviorTypes.map((behaviorType,index)=>
+C3.New(C3.BehaviorInstance,{runtime:this._runtime,behaviorType:behaviorType,instance:this,index}));this._siblings=this._objectType.IsInContainer()?[]:null;this._timeScale=-1;this._dispatcher=null;const plugin=this.GetPlugin();if(plugin.MustPreDraw())this._flags|=FLAG_MUST_PREDRAW;if(plugin.IsWorldType()){this._worldInfo=C3.New(C3.WorldInfo,this,opts.layer);if(opts.worldData)this._worldInfo.Init(opts.worldData);else{this._worldInfo.InitNoData();const [width,height]=this._objectType.GetDefaultInstanceSize();
+this._worldInfo.SetSize(width,height);if(this.GetObjectClass().UsesEffects())this._worldInfo.GetInstanceEffectList().LoadDefaultEffectParameters()}}if(opts.instVarData)this._LoadInstanceVariableData(opts.instVarData);else this._LoadDefaultInstanceVariables()}Release(){if(this._iScriptInterface){this._iScriptInterface._Release();this._iScriptInterface=null}if(this._behaviorInstances.length>0){for(const behInst of this._behaviorInstances)behInst.Release();C3.clearArray(this._behaviorInstances)}this._sdkInst.Release();
+this._sdkInst=null;const savedData=savedDataMaps.get(this);if(savedData){savedData.clear();savedDataMaps.delete(this)}const unsavedData=unsavedDataMaps.get(this);if(unsavedData){unsavedData.clear();unsavedDataMaps.delete(this)}if(this._siblings)C3.clearArray(this._siblings);if(this._dispatcher){this._dispatcher.Release();this._dispatcher=null}this._runtime=null;this._objectType=null;if(this._instVarValues.length>0)C3.clearArray(this._instVarValues);if(this._worldInfo){this._worldInfo.Release();this._worldInfo=
+null}}_LoadInstanceVariableData(instVarData){if(instVarData.length>0){this._instVarValues=[];C3.shallowAssignArray(this._instVarValues,instVarData)}}_LoadDefaultInstanceVariables(){const len=this._objectType.GetInstanceVariablesCount();if(len===0)return;this._instVarValues=[];const typeToInitValue=[0,0,""];for(let i=0;i{const objectClass=objectClass_||inst.GetObjectClass();const instSet=pickMap.get(objectClass);if(instSet)instSet.add(inst);else pickMap.set(objectClass,new Set([inst]))};addInst(this,createdObjectClass);if(this.IsInContainer())for(const s of this.siblings())addInst(s);if(includeHierarchy)for(const c of this.allChildren())addInst(c)}VerifySupportsSceneGraph(){if(!this.GetPlugin().SupportsSceneGraph())throw new Error("object does not support scene graph");
+}HasParent(){return this.GetParent()!==null}GetParent(){const wi=this.GetWorldInfo();if(!wi)return null;const parentWi=wi.GetParent();return parentWi?parentWi.GetInstance():null}GetTopParent(){const wi=this.GetWorldInfo();if(!wi)return null;const parentWi=wi.GetTopParent();return parentWi?parentWi.GetInstance():null}*parents(){const wi=this.GetWorldInfo();if(!wi)return;for(const parentWi of wi.parents())yield parentWi.GetInstance()}HasChild(child){if(!child)return false;for(const c of this.children())if(c===
+child)return true;return false}HasChildren(){const wi=this.GetWorldInfo();return wi?wi.HasChildren():false}GetChildrenOfObjectClass(objectClass){const wi=this.GetWorldInfo();if(!wi)return[];const objectClassName=objectClass.GetName();return wi.GetChildren().map(wi=>wi.GetInstance()).filter(i=>i.GetObjectClass().GetName()===objectClassName)}GetChildren(){const wi=this.GetWorldInfo();if(!wi)return[];return wi.GetChildren().map(wi=>wi.GetInstance())}*children(){const wi=this.GetWorldInfo();if(!wi)return;
+for(const childWi of wi.children())yield childWi.GetInstance()}*allChildren(){const wi=this.GetWorldInfo();if(!wi)return;for(const childWi of wi.allChildren())yield childWi.GetInstance()}GetChildCount(){const wi=this.GetWorldInfo();return wi?wi.GetChildCount():0}GetParentCount(){return[...this.parents()].length}GetAllChildCount(){const wi=this.GetWorldInfo();return wi?wi.GetAllChildCount():0}GetChildAt(index){const wi=this.GetWorldInfo();if(!wi)return null;const childWi=wi.GetChildAt(index);return childWi?
+childWi.GetInstance():null}AddChild(childInst,opts){this.VerifySupportsSceneGraph();childInst.VerifySupportsSceneGraph();this.GetWorldInfo().AddChild(childInst.GetWorldInfo(),opts||{})}RemoveChild(childInst){const wi=this.GetWorldInfo();if(!wi)return;wi.RemoveChild(childInst.GetWorldInfo())}GetDestroyWithParent(){const wi=this.GetWorldInfo();return wi?wi.GetDestroyWithParent():false}SetupInitialSceneGraphConnections(){const wi=this.GetWorldInfo();if(!wi)return;const childrenData=wi.GetSceneGraphChildrenExportData();
+if(!childrenData)return;for(const childData of childrenData){const child=this._runtime.GetInstanceByUID(childData[2]);if(child){const flags=childData[3];this.AddChild(child,{transformX:!!(flags>>0&1),transformY:!!(flags>>1&1),transformWidth:!!(flags>>2&1),transformHeight:!!(flags>>3&1),transformAngle:!!(flags>>4&1),destroyWithParent:!!(flags>>5&1),transformZElevation:!!(flags>>6&1),transformOpacity:!!(flags>>7&1),transformVisibility:!!(flags>>8&1)})}}}SetupPersistedSceneGraphConnections(instanceToPersistedDataMap,
+persistedIndexToInstanceMap){const persistedData=instanceToPersistedDataMap.get(this);if(!persistedData)return;for(const persistedChildData of persistedData["sceneGraphJson"]["children"]){const child=persistedIndexToInstanceMap.get(persistedChildData["index"]);if(!child)continue;const flags=persistedChildData["flags"];this.AddChild(child,{transformX:!!(flags>>0&1),transformY:!!(flags>>1&1),transformWidth:!!(flags>>2&1),transformHeight:!!(flags>>3&1),transformAngle:!!(flags>>4&1),destroyWithParent:!!(flags>>
+5&1),transformZElevation:!!(flags>>6&1),transformOpacity:!!(flags>>7&1),transformVisibility:!!(flags>>8&1)})}}GetTemplateName(){const templateManager=this._runtime.GetTemplateManager();return templateManager?templateManager.GetInstanceTemplateName(this):""}IsInContainer(){return this._siblings!==null}_AddSibling(inst){this._siblings.push(inst)}GetSiblings(){return this._siblings}HasSibling(objectClass){return!!this.GetSibling(objectClass)}GetSibling(objectClass){const siblings=this.siblings();if(siblings===
+null||siblings.length===0)return false;for(const s of siblings)if(s.GetObjectClass()===objectClass)return s;return null}siblings(){return this._siblings}SetSiblingsSinglePicked(){for(const s of this.siblings())s.GetObjectClass().GetCurrentSol().SetSinglePicked(s)}_PushSiblingsToSolInstances(){for(const s of this.siblings())s.GetObjectClass().GetCurrentSol()._PushInstance(s)}_SetSiblingsToSolInstancesIndex(i){for(const s of this.siblings())s.GetObjectClass().GetCurrentSol()._GetOwnInstances()[i]=s}_PushSiblingsToSolElseInstances(){for(const s of this.siblings())s.GetObjectClass().GetCurrentSol()._PushElseInstance(s)}_SetSiblingsToSolElseInstancesIndex(i){for(const s of this.siblings())s.GetObjectClass().GetCurrentSol()._GetOwnElseInstances()[i]=
+s}GetPlugin(){return this._objectType.GetPlugin()}_SetIID(i){this._iid=i}GetIID(){this._objectType._UpdateIIDs();return this._iid}GetUID(){return this._uid}GetPUID(){return this._puid}GetBehaviorInstances(){return this._behaviorInstances}GetBehaviorInstanceFromCtor(ctor){if(!ctor)return null;for(const behInst of this._behaviorInstances)if(behInst.GetBehavior()instanceof ctor)return behInst;return null}GetBehaviorSdkInstanceFromCtor(ctor){if(!ctor)return null;const behInst=this.GetBehaviorInstanceFromCtor(ctor);
+if(behInst)return behInst.GetSdkInstance();else return null}GetBehaviorIndexBySID(sid){const behaviorInstances=this._behaviorInstances;for(let i=0,len=behaviorInstances.length;i=instVarValues.length)throw new RangeError("invalid instance variable");return instVarValues[index]}_GetInstanceVariableValueUnchecked(index){return this._instVarValues[index]}_GetInstanceVariableTypedValue(index){const ret=this._instVarValues[index];if(this._objectType.GetInstanceVariableType(index)===0)return!!ret;else return ret}SetInstanceVariableValue(index,value){index=index|0;const instVarValues=this._instVarValues;if(index<
+0||index>=instVarValues.length)throw new RangeError("invalid instance variable");const type=this._objectType.GetInstanceVariableType(index);switch(type){case 0:instVarValues[index]=value?1:0;break;case 1:instVarValues[index]=typeof value==="number"?value:parseFloat(value);break;case 2:instVarValues[index]=typeof value==="string"?value:value.toString();break;default:throw new Error("unknown instance variable type");}}SetInstanceVariableOffset(index,offset){if(offset===0)return;index=index|0;const instVarValues=
+this._instVarValues;if(index<0||index>=instVarValues.length)throw new RangeError("invalid instance variable");const lastValue=instVarValues[index];if(typeof lastValue==="number")if(typeof offset==="number")instVarValues[index]+=offset;else instVarValues[index]+=parseFloat(offset);else if(typeof lastValue==="boolean")throw new Error("can not set offset of boolean variable");else if(typeof lastValue==="string")throw new Error("can not set offset of string variable");else throw new Error("unknown instance variable type");
+}GetSavedDataMap(){let ret=savedDataMaps.get(this);if(ret)return ret;ret=new Map;savedDataMaps.set(this,ret);return ret}GetUnsavedDataMap(){let ret=unsavedDataMaps.get(this);if(ret)return ret;ret=new Map;unsavedDataMaps.set(this,ret);return ret}_HasAnyCreateDestroyHandler(name){const objectType=this.GetObjectClass();if(objectType.UserScriptDispatcher().HasAnyHandlerFor(name))return true;for(const family of objectType.GetFamilies())if(family.UserScriptDispatcher().HasAnyHandlerFor(name))return true;
+if(this._runtime.UserScriptDispatcher().HasAnyHandlerFor(name))return true;return false}_TriggerOnCreatedOnSelfAndRelated(){const instancesToTriggerOnCreated=new Set;instancesToTriggerOnCreated.add(this);const wi=this.GetWorldInfo();if(wi&&wi.HasChildren())for(const c of this.allChildren()){instancesToTriggerOnCreated.add(c);if(!c.IsInContainer())continue;for(const s of c.siblings())instancesToTriggerOnCreated.add(s)}if(this.IsInContainer())for(const s of this.siblings())instancesToTriggerOnCreated.add(s);
+for(const instance of instancesToTriggerOnCreated.values())instance._TriggerOnCreated()}_TriggerOnCreated(){if(this._objectType._GetUserScriptInstanceClass())this.GetInterfaceClass();if(this._HasAnyCreateDestroyHandler("instancecreate")){const objectType=this.GetObjectClass();const instCreateEvent=new C3.Event("instancecreate");instCreateEvent.instance=this.GetInterfaceClass();objectType.DispatchUserScriptEvent(instCreateEvent);for(const family of objectType.GetFamilies())family.DispatchUserScriptEvent(instCreateEvent);
+this._runtime.DispatchUserScriptEvent(instCreateEvent)}this._runtime.Trigger(this.GetPlugin().constructor.Cnds.OnCreated,this,null)}_TriggerOnDestroyed(){this._runtime.Trigger(this.GetPlugin().constructor.Cnds.OnDestroyed,this,null)}_FireDestroyedScriptEvents(isEndingLayout){if(this._iScriptInterface){const e=new C3.Event("destroy");e.isEndingLayout=isEndingLayout;this.DispatchUserScriptEvent(e)}if(!this._HasAnyCreateDestroyHandler("instancedestroy"))return;const objectType=this.GetObjectClass();
+const instDestroyEvent=new C3.Event("instancedestroy");instDestroyEvent.instance=this.GetInterfaceClass();instDestroyEvent.isEndingLayout=isEndingLayout;objectType.DispatchUserScriptEvent(instDestroyEvent);for(const family of objectType.GetFamilies())family.DispatchUserScriptEvent(instDestroyEvent);this._runtime.DispatchUserScriptEvent(instDestroyEvent)}_GetDebuggerProperties(){return this._sdkInst.GetDebuggerProperties()}SaveToJson(mode="full"){const o={};if(mode==="full")o["uid"]=this.GetUID();
+else o["c3"]=true;if(mode!=="visual-state"){const savedData=savedDataMaps.get(this);if(savedData&&savedData.size)o["ex"]=C3.ToSuperJSON(savedData);if(this.GetTimeScale()!==-1)o["mts"]=this.GetTimeScale();if(this._objectType.GetInstanceVariablesCount()>0){const ivs={};const ivSids=this._objectType.GetInstanceVariableSIDs();for(let i=0,len=this._instVarValues.length;i=this._instVarValues.length)continue;let v=value;if(v===null)v=NaN;this._instVarValues[index]=v}}if(this.GetPlugin().IsWorldType()){const worldData=o["w"];const layerSid=worldData["l"];if(this._worldInfo.GetLayer().GetSID()!==layerSid){const oldLayer=this._worldInfo.GetLayer();const newLayer=oldLayer.GetLayout().GetLayerBySID(layerSid);
+if(newLayer){this._worldInfo._SetLayer(newLayer);oldLayer._RemoveInstance(this,true);newLayer._AddInstance(this,true);newLayer.SetZIndicesChanged(this);this._worldInfo.SetBboxChanged()}else if(mode==="full")this._runtime.DestroyInstance(this)}this._worldInfo._LoadFromJson(worldData,mode)}if(mode!=="visual-state"){const behs=o["behs"];if(behs)for(const [sidStr,data]of Object.entries(behs)){const sid=parseInt(sidStr,10);const index=this.GetBehaviorIndexBySID(sid);if(index<0||index>=this._behaviorInstances.length)continue;
+this._behaviorInstances[index].LoadFromJson(data)}}const ownData=o["data"];if(ownData)this._sdkInst.LoadFromJson(ownData,mode)}GetInterfaceClass(){return this._iScriptInterface||this._InitUserScriptInterface()}HasScriptInterface(){return!!this._iScriptInterface}_InitUserScriptInterface(){const DefaultScriptClass=this._worldInfo?self.IWorldInstance:IInstance;const SdkScriptClass=this._sdkInst.GetScriptInterfaceClass();const UserScriptClass=this._objectType._GetUserScriptInstanceClass();const ScriptInterfaceClass=
+UserScriptClass||SdkScriptClass||DefaultScriptClass;IInstance._Init(this);this._iScriptInterface=new ScriptInterfaceClass;IInstance._Init(null);if(SdkScriptClass&&!(this._iScriptInterface instanceof DefaultScriptClass))throw new TypeError(`script interface class '${SdkScriptClass.name}' does not extend the right base class '${DefaultScriptClass.name}'`);if(UserScriptClass){const ExpectedBaseClass=SdkScriptClass||DefaultScriptClass;if(!(this._iScriptInterface instanceof ExpectedBaseClass))throw new TypeError(`setInstanceClass(): class '${UserScriptClass.name}' does not extend the right base class - check it extends the right class, e.g. globalThis.InstanceType.MyObjectName`);
+}return this._iScriptInterface}_GetInstVarsScriptDescriptor(instDescriptors){if(this._instVarValues.length===0)return;const varDescriptors={};const instVarJsPropNames=this._objectType._GetAllInstanceVariableJsPropNames();for(let i=0,len=instVarJsPropNames.length;i0}GetChildren(){return this._children}_MaybeSortChildren(){if(!this.HasChildren())return;if(!this._tmpSceneGraphChildrenIndexes)return;if(this._children.length===1)return;this._children.sort((f,s)=>{const fIndex=this._tmpSceneGraphChildrenIndexes.get(f.GetInstance());
+const sIndex=this._tmpSceneGraphChildrenIndexes.get(s.GetInstance());if(C3.IsFiniteNumber(fIndex)&&C3.IsFiniteNumber(sIndex))return fIndex-sIndex;return 0})}GetStartScaleX(){return this._startScaleX}SetStartScaleX(sx){this._startScaleX=sx}GetStartScaleY(){return this._startScaleY}SetStartScaleY(sy){this._startScaleY=sy}GetStartOpacity(){return this._startOpacity}GetOwnOpacity(){return this._ownOpacity}SetOwnOpacity(ownOpacity){this._ownOpacity=ownOpacity}_GetStartWidth(){if(this._startWidth===0)return Number.EPSILON;
+return this._startWidth}_GetStartHeight(){if(this._startHeight===0)return Number.EPSILON;return this._startHeight}GetParentScaleX(){if(this._owner.GetTransformWithParentWidth()){const p=this._parent;let cw=p.GetWidth();let sw=p._GetSceneGraphInfo()._GetStartWidth();if(cw===0)cw=Number.EPSILON;if(sw===Number.EPSILON&&cw===Number.EPSILON)return 1;if(sw===Number.EPSILON&&cw!==Number.EPSILON){const sdkIntance=p.GetInstance().GetSdkInstance();if(sdkIntance.IsOriginalSizeKnown())return 1+cw/sdkIntance.GetOriginalWidth()}return cw/
+sw}return 1}GetParentScaleY(){if(this._owner.GetTransformWithParentHeight()){const p=this._parent;let ch=p.GetHeight();let sh=p._GetSceneGraphInfo()._GetStartHeight();if(ch===0)ch=Number.EPSILON;if(sh===Number.EPSILON&&ch===Number.EPSILON)return 1;if(sh===Number.EPSILON&&ch!==Number.EPSILON){const sdkIntance=p.GetInstance().GetSdkInstance();if(sdkIntance.IsOriginalSizeKnown())return 1+ch/sdkIntance.GetOriginalHeight()}return ch/sh}return 1}GetParentStartAngle(){return this._parentStartAngle}_SaveToJsonProperties(){return{"sw":this._startWidth,
+"sh":this._startHeight,"sx":this._startScaleX,"sy":this._startScaleY,"psa":this._parentStartAngle,"oo":this._ownOpacity,"so":this._startOpacity}}_SaveToJson(mode){return Object.assign(this._SaveToJsonProperties(),{"p":this._GetParentJson(mode),"c":this._GetChildrenJson(mode)})}_GetFlagsString(wi){let flagsStr="";if(wi.GetTransformWithParentX())flagsStr+="x";if(wi.GetTransformWithParentY())flagsStr+="y";if(wi.GetTransformWithParentWidth())flagsStr+="w";if(wi.GetTransformWithParentHeight())flagsStr+=
+"h";if(wi.GetTransformWithParentAngle())flagsStr+="a";if(wi.GetTransformWithParentZElevation())flagsStr+="z";if(wi.GetDestroyWithParent())flagsStr+="d";if(wi.GetTransformWithParentOpacity())flagsStr+="o";if(wi.GetTransformWithParentVisibility())flagsStr+="v";return flagsStr}_GetParentJson(mode){if(!this._parent)return null;if(!this._parent.GetInstance()||this._parent.GetInstance().IsDestroyed())return null;return this._GetInstanceJson(this._parent,this._owner,mode)}_GetChildrenJson(mode){return this._children.map(c=>
+{return this._GetInstanceJson(c,c,mode)})}_GetInstanceJson(wi,flagsSource,mode){const inst=wi.GetInstance();const ret={};ret["uid"]=inst.GetUID();ret["f"]=this._GetFlagsString(flagsSource);ret["offsets"]=flagsSource._SaveSceneGraphPropertiesToJson();ret["data"]=C3.SceneGraphInfo.GetSceneGraphInstanceDataFromInstance(inst);ret["oci"]=inst.GetObjectClass().GetIndex();if(mode==="state"){ret["inst"]=inst.SaveToJson();ret["instIndex"]=NaN}else{ret["instIndex"]=inst.GetObjectClass().GetInstances().indexOf(inst);
+ret["inst"]=null}return ret}_LoadFromJson(o){this._startWidth=o["sw"];this._startHeight=o["sh"];this._startScaleX=o["sx"];this._startScaleY=o["sy"];this._parentStartAngle=o["psa"];this._ownOpacity=o["oo"];this._startOpacity=o["so"]}_SetTmpSceneGraphChildren(tmpSceneGraphChildren,tmpSceneGraphChildrenIndexes){this._tmpSceneGraphChildren=tmpSceneGraphChildren;this._tmpSceneGraphChildrenIndexes=tmpSceneGraphChildrenIndexes}_OnAfterLoad(o,opts){const owner=this._owner;const runtime=owner.GetRuntime();
+const processedExistingWis=new Set;if(o["p"]&&!this._parent){const parentUid=o["p"]["uid"];const parentInst=runtime.GetInstanceByUID(parentUid);if(opts&&!opts.ignoreMissingInstances);if(parentInst){const parentWi=parentInst.GetWorldInfo();if(parentInst.HasChild(this._owner.GetInstance()))this._parent=parentWi;else{if(opts&&opts.instancesDoingAfterLoadMap)if(opts.instancesDoingAfterLoadMap.has(parentInst))return;parentInst.AddChild(this._owner.GetInstance(),this._GetFlagsObj(o["p"]["f"]));if(!processedExistingWis.has(this._owner))this._owner._LoadSceneGraphPropertiesFromJson(o["p"]["offsets"]);
+processedExistingWis.add(this._owner);const pwi=parentInst.GetWorldInfo();pwi._GetSceneGraphInfo()._MaybeSortChildren()}}else if(C3.IsFiniteNumber(o["p"]["oci"])){const objectClass=runtime.GetObjectClassByIndex(o["p"]["oci"]);const system=runtime.GetSystemPlugin();const parentInstance=runtime.CreateInstance(objectClass,owner.GetLayer(),0,0,true);if(opts&&!opts.ignoreMissingInstances);if(parentInstance){const instData=this._GetInstanceData(o["p"],runtime);parentInstance.LoadFromJson(instData);const parentWi=
+parentInstance.GetWorldInfo();parentWi.GetLayer().SortAndAddInstancesByZIndex(parentInstance);parentInstance.AddChild(owner.GetInstance(),this._GetFlagsObj(o["p"]["f"]));const pwi=parentInstance.GetWorldInfo();pwi._GetSceneGraphInfo()._MaybeSortChildren()}}}const childInstances=[];for(const childData of o["c"]){const childUid=childData["uid"];const childInst=runtime.GetInstanceByUID(childUid);if(childInst)childInstances.push(childInst)}let childIndex=0;for(const childData of o["c"]){const childUid=
+childData["uid"];const childInst=runtime.GetInstanceByUID(childUid);if(opts&&!opts.ignoreMissingInstances);if(childInst){if(this._tmpSceneGraphChildren&&this._tmpSceneGraphChildren[childIndex]){const existingChildIntance=this._tmpSceneGraphChildren[childIndex];if(existingChildIntance.GetObjectClass()!==childInst.GetObjectClass()){childIndex++;continue}if(existingChildIntance.IsDestroyed()){childIndex++;continue}const newChildData=o["c"][childIndex];this._AddAndSetChildInstance(existingChildIntance.GetWorldInfo(),
+newChildData,processedExistingWis,true);childIndex++;continue}const objectClass=childInst.GetObjectClass();const childrenCount=this._GetInstancesOfObjectClassCount(childInstances,objectClass);const childrenOfClassCount=owner.GetInstance().GetChildrenOfObjectClass(objectClass).length;if(childrenCount===childrenOfClassCount){const existingChild=owner.GetInstance().GetChildAt(childIndex);const existingChildWi=existingChild.GetWorldInfo();if(existingChildWi){if(!processedExistingWis.has(existingChildWi))existingChildWi._LoadSceneGraphPropertiesFromJson(childData["offsets"]);
+processedExistingWis.add(existingChildWi)}childIndex++;continue}if(childInst.HasParent()){const childWi=this._CreateNewChildInstance(childData,opts);this._AddAndSetChildInstance(childWi,childData,processedExistingWis);childIndex++;continue}this._AddAndSetChildInstance(childInst.GetWorldInfo(),childData,processedExistingWis)}else if(this._tmpSceneGraphChildren&&this._tmpSceneGraphChildren[childIndex]){const existingChildIntance=this._tmpSceneGraphChildren[childIndex];const objectClass=runtime.GetObjectClassByIndex(this._GetObjectClassIndex(childData));
+if(existingChildIntance.GetObjectClass()!==objectClass){childIndex++;continue}if(existingChildIntance.IsDestroyed()){childIndex++;continue}const newChildData=o["c"][childIndex];this._AddAndSetChildInstance(existingChildIntance.GetWorldInfo(),newChildData,processedExistingWis)}else{const childWi=this._CreateNewChildInstance(childData,opts);this._AddAndSetChildInstance(childWi,childData,processedExistingWis)}childIndex++}}_GetFlagsObj(flagsString){const opts={};opts.transformX=flagsString.includes("x");
+opts.transformY=flagsString.includes("y");opts.transformWidth=flagsString.includes("w");opts.transformHeight=flagsString.includes("h");opts.transformAngle=flagsString.includes("a");opts.transformZElevation=flagsString.includes("z");opts.destroyWithParent=flagsString.includes("d");opts.transformOpacity=flagsString.includes("o");opts.transformVisibility=flagsString.includes("v");return opts}_GetObjectClassIndex(childData){if(C3.IsFiniteNumber(childData["oci"]))return childData["oci"];return childData[1]}_CreateNewChildInstance(childData,
+opts){if(!C3.IsFiniteNumber(childData["oci"]))return;const owner=this._owner;const runtime=owner.GetRuntime();let childInstance;if(childData["data"])childInstance=runtime.CreateInstanceFromData(childData["data"],owner.GetLayer(),false,0,0,false,true);else{const objectClass=runtime.GetObjectClassByIndex(childData["oci"]);childInstance=runtime.CreateInstance(objectClass,owner.GetLayer(),0,0,true)}if(opts&&!opts.ignoreMissingInstances);if(!childInstance)return;const instData=this._GetInstanceData(childData,
+runtime);childInstance.LoadFromJson(instData);const childWi=childInstance.GetWorldInfo();childWi.GetLayer().SortAndAddInstancesByZIndex(childInstance,true);return childWi}_AddAndSetChildInstance(childWi,childData,processedExistingWis,setJson=true){const owner=this._owner;const added=owner.AddChild(childWi,this._GetFlagsObj(childData["f"]));if(added&&setJson){if(!processedExistingWis.has(childWi))childWi._LoadSceneGraphPropertiesFromJson(childData["offsets"]);processedExistingWis.add(childWi)}this._MaybeSortChildren()}_GetInstancesOfObjectClassCount(instances,
+objectClass){return instances.filter(i=>i.GetObjectClass().GetName()===objectClass.GetName()).length}_GetInstanceData(json,runtime){if(C3.IsFiniteNumber(json["instIndex"])){const objectClass=runtime.GetObjectClassByIndex(json["oci"]);const instancesJson=objectClass._GetLoadInstancesJson();return instancesJson[json["instIndex"]]}else if(C3.IsString(json["inst"]))return JSON.parse(json["inst"]);else if(json["inst"])return json["inst"]}static GetSceneGraphInstanceDataFromInstance(sourceInstance){let instData=
+sourceInstance.GetWorldInfo().GetLayer().GetInitialInstanceData(sourceInstance.GetUID());if(!instData)return null;instData=JSON.parse(JSON.stringify(instData));const newSgiData=[];for(const child of[...sourceInstance.GetChildren()]){const childWi=child.GetWorldInfo();newSgiData.push([childWi.GetLayout().GetSID(),childWi.GetLayer().GetIndex(),child.GetUID(),C3.SceneGraphInfo._GetFlagsNumber(childWi),child.GetObjectClass().IsInContainer()?1:0,childWi.GetZIndex(),C3.SceneGraphInfo.GetSceneGraphInstanceDataFromInstance(child)])}if(C3.IsArray(instData[0][14]))instData[0][14][1]=
+newSgiData;else{instData[0][14]=[];instData[0][14][0]=C3.SceneGraphInfo._GetDefaultFlagsNumber();instData[0][14][1]=newSgiData;instData[0][14][2]=sourceInstance.GetWorldInfo().GetZIndex()}return instData}static _GetFlagsNumber(wi){let flagsNumber=0;flagsNumber|=Number(wi.GetTransformWithParentVisibility())<<8;flagsNumber|=Number(wi.GetTransformWithParentOpacity())<<7;flagsNumber|=Number(wi.GetTransformWithParentZElevation())<<6;flagsNumber|=Number(wi.GetDestroyWithParent())<<5;flagsNumber|=Number(wi.GetTransformWithParentAngle())<<
+4;flagsNumber|=Number(wi.GetTransformWithParentHeight())<<3;flagsNumber|=Number(wi.GetTransformWithParentWidth())<<2;flagsNumber|=Number(wi.GetTransformWithParentY())<<1;flagsNumber|=Number(wi.GetTransformWithParentX())<<0;return flagsNumber}static _GetDefaultFlagsNumber(wi){let flagsNumber=0;flagsNumber|=1<<8;flagsNumber|=1<<7;flagsNumber|=1<<6;flagsNumber|=1<<5;flagsNumber|=1<<4;flagsNumber|=1<<3;flagsNumber|=1<<2;flagsNumber|=1<<1;flagsNumber|=1<<0;return flagsNumber}};
+
+}
+
+// objects/worldInfo.js
+{
+'use strict';const C3=self.C3;const glMatrix=self.glMatrix;const vec3=glMatrix.vec3;const vec4=glMatrix.vec4;const tempRect=C3.New(C3.Rect);const tempQuad=C3.New(C3.Quad);const bboxChangeEvent=C3.New(C3.Event,"bboxchange",false);const tempColor=C3.New(C3.Color,0,0,0,0);const tempCollisionPoly=C3.New(C3.CollisionPoly);const DEFAULT_COLOR=C3.New(C3.Color,1,1,1,1);const DEFAULT_RENDER_CELLS=C3.New(C3.Rect,0,0,-1,-1);const DEFAULT_COLLISION_CELLS=C3.New(C3.Rect,0,0,-1,-1);
+const VALID_SET_MESH_POINT_MODES=new Set(["absolute","relative"]);const EMPTY_ARRAY=[];let enableUpdateRendererStateGroup=true;const FLAG_IS_VISIBLE=1<<0;const FLAG_BBOX_CHANGED=1<<1;const FLAG_ENABLE_BBOX_CHANGED_EVENT=1<<2;const FLAG_COLLISION_ENABLED=1<<3;const FLAG_COLLISION_CELL_CHANGED=1<<4;const FLAG_SOLID_FILTER_INCLUSIVE=1<<5;const FLAG_HAS_ANY_ACTIVE_EFFECT=1<<6;const FLAG_IS_ROTATABLE=1<<7;const FLAG_DESTROYED=1<<8;const FLAG_DESTROY_WITH_PARENT=1<<9;
+const FLAG_TRANSFORM_WITH_PARENT_X=1<<10;const FLAG_TRANSFORM_WITH_PARENT_Y=1<<11;const FLAG_TRANSFORM_WITH_PARENT_W=1<<12;const FLAG_TRANSFORM_WITH_PARENT_H=1<<13;const FLAG_TRANSFORM_WITH_PARENT_A=1<<14;const FLAG_TRANSFORM_WITH_PARENT_Z_ELEVATION=1<<15;const FLAG_TRANSFORM_WITH_PARENT_OPACITY=1<<22;const FLAG_TRANSFORM_WITH_PARENT_VISIBILITY=1<<23;
+const MASK_ALL_SCENE_GRAPH_FLAGS=FLAG_DESTROY_WITH_PARENT|FLAG_TRANSFORM_WITH_PARENT_X|FLAG_TRANSFORM_WITH_PARENT_Y|FLAG_TRANSFORM_WITH_PARENT_W|FLAG_TRANSFORM_WITH_PARENT_H|FLAG_TRANSFORM_WITH_PARENT_A|FLAG_TRANSFORM_WITH_PARENT_Z_ELEVATION|FLAG_TRANSFORM_WITH_PARENT_OPACITY|FLAG_TRANSFORM_WITH_PARENT_VISIBILITY;const FLAG_MESH_CHANGED=1<<16;const FLAG_PHYSICS_BODY_CHANGED=1<<17;const FLAG_SIN_COS_ANGLE_CHANGED=1<<18;const FLAG_USE_POINTS_SHADER_PROGRAM=1<<19;const FLAG_DRAW_BACK_FACE_ONLY=1<<20;
+const FLAG_DRAW_NON_BACK_FACES_ONLY=1<<21;const FLAG_BLEND_MODE_BIT_OFFSET=26;const FLAG_BLEND_MODE_MASK=31<=children.length)return null;return children[index]}_CreateSceneGraphInfo(parent){if(!this._sceneGraphInfo)this._sceneGraphInfo=C3.New(C3.SceneGraphInfo,this);if(parent)this._sceneGraphInfo.SetParent(parent)}_GetSceneGraphInfo(){return this._sceneGraphInfo}_ReleaseSceneGraphInfo(){if(!this._sceneGraphInfo)return;
+this._sceneGraphInfo.Release();this._sceneGraphInfo=null}_SetParent(parent){if(parent){parent._CreateSceneGraphInfo(null);this._CreateSceneGraphInfo(parent)}else{if(this._sceneGraphInfo)this._sceneGraphInfo.SetParent(null);if(!this.HasChildren())this._ReleaseSceneGraphInfo()}}_HasAnyParent(child){if(!this.HasParent())return false;const parent=this.GetParent();if(parent===child)return true;return parent._HasAnyParent(child)}_HasChildRecursive(child){if(this.HasChild(child))return true;for(const c of this.GetChildren())if(c._HasChildRecursive(child))return true;
+return false}_AddChildToSceneGraphInfo(child){this._sceneGraphInfo.GetChildren().push(child)}_RemoveChildFromSceneGraphInfo(child){const children=this._sceneGraphInfo.GetChildren();const index=children.indexOf(child);if(index!==-1)children.splice(index,1);if(children.length===0&&!this.HasParent())this._ReleaseSceneGraphInfo();if(!child.HasChildren())child._ReleaseSceneGraphInfo()}GetSceneGraphChildrenExportData(){const data=sceneGraphExportDataMap.get(this);return data?data.childrenData:null}GetSceneGraphZIndexExportData(){const data=
+sceneGraphExportDataMap.get(this);return data?data.zIndexData:NaN}GetSceneGraphZIndex(){const sceneGraphZIndex=sceneGraphZIndexMap.get(this);return C3.IsFiniteNumber(sceneGraphZIndex)?sceneGraphZIndex:NaN}SetSceneGraphZIndex(z){sceneGraphZIndexMap.set(this,z)}SetUsePointsShaderProgram(){this._SetFlag(FLAG_USE_POINTS_SHADER_PROGRAM,true);this._UpdateRendererStateGroup()}_UpdateRendererStateGroup(){if(!enableUpdateRendererStateGroup)return;const renderer=this._runtime.GetRenderer();if(this._stateGroup)renderer.ReleaseStateGroup(this._stateGroup);
+let shaderProgram;if((this._flags&FLAG_USE_POINTS_SHADER_PROGRAM)!==0)shaderProgram=renderer.GetPointsRenderingProgram()||"";else shaderProgram=renderer.GetTextureFillShaderProgram()||"";this._stateGroup=renderer.AcquireStateGroup(shaderProgram,this.GetBlendMode(),this._colorPremultiplied,this.GetZElevation())}GetRendererStateGroup(){return this._stateGroup}HasDefaultColor(){return this._color===DEFAULT_COLOR}SetBlendMode(bm){bm=bm|0;if(bm<0||bm>31)throw new RangeError("invalid blend mode");
+if(this.GetBlendMode()===bm)return;this._flags=this._flags&~FLAG_BLEND_MODE_MASK|bm<>FLAG_BLEND_MODE_BIT_OFFSET}_SetLayer(layer,updateRenderCell){const doUpdateRenderCell=updateRenderCell&&this._layer!==layer;if(doUpdateRenderCell)this._RemoveFromRenderCells();this._layer=layer;if(doUpdateRenderCell)this._UpdateRenderCell();if(this.GetZElevation()!==0)this._layer._SetAnyInstanceZElevated()}GetLayer(){return this._layer}GetLayout(){return this.GetLayer().GetLayout()}_SetZIndex(z){this._zIndex=
+z|0}GetZIndex(){this._layer._UpdateZIndices();return this._zIndex}_SetHTMLZIndex(z){this._htmlZIndex=z|0}GetHTMLZIndex(){this._layer._UpdateHTMLZIndices();return this._htmlZIndex}_GetLastCachedZIndex(){return this._zIndex}_SetFlag(bit,enable){if(enable)this._flags|=bit;else this._flags&=~bit}IsVisible(){return(this._flags&FLAG_IS_VISIBLE)!==0}SetVisible(v){this._SetFlag(FLAG_IS_VISIBLE,v);if(!this.HasChildren())return;for(const child of this.GetChildren())if(child.GetTransformWithParentVisibility())child.SetVisible(v)}IsCollisionEnabled(){return(this._flags&
+FLAG_COLLISION_ENABLED)!==0}SetCollisionEnabled(e){e=!!e;if(this.IsCollisionEnabled()===e)return;this._SetFlag(FLAG_COLLISION_ENABLED,e);if(e)this.SetBboxChanged();else this._RemoveFromCollisionCells()}SetSolidCollisionFilter(isInclusive,tags){this._SetFlag(FLAG_SOLID_FILTER_INCLUSIVE,isInclusive);if(this._solidFilterTags)this._solidFilterTags.clear();if(!tags.trim()){this._solidFilterTags=null;return}if(!this._solidFilterTags)this._solidFilterTags=new Set;for(const tag of tags.split(" "))if(tag)this._solidFilterTags.add(tag.toLowerCase())}IsSolidCollisionAllowed(solidTagSet){const isInclusive=
+(this._flags&FLAG_SOLID_FILTER_INCLUSIVE)!==0;const filterTags=this._solidFilterTags;if(!solidTagSet||!filterTags)return!isInclusive;for(const tag of filterTags)if(solidTagSet.has(tag))return isInclusive;return!isInclusive}SetBboxChanged(){this._flags|=FLAG_BBOX_CHANGED|FLAG_COLLISION_CELL_CHANGED|FLAG_MESH_CHANGED;this._objectClass._SetAnyCollisionCellChanged(true);this._runtime.UpdateRender();if(this._layer.UsesRenderCells()){this.CalculateBbox(this._boundingBox,this._boundingQuad,true);this._flags&=
+~FLAG_BBOX_CHANGED;this._UpdateRenderCell()}if((this._flags&FLAG_ENABLE_BBOX_CHANGED_EVENT)!==0)this._inst.Dispatcher().dispatchEvent(bboxChangeEvent);if(this._sceneGraphInfo!==null){const children=this._sceneGraphInfo.GetChildren();for(let i=0,len=children.length;i=layer.GetCameraZ())return false;
+layer.GetViewportForZ(totalZElevation,tempRect);return tempRect.intersectsRect(this.GetBoundingBox())}IsInViewport3D(viewFrustum){const bbox=this.GetBoundingBox();const minX=bbox.getLeft();const maxX=bbox.getRight();const minY=bbox.getTop();const maxY=bbox.getBottom();const minZ=this.GetTotalZElevation();const maxZ=minZ+this.GetDepth();return viewFrustum.ContainsAABB(minX,minY,minZ,maxX,maxY,maxZ)}IsInViewport2(){const layer=this.GetLayer();if(layer.Has3DCamera())return this.IsInViewport3D(layer._GetViewFrustum());
+else{const layout=layer.GetLayout();return this.IsInViewport(layer.GetViewport(),layout.HasVanishingPointOutsideViewport(),layout.IsOrthographicProjection())}}_SetDrawBackFaceOnly(e){this._SetFlag(FLAG_DRAW_BACK_FACE_ONLY,e)}_SetDrawNonBackFacesOnly(e){this._SetFlag(FLAG_DRAW_NON_BACK_FACES_ONLY,e)}IsDrawBackFaceOnly(){return(this._flags&FLAG_DRAW_BACK_FACE_ONLY)!==0}IsDrawNonBackFacesOnly(){return(this._flags&FLAG_DRAW_NON_BACK_FACES_ONLY)!==0}SetSourceCollisionPoly(poly){this._sourceCollisionPoly=
+poly;this._DiscardTransformedCollisionPoly();if(this.HasMesh())this._meshInfo.meshPoly=null}GetSourceCollisionPoly(){return this._sourceCollisionPoly}HasOwnCollisionPoly(){return this._sourceCollisionPoly!==null||this.HasMesh()}GetTransformedCollisionPoly(){return this._GetCustomTransformedCollisionPolyPrecalc(this.GetWidth(),this.GetHeight(),this.GetAngle(),this.GetSinAngle(),this.GetCosAngle())}GetCustomTransformedCollisionPoly(w,h,a){let sina=0;let cosa=1;if(a!==0){sina=Math.sin(a);cosa=Math.cos(a)}return this._GetCustomTransformedCollisionPolyPrecalc(w,
+h,a,sina,cosa)}_GetCustomTransformedCollisionPolyPrecalc(w,h,a,sinA,cosA){let tpi=this._transformedPolyInfo;if(tpi===null){tpi={poly:C3.New(C3.CollisionPoly),width:NaN,height:NaN,angle:NaN};this._transformedPolyInfo=tpi}const transformedPoly=tpi.poly;if(tpi.width===w&&tpi.height===h&&tpi.angle===a)return transformedPoly;const sourcePoly=this._sourceCollisionPoly;if(this.HasMesh()){const ox=this.GetOriginX();const oy=this.GetOriginY();const sourceMesh=this.GetSourceMesh();let meshPoly=this._meshInfo.meshPoly;
+if(!meshPoly){if(sourcePoly){tempCollisionPoly.copy(sourcePoly);tempCollisionPoly.offset(ox,oy)}else tempCollisionPoly.setDefaultPoints();meshPoly=sourceMesh.InsertPolyMeshVertices(tempCollisionPoly);this._meshInfo.meshPoly=meshPoly}sourceMesh.TransformCollisionPoly(meshPoly,transformedPoly);transformedPoly.offset(-ox,-oy);transformedPoly.transformPrecalc(w,h,sinA,cosA)}else if(sourcePoly){transformedPoly.copy(sourcePoly);transformedPoly.transformPrecalc(w,h,sinA,cosA)}else transformedPoly.setFromQuad(this.GetBoundingQuad(),
+-this.GetX(),-this.GetY());tpi.width=w;tpi.height=h;tpi.angle=a;return transformedPoly}_DiscardTransformedCollisionPoly(){this.SetPhysicsBodyChanged(true);const tpi=this._transformedPolyInfo;if(tpi===null)return;tpi.width=NaN}CreateMesh(hsize,vsize){hsize=Math.floor(hsize);vsize=Math.floor(vsize);if(!this.GetInstance().GetPlugin().SupportsMesh())throw new Error("object does not support mesh");this.ReleaseMesh();this._meshInfo={sourceMesh:C3.New(C3.Gfx.Mesh,hsize,vsize),transformedMesh:C3.New(C3.Gfx.Mesh,
+hsize,vsize),meshPoly:null}}HasMesh(){return this._meshInfo!==null}GetSourceMesh(){if(!this.HasMesh())throw new Error("no mesh");return this._meshInfo.sourceMesh}GetTransformedMesh(){if(!this.HasMesh())throw new Error("no mesh");return this._meshInfo.transformedMesh}SetMeshChanged(e){this._SetFlag(FLAG_MESH_CHANGED,e)}IsMeshChanged(){return(this._flags&FLAG_MESH_CHANGED)!==0}SetPhysicsBodyChanged(e){this._SetFlag(FLAG_PHYSICS_BODY_CHANGED,e)}IsPhysicsBodyChanged(){return(this._flags&FLAG_PHYSICS_BODY_CHANGED)!==
+0}_ExpandBboxForMesh(bbox){const sourceMesh=this._meshInfo.sourceMesh;const minX=Math.min(sourceMesh.GetMinX(),0);const minY=Math.min(sourceMesh.GetMinY(),0);const maxX=Math.max(sourceMesh.GetMaxX(),1);const maxY=Math.max(sourceMesh.GetMaxY(),1);const w=bbox.width();const h=bbox.height();bbox.offsetLeft(minX*w);bbox.offsetTop(minY*h);bbox.offsetRight((maxX-1)*w);bbox.offsetBottom((maxY-1)*h);this._depth=sourceMesh.GetMaxZ()}ReleaseMesh(){if(!this._meshInfo)return;this._meshInfo.sourceMesh.Release();
+this._meshInfo.transformedMesh.Release();this._meshInfo=null;this._DiscardTransformedCollisionPoly()}SetMeshPoint(col,row,opts){col=Math.floor(col);row=Math.floor(row);const mode=opts.mode||"absolute";if(!VALID_SET_MESH_POINT_MODES.has(mode))throw new Error("invalid mode");const isRelative=mode==="relative";let posx=opts.x;let posy=opts.y;const zElevation=opts.zElevation;let texu=typeof opts.u==="number"?opts.u:isRelative?0:-1;let texv=typeof opts.v==="number"?opts.v:isRelative?0:-1;if(!this.HasMesh())return false;
+const sourceMesh=this.GetSourceMesh();const p=sourceMesh.GetMeshPointAt(col,row);if(p===null)return false;let ret=false;if(typeof zElevation==="number"&&p.GetZElevation()!==zElevation){p.SetZElevation(zElevation);ret=true}if(isRelative){posx+=col/(sourceMesh.GetHSize()-1);posy+=row/(sourceMesh.GetVSize()-1)}if(texu===-1&&!isRelative)texu=p.GetU();else{if(isRelative)texu+=col/(sourceMesh.GetHSize()-1);texu=C3.clamp(texu,0,1)}if(texv===-1&&!isRelative)texv=p.GetV();else{if(isRelative)texv+=row/(sourceMesh.GetVSize()-
+1);texv=C3.clamp(texv,0,1)}if(p.GetX()===posx&&p.GetY()===posy&&p.GetU()===texu&&p.GetV()===texv)return ret;p.SetX(posx);p.SetY(posy);p.SetU(texu);p.SetV(texv);this._DiscardTransformedCollisionPoly();return true}HasTilemap(){return this._inst.HasTilemap()}ContainsPoint(x,y){if(!this.GetBoundingBox().containsPoint(x,y))return false;if(!this.GetBoundingQuad().containsPoint(x,y))return false;if(this.HasTilemap())return this._inst.GetSdkInstance().TestPointOverlapTile(x,y);if(!this.HasOwnCollisionPoly())return true;
+return this.GetTransformedCollisionPoly().containsPoint(x-this.GetX(),y-this.GetY())}_IsCollisionCellChanged(){return(this._flags&FLAG_COLLISION_CELL_CHANGED)!==0}_UpdateCollisionCell(){if(!this._IsCollisionCellChanged()||!this.IsCollisionEnabled()||(this._flags&FLAG_DESTROYED)!==0)return;const bbox=this.GetBoundingBox();const grid=this._objectClass._GetCollisionCellGrid();const collisionCells=this._collisionCells;tempRect.set(grid.XToCell(bbox.getLeft()),grid.YToCell(bbox.getTop()),grid.XToCell(bbox.getRight()),
+grid.YToCell(bbox.getBottom()));if(collisionCells.equals(tempRect))return;const inst=this._inst;if(collisionCells===DEFAULT_COLLISION_CELLS){grid.Update(inst,null,tempRect);this._collisionCells=C3.New(C3.Rect,tempRect)}else{grid.Update(inst,collisionCells,tempRect);collisionCells.copy(tempRect)}this._flags&=~FLAG_COLLISION_CELL_CHANGED}_SetCollisionCellChanged(){this._flags|=FLAG_COLLISION_CELL_CHANGED}_RemoveFromCollisionCells(){const collisionCells=this._collisionCells;if(collisionCells===DEFAULT_COLLISION_CELLS)return;
+this._objectClass._GetCollisionCellGrid().Update(this._inst,collisionCells,null);this._collisionCells=DEFAULT_COLLISION_CELLS}_UpdateRenderCell(){const layer=this.GetLayer();if(!layer.UsesRenderCells()||(this._flags&FLAG_DESTROYED)!==0)return;const renderGrid=layer.GetRenderGrid();const bbox=this.GetBoundingBox();const renderCells=this._renderCells;tempRect.set(renderGrid.XToCell(bbox.getLeft()),renderGrid.YToCell(bbox.getTop()),renderGrid.XToCell(bbox.getRight()),renderGrid.YToCell(bbox.getBottom()));
+if(renderCells.equals(tempRect))return;const inst=this._inst;if(renderCells===DEFAULT_RENDER_CELLS){renderGrid.Update(inst,null,tempRect);this._renderCells=C3.New(C3.Rect,tempRect)}else{renderGrid.Update(inst,renderCells,tempRect);renderCells.copy(tempRect)}layer.SetRenderListStale()}_RemoveFromRenderCells(){const renderCells=this._renderCells;if(renderCells===DEFAULT_RENDER_CELLS)return;this.GetLayer().GetRenderGrid().Update(this._inst,renderCells,null);this._renderCells=DEFAULT_RENDER_CELLS}GetRenderCellRange(){return this._renderCells}ZOrderMoveToTop(){const inst=
+this._inst;const layer=this._layer;const layerInstances=layer._GetInstances();if(layerInstances.length&&layerInstances.at(-1)===inst)return;layer._RemoveInstance(inst,false);layer._AddInstance(inst,false);this._runtime.UpdateRender()}ZOrderMoveToBottom(){const inst=this._inst;const layer=this._layer;const layerInstances=layer._GetInstances();if(layerInstances.length&&layerInstances[0]===inst)return;layer._RemoveInstance(inst,false);layer._PrependInstance(inst,false);this._runtime.UpdateRender()}ZOrderMoveToLayer(layerMove){const inst=
+this._inst;const curLayer=this._layer;if(curLayer.GetLayout()!==layerMove.GetLayout())throw new Error("layer from different layout");if(layerMove===curLayer)return;curLayer._RemoveInstance(inst,true);this._SetLayer(layerMove);layerMove._AddInstance(inst,true);this._runtime.UpdateRender()}ZOrderMoveAdjacentToInstance(otherInst,isAfter){const inst=this._inst;let didChangeLayer=false;const curLayer=this._layer;if(otherInst.GetUID()===inst.GetUID())return;const otherWi=otherInst.GetWorldInfo();if(!otherWi)throw new Error("expected world instance");
+const otherLayer=otherWi.GetLayer();if(curLayer.GetIndex()!==otherLayer.GetIndex()){curLayer._RemoveInstance(inst,true);this._SetLayer(otherLayer);otherLayer._AddInstance(inst,true);didChangeLayer=true}const didChangeZOrder=otherLayer.MoveInstanceAdjacent(inst,otherInst,!!isAfter);if(didChangeLayer||didChangeZOrder)this._runtime.UpdateRender()}GetInstanceEffectList(){return this._instanceEffectList}_SetHasAnyActiveEffect(e){this._SetFlag(FLAG_HAS_ANY_ACTIVE_EFFECT,e)}HasAnyActiveEffect(){return(this._flags&
+FLAG_HAS_ANY_ACTIVE_EFFECT)!==0}_SaveToJson(mode){const o={"x":this.GetX(),"y":this.GetY(),"w":this.GetWidth(),"h":this.GetHeight(),"l":this.GetLayer().GetSID(),"zi":this.GetZIndex()};if(this.GetZElevation()!==0)o["ze"]=this.GetZElevation();if(this.GetAngle()!==0)o["a"]=this._GetAngleNoReflect();if(!this.HasDefaultColor())o["c"]=this._color.toJSON();if(this.GetOriginX()!==.5)o["oX"]=this.GetOriginX();if(this.GetOriginY()!==.5)o["oY"]=this.GetOriginY();if(this.GetBlendMode()!==0)o["bm"]=this.GetBlendMode();
+if(!this.IsVisible())o["v"]=this.IsVisible();if(!this.IsCollisionEnabled())o["ce"]=this.IsCollisionEnabled();if(this.IsBboxChangeEventEnabled())o["be"]=this.IsBboxChangeEventEnabled();if(this._instanceEffectList)o["fx"]=this._instanceEffectList._SaveToJson();const isSolidFilterInclusive=(this._flags&FLAG_SOLID_FILTER_INCLUSIVE)!==0;if(isSolidFilterInclusive)o["sfi"]=isSolidFilterInclusive;if(this._solidFilterTags)o["sft"]=[...this._solidFilterTags].join(" ");if(this._sceneGraphInfo&&mode!=="visual-state"){o["sgi"]=
+this._sceneGraphInfo._SaveToJson(mode);if(sceneGraphExportDataMap.has(this)){o["sgcd"]=sceneGraphExportDataMap.get(this).childrenData;o["sgzid"]=sceneGraphExportDataMap.get(this).zIndexData}}if(this.HasMesh())o["mesh"]=this.GetSourceMesh().SaveToJson();return o}_SaveSceneGraphPropertiesToJson(){return{"x":this._x,"y":this._y,"z":this._zElevation,"w":this._w,"h":this._h,"a":this._a,"sgi":this._GetSceneGraphInfo()?this._GetSceneGraphInfo()._SaveToJsonProperties():null}}_LoadSceneGraphPropertiesFromJson(o){if(!o)return;
+this._x=o["x"];this._y=o["y"];this._zElevation=o["z"];this._w=o["w"];this._h=o["h"];this._a=o["a"];if(o["sgi"]&&this._GetSceneGraphInfo())this._GetSceneGraphInfo()._LoadFromJson(o["sgi"]);this._MarkSinCosAngleChanged();this.SetBboxChanged()}_SetupSceneGraphConnectionsOnChangeOfLayout(){this._ReleaseTmpSceneGraphInfo();this._ResetAllSceneGraphState();this._CreateSceneGraphInfo(null);if(this._sceneGraphInfo)this._sceneGraphInfo._SetTmpSceneGraphChildren(this._tmpSceneGraphChildren,this._tmpSceneGraphChildrenIndexes)}_OnBeforeLoad(mode){if(mode!==
+"visual-state")this._ResetAllSceneGraphState()}_OnAfterLoad(o,mode="full",opts=null){if(o.hasOwnProperty("sgi")&&mode!=="visual-state"){if((this._flags&FLAG_DESTROYED)!==0)return;this._sceneGraphInfo._OnAfterLoad(o["sgi"],opts)}}_OnAfterLoad2(o,mode="full",opts=null){if(o.hasOwnProperty("sgi")&&mode!=="visual-state"){if((this._flags&FLAG_DESTROYED)!==0)return;this._sceneGraphInfo._SetTmpSceneGraphChildren(null,null);this._ReleaseTmpSceneGraphInfo();this.SetBboxChanged()}}_LoadFromJson(o,mode){enableUpdateRendererStateGroup=
+false;this.SetX(o["x"]);this.SetY(o["y"]);this.SetWidth(o["w"]);this.SetHeight(o["h"]);this._SetZIndex(o["zi"]);this.SetZElevation(o.hasOwnProperty("ze")?o["ze"]:0);this.SetAngle(o.hasOwnProperty("a")?o["a"]:0);if(o.hasOwnProperty("c"))tempColor.setFromJSON(o["c"]);else if(o.hasOwnProperty("o")){tempColor.copyRgb(this._color);tempColor.a=o["o"]}else tempColor.setRgba(1,1,1,1);this._SetColor(tempColor);this.SetOriginX(o.hasOwnProperty("oX")?o["oX"]:.5);this.SetOriginY(o.hasOwnProperty("oY")?o["oY"]:
+.5);this.SetBlendMode(o.hasOwnProperty("bm")?o["bm"]:0);this.SetVisible(o.hasOwnProperty("v")?o["v"]:true);this.SetCollisionEnabled(o.hasOwnProperty("ce")?o["ce"]:true);this.SetBboxChangeEventEnabled(o.hasOwnProperty("be")?o["be"]:false);this.SetSolidCollisionFilter(o.hasOwnProperty("sfi")?o["sfi"]:false,o.hasOwnProperty("sft")?o["sft"]:"");if(this._instanceEffectList&&o.hasOwnProperty("fx"))this._instanceEffectList._LoadFromJson(o["fx"]);if(!o.hasOwnProperty("sgi")&&mode!=="visual-state")if(this._tmpSceneGraphChildren)for(const inst of this._tmpSceneGraphChildren){if(inst.IsDestroyed())continue;
+this._runtime.DestroyInstance(inst)}if(o.hasOwnProperty("sgi")&&mode!=="visual-state"){this._CreateSceneGraphInfo(null);const sgi=this._sceneGraphInfo;const sgiData=o["sgi"];sgi._LoadFromJson(sgiData);sgi._SetTmpSceneGraphChildren(this._tmpSceneGraphChildren,this._tmpSceneGraphChildrenIndexes);if(o["sgcd"]&&C3.IsFiniteNumber(o["sgzid"]))sceneGraphExportDataMap.set(this,{childrenData:o["sgcd"],zIndexData:o["sgzid"]})}if(o.hasOwnProperty("mesh")){const meshData=o["mesh"];this.CreateMesh(meshData["cols"],
+meshData["rows"]);this.GetSourceMesh().LoadFromJson(meshData)}else this.ReleaseMesh();this.SetBboxChanged();enableUpdateRendererStateGroup=true;this._UpdateRendererStateGroup();if(mode!=="visual-state")this._runtime.AddInstanceNeedingAfterLoad(this.GetInstance(),o)}};
+
+}
+
+// objects/behaviorType.js
+{
+'use strict';const C3=self.C3;
+C3.BehaviorType=class BehaviorType extends C3.DefendedBase{constructor(objectClass,data){super();const runtime=objectClass.GetRuntime();const pluginManager=runtime.GetPluginManager();const BehaviorCtor=runtime.GetObjectReference(data[1]);if(!pluginManager.HasBehaviorByConstructorFunction(BehaviorCtor))pluginManager.CreateBehavior(data);this._runtime=runtime;this._objectClass=objectClass;this._behavior=pluginManager.GetBehaviorByConstructorFunction(BehaviorCtor);this._sdkType=null;this._instSdkCtor=
+BehaviorCtor.Instance;this._sid=data[2];this._name=data[0];this._jsPropName=this._runtime.GetJsPropName(data[3]);this._sdkType=C3.New(BehaviorCtor.Type,this);this.OnCreate()}static Create(objectClass,behaviorTypeData){return C3.New(C3.BehaviorType,objectClass,behaviorTypeData)}Release(){this._runtime=null;this._behavior=null;this._sdkType.Release();this._sdkType=null;this._instSdkCtor=null}GetSdkType(){return this._sdkType}OnCreate(){this._sdkType.OnCreate()}GetRuntime(){return this._runtime}GetObjectClass(){return this._objectClass}GetBehavior(){return this._behavior}GetInstanceSdkCtor(){return this._instSdkCtor}GetName(){return this._name}GetSID(){return this._sid}GetJsPropName(){return this._jsPropName}};
+
+}
+
+// objects/behaviorInstance.js
+{
+'use strict';const C3=self.C3;const IBehaviorInstance=self.IBehaviorInstance;
+C3.BehaviorInstance=class BehaviorInstance extends C3.DefendedBase{constructor(opts){super();this._runtime=opts.runtime;this._behaviorType=opts.behaviorType;this._behavior=this._behaviorType.GetBehavior();this._inst=opts.instance;this._index=opts.index;this._sdkInst=null;this._iScriptInterface=null;this._behavior._AddInstance(this._inst)}Release(){if(this._iScriptInterface){this._iScriptInterface._Release();this._iScriptInterface=null}this._behavior._RemoveInstance(this._inst);this._sdkInst.Release();
+this._sdkInst=null;this._runtime=null;this._behaviorType=null;this._behavior=null;this._inst=null}_CreateSdkInstance(properties){if(this._sdkInst)throw new Error("already got sdk instance");this._sdkInst=C3.New(this._behaviorType.GetInstanceSdkCtor(),this,properties)}GetSdkInstance(){return this._sdkInst}GetObjectInstance(){return this._inst}GetRuntime(){return this._runtime}GetBehaviorType(){return this._behaviorType}GetBehavior(){return this._behavior}_GetIndex(){return this._index}PostCreate(){this._sdkInst.PostCreate()}OnSpriteFrameChanged(prevFrame,
+nextFrame){this._sdkInst.OnSpriteFrameChanged(prevFrame,nextFrame)}_GetDebuggerProperties(){return this._sdkInst.GetDebuggerProperties()}SaveToJson(){return this._sdkInst.SaveToJson()}LoadFromJson(o){return this._sdkInst.LoadFromJson(o)}static SortByTickSequence(a,b){const instA=a.GetObjectInstance();const instB=b.GetObjectInstance();const typeIndexA=instA.GetObjectClass().GetIndex();const typeIndexB=instB.GetObjectClass().GetIndex();if(typeIndexA!==typeIndexB)return typeIndexA-typeIndexB;const seqA=
+instA.GetPUID();const seqB=instB.GetPUID();if(seqA!==seqB)return seqA-seqB;return a.GetBehaviorInstance()._GetIndex()-b.GetBehaviorInstance()._GetIndex()}_InitScriptInterface(){const DefaultScriptClass=IBehaviorInstance;const SdkScriptClass=this._sdkInst.GetScriptInterfaceClass();const ScriptInterfaceClass=SdkScriptClass||DefaultScriptClass;IBehaviorInstance._Init(this);this._iScriptInterface=new ScriptInterfaceClass;IBehaviorInstance._Init(null);if(SdkScriptClass&&!(this._iScriptInterface instanceof
+DefaultScriptClass))throw new TypeError(`script interface class '${SdkScriptClass.name}' does not extend the right base class '${DefaultScriptClass.name}'`);return this._iScriptInterface}GetScriptInterface(){return this._iScriptInterface||this._InitScriptInterface()}HasScriptInterface(){return!!this._iScriptInterface}};
+
+}
+
+// objects/effectList.js
+{
+'use strict';const C3=self.C3;
+C3.EffectList=class EffectList extends C3.DefendedBase{constructor(owner,data){super();this._owner=owner;this._allEffectTypes=[];this._activeEffectTypes=[];this._effectTypesByName=new Map;this._effectParams=[];this._effectParamBuffers=[];this._allInstanceEffectLists=new Set;this._preservesOpaqueness=true;for(const d of data){const et=C3.New(C3.EffectType,this,d,this._allEffectTypes.length);this._allEffectTypes.push(et);this._effectTypesByName.set(et.GetName().toLowerCase(),et);if(d.length>=3)this._effectParams.push(this._LoadSingleEffectParameters(et,
+d[2]))}this.GetRuntime()._AddEffectList(this)}Release(){this.GetRuntime()._RemoveEffectList(this);for(const cpb of this._effectParamBuffers)cpb.Release();C3.clearArray(this._effectParamBuffers);C3.clearArray(this._allEffectTypes);C3.clearArray(this._activeEffectTypes);this._effectTypesByName.clear();C3.clearArray(this._effectParams);this._owner=null}_AddInstanceEffectList(iel){this._allInstanceEffectLists.add(iel)}_RemoveInstanceEffectList(iel){this._allInstanceEffectLists.delete(iel)}_InitRenderer(renderer){if(renderer.IsWebGPU()){this._effectParamBuffers=
+this._allEffectTypes.map(et=>{const shaderProgram=et.GetShaderProgram();if(shaderProgram.GetCustomParametersByteSize()>0)return C3.New(C3.Gfx.WebGPUEffectCustomParamsBuffer,shaderProgram);else return null});this._UpdateAllEffectParamBuffers()}for(const iel of this._allInstanceEffectLists)iel._InitRenderer(renderer)}PrependEffectTypes(arr){if(!arr.length)return;this._allEffectTypes=arr.concat(this._allEffectTypes);for(const et of arr)this._effectTypesByName.set(et.GetName().toLowerCase(),et);for(let i=
+0,len=this._allEffectTypes.length;i0}GetEffectTypeByName(name){return this._effectTypesByName.get(name.toLowerCase())||null}GetEffectTypeByIndex(index){index=Math.floor(+index);if(index<0||index>=this._allEffectTypes.length)throw new RangeError("invalid effect type index");return this._allEffectTypes[index]}IsEffectIndexActive(index){return this.GetEffectTypeByIndex(index).IsActive()}SetEffectIndexActive(index,
+a){this.GetEffectTypeByIndex(index).SetActive(a)}GetActiveEffectTypes(){return this._activeEffectTypes}HasAnyActiveEffect(){return this._activeEffectTypes.length>0}PreservesOpaqueness(){return this._preservesOpaqueness}GetEffectParametersForIndex(index){return this._effectParams[index]}_GetEffectChainShaderParametersForIndex(index){if(index=this._effectParams.length)return null;const effectParams=this._effectParams[effectIndex];if(paramIndex<0||paramIndex>=effectParams.length)return null;return effectParams[paramIndex]}SetEffectParameter(effectIndex,paramIndex,value){if(effectIndex<0||effectIndex>=this._effectParams.length)return false;const effectParams=this._effectParams[effectIndex];if(paramIndex<0||paramIndex>=effectParams.length)return false;const oldValue=effectParams[paramIndex];if(oldValue instanceof C3.Color){if(oldValue.equalsIgnoringAlpha(value))return false;
+oldValue.copyRgb(value)}else{if(oldValue===value)return false;effectParams[paramIndex]=value}if(effectIndex
+({"name":et.GetName(),"active":et.IsActive(),"params":C3.EffectList.SaveFxParamsToJson(this._effectParams[et.GetIndex()])}))}LoadFromJson(arr){for(const o of arr){const et=this.GetEffectTypeByName(o["name"]);if(!et)continue;et.SetActive(o["active"]);this._effectParams[et.GetIndex()]=C3.EffectList.LoadFxParamsFromJson(o["params"])}this.UpdateActiveEffects();this._UpdateAllEffectParamBuffers()}};
+
+}
+
+// objects/effectType.js
+{
+'use strict';const C3=self.C3;
+C3.EffectType=class EffectType extends C3.DefendedBase{constructor(effectList,data,index){super();this._effectList=effectList;this._id=data[0];this._name=data[1];this._index=index;this._shaderProgram=null;this._isActive=true}Release(){this._effectList=null;this._shaderProgram=null}Clone(effectListOwner){const ret=C3.New(C3.EffectType,effectListOwner,[this._id,this._name],-1);ret._shaderProgram=this._shaderProgram;ret._isActive=this._isActive;return ret}_InitRenderer(renderer){const shaderProgram=renderer.GetShaderProgramByName(this._id);
+if(!shaderProgram)throw new Error("failed to find shader program '"+this._id+"'");this._shaderProgram=shaderProgram}GetEffectList(){return this._effectList}GetName(){return this._name}_SetIndex(i){this._index=i}GetIndex(){return this._index}GetOwner(){return this._effectList.GetOwner()}GetRuntime(){return this._effectList.GetRuntime()}SetActive(a){this._isActive=!!a}IsActive(){return this._isActive}GetShaderProgram(){return this._shaderProgram}GetDefaultParameterValues(){const ret=[];for(let i=0,
+len=this._shaderProgram.GetParameterCount();i{const inst=effectChain.GetContentObject();
+const wi=inst.GetWorldInfo();renderer.SetColor(wi.GetPremultipliedColor());renderer.SetCurrentZ(wi.GetTotalZElevation());inst.Draw(renderer);renderer.SetCurrentZ(0)},getSourceTextureInfo:inst=>{const srcTexRect=inst.GetCurrentTexRect();const [srcWidth,srcHeight]=inst.GetCurrentSurfaceSize();return{srcTexRect,srcWidth,srcHeight}},getShaderParameters:index=>this._GetEffectChainShaderParametersForIndex(index)});this._activeEffectFlags=[];this._activeEffectTypes=[];this._preservesOpaqueness=true;this._effectParams=
+[];this._effectParamBuffers=[];this._InitRenderer(inst.GetRuntime().GetRenderer());for(let i=0,len=this._effectList.GetAllEffectTypes().length;i{const shaderProgram=et.GetShaderProgram();if(shaderProgram.GetCustomParametersByteSize()>0)return C3.New(C3.Gfx.WebGPUEffectCustomParamsBuffer,shaderProgram);else return null})}_LoadEffectParameters(data){let index=0;for(const e of data){this._effectParams.push(this._LoadSingleEffectParameters(index,
+e));++index}this._UpdateAllEffectParamBuffers();this.UpdateActiveEffects()}_LoadSingleEffectParameters(index,arr){this._activeEffectFlags[index]=arr[0];const ret=arr.slice(1);for(let i=0,len=ret.length;i0;const isRotatedOrNegativeSizeInstance=wi.GetAngle()!==0||wi.GetWidth()<0||wi.GetHeight()<0;const isTexRotated=inst.IsCurrentTexRotated();if(!this._needsRebuildSteps&&isDefaultColor===this._wasDefaultColor&&is3D===this._was3D&&
+isRotatedOrNegativeSizeInstance===this._wasRotatedOrNegativeSize&&isTexRotated===this._wasTexRotated&&!this._effectChain.NeedsRebuild())return;this._effectChain.BuildSteps(this._activeEffectTypes.map(e=>e.GetShaderProgram()),{indexMap:this._activeEffectTypes.map(e=>e.GetIndex()),forcePreDraw:!isDefaultColor||inst.MustPreDraw(),is3D,isSourceTextureRotated:isTexRotated,isRotatedOrNegativeSizeInstance});this._needsRebuildSteps=false;this._wasDefaultColor=isDefaultColor;this._was3D=is3D;this._wasRotatedOrNegativeSize=
+isRotatedOrNegativeSizeInstance;this._wasTexRotated=isTexRotated}GetActiveEffectTypes(){return this._activeEffectTypes}GetEffectParametersForIndex(index){return this._effectParams[index]}_GetEffectChainShaderParametersForIndex(index){if(index=this._effectParams.length)return null;const effectParams=this._effectParams[effectIndex];
+if(paramIndex<0||paramIndex>=effectParams.length)return null;return effectParams[paramIndex]}SetEffectParameter(effectIndex,paramIndex,value){if(effectIndex<0||effectIndex>=this._effectParams.length)return false;const effectParams=this._effectParams[effectIndex];if(paramIndex<0||paramIndex>=effectParams.length)return false;const oldValue=effectParams[paramIndex];if(oldValue instanceof C3.Color){if(oldValue.equalsIgnoringAlpha(value))return false;oldValue.copyRgb(value)}else{if(oldValue===value)return false;
+effectParams[paramIndex]=value}if(effectIndex
+et.GetShaderProgram().BlendsBackground())}IsEffectIndexActive(i){return this._activeEffectFlags[i]}SetEffectIndexActive(i,e){this._activeEffectFlags[i]=!!e}GetAllEffectTypes(){return this._effectList.GetAllEffectTypes()}_SaveToJson(){return this._effectList.GetAllEffectTypes().map(et=>({"name":et.GetName(),"active":this._activeEffectFlags[et.GetIndex()],"params":C3.EffectList.SaveFxParamsToJson(this._effectParams[et.GetIndex()])}))}_LoadFromJson(arr){for(const o of arr){const et=this._effectList.GetEffectTypeByName(o["name"]);
+if(!et)continue;this._activeEffectFlags[et.GetIndex()]=o["active"];this._effectParams[et.GetIndex()]=C3.EffectList.LoadFxParamsFromJson(o["params"])}this.UpdateActiveEffects();this._UpdateAllEffectParamBuffers()}};
+
+}
+
+// collisions/collisionEngine.js
+{
+'use strict';const C3=self.C3;const tempCandidates=[];const tileCollRectCandidates=[];const tempJumpthruRet=[];const tempPolyA=C3.New(C3.CollisionPoly);const tempPolyB=C3.New(C3.CollisionPoly);const tempQuad=C3.New(C3.Quad);const tempRect=C3.New(C3.Rect);const tempRect2=C3.New(C3.Rect);let tempPolyC=null;let tempRect3=null;let tempQuadB=null;
+C3.CollisionEngine=class CollisionEngine extends C3.DefendedBase{constructor(runtime){super();this._runtime=runtime;this._collisionCellWidth=0;this._collisionCellHeight=0;this._registeredCollisions=[];this._collisionCheckCount=0;this._collisionCheckSec=0;this._polyCheckCount=0;this._polyCheckSec=0;this._iCollisionEngine=new self.ICollisionEngine(this)}Release(){this._runtime=null}GetRuntime(){return this._runtime}GetICollisionEngine(){return this._iCollisionEngine}_Update1sStats(){this._collisionCheckSec=
+this._collisionCheckCount;this._collisionCheckCount=0;this._polyCheckSec=this._polyCheckCount;this._polyCheckCount=0}Get1secCollisionChecks(){return this._collisionCheckSec}Get1secPolyChecks(){return this._polyCheckSec}RegisterCollision(a,b){const aw=a.GetWorldInfo();const bw=b.GetWorldInfo();if(!aw||!bw)return;if(!aw.IsCollisionEnabled()||!bw.IsCollisionEnabled())return;this._registeredCollisions.push([a,b])}AddRegisteredCollisionCandidates(inst,otherType,arr){for(const [a,b]of this._registeredCollisions){let otherInst=
+null;if(inst===a)otherInst=b;else if(inst===b)otherInst=a;else continue;if(!otherInst.BelongsToObjectClass(otherType))continue;if(!arr.includes(otherInst))arr.push(otherInst)}}CheckRegisteredCollision(a,b){if(!this._registeredCollisions.length)return false;for(const [c,d]of this._registeredCollisions)if(a===c&&b===d||a===d&&b===c)return true;return false}ClearRegisteredCollisions(){C3.clearArray(this._registeredCollisions)}TestOverlap(a,b){if(!a||!b||a===b)return false;const aw=a.GetWorldInfo();const bw=
+b.GetWorldInfo();if(!aw.IsCollisionEnabled()||!bw.IsCollisionEnabled())return false;this._collisionCheckCount++;const layerA=aw.GetLayer();const layerB=bw.GetLayer();const areLayerTransformsCompatible=layerA.IsTransformCompatibleWith(layerB);if(areLayerTransformsCompatible)return this._TestOverlap_SameLayers(aw,bw);else return this._TestOverlap_DifferentLayers(aw,bw)}_TestOverlap_SameLayers(aw,bw){if(!aw.GetBoundingBox().intersectsRect(bw.GetBoundingBox()))return false;this._polyCheckCount++;if(!aw.GetBoundingQuad().intersectsQuad(bw.GetBoundingQuad()))return false;
+if(aw.HasTilemap()&&bw.HasTilemap())return false;if(aw.HasTilemap())return this.TestTilemapOverlap(aw,bw);else if(bw.HasTilemap())return this.TestTilemapOverlap(bw,aw);if(!aw.HasOwnCollisionPoly()&&!bw.HasOwnCollisionPoly())return true;const polyA=aw.GetTransformedCollisionPoly();const polyB=bw.GetTransformedCollisionPoly();return polyA.intersectsPoly(polyB,bw.GetX()-aw.GetX(),bw.GetY()-aw.GetY())}_TestOverlap_DifferentLayers(aw,bw){const aIsTileMap=aw.HasTilemap();const bIsTileMap=bw.HasTilemap();
+if(aIsTileMap&&!bIsTileMap)return this.TestTilemapOverlapDifferentLayers(aw,bw);else if(bIsTileMap&&!aIsTileMap)return this.TestTilemapOverlapDifferentLayers(bw,aw);else if(!bIsTileMap&&!aIsTileMap){const layerA=aw.GetLayer();const layerB=bw.GetLayer();tempPolyA.copy(aw.GetTransformedCollisionPoly());tempPolyB.copy(bw.GetTransformedCollisionPoly());const ptsArrA=tempPolyA.pointsArr();for(let i=0,len=ptsArrA.length;i{let ret=interactiveLayersCache.get(layer);if(typeof ret==="undefined"){ret=layer.IsSelfAndParentsInteractive();interactiveLayersCache.set(layer,ret)}return ret};if(sol.IsSelectAll()){if(!isInverted){sol._SetSelectAll(false);C3.clearArray(sol._GetOwnInstances())}if(isOrBlock)C3.clearArray(sol._GetOwnElseInstances());
+for(const inst of objectClass.GetInstances()){const wi=inst.GetWorldInfo();const layer=wi.GetLayer();let containsPoint=false;if(isLayerInteractive(layer)&&wi.IsInViewport2()){const [lx,ly]=layer.CanvasCssToLayer(ptx,pty,wi.GetTotalZElevation());containsPoint=wi.ContainsPoint(lx,ly)}if(containsPoint)if(isInverted)return false;else sol._PushInstance(inst);else if(isOrBlock)sol._PushElseInstance(inst)}}else{let arr;let isPickingElseInstances=false;if(isOrBlock)if(this._runtime.IsCurrentConditionFirst()&&
+!sol._GetOwnElseInstances().length&&sol._GetOwnInstances().length)arr=sol._GetOwnInstances();else{arr=sol._GetOwnElseInstances();isPickingElseInstances=true}else arr=sol._GetOwnInstances();let j=0;for(let i=0,len=arr.length;i0){const PI=Math.PI;this.hitNormal=C3.clampAngle(this.hitNormal+PI);this.normalX=-this.normalX;this.normalY=-this.normalY}}TestInstanceSegment(inst,sx1,sy1,sx2,sy2){const t=C3.rayIntersect(this.x1,
+this.y1,this.x2,this.y2,sx1,sy1,sx2,sy2);if(t>=0&&t[this.GetDrawWidth(),this.GetDrawHeight()],getRenderTarget:()=>this.GetEffectCompositorRenderTarget(),releaseRenderTarget:rt=>this.ReleaseEffectCompositorRenderTarget(rt),getTime:()=>this.GetRuntime().GetGameTime(),redraw:()=>this.GetRuntime().UpdateRender()});this._gpuTimeStartFrame=0;this._gpuTimeEndFrame=0;this._gpuLastUtilisation=NaN;this._gpuFrameTimingsBuffer=
+null;this._layersGpuProfile=new Map;this._gpuCurUtilisation=NaN;this._webgpuFrameTimings=new Map;this._snapshotFormat="";this._snapshotQuality=1;this._snapshotArea=C3.New(C3.Rect);this._snapshotUrl="";this._snapshotPromise=null;this._snapshotResolve=null;this._isPastingToDrawingCanvas=0;this._loaderStartTime=0;this._rafId=-1;this._loadingProgress=0;this._loadingprogress_handler=e=>this._loadingProgress=e.progress;this._percentText=null;this._splashTextures={logo:null,powered:null,website:null};this._splashFrameNumber=
+0;this._splashFadeInFinishTime=0;this._splashFadeOutStartTime=0;this._splashState="fade-in";this._splashDoneResolve=null;this._splashDonePromise=new Promise(resolve=>this._splashDoneResolve=resolve)}_SetGPUPowerPreference(pref){this._gpuPreference=pref}_SetWebGPUEnabled(e){this._isWebGPUEnabled=!!e}_SetZAxisScale(s){this._zAxisScale=s}_SetFieldOfView(f){this._fieldOfView=f}_SetZDistances(zNear,zFar){this._zNear=zNear;this._zFar=zFar}_SetLimitedToWebGL1(l){this._isLimitedToWebGL1=!!l}async CreateCanvas(opts){let mainCanvas=
+opts["canvas"];this._canvasLayers.push({canvas:mainCanvas,ctx:null});this._runtime.AddDOMComponentMessageHandler("runtime","window-resize",e=>this._OnWindowResize(e));this._runtime.AddDOMComponentMessageHandler("runtime","fullscreenchange",e=>this._OnFullscreenChange(e));this._runtime.AddDOMComponentMessageHandler("runtime","fullscreenerror",e=>this._OnFullscreenError(e));mainCanvas.addEventListener("webglcontextlost",e=>this._OnWebGLContextLost(e));mainCanvas.addEventListener("webglcontextrestored",
+e=>this._OnWebGLContextRestored(e));this._isDocumentFullscreen=!!opts["isFullscreen"];const useWebGPU=navigator["gpu"]&&this._isWebGPUEnabled;let hasMajorPerformanceCaveat=false;if(useWebGPU)try{await this._InitWebGPUContext(true)}catch(err){this._MaybeLogRendererError("WebGPU",err);this._webgpuRenderer=null}if(!this.GetRenderer())try{await this._InitWebGLContext(true)}catch(err){this._MaybeLogRendererError("WebGL",err);this._webglRenderer=null}if(!this.GetRenderer())hasMajorPerformanceCaveat=true;
+if(!this.GetRenderer()&&useWebGPU)try{await this._InitWebGPUContext(false)}catch(err){this._MaybeLogRendererError("WebGPU",err);this._webgpuRenderer=null}if(!this.GetRenderer())try{await this._InitWebGLContext(false)}catch(err){this._MaybeLogRendererError("WebGL",err);this._webglRenderer=null}const renderer=this.GetRenderer();if(!renderer)throw new Error("failed to acquire a renderer - check WebGL or WebGPU is supported");renderer.SetHasMajorPerformanceCaveat(hasMajorPerformanceCaveat);if(this._webgpuRenderer){this._webgpuRenderer.ondevicelost=
+()=>this._OnWebGPUDeviceLost();this._webgpuRenderer.ondevicerestored=()=>this._OnWebGPUDeviceRestored()}if(this._zAxisScale==="normalized")renderer.SetZAxisScaleNormalized();else{renderer.SetZAxisScaleRegular();renderer.SetFovY(this._fieldOfView)}this.SetSize(opts["windowInnerWidth"],opts["windowInnerHeight"],true);await this._InitRenderer()}_MaybeLogRendererError(rendererType,err){if(err&&typeof err.message==="string"&&err.message.startsWith("renderer-unavailable"))return;console.error(`Error creating ${rendererType} renderer: `,
+err)}async _InitWebGPUContext(failIfMajorPerformanceCaveat){const ctorOpts={nearZ:this._zNear,farZ:this._zFar};const rendererOpts={powerPreference:this._gpuPreference,depth:this._runtime.Uses3DFeatures(),failIfMajorPerformanceCaveat,usesBackgroundBlending:this._runtime.UsesAnyBackgroundBlending(),canSampleBackbuffer:this._runtime.UsesAnyCrossSampling(),canSampleDepth:this._runtime.UsesAnyDepthSampling()};this._webgpuRenderer=C3.New(C3.Gfx.WebGPURenderer,ctorOpts);await this._webgpuRenderer.Create(this._canvasLayers[0].canvas,
+rendererOpts)}async _InitWebGLContext(failIfMajorPerformanceCaveat){const rendererOpts={powerPreference:this._gpuPreference,enableGpuProfiling:true,depth:this._runtime.Uses3DFeatures(),canSampleDepth:this._runtime.UsesAnyDepthSampling(),failIfMajorPerformanceCaveat,nearZ:this._zNear,farZ:this._zFar};if(this._isLimitedToWebGL1)rendererOpts.maxWebGLVersion=1;if(C3.Platform.OS==="Android"&&C3.Platform.BrowserEngine==="Chromium"&&C3.Platform.BrowserVersionNumber<75){console.warn("[Construct] Disabling WebGL 2 because this device appears to be affected by crbug.com/934823. Install software updates to avoid this.");
+rendererOpts.maxWebGLVersion=1}if(this._runtime.GetCompositingMode()==="standard")rendererOpts.alpha=true;else{rendererOpts.alpha=false;rendererOpts.lowLatency=true}this._webglRenderer=C3.New(C3.Gfx.WebGLRenderer,this._canvasLayers[0].canvas,rendererOpts);await this._webglRenderer.InitState()}async _InitWebGPU(){if(this._shaderData){const promises=[];for(const [id,data]of Object.entries(this._shaderData)){data.src=data.wgsl;const vertexSrc=C3.Gfx.WebGPUShaderProgram.GetDefaultVertexShaderSource();
+promises.push(this._webgpuRenderer.CreateShaderProgram(Object.assign({vertexSrc,name:id},data)))}await Promise.all(promises)}}async _InitWebGL(){if(this._shaderData){const promises=[];for(const [id,data]of Object.entries(this._shaderData)){let vertexSrc;if(data.glslWebGL2&&this._webglRenderer.GetWebGLVersionNumber()>=2){data.src=data.glslWebGL2;vertexSrc=C3.Gfx.WebGLShaderProgram.GetDefaultVertexShaderSource_WebGL2()}else{if(!data.glsl)throw new Error(`shader '${id}' does not support WebGL 1`);data.src=
+data.glsl;vertexSrc=C3.Gfx.WebGLShaderProgram.GetDefaultVertexShaderSource()}promises.push(this._webglRenderer.CreateShaderProgram(Object.assign({vertexSrc,name:id},data)))}await Promise.all(promises);this._webglRenderer.ResetLastProgram();this._webglRenderer.SetTextureFillMode()}if(this._webglRenderer.SupportsGPUProfiling())this._gpuFrameTimingsBuffer=C3.New(C3.Gfx.WebGLQueryResultBuffer,this._webglRenderer)}async _InitRenderer(){if(this._webgpuRenderer)await this._InitWebGPU();else if(this._webglRenderer)await this._InitWebGL();
+const renderer=this.GetRenderer();renderer.SetMipmapsEnabled(this._enableMipmaps);if(renderer.SupportsGPUProfiling())this._gpuLastUtilisation=0;for(const effectList of this._runtime._GetAllEffectLists()){for(const effectType of effectList.GetAllEffectTypes())effectType._InitRenderer(renderer);effectList._InitRenderer(renderer);effectList.UpdateActiveEffects()}}Release(){this._runtime=null;this._webglRenderer=null;this._canvasLayers.length=0}IsInWorker(){return this._runtime.IsInWorker()}_OnWindowResize(e){const runtime=
+this._runtime;if(runtime.IsExportToVideo())return;const dpr=e["devicePixelRatio"];if(this.IsInWorker())self.devicePixelRatio=dpr;runtime._SetDevicePixelRatio(dpr);this._isDocumentFullscreen=!!e["isFullscreen"];this.SetSize(e["innerWidth"],e["innerHeight"]);runtime.UpdateRender();const ev=new C3.Event("window-resize");ev.data=e;runtime.Dispatcher().dispatchEventAndWaitAsyncSequential(ev);const ev2=new C3.Event("resize");ev2.cssWidth=this.GetCssWidth();ev2.cssHeight=this.GetCssHeight();ev2.deviceWidth=
+this.GetDeviceWidth();ev2.deviceHeight=this.GetDeviceHeight();runtime.DispatchUserScriptEvent(ev2);if(runtime.IsDebug()&&(runtime.HitBreakpoint()||self.C3Debugger.IsDebuggerPaused()))runtime.Render()}_OnFullscreenChange(e){this._isDocumentFullscreen=!!e["isFullscreen"];this.SetSize(e["innerWidth"],e["innerHeight"],true);this._runtime.UpdateRender()}_OnFullscreenError(e){this._isDocumentFullscreen=!!e["isFullscreen"];this.SetSize(e["innerWidth"],e["innerHeight"],true);this._runtime.UpdateRender()}SetSize(availableWidth,
+availableHeight,force=false){availableWidth=Math.floor(availableWidth);availableHeight=Math.floor(availableHeight);if(availableWidth<=0||availableHeight<=0)throw new Error("invalid size");if(this._windowInnerWidth===availableWidth&&this._windowInnerHeight===availableHeight&&!force)return;this._windowInnerWidth=availableWidth;this._windowInnerHeight=availableHeight;const fullscreenMode=this.GetCurrentFullscreenMode();if(fullscreenMode==="letterbox-scale")this._CalculateLetterboxScale(availableWidth,
+availableHeight);else if(fullscreenMode==="letterbox-integer-scale")this._CalculateLetterboxIntegerScale(availableWidth,availableHeight);else if(fullscreenMode==="off")this._CalculateFixedSizeCanvas(availableWidth,availableHeight);else this._CalculateFullsizeCanvas(availableWidth,availableHeight);this._UpdateFullscreenScalingQuality(fullscreenMode);for(const {canvas}of this._canvasLayers){canvas.width=this._canvasDeviceWidth;canvas.height=this._canvasDeviceHeight}this._runtime.PostComponentMessageToDOM("canvas",
+"update-size",{"marginLeft":this._canvasCssOffsetX,"marginTop":this._canvasCssOffsetY,"styleWidth":this._canvasCssWidth,"styleHeight":this._canvasCssHeight,"displayScale":this.GetDisplayScale()});const renderer=this.GetRenderer();renderer.SetSize(this._canvasDeviceWidth,this._canvasDeviceHeight,true);for(const rt of this._availableAdditionalRenderTargets)renderer.DeleteRenderTarget(rt);C3.clearArray(this._availableAdditionalRenderTargets);renderer.CalculatePerspectiveMatrix(this._defaultProjectionMatrix,
+this.GetDrawWidth()/this.GetDrawHeight());const layoutManager=this._runtime.GetLayoutManager();layoutManager.SetAllLayerProjectionChanged();layoutManager.SetAllLayerMVChanged()}GetDefaultProjectionMatrix(){return this._defaultProjectionMatrix}_CalculateLetterboxScale(availableWidth,availableHeight){const dpr=this._runtime.GetDevicePixelRatio();const originalViewportWidth=this._runtime.GetOriginalViewportWidth();const originalViewportHeight=this._runtime.GetOriginalViewportHeight();const originalAspectRatio=
+originalViewportWidth/originalViewportHeight;const availableAspectRatio=availableWidth/availableHeight;if(availableAspectRatio>originalAspectRatio){const letterboxedWidth=availableHeight*originalAspectRatio;this._canvasCssWidth=Math.round(letterboxedWidth);this._canvasCssHeight=availableHeight;this._canvasCssOffsetX=Math.floor((availableWidth-this._canvasCssWidth)/2);this._canvasCssOffsetY=0}else{const letterboxedHeight=availableWidth/originalAspectRatio;this._canvasCssWidth=availableWidth;this._canvasCssHeight=
+Math.round(letterboxedHeight);this._canvasCssOffsetX=0;this._canvasCssOffsetY=Math.floor((availableHeight-this._canvasCssHeight)/2)}this._canvasDeviceWidth=Math.round(this._canvasCssWidth*dpr);this._canvasDeviceHeight=Math.round(this._canvasCssHeight*dpr);this._runtime.SetViewportSize(originalViewportWidth,originalViewportHeight)}_CalculateLetterboxIntegerScale(availableWidth,availableHeight){const dpr=this._runtime.GetDevicePixelRatio();if(dpr!==1){availableWidth+=1;availableHeight+=1}const originalViewportWidth=
+this._runtime.GetOriginalViewportWidth();const originalViewportHeight=this._runtime.GetOriginalViewportHeight();const originalAspectRatio=originalViewportWidth/originalViewportHeight;const availableAspectRatio=availableWidth/availableHeight;let intScale;if(availableAspectRatio>originalAspectRatio){const letterboxedWidth=availableHeight*originalAspectRatio;intScale=letterboxedWidth*dpr/originalViewportWidth}else{const letterboxedHeight=availableWidth/originalAspectRatio;intScale=letterboxedHeight*
+dpr/originalViewportHeight}if(intScale>1)intScale=Math.floor(intScale);else if(intScale<1)intScale=1/Math.ceil(1/intScale);this._canvasDeviceWidth=Math.round(originalViewportWidth*intScale);this._canvasDeviceHeight=Math.round(originalViewportHeight*intScale);this._canvasCssWidth=this._canvasDeviceWidth/dpr;this._canvasCssHeight=this._canvasDeviceHeight/dpr;this._canvasCssOffsetX=Math.max(Math.floor((availableWidth-this._canvasCssWidth)/2),0);this._canvasCssOffsetY=Math.max(Math.floor((availableHeight-
+this._canvasCssHeight)/2),0);this._runtime.SetViewportSize(originalViewportWidth,originalViewportHeight)}_CalculateFullsizeCanvas(availableWidth,availableHeight){const dpr=this._runtime.GetDevicePixelRatio();this._canvasCssWidth=availableWidth;this._canvasCssHeight=availableHeight;this._canvasDeviceWidth=Math.round(this._canvasCssWidth*dpr);this._canvasDeviceHeight=Math.round(this._canvasCssHeight*dpr);this._canvasCssOffsetX=0;this._canvasCssOffsetY=0;const displayScale=this.GetDisplayScale();this._runtime.SetViewportSize(this._canvasCssWidth/
+displayScale,this._canvasCssHeight/displayScale)}_CalculateFixedSizeCanvas(availableWidth,availableHeight){const dpr=this._runtime.GetDevicePixelRatio();this._canvasCssWidth=this._runtime.GetViewportWidth();this._canvasCssHeight=this._runtime.GetViewportHeight();this._canvasDeviceWidth=Math.round(this._canvasCssWidth*dpr);this._canvasDeviceHeight=Math.round(this._canvasCssHeight*dpr);if(this.IsDocumentFullscreen()){this._canvasCssOffsetX=Math.floor((availableWidth-this._canvasCssWidth)/2);this._canvasCssOffsetY=
+Math.floor((availableHeight-this._canvasCssHeight)/2)}else{this._canvasCssOffsetX=0;this._canvasCssOffsetY=0}this._runtime.SetViewportSize(this._runtime.GetViewportWidth(),this._runtime.GetViewportHeight())}_UpdateFullscreenScalingQuality(fullscreenMode){if(this._wantFullscreenScalingQuality==="high"){this._drawWidth=this._canvasDeviceWidth;this._drawHeight=this._canvasDeviceHeight;this._fullscreenScalingQuality="high"}else{let viewportWidth,viewportHeight;if(this.GetCurrentFullscreenMode()==="off"){viewportWidth=
+this._runtime.GetViewportWidth();viewportHeight=this._runtime.GetViewportHeight()}else{viewportWidth=this._runtime.GetOriginalViewportWidth();viewportHeight=this._runtime.GetOriginalViewportHeight()}if(this._canvasDeviceWidthoriginalAspectRatio)this._drawHeight=this._drawWidth/currentAspectRatio}else if(fullscreenMode==="scale-outer"){const originalAspectRatio=viewportWidth/viewportHeight;const currentAspectRatio=this._windowInnerWidth/this._windowInnerHeight;
+if(currentAspectRatio>originalAspectRatio)this._drawWidth=this._drawHeight*currentAspectRatio;else if(currentAspectRatiooriginalAspectRatio||fullscreenMode==="scale-inner"&¤tAspectRatio=this._canvasLayers.length)return;const mainCanvas=this.GetMainCanvas();const destCtx=this._canvasLayers[htmlIndex].ctx;destCtx.globalCompositeOperation="copy";destCtx.drawImage(mainCanvas,
+0,0)}GetAdditionalRenderTarget(opts){opts.depth=this._runtime.Uses3DFeatures();const arr=this._availableAdditionalRenderTargets;const useIndex=arr.findIndex(rt=>rt.IsCompatibleWithOptions(opts));let ret;if(useIndex!==-1){ret=arr[useIndex];arr.splice(useIndex,1)}else ret=this.GetRenderer().CreateRenderTarget(opts);this._usedAdditionalRenderTargets.add(ret);return ret}ReleaseAdditionalRenderTarget(renderTarget){if(!this._usedAdditionalRenderTargets.has(renderTarget))throw new Error("render target not in use");
+this._usedAdditionalRenderTargets.delete(renderTarget);this._availableAdditionalRenderTargets.push(renderTarget)}GetEffectCompositorRenderTarget(){const opts={sampling:this._runtime.GetSampling()};if(this.GetCurrentFullscreenScalingQuality()==="low"){opts.width=this.GetDrawWidth();opts.height=this.GetDrawHeight()}return this.GetAdditionalRenderTarget(opts)}ReleaseEffectCompositorRenderTarget(renderTarget){this.ReleaseAdditionalRenderTarget(renderTarget)}*activeLayersGpuProfiles(){for(const layout of this._runtime.GetLayoutManager().runningLayouts())for(const layer of layout.GetLayers()){const p=
+this._layersGpuProfile.get(layer);if(p)yield p}}GetLayerTimingsBuffer(layer){if(!this.GetRenderer().SupportsGPUProfiling())return null;let p=this._layersGpuProfile.get(layer);if(!p){p={name:layer.GetName(),timingsBuffer:C3.New(C3.Gfx.WebGLQueryResultBuffer,this._webglRenderer),curUtilisation:0,lastUtilisation:0};this._layersGpuProfile.set(layer,p)}return p.timingsBuffer}_Update1sFrameRange(){const renderer=this.GetRenderer();if(!renderer.SupportsGPUProfiling())return;if(this._gpuTimeEndFrame===0){this._gpuTimeEndFrame=
+renderer.GetFrameNumber();this._gpuCurUtilisation=NaN;for(const p of this.activeLayersGpuProfiles())p.curUtilisation=NaN}}_UpdateTick(){if(this._webglRenderer&&this._webglRenderer.SupportsGPUProfiling())this._UpdateTick_WebGL();if(this._webgpuRenderer&&this._webgpuRenderer.SupportsGPUProfiling())this._UpdateTick_WebGPU()}_UpdateTick_WebGL(){if(!isNaN(this._gpuCurUtilisation))return;this._gpuCurUtilisation=this._gpuFrameTimingsBuffer.GetFrameRangeResultSum(this._gpuTimeStartFrame,this._gpuTimeEndFrame);
+if(isNaN(this._gpuCurUtilisation))return;if(this._runtime.IsDebug())for(const p of this.activeLayersGpuProfiles()){p.curUtilisation=p.timingsBuffer.GetFrameRangeResultSum(this._gpuTimeStartFrame,this._gpuTimeEndFrame);if(isNaN(p.curUtilisation))return}this._gpuFrameTimingsBuffer.DeleteAllBeforeFrameNumber(this._gpuTimeEndFrame);this._gpuLastUtilisation=Math.min(this._gpuCurUtilisation,1);if(this._runtime.IsDebug()){for(const p of this.activeLayersGpuProfiles()){p.timingsBuffer.DeleteAllBeforeFrameNumber(this._gpuTimeEndFrame);
+p.lastUtilisation=Math.min(p.curUtilisation,1)}self.C3Debugger.UpdateGPUProfile(this._gpuLastUtilisation,[...this.activeLayersGpuProfiles()])}this._gpuTimeStartFrame=this._gpuTimeEndFrame;this._gpuTimeEndFrame=0}GetGPUFrameTimingsBuffer(){return this._gpuFrameTimingsBuffer}_UpdateTick_WebGPU(){if(this._gpuTimeEndFrame===0)return;for(let frameNumber=this._gpuTimeStartFrame;frameNumber{this._snapshotResolve=resolve});return this._snapshotPromise}_MaybeTakeSnapshot(){if(!this._snapshotFormat)return;let canvas=this.GetMainCanvas();const snapArea=this._snapshotArea;const x=C3.clamp(Math.floor(snapArea.getLeft()),0,canvas.width);const y=C3.clamp(Math.floor(snapArea.getTop()),0,canvas.height);let w=snapArea.width();if(w===0)w=canvas.width-x;else w=C3.clamp(Math.floor(w),0,canvas.width-x);
+let h=snapArea.height();if(h===0)h=canvas.height-y;else h=C3.clamp(Math.floor(h),0,canvas.height-y);if((x!==0||y!==0||w!==canvas.width||h!==canvas.height)&&(w>0&&h>0)){const cropCanvas=C3.CreateCanvas(w,h);const ctx=cropCanvas.getContext("2d");ctx.drawImage(canvas,x,y,w,h,0,0,w,h);canvas=cropCanvas}C3.CanvasToBlob(canvas,this._snapshotFormat,this._snapshotQuality).then(blob=>{if(this._snapshotUrl)URL.revokeObjectURL(this._snapshotUrl);this._snapshotUrl=URL.createObjectURL(blob);this._snapshotPromise=
+null;this._snapshotResolve(this._snapshotUrl)});this._snapshotFormat="";this._snapshotQuality=1}GetCanvasSnapshotUrl(){return this._snapshotUrl}SetIsPastingToDrawingCanvas(p){if(p)this._isPastingToDrawingCanvas++;else this._isPastingToDrawingCanvas--}IsPastingToDrawingCanvas(){return this._isPastingToDrawingCanvas>0}InitLoadingScreen(loaderStyle){const renderer=this.GetRenderer();if(loaderStyle===2){this._percentText=C3.New(C3.Gfx.RendererText,this.GetRenderer());this._percentText.SetFontName("Arial");
+this._percentText.SetFontSize(16);this._percentText.SetHorizontalAlignment("center");this._percentText.SetVerticalAlignment("center");this._percentText.SetSize(PERCENTTEXT_WIDTH,PERCENTTEXT_HEIGHT)}else if(loaderStyle===0){const loadingLogoAsset=this._runtime.GetLoadingLogoAsset();if(loadingLogoAsset)loadingLogoAsset.LoadStaticTexture(renderer).catch(err=>console.warn(`[C3 runtime] Failed to create texture for loading logo: `,err))}else if(loaderStyle===4){this._LoadSvgSplashImage("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNi4wLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DQo8c3ZnIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiDQoJIHdpZHRoPSIxNzAwLjc5MDA0cHgiIGhlaWdodD0iMTcwMC43OTAwNHB4IiB2aWV3Qm94PSIyODcgMzE3IDExMjUgMTEyNSINCgkgZW5hYmxlLWJhY2tncm91bmQ9Im5ldyAwIDAgMTcwMC43OTAwNCAxNzAwLjc5MDA0IiB4bWw6c3BhY2U9InByZXNlcnZlIj4NCjxnIGlkPSJsb2dvIj4NCgk8Zz4NCgkJPGc+DQoJCQk8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZmlsbD0iI0ZGRkZGRiIgZD0iTTM1NC45Nzc1NCwxMTk1LjYyMzA1DQoJCQkJYzExLjM4NDc3LDAsMjIuMDEyNywzLjIzNzMsMzEuMDE3NTgsOC44Mzc4OWMxLjk0NjI5LDEuMjEwOTQsMi41ODQ5NiwzLjc0OTAyLDEuNDM4NDgsNS43MzQzOGwtNC45MzI2Miw4LjU0MTk5DQoJCQkJYy0zLjI3ODMyLDUuNjc5NjktMTAuMDMzMiw4LjM3Njk1LTE2LjMxNzM4LDYuNTAwOThjLTIuNzY0NjUtMC44MjUyLTUuNjkzMzYtMS4yNjg1NS04LjcyNjU2LTEuMjY4NTUNCgkJCQljLTE2LjgyOTEsMC0zMC40NzI2NiwxMy42NDM1NS0zMC40NzI2NiwzMC40NzI2NmMwLDE2LjgyODEzLDEzLjY0MzU1LDMwLjQ3MjY2LDMwLjQ3MjY2LDMwLjQ3MjY2DQoJCQkJYzMuMDMzMiwwLDUuOTYxOTEtMC40NDMzNiw4LjcyNjU2LTEuMjY4NTVjNi4yOTQ5Mi0xLjg3OTg4LDEzLjAzMzIsMC44MTE1MiwxNi4zMTczOCw2LjUwMDk4bDQuOTMxNjQsOC41NDE5OQ0KCQkJCWMxLjE0NzQ2LDEuOTg4MjgsMC41MTA3NCw0LjUyMzQ0LTEuNDM4NDgsNS43MzQzOGMtOS4wMDM5MSw1LjYwMTU2LTE5LjYzMTg0LDguODM3ODktMzEuMDE2Niw4LjgzNzg5DQoJCQkJYy0zMi40ODUzNSwwLTU4LjgxOTM0LTI2LjMzNDk2LTU4LjgxOTM0LTU4LjgxOTM0QzI5Ni4xNTgyLDEyMjEuOTU3MDMsMzIyLjQ5MjE5LDExOTUuNjIzMDUsMzU0Ljk3NzU0LDExOTUuNjIzMDUNCgkJCQlMMzU0Ljk3NzU0LDExOTUuNjIzMDV6IE03MDMuMjE0ODQsMTI1OS4xNzU3OGMtMTQuNTU5NTctOS44MTczOC0yMC4yMDMxMy0yMC4wMzIyMy0yMC4yMDMxMy0zMy4wODAwOA0KCQkJCWMwLTE4LjQ4OTI2LDE1LjcxNDg0LTI5Ljc2MzY3LDM4LjI2NjYtMjkuNzYzNjdjOS42NTcyMywwLDE4LjcyMTY4LDIuNTQyOTcsMjYuNTU5NTcsNi45OTQxNA0KCQkJCWMyLjA0OTgsMS4xNjQwNiwyLjc2MTcyLDMuNzgzMiwxLjU4MzAxLDUuODI0MjJsLTMuNDE3OTcsNS45MTk5MmMtMy4yNDcwNyw1LjYyNDAyLTkuOTA4Miw4LjMzMTA1LTE2LjE1MzMyLDYuNTQ4ODMNCgkJCQljLTIuNzIzNjMtMC43NzYzNy01LjU5ODYzLTEuMTkyMzgtOC41NzEyOS0xLjE5MjM4Yy0xMC40OTAyMywwLTExLjU5ODYzLDkuNTc2MTctNC44NTc0MiwxNC4xMjMwNWwyMy42ODY1MiwxNS45NzY1Ng0KCQkJCWM5Ljk5MDIzLDYuNzM4MjgsMTUuODk1NTEsMTcuMDY2NDEsMTUuODk1NTEsMjguNzE4NzVjMCwxOC43ODYxMy0xNS4wMDY4NCwzMy4zMDc2Mi0zOC4yNjc1OCwzMy4zMDc2Mg0KCQkJCWMtOS41MjI0NiwwLTE4LjU4Nzg5LTEuOTU3MDMtMjYuODE1NDMtNS40OTAyM2MtNy43ODEyNS0zLjMzOTg0LTEwLjkzMzU5LTEyLjc4MjIzLTYuNjk3MjctMjAuMTE4MTZsMy40ODczLTYuMDQxOTkNCgkJCQljMS4yMTM4Ny0yLjA5OTYxLDMuOTMxNjQtMi43NTk3Nyw1Ljk3NDYxLTEuNDU2MDVjNi44NTkzOCw0LjM4MjgxLDE2LjQ5MDIzLDcuNTk0NzMsMjQuNzU4NzksNy41OTQ3Mw0KCQkJCWMxMC41NDU5LDAsMTEuMzI4MTMtOS45NTg5OCwzLjc2NzU4LTE1LjA1NzYyTDcwMy4yMTQ4NCwxMjU5LjE3NTc4TDcwMy4yMTQ4NCwxMjU5LjE3NTc4eiBNOTg0LjYzMDg2LDEyMDIuMDAwOTgNCgkJCQljMC0yLjM0NzY2LDEuOTAzMzItNC4yNTE5NSw0LjI1MTk1LTQuMjUxOTVoOS45MjE4OGM3LjgyNzE1LDAsMTQuMTcyODUsNi4zNDU3LDE0LjE3Mjg1LDE0LjE3MzgzdjU3LjQwMTM3DQoJCQkJYzAsOC42MTAzNSw2Ljk4MDQ3LDE1LjU5MDgyLDE1LjU5MDgyLDE1LjU5MDgyczE1LjU5MDgyLTYuOTgwNDcsMTUuNTkwODItMTUuNTkwODJ2LTU3LjQwMTM3DQoJCQkJYzAtNy44MjgxMyw2LjM0NTctMTQuMTczODMsMTQuMTcyODUtMTQuMTczODNoOS45MjA5YzIuMzQ4NjMsMCw0LjI1MTk1LDEuOTA0Myw0LjI1MTk1LDQuMjUxOTV2NjcuMzIzMjQNCgkJCQljMCwyNC4yNjU2My0xOS42NzA5LDQzLjkzNzUtNDMuOTM2NTIsNDMuOTM3NXMtNDMuOTM3NS0xOS42NzE4OC00My45Mzc1LTQzLjkzNzVWMTIwMi4wMDA5OEw5ODQuNjMwODYsMTIwMi4wMDA5OHoNCgkJCQkgTTQ2Ni44NjkxNCwxMTk1LjYyMzA1YzMyLjQ4NDM4LDAsNTguODE4MzYsMjYuMzMzOTgsNTguODE4MzYsNTguODE5MzRjMCwzMi40ODQzOC0yNi4zMzM5OCw1OC44MTkzNC01OC44MTgzNiw1OC44MTkzNA0KCQkJCWMtMzIuNDg2MzMsMC01OC44MTkzNC0yNi4zMzQ5Ni01OC44MTkzNC01OC44MTkzNEM0MDguMDQ5OCwxMjIxLjk1NzAzLDQzNC4zODI4MSwxMTk1LjYyMzA1LDQ2Ni44NjkxNCwxMTk1LjYyMzA1DQoJCQkJTDQ2Ni44NjkxNCwxMTk1LjYyMzA1eiBNNDY2Ljg2OTE0LDEyMjUuMDMzMmMtMTYuMjQzMTYsMC0yOS40MTAxNiwxMy4xNjY5OS0yOS40MTAxNiwyOS40MDkxOA0KCQkJCXMxMy4xNjY5OSwyOS40MDgyLDI5LjQxMDE2LDI5LjQwODJjMTYuMjQxMjEsMCwyOS40MDgyLTEzLjE2NjAyLDI5LjQwODItMjkuNDA4MlM0ODMuMTEwMzUsMTIyNS4wMzMyLDQ2Ni44NjkxNCwxMjI1LjAzMzINCgkJCQlMNDY2Ljg2OTE0LDEyMjUuMDMzMnogTTU1Ni43MzI0MiwxMzExLjEzNDc3Yy0yLjM0NzY2LDAtNC4yNTE5NS0xLjkwMjM0LTQuMjUxOTUtNC4yNXYtOTQuOTYxOTENCgkJCQljMC03LjgyODEzLDYuMzQ1Ny0xNC4xNzM4MywxNC4xNzM4My0xNC4xNzM4M2gzLjk1ODk4YzQuNjI1LDAsOC45NTg5OCwyLjI1Njg0LDExLjYxMTMzLDYuMDQ1OWw0MS4xMjIwNyw1OC43NDcwN3YtNTAuNjE5MTQNCgkJCQljMC03LjgyODEzLDYuMzQ1Ny0xNC4xNzM4MywxNC4xNzI4NS0xNC4xNzM4M2g5LjkyMTg4YzIuMzQ3NjYsMCw0LjI1MTk1LDEuOTA0Myw0LjI1MTk1LDQuMjUxOTV2OTQuOTYwOTQNCgkJCQljMCw3LjgyOTEtNi4zNDU3LDE0LjE3Mjg1LTE0LjE3MzgzLDE0LjE3Mjg1aC0zLjk1ODk4Yy00LjYyNSwwLTguOTU4OTgtMi4yNTU4Ni0xMS42MTEzMy02LjA0NDkybC00MS4xMjIwNy01OC43NDYwOXY1MC42MTgxNg0KCQkJCWMwLDcuODI5MS02LjM0NTcsMTQuMTcyODUtMTQuMTcyODUsMTQuMTcyODVINTU2LjczMjQyTDU1Ni43MzI0MiwxMzExLjEzNDc3eiBNMTIxNS4wMjA1MSwxMjExLjkyMjg1DQoJCQkJYzAtNy44MjgxMyw2LjM0NTctMTQuMTczODMsMTQuMTcyODUtMTQuMTczODNoNTAuMzE1NDNjMi4zNDg2MywwLDQuMjUxOTUsMS45MDQzLDQuMjUxOTUsNC4yNTE5NXY1LjY2OTkyDQoJCQkJYzAsNy44MjcxNS02LjM0NTcsMTQuMTcyODUtMTQuMTcyODUsMTQuMTcyODVoLTYuMDI0NDF2NzUuMTE4MTZjMCw3LjgyOTEtNi4zNDU3LDE0LjE3Mjg1LTE0LjE3Mjg1LDE0LjE3Mjg1aC05LjkyMTg4DQoJCQkJYy0yLjM0ODYzLDAtNC4yNTE5NS0xLjkwMjM0LTQuMjUxOTUtNC4yNXYtODUuMDQxMDJoLTE1Ljk0NDM0Yy0yLjM0ODYzLDAtNC4yNTE5NS0xLjkwMzMyLTQuMjUxOTUtNC4yNTE5NVYxMjExLjkyMjg1DQoJCQkJTDEyMTUuMDIwNTEsMTIxMS45MjI4NXogTTc3Ni40NDkyMiwxMjExLjkyMjg1YzAtNy44MjgxMyw2LjM0NTctMTQuMTczODMsMTQuMTczODMtMTQuMTczODNoNTAuMzE0NDUNCgkJCQljMi4zNDk2MSwwLDQuMjUxOTUsMS45MDQzLDQuMjUxOTUsNC4yNTE5NXY1LjY2OTkyYzAsNy44MjcxNS02LjM0NTcsMTQuMTcyODUtMTQuMTcxODgsMTQuMTcyODVoLTYuMDI1Mzl2NzUuMTE4MTYNCgkJCQljMCw3LjgyOTEtNi4zNDU3LDE0LjE3Mjg1LTE0LjE3Mjg1LDE0LjE3Mjg1aC05LjkyMDljLTIuMzQ5NjEsMC00LjI1MTk1LTEuOTAyMzQtNC4yNTE5NS00LjI1di04NS4wNDEwMmgtMTUuOTQ1MzENCgkJCQljLTIuMzQ3NjYsMC00LjI1MTk1LTEuOTAzMzItNC4yNTE5NS00LjI1MTk1VjEyMTEuOTIyODVMNzc2LjQ0OTIyLDEyMTEuOTIyODV6IE05MjkuNjA0NDksMTI3Mi4wMjI0NmwyNi45NTgwMSwzMi4xMjc5Mw0KCQkJCWMyLjMxNDQ1LDIuNzU3ODEsMC4zNDM3NSw2Ljk4NDM4LTMuMjU2ODQsNi45ODQzOGgtMTkuNzA1MDhjLTQuMTg5NDUsMC04LjE2NTA0LTEuODUxNTYtMTAuODU3NDItNS4wNjA1NWwtMjIuNjgxNjQtMjcuMDMxMjUNCgkJCQl2MjcuODQxOGMwLDIuMzQ3NjYtMS45MDMzMiw0LjI1LTQuMjUxOTUsNC4yNWgtOS45MjA5Yy03LjgyNzE1LDAtMTQuMTcyODUtNi4zNDM3NS0xNC4xNzI4NS0xNC4xNzI4NXYtODUuMDM5MDYNCgkJCQljMC03LjgyODEzLDYuMzQ1Ny0xNC4xNzM4MywxNC4xNzI4NS0xNC4xNzM4M2gyOS43NjM2N2MyMi43MDAyLDAsNDEuMTAyNTQsMTcuMTMzNzksNDEuMTAyNTQsMzguMjY4NTUNCgkJCQlDOTU2Ljc1NDg4LDEyNTIuNTkwODIsOTQ1LjQzNjUyLDEyNjYuNzAyMTUsOTI5LjYwNDQ5LDEyNzIuMDIyNDZMOTI5LjYwNDQ5LDEyNzIuMDIyNDZ6IE05MDAuMDYxNTIsMTIyMS44NDM3NXYzMi41OTg2M2g4LjUwMzkxDQoJCQkJYzEwLjk1ODk4LDAsMTkuODQyNzctNy4yOTc4NSwxOS44NDI3Ny0xNi4yOTg4M2MwLTkuMDAxOTUtOC44ODM3OS0xNi4yOTk4LTE5Ljg0Mjc3LTE2LjI5OThIOTAwLjA2MTUyTDkwMC4wNjE1MiwxMjIxLjg0Mzc1eg0KCQkJCSBNMTE1OC4zNTkzOCwxMTk1LjYyMzA1YzExLjM4NDc3LDAsMjIuMDEyNywzLjIzNzMsMzEuMDE3NTgsOC44Mzc4OWMxLjk0NzI3LDEuMjEwOTQsMi41ODQ5NiwzLjc0OTAyLDEuNDM4NDgsNS43MzQzOA0KCQkJCWwtNC45MzI2Miw4LjU0MTk5Yy0zLjI3ODMyLDUuNjc5NjktMTAuMDMzMiw4LjM3Njk1LTE2LjMxNzM4LDYuNTAwOThjLTIuNzY0NjUtMC44MjUyLTUuNjkzMzYtMS4yNjg1NS04LjcyNTU5LTEuMjY4NTUNCgkJCQljLTE2LjgyOTEsMC0zMC40NzI2NiwxMy42NDM1NS0zMC40NzI2NiwzMC40NzI2NmMwLDE2LjgyODEzLDEzLjY0MzU1LDMwLjQ3MjY2LDMwLjQ3MjY2LDMwLjQ3MjY2DQoJCQkJYzMuMDMyMjMsMCw1Ljk2MDk0LTAuNDQzMzYsOC43MjU1OS0xLjI2ODU1YzYuMjk1OS0xLjg3OTg4LDEzLjAzMzIsMC44MTE1MiwxNi4zMTgzNiw2LjUwMDk4bDQuOTMwNjYsOC41NDE5OQ0KCQkJCWMxLjE0NzQ2LDEuOTg4MjgsMC41MTA3NCw0LjUyMzQ0LTEuNDM3NSw1LjczNDM4Yy05LjAwNDg4LDUuNjAxNTYtMTkuNjMyODEsOC44Mzc4OS0zMS4wMTc1OCw4LjgzNzg5DQoJCQkJYy0zMi40ODUzNSwwLTU4LjgxOTM0LTI2LjMzNDk2LTU4LjgxOTM0LTU4LjgxOTM0QzEwOTkuNTQwMDQsMTIyMS45NTcwMywxMTI1Ljg3NDAyLDExOTUuNjIzMDUsMTE1OC4zNTkzOCwxMTk1LjYyMzA1eiIvPg0KCQkJPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGZpbGw9IiMwMEZGREEiIGQ9Ik0xMzE4LjE5NzI3LDEyMDYuMDMyMjMNCgkJCQljMC03LjgyODEzLDYuMzQ1Ny0xNC4xNzM4MywxNC4xNzI4NS0xNC4xNzM4M2MyMC42NTYyNSwwLDQxLjMxMjUsMCw2MS45Njg3NSwwYzMuNDI5NjksMCw1LjQ1MDIsMy44ODA4NiwzLjQ4MzQsNi42OTA0Mw0KCQkJCWwtMTkuMjk2ODgsMjcuNTY3MzhjMTUuNTQyOTcsOC4zNzU5OCwyNi4xMDY0NSwyNC44MDA3OCwyNi4xMDY0NSw0My42OTUzMWMwLDI3LjM5NzQ2LTIyLjIwODk4LDQ5LjYwNjQ1LTQ5LjYwNjQ1LDQ5LjYwNjQ1DQoJCQkJYy0xNi42ODg0OCwwLTMxLjQ1MTE3LTguMjQwMjMtNDAuNDQzMzYtMjAuODc1OThjLTEuNDUwMi0yLjAzOTA2LTAuODMxMDUtNC44OTk0MSwxLjMzNTk0LTYuMTUyMzRsMTAuOTc3NTQtNi4zMzc4OQ0KCQkJCWM0Ljg4MTg0LTIuODE4MzYsMTAuOTc5NDktMi40NzU1OSwxNS41MTQ2NSwwLjg3MzA1YzMuNTI4MzIsMi42MDU0Nyw3Ljg5MTYsNC4xNDY0OCwxMi42MTUyMyw0LjE0NjQ4DQoJCQkJYzExLjc0MjE5LDAsMjEuMjU5NzctOS41MTg1NSwyMS4yNTk3Ny0yMS4yNTk3N3MtOS41MTc1OC0yMS4yNTk3Ny0yMS4yNTk3Ny0yMS4yNTk3N2gtMTUuMjE3NzcNCgkJCQljLTMuNDI5NjksMC01LjQ1MDItMy44ODA4Ni0zLjQ4NDM4LTYuNjkwNDNsMTguMTM1NzQtMjUuOTA4MmgtMzIuMDA5NzdjLTIuMzQ4NjMsMC00LjI1MTk1LTEuOTAzMzItNC4yNTE5NS00LjI1MTk1VjEyMDYuMDMyMjN6DQoJCQkJIi8+DQoJCTwvZz4NCgkJPGc+DQoJCQk8Zz4NCgkJCQk8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZmlsbD0iI0RBRThGNyIgZD0iTTg1MC4zOTU1MSw4NTcuNTkxOA0KCQkJCQljLTUwLjM1NjQ1LDAtOTQuMzI1Mi0yNy4zNTY0NS0xMTcuODUyNTQtNjguMDIwNTFsLTgwLjAzMDI3LDQ2LjIwNDFjLTQuNjU1MjcsMi42ODk0NS02LjEzMTg0LDguNzE4NzUtMy4yNDkwMiwxMy4yNTU4Ng0KCQkJCQljNDIuMjM3Myw2Ni40ODYzMywxMTYuNTMzMiwxMTAuNjA3NDIsMjAxLjEzMTg0LDExMC42MDc0MmM4OC4xMjU5OCwwLDE2NS4wNzEyOS00Ny44NzUsMjA2LjI0MzE2LTExOS4wMzYxM2wtODAuNDg3My00Ni40Njk3Mw0KCQkJCQljLTQuMzEzNDgtMi40OTAyMy05LjgwMTc2LTEuMjA1MDgtMTIuNTcwMzEsMi45MzU1NUM5MzkuMTc1NzgsODMzLjU2MjUsODk3LjU5MTgsODU3LjU5MTgsODUwLjM5NTUxLDg1Ny41OTE4DQoJCQkJCUw4NTAuMzk1NTEsODU3LjU5MTh6IE0xMTM2LjcyMTY4LDU1Ni4yMTc3N2M0LjYxNDI2LTIuNjYzMDksNi4xMTAzNS04LjYxOTE0LDMuMzEyNS0xMy4xNTEzNw0KCQkJCQljLTU5LjkxNTA0LTk3LjAzMDI3LTE2Ny4yMjQ2MS0xNjEuNjk0MzQtMjg5LjYzODY3LTE2MS42OTQzNGMtMTI1Ljg5MzU1LDAtMjM1LjgxMzQ4LDY4LjM5MjU4LTI5NC42MzM3OSwxNzAuMDQ5OA0KCQkJCQlsODAuMzc2OTUsNDYuNDA2MjVjNC4zOTc0NiwyLjUzOTA2LDEwLjAwMTk1LDEuMTQ5NDEsMTIuNzEwOTQtMy4xNDU1MQ0KCQkJCQljNDIuMTY0MDYtNjYuODUxNTYsMTE2LjY2ODk1LTExMS4yNjM2NywyMDEuNTQ1OS0xMTEuMjYzNjdjODguMTI1OTgsMCwxNjUuMDcxMjksNDcuODc1OTgsMjA2LjI0MzE2LDExOS4wMzYxMw0KCQkJCQlMMTEzNi43MjE2OCw1NTYuMjE3Nzd6Ii8+DQoJCQkJPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGZpbGw9IiNBNUJBQzgiIGQ9Ik04NTAuMzk1NTEsOTU5LjYzODY3DQoJCQkJCWMtODQuNTk4NjMsMC0xNTguODk0NTMtNDQuMTIxMDktMjAxLjEzMTg0LTExMC42MDc0MmMtMi44NzY5NS00LjUzMDI3LTEuMzk5NDEtMTAuNTcwMzEsMy4yNDkwMi0xMy4yNTU4Nmw4MC4wMzAyNy00Ni4yMDQxDQoJCQkJCWMtMTEuNTgxMDUtMjAuMDE2Ni0xOC4yMDk5Ni00My4yNTQ4OC0xOC4yMDk5Ni02OC4wNDE5OWMwLTc0Ljc4NTE2LDYwLjU1NzYyLTEzNi4wNjI1LDEzNi4wNjI1LTEzNi4wNjI1DQoJCQkJCWM0Ny4xOTYyOSwwLDg4Ljc4MDI3LDI0LjAyOTMsMTEzLjE4NTU1LDYwLjUyMjQ2YzIuNzY0NjUsNC4xMzM3OSw4LjI2MzY3LDUuNDIxODgsMTIuNTcwMzEsMi45MzU1NWw4MC40ODczLTQ2LjQ2OTczDQoJCQkJCWMtNDEuMTcxODgtNzEuMTYwMTYtMTE4LjExNzE5LTExOS4wMzYxMy0yMDYuMjQzMTYtMTE5LjAzNjEzYy04NC44NzY5NSwwLTE1OS4zODE4NCw0NC40MTIxMS0yMDEuNTQ1OSwxMTEuMjYzNjcNCgkJCQkJYy0yLjcwNjA1LDQuMjkxMDItOC4zMTgzNiw1LjY4MTY0LTEyLjcxMDk0LDMuMTQ1NTFsLTgwLjM3Njk1LTQ2LjQwNjI1DQoJCQkJCWMtMjguOTUyMTUsNTAuMDQwMDQtNDUuNTIzNDQsMTA4LjEzOTY1LTQ1LjUyMzQ0LDE3MC4xMDc0MmMwLDE4Ni45NjM4NywxNTEuMzk0NTMsMzQwLjE1NzIzLDM0MC4xNTcyMywzNDAuMTU3MjMNCgkJCQkJYzEyMi40MTQwNiwwLDIyOS43MjM2My02NC42NjQwNiwyODkuNjM4NjctMTYxLjY5NTMxYzIuNzk0OTItNC41MjYzNywxLjI5NDkyLTEwLjQ5MDIzLTMuMzEyNS0xMy4xNTEzN2wtODAuMDgzMDEtNDYuMjM3Mw0KCQkJCQlDMTAxNS40NjY4LDkxMS43NjM2Nyw5MzguNTIxNDgsOTU5LjYzODY3LDg1MC4zOTU1MSw5NTkuNjM4Njd6Ii8+DQoJCQk8L2c+DQoJCQk8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZmlsbD0iIzAwRkZEQSIgZD0iTTExMzcuMTg1NTUsNzU4LjExMzI4di03My4xNjc5N2wtNjMuMzY1MjMsMzYuNTgzOTgNCgkJCQlMMTEzNy4xODU1NSw3NTguMTEzMjhMMTEzNy4xODU1NSw3NTguMTEzMjh6IE0xMDI2LjU3NjE3LDcwNS4xNjQwNmwxMjAuMDU4NTktNjkuMzE2NDENCgkJCQljMTIuNTY4MzYtNy4yNTU4NiwyOC4zNDQ3MywxLjg1MjU0LDI4LjM0NTcsMTYuMzY2MjF2MTM4LjYzMDg2Yy0wLjAwMDk4LDE0LjUxMjctMTUuNzc3MzQsMjMuNjIyMDctMjguMzQ1NywxNi4zNjYyMQ0KCQkJCWwtMTIwLjA1ODU5LTY5LjMxNjQxQzEwMTQuMDI4MzIsNzMwLjY0OTQxLDEwMTQuMDI4MzIsNzEyLjQwOTE4LDEwMjYuNTc2MTcsNzA1LjE2NDA2eiIvPg0KCQk8L2c+DQoJPC9nPg0KPC9nPg0KPC9zdmc+DQo=").then(tex=>
+{if(this._splashState==="done")renderer.DeleteTexture(tex);else this._splashTextures.logo=tex}).catch(err=>console.warn("Failed to load splash image: ",err));this._LoadBitmapSplashImage("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAABABAMAAACekdKMAAAAMFBMVEUAAAByfYZyfYZyfYZyfYZyfYZyfYZyfYZyfYZyfYZyfYZyfYZyfYZyfYZyfYZyfYYgo7vbAAAAD3RSTlMAmd137hFVqjO7zCKIRGZ881JRAAAFY0lEQVR42u2aPW/bVhSGn1iiPizZ8D+QgSJBNglFmiboQA0NUKAD1XotYA0BOspAkZnqx24vnTrIQNCpg4QkQMcYKDoW9j9w5y6qLNqWFDlvh3tJUa6ddHBhAuS7SKBIQffhuee851CQKVOmTJkyZcqUKXmqa8O+uyNlABKsFRmdP0o5AOle2gHoWdoBzFrpBHACwPeetJNmAFSlt6kGwGH0LqUAVqRuqgHkpEaqAVRkfvOWr+Dh9Rc4j6VvwnrhPNAbgK2ezj+yx7Z6GjUuASi4Ch4lHQAGwBeRK1rROQAdUx5K0hE4NUkaAdS02ZEuoms2wkCSgvYSgFJfkn6CobkSPG0mEcAOrHnGFOxAToHNjk/MygLgO/PxL0BN9yRdQKlufMQAoCdJGi8BOJYknXTJ269cu9HtdqNb4Ni6oimUbFb0dAZQ1DmULJ+TFtT0qQHwg73mLlCMfFUMQPR5VWrbmttNHICC1KDiSZ+w3pMOwFPDhP4IYFtv4ZX0nIorbUBNmjWAiqdZg5fmNFd6jvPhJQDjAV9LI0r28IpmycsBZalNWfoRWJcuoKY9c7cCkwpOwdcIqNT1BmrSgQkNbQAvpAGOF+aHOIBpCxhKR/TVBNjVOHkAOgrg2N6aoU7sklmVidtD7bNm/fIrjaBmk+Sxea142iBnTyguAfjZZscNXLOdXFM8EgVgXRpDz/6yonTEts6AXdV1APTVoKigFSXEmj3XN0kSV01WFQwAHC8O4Mhagye8NgHS137SALzsS3dxwhtXkQ4oaw64eqomOFKXbc2xJbFLTX8DOHYnsKsJu2Gdu8IIuTqjrMB8eyM5ACIFXQo2S5t7lNMM6AdFTaCgADqahHW8EQIohBk9rzEdE+JXAtjVmHWpDTmplUAA96Ea/bJDnVKSWjgaFTSHqubgmjVDXQchgFy4wBXNcXV6LYC8RjbEypomcCAyBopRShxqAn21yenM8WawqjOoKVbmLYBFndeImsnyVwJY1RR8NW1FTRiA6UNTCsP6fKwLONQBZTXx1WVbT0KbtwygvAxg81oAZU0xe2QYxkmyrDDx2DzWBXTUZFs7dNQwHUEMwN4VAKb47wOQ1wj8Gx0+/Y8A8powVJtt7XOoxn8A8N4IqCrA8cJUmzgAl3JAUWN8tSjqDX0NwI/XbwugGLe178oBK7bBaBesm0gggOUqwLrOHe8c1jV2NAMOw/XFAFRth2dr/burANS1cSc0C8kDsB7zAZvgKCjoLTiaFqwpmvwLQC7e2b3PB4CrZj48KXkAKktOEPr6VqeAr680udzEWACluK0LreJ1ThBe6+w4HkfJAhD1AtbAu3qgPcDVX2oCK9bqxwFQ1+fRsVW7va/uBZpAWaND652TCGBoM1rHHN6VmQlsq6cdE+4mC75oLAC49prKB1zTDd6NukHIKahbIkkEsGrmAQWZbZqXNLClrg04dTP4KnjnCwBfmgkZT7WD45k94C8BmA3MPGBgeqcbfQBxwwDsRMi3N7Iqc3dzsuVhV5ofkevpJOoGKUn6Ax5L92F49USoayZCls08uQDiM0ETCWPb8k7DMmH02SICGC7ayVhnsABwEpsZQkfxUpI4ALGpsFn4xCbHcVjnwgnvAkBh0U6CbzqrXgzA1E6FB9YOJGcacgUAfl36t0Ro/SIDUDEL/D1WBcJr5q0oRoJ2LQZgZJ4LPIu2RCPJAJafDLm2Yr2OHmQ4H0vzBksA2PKl38L3fY0aLAFYejK0ZpJhelVKzkj8dlRNzkj8dpRP0DTkVjTUXroB9PVnqtefS9I05BZU8NOdAyUl5q8RtwUg6KYcwP1Up8CanpMpU6ZMmTLdgP4BRYsi23xEdOAAAAAASUVORK5CYII=").then(tex=>{if(this._splashState==="done")renderer.DeleteTexture(tex);else this._splashTextures.powered=tex}).catch(err=>console.warn("Failed to load splash image: ",err));this._LoadBitmapSplashImage("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAABABAMAAACekdKMAAAAMFBMVEUAAAByfYZyfYZyfYZyfYZyfYZyfYZyfYZyfYZyfYZyfYZyfYZyfYZyfYZyfYZyfYYgo7vbAAAAD3RSTlMAdxHdu4hmVZnuRMwzqiLYE4y2AAAFw0lEQVR42u2Yy+9LQRTHp6Xq0VIkXkFvwkYslAWJiGJj2a6sJJe/oF3YWGElEQmxkYi4ErFWNpatWFmIx9Lm1sJCLKgqraqv82h726l6hOuRzDf53TtnOr+ZOZ+ZOffca5ycnJycnJycnJycnJycnJz+pi7g2G9osxjvzX8qB8ABcAAcgH8XwDa85dspNOiaRDuAR4U0PnHtDuyy7IJRJS6gvVmL6TywVkp4ZxIhulUxFvlaXQTrgEHbnMDH5XRjlXCdb+uAnc2ojWgFFTYBZ8e9tzcaswAk6v/3K4sPfPNRFj87IXj+KXQUS9m2jXoH1lMuLq2DtEcAtNMBT9PjanFq7ySAhbABVEAaeDaAwkk2D7GRqctAMQJIq2sBauLnB/VxCfqKpWrbRhSC1W5SMQ9RTgBUwKpF1ccmAIQ2gCxE+20Au9nSESvDgeIDkJSBMpA9vgyXdsj0H0GORL3n2fbwPOKoSQS4Q2cBOGzSJbQYAHDbZEI+rEuBcyZRlF71fIP/x0wBuIBOw6xH3xu2GQFAP2cegmvSwHkeqBZjECzB46UXD3bg8UKJCT6QYzgDY9uiU7hC11doERq6MAZ2CPJ7ipEulOrteDcB4KOZBpBG7zrV1JGzATzmIdnrl/go3bRiBJBHlZc+6ItjuQQ+yFLz8Gka2LZFRVTFGdoQJQ0LPodHnXkS8AjlRWkBLwKQswAs0PDzGpcsAAMNuG+5WgdqxwjgEcp8qcBjN5oZdPhEvOfhU/hsbJuVloWV6WWgp2IBLxXQNEwLDfKqoMXrEQBjATiFA3qePlgAZJRl+EStdaAQjfgALOC1zfeX8ALV+7S69JdALWjxHGqztmxyMnTD6OOBWvAdGDkn60c6vrI5H4CPnOJsWQDe8G0hIU0MB8ojFx+AFAeqeitLy5FkL3w0yNNcSOx3oDxjjxaH9XxldZluY5NBfwrAQvQbRjQXAO8UqVq5dh6A7HCgWzgdFwBdgOX4lMZbTndkWWkDN07Bk+zItllLdHm1+FkLwBSADNDf8B0AnGOp5gFYgJEexwcgGQx4iyeD9ybFkWsbDZbv0+2Y8XvGtqMpWsUimpMAzA1AUrj5ALjm2wCoONKB+ACYsEeDlU04MMs4imeJQqljslSuD4xl/zgAsx6ku/8DgDwaO9AwFU56qhzOPiXpKCzCpSSdb8v+CQDmXshb99cARAPFCOA1chWaFXlP55yn2FqEgiFvOSzYtmiJzisKB7MxQPS8iO63YsD3AHDv8QPgjR92eKuf9vts1wdZjvZhN4XajD35FNDiR7ln0LYBaILY+OZT4DsA+BkTP4AUrgXkxSJcDFps+72X7EGlx6mBbU/lAbdQjvKA7hSAlSuHxdw0gORsHrAUnXkAUuj+AQAZdHGRp9bShX2ECz1JRSk4zNhRJqj5SZQJfpgCUNS2eRsAP/usTDAxPxFKA834AZgAOM1z6qGgxxpdmUDQNjP25LtAsojxu0AehSkAF6RLXWR/EkAdVYEevQtswVtpMwuAB1JGh2jbxQcgBKrig/qSxTD6o2Nm7fttSY6uUnErV+jb4CJyaArAI5luJkCDOy5HAPISSB5A3wYbhJERahvtPALAAw2EI9Vzsh2TTuk23qEceN9d4vVVv227hNroe0CRi/o9IKTZTQFIAc/M8jwGEiouG2/042u8u25uAuPvAavRH7XhzqcBpICdRpssRa+aNLFoh2JeyBzU08fih/ht20WZXghW34s+/ZQnAKhzojsSH4CC/sjARPKamLXacOfTAIwfNSkCbROLluG9Tm2gdl3PY178tu2SBIpFQ6fHH//2GAvAogCkjtGDEAFQYPsu6DdBqw11bgFIF8dNHsQGIEFRSDOe0RS9YYJk23JMrw+/Cr9bFX0VXmNsACbhA088qXhBrMYAlq8Gjhh//FX4YNSGO7cASO9n9B99AuHk5OTk5OTk5OTk5OTk5OTk5OT0VX0B7+fX+9cwWYYAAAAASUVORK5CYII=").then(tex=>{if(this._splashState===
+"done")renderer.DeleteTexture(tex);else this._splashTextures.website=tex}).catch(err=>console.warn("Failed to load splash image: ",err))}}async _LoadSvgSplashImage(url){url=(new URL(url,this._runtime.GetRuntimeBaseURL())).toString();const blob=await C3.FetchBlob(url);const drawable=await this._runtime.RasterSvgImage(blob,2048,2048);return await this.GetRenderer().CreateStaticTextureAsync(drawable,{mipMapQuality:"high"})}async _LoadBitmapSplashImage(url){url=(new URL(url,this._runtime.GetRuntimeBaseURL())).toString();
+const blob=await C3.FetchBlob(url);return await this.GetRenderer().CreateStaticTextureAsync(blob,{mipMapQuality:"high"})}HideCordovaSplashScreen(){this._runtime.PostComponentMessageToDOM("runtime","hide-cordova-splash")}StartLoadingScreen(){this._loaderStartTime=Date.now();this._runtime.Dispatcher().addEventListener("loadingprogress",this._loadingprogress_handler);this._rafId=requestAnimationFrame(()=>this._DrawLoadingScreen());const loaderStyle=this._runtime.GetLoaderStyle();if(loaderStyle!==3)this.HideCordovaSplashScreen()}async EndLoadingScreen(){const renderer=
+this.GetRenderer();this._loadingProgress=1;const loaderStyle=this._runtime.GetLoaderStyle();if(loaderStyle===4)await this._splashDonePromise;this._splashDoneResolve=null;this._splashDonePromise=null;if(this._rafId!==-1){cancelAnimationFrame(this._rafId);this._rafId=-1}this._runtime.Dispatcher().removeEventListener("loadingprogress",this._loadingprogress_handler);this._loadingprogress_handler=null;if(this._percentText){this._percentText.Release();this._percentText=null}this._runtime.ReleaseLoadingLogoAsset();
+renderer.Start();if(this._splashTextures.logo){renderer.DeleteTexture(this._splashTextures.logo);this._splashTextures.logo=null}if(this._splashTextures.powered){renderer.DeleteTexture(this._splashTextures.powered);this._splashTextures.powered=null}if(this._splashTextures.website){renderer.DeleteTexture(this._splashTextures.website);this._splashTextures.website=null}renderer.ClearRgba(0,0,0,0);renderer.Finish();this._splashState="done";this._gpuTimeStartFrame=renderer.GetFrameNumber();if(loaderStyle===
+3)this.HideCordovaSplashScreen()}_DrawLoadingScreen(){if(this._rafId===-1)return;const renderer=this.GetRenderer();renderer.Start();this._rafId=-1;const hasHadError=this._runtime.GetAssetManager().HasHadErrorLoading();const loaderStyle=this._runtime.GetLoaderStyle();if(loaderStyle!==3){this.SetCssTransform(renderer);renderer.ClearRgba(0,0,0,0);renderer.ResetColor();renderer.SetTextureFillMode();renderer.SetTexture(null)}if(loaderStyle===0)this._DrawProgressBarAndLogoLoadingScreen(hasHadError);else if(loaderStyle===
+1)this._DrawProgressBarLoadingScreen(hasHadError,PROGRESSBAR_WIDTH,0);else if(loaderStyle===2)this._DrawPercentTextLoadingScreen(hasHadError);else if(loaderStyle===3)C3.noop();else if(loaderStyle===4)this._DrawSplashLoadingScreen(hasHadError);else throw new Error("invalid loader style");renderer.Finish();this._rafId=requestAnimationFrame(()=>this._DrawLoadingScreen())}_DrawPercentTextLoadingScreen(hasHadError){if(hasHadError)this._percentText.SetColorRgb(1,0,0);else this._percentText.SetColorRgb(.6,
+.6,.6);this._percentText.SetText(Math.round(this._loadingProgress*100)+"%");const midX=this._canvasCssWidth/2;const midY=this._canvasCssHeight/2;const hw=PERCENTTEXT_WIDTH/2;const hh=PERCENTTEXT_HEIGHT/2;tempQuad.setRect(midX-hw,midY-hh,midX+hw,midY+hh);const renderer=this.GetRenderer();renderer.SetTexture(this._percentText.GetTexture());renderer.Quad3(tempQuad,this._percentText.GetTexRect())}_DrawProgressBarLoadingScreen(hasHadError,width,yOff){const renderer=this.GetRenderer();const height=PROGRESSBAR_HEIGHT;
+renderer.SetColorFillMode();if(hasHadError)renderer.SetColorRgba(1,0,0,1);else renderer.SetColorRgba(.118,.565,1,1);const midX=this._canvasCssWidth/2;const midY=this._canvasCssHeight/2;const hw=width/2;const hh=height/2;tempRect.setWH(midX-hw,midY-hh+yOff,Math.floor(width*this._loadingProgress),height);renderer.Rect(tempRect);tempRect.setWH(midX-hw,midY-hh+yOff,width,height);tempRect.offset(-.5,-.5);tempRect.inflate(.5,.5);renderer.SetColorRgba(0,0,0,1);renderer.LineRect2(tempRect);tempRect.inflate(1,
+1);renderer.SetColorRgba(1,1,1,1);renderer.LineRect2(tempRect)}_DrawProgressBarAndLogoLoadingScreen(hasHadError){const renderer=this.GetRenderer();const loadingLogoAsset=this._runtime.GetLoadingLogoAsset();if(!loadingLogoAsset){this._DrawProgressBarLoadingScreen(hasHadError,PROGRESSBAR_WIDTH,0);return}const logoTexture=loadingLogoAsset.GetTexture();if(!logoTexture){this._DrawProgressBarLoadingScreen(hasHadError,PROGRESSBAR_WIDTH,0);return}const logoW=logoTexture.GetWidth();const logoH=logoTexture.GetHeight();
+const midX=this._canvasCssWidth/2;const midY=this._canvasCssHeight/2;const hw=logoW/2;const hh=logoH/2;tempQuad.setRect(midX-hw,midY-hh,midX+hw,midY+hh);renderer.SetTexture(logoTexture);renderer.Quad(tempQuad);this._DrawProgressBarLoadingScreen(hasHadError,logoW,hh+16)}_DrawSplashLoadingScreen(hasHadError){const renderer=this.GetRenderer();const logoTex=this._splashTextures.logo;const poweredTex=this._splashTextures.powered;const websiteTex=this._splashTextures.website;const nowTime=Date.now();if(this._splashFrameNumber===
+0)this._loaderStartTime=nowTime;const allowQuickSplash=this._runtime.IsPreview()||this._runtime.IsFBInstantAvailable()&&!this._runtime.IsCordova();const splashAfterFadeOutWait=allowQuickSplash?0:SPLASH_AFTER_FADEOUT_WAIT_TIME;const splashMinDisplayTime=allowQuickSplash?0:SPLASH_MIN_DISPLAY_TIME;let a=1;if(this._splashState==="fade-in")a=Math.min((nowTime-this._loaderStartTime)/SPLASH_FADE_DURATION,1);else if(this._splashState==="fade-out")a=Math.max(1-(nowTime-this._splashFadeOutStartTime)/SPLASH_FADE_DURATION,
+0);renderer.SetColorFillMode();renderer.SetColorRgba(.231*a,.251*a,.271*a,a);tempRect.set(0,0,this._canvasCssWidth,this._canvasCssHeight);renderer.Rect(tempRect);const w=Math.ceil(this._canvasCssWidth);const h=Math.ceil(this._canvasCssHeight);let drawW,drawH;if(this._canvasCssHeight>256){renderer.SetColorRgba(.302*a,.334*a,.365*a,a);drawW=w;drawH=Math.max(h*.005,2);tempRect.setWH(0,h*.8-drawH/2,drawW,drawH);renderer.Rect(tempRect);if(hasHadError)renderer.SetColorRgba(a,0,0,a);else renderer.SetColorRgba(.161*
+a,.953*a,.816*a,a);drawW=w*this._loadingProgress;tempRect.setWH(w*.5-drawW/2,h*.8-drawH/2,drawW,drawH);renderer.Rect(tempRect);renderer.SetColorRgba(a,a,a,a);renderer.SetTextureFillMode();if(poweredTex){drawW=C3.clamp(h*.22,105,w*.6)*1.5;drawH=drawW/8;tempRect.setWH(w*.5-drawW/2,h*.2-drawH/2,drawW,drawH);renderer.SetTexture(poweredTex);renderer.Rect(tempRect)}if(logoTex){drawW=Math.min(h*.395,w*.95);drawH=drawW;tempRect.setWH(w*.5-drawW/2,h*.485-drawH/2,drawW,drawH);renderer.SetTexture(logoTex);renderer.Rect(tempRect)}if(websiteTex){drawW=
+C3.clamp(h*.22,105,w*.6)*1.5;drawH=drawW/8;tempRect.setWH(w*.5-drawW/2,h*.868-drawH/2,drawW,drawH);renderer.SetTexture(websiteTex);renderer.Rect(tempRect)}}else{renderer.SetColorRgba(.302*a,.334*a,.365*a,a);drawW=w;drawH=Math.max(h*.005,2);tempRect.setWH(0,h*.85-drawH/2,drawW,drawH);renderer.Rect(tempRect);if(hasHadError)renderer.SetColorRgba(a,0,0,a);else renderer.SetColorRgba(.161*a,.953*a,.816*a,a);drawW=w*this._loadingProgress;tempRect.setWH(w*.5-drawW/2,h*.85-drawH/2,drawW,drawH);renderer.Rect(tempRect);
+renderer.SetColorRgba(a,a,a,a);renderer.SetTextureFillMode();if(logoTex){drawW=h*.55;drawH=drawW;tempRect.setWH(w*.5-drawW/2,h*.45-drawH/2,drawW,drawH);renderer.SetTexture(logoTex);renderer.Rect(tempRect)}}this._splashFrameNumber++;if(this._splashState==="fade-in"&&nowTime-this._loaderStartTime>=SPLASH_FADE_DURATION&&this._splashFrameNumber>=2){this._splashState="wait";this._splashFadeInFinishTime=nowTime}if(this._splashState==="wait"&&nowTime-this._splashFadeInFinishTime>=splashMinDisplayTime&&this._loadingProgress>=
+1){this._splashState="fade-out";this._splashFadeOutStartTime=nowTime}if(this._splashState==="fade-out"&&nowTime-this._splashFadeOutStartTime>=SPLASH_FADE_DURATION+splashAfterFadeOutWait||allowQuickSplash&&this._loadingProgress>=1&&nowTime-this._loaderStartTime<500)this._splashDoneResolve()}};
+
+}
+
+// runtime.js
+{
+'use strict';const C3=self.C3;const C3Debugger=self.C3Debugger;const assert=self.assert;const DEFAULT_RUNTIME_OPTS={"messagePort":null,"runtimeBaseUrl":"","headless":false,"hasDom":true,"isInWorker":false,"useAudio":true,"projectData":"","exportType":""};let ife=true;
+C3.Runtime=class C3Runtime extends C3.DefendedBase{constructor(opts){opts=Object.assign({},DEFAULT_RUNTIME_OPTS,opts);super();this._messagePort=opts["messagePort"];this._runtimeBaseUrl=opts["runtimeBaseUrl"];this._previewUrl=opts["previewUrl"];this._isHeadless=!!opts["headless"];this._hasDom=!!opts["hasDom"];this._isInWorker=!!opts["isInWorker"];ife=opts["ife"];this._useAudio=!!opts["useAudio"];this._exportType=opts["exportType"];this._isiOSCordova=!!opts["isiOSCordova"];this._isiOSWebView=!!opts["isiOSWebView"];
+this._isWindowsWebView2=!!opts["isWindowsWebView2"];this._isAnyWebView2Wrapper=!!opts["isAnyWebView2Wrapper"];this._isFBInstantAvailable=!!opts["isFBInstantAvailable"];this._opusWasmScriptUrl=opts["opusWasmScriptUrl"];this._opusWasmBinaryUrl=opts["opusWasmBinaryUrl"];this._isDebug=!!(this._exportType==="preview"&&opts["isDebug"]);this._breakpointsEnabled=this._isDebug;this._isDebugging=this._isDebug;this._debuggingDisabled=0;this._additionalLoadPromises=[];this._additionalCreatePromises=[];this._isUsingCreatePromises=
+false;this._projectName="";this._projectVersion="";this._projectUniqueId="";this._appId="";this._originalViewportWidth=0;this._originalViewportHeight=0;this._devicePixelRatio=self.devicePixelRatio;this._parallaxXorigin=0;this._parallaxYorigin=0;this._viewportWidth=0;this._viewportHeight=0;this._loaderStyle=0;this._usesLoaderLayout=false;this._isLoading=true;this._usesAnyBackgroundBlending=false;this._usesAnyCrossSampling=false;this._usesAnyDepthSampling=false;this._loadingLogoAsset=null;this._assetManager=
+C3.New(C3.AssetManager,this,opts);this._layoutManager=C3.New(C3.LayoutManager,this);this._eventSheetManager=C3.New(C3.EventSheetManager,this);this._pluginManager=C3.New(C3.PluginManager,this,opts["wrapperComponentIds"]);this._collisionEngine=C3.New(C3.CollisionEngine,this);this._timelineManager=C3.New(C3.TimelineManager,this);this._transitionManager=C3.New(C3.TransitionManager,this);this._templateManager=C3.New(C3.TemplateManager,this);this._flowchartManager=C3.New(C3.FlowchartManager,this);this._textIconManager=
+C3.New(C3.TextIconManager,{getIconSetMeta:iconSource=>this._GetTextIconSetMeta(iconSource),getIconSetContent:iconSource=>this._GetTextIconSetContent(iconSource)});this._iconChangeHandlers=new Map;this._allObjectClasses=[];this._objectClassesByName=new Map;this._objectClassesBySid=new Map;this._familyCount=0;this._allContainers=[];this._allEffectLists=new Set;this._currentLayoutStack=[];this._instancesPendingCreate=[];this._instancesPendingDestroy=new Map;this._hasPendingInstances=false;this._isFlushingPendingInstances=
+false;this._objectCount=0;this._nextUid=0;this._instancesByUid=new Map;this._instancesToReleaseAtEndOfTick=new Set;this._instancesToReleaseAffectedObjectClasses=new Set;this._objectReferenceTable=[];this._jsPropNameTable=[];this._canvasManager=null;this._uses3dFeatures=false;this._framerateMode="vsync";this._compositingMode="standard";this._sampling="trilinear";this._isPixelRoundingEnabled=false;this._needRender=true;this._pauseOnBlur=false;this._isPausedOnBlur=false;this._exportToVideo=null;this._tickCallbacks=
+{normal:timestamp=>{this._rafId=-1;this._ruafId=-1;this.Tick(timestamp)},tickOnly:timestamp=>{this._ruafId=-1;this.Tick(timestamp,false,"skip-render")},renderOnly:()=>{this._rafId=-1;this.Render()}};this._rafId=-1;this._ruafId=-1;this._tickCount=0;this._tickCountNoSave=0;this._hasStarted=false;this._isInTick=false;this._hasStartedTicking=false;this._isLayoutFirstTick=true;this._suspendCount=0;this._scheduleTriggersThrottle=new C3.PromiseThrottle(1);this._randomNumberCallback=()=>Math.random();this._startTime=
+0;this._lastTickTime=0;this._dtRaw=0;this._dt1=0;this._dt=0;this._timeScale=1;this._minimumFramerate=30;this._gameTime=C3.New(C3.KahanSum);this._gameTimeRaw=C3.New(C3.KahanSum);this._wallTime=C3.New(C3.KahanSum);this._instanceTimes=new Map;this._fpsFrameCount=-1;this._fpsLastTime=0;this._fps=0;this._mainThreadTimeCounter=0;this._mainThreadTime=0;this._isLoadingState=false;this._saveToSlotName="";this._loadFromSlotName="";this._loadFromJson=null;this._lastSaveJson="";this._projectStorage=null;this._savegamesStorage=
+null;this._dispatcher=C3.New(C3.Event.Dispatcher);this._domEventHandlers=new Map;this._pendingResponsePromises=new Map;this._nextDomResponseId=0;this._didRequestDeviceOrientationEvent=false;this._didRequestDeviceMotionEvent=false;this._isReadyToHandleEvents=false;this._waitingToHandleEvents=[];this._eventObjects={"pretick":C3.New(C3.Event,"pretick",false),"tick":C3.New(C3.Event,"tick",false),"tick2":C3.New(C3.Event,"tick2",false),"instancedestroy":C3.New(C3.Event,"instancedestroy",false),"beforelayoutchange":C3.New(C3.Event,
+"beforelayoutchange",false),"layoutchange":C3.New(C3.Event,"layoutchange",false)};this._eventObjects["instancedestroy"].instance=null;this._userScriptDispatcher=C3.New(C3.Event.Dispatcher);this._userScriptEventObjects=null;this._behInstsToTick=C3.New(C3.RedBlackSet,C3.BehaviorInstance.SortByTickSequence);this._behInstsToPostTick=C3.New(C3.RedBlackSet,C3.BehaviorInstance.SortByTickSequence);this._behInstsToTick2=C3.New(C3.RedBlackSet,C3.BehaviorInstance.SortByTickSequence);this._jobScheduler=C3.New(C3.JobSchedulerRuntime,
+this,opts["jobScheduler"]);if(opts["canvas"])this._canvasManager=C3.New(C3.CanvasManager,this);this._messagePort.onmessage=e=>this["_OnMessageFromDOM"](e.data);this.AddDOMComponentMessageHandler("runtime","visibilitychange",e=>this._OnVisibilityChange(e));this.AddDOMComponentMessageHandler("runtime","wrapper-extension-message",e=>this._OnWrapperExtensionMessage(e));this.AddDOMComponentMessageHandler("runtime","opus-decode",e=>this._WasmDecodeWebMOpus(e["arrayBuffer"]));this.AddDOMComponentMessageHandler("runtime",
+"get-remote-preview-status-info",()=>this._GetRemotePreviewStatusInfo());this.AddDOMComponentMessageHandler("runtime","js-invoke-function",e=>this._InvokeFunctionFromJS(e));this.AddDOMComponentMessageHandler("runtime","go-to-last-error-script",self["goToLastErrorScript"]);this.AddDOMComponentMessageHandler("runtime","offline-audio-render-completed",e=>this._OnOfflineAudioRenderCompleted(e));this._dispatcher.addEventListener("window-blur",e=>this._OnWindowBlur(e));this._dispatcher.addEventListener("window-focus",
+()=>this._OnWindowFocus());this._timelineManager.AddRuntimeListeners();this._templateManager.AddRuntimeListeners();this._iRuntime=null;this._interfaceMap=new WeakMap;this._commonScriptInterfaces={keyboard:null,mouse:null,touch:null};this._instancesNeedingAfterLoadMap=new WeakMap;this._instancesNeedingAfterLoadArray=[]}static Create(opts){return C3.New(C3.Runtime,opts)}Release(){C3.clearArray(this._allObjectClasses);this._objectClassesByName.clear();this._objectClassesBySid.clear();this._layoutManager.Release();
+this._layoutManager=null;this._eventSheetManager.Release();this._eventSheetManager=null;this._pluginManager.Release();this._pluginManager=null;this._assetManager.Release();this._assetManager=null;this._collisionEngine.Release();this._collisionEngine=null;this._timelineManager.Release();this._timelineManager=null;this._transitionManager.Release();this._transitionManager=null;this._templateManager.Release();this._templateManager=null;this._flowchartManager.Release();this._flowchartManager=null;this._textIconManager.Release();
+this._textIconManager=null;if(this._canvasManager){this._canvasManager.Release();this._canvasManager=null}this._dispatcher.Release();this._dispatcher=null;this._tickEvent=null}["_OnMessageFromDOM"](data){const type=data["type"];if(type==="event")this._OnEventFromDOM(data);else if(type==="result")this._OnResultFromDOM(data);else throw new Error(`unknown message '${type}'`);}_OnEventFromDOM(e){if(!this._isReadyToHandleEvents){this._waitingToHandleEvents.push(e);return}const component=e["component"];
+const handler=e["handler"];const data=e["data"];const dispatchOpts=e["dispatchOpts"];const dispatchRuntimeEvent=!!(dispatchOpts&&dispatchOpts["dispatchRuntimeEvent"]);const dispatchUserScriptEvent=!!(dispatchOpts&&dispatchOpts["dispatchUserScriptEvent"]);const responseId=e["responseId"];if(component==="runtime"){if(dispatchRuntimeEvent){const event=new C3.Event(handler);event.data=data;this._dispatcher.dispatchEventAndWaitAsyncSequential(event)}if(dispatchUserScriptEvent){const event=new C3.Event(handler,
+true);for(const [key,value]of Object.entries(data))event[key]=value;this.DispatchUserScriptEvent(event)}}const handlerMap=this._domEventHandlers.get(component);if(!handlerMap){if(!dispatchRuntimeEvent&&!dispatchUserScriptEvent)console.warn(`[Runtime] No DOM event handlers for component '${component}'`);return}const func=handlerMap.get(handler);if(!func){if(!dispatchRuntimeEvent&&!dispatchUserScriptEvent)console.warn(`[Runtime] No DOM handler '${handler}' for component '${component}'`);return}let ret=
+null;try{ret=func(data)}catch(err){console.error(`Exception in '${component}' handler '${handler}':`,err);if(responseId!==null)this._PostResultToDOM(responseId,false,""+err);return}if(responseId!==null)if(ret&&ret.then)ret.then(result=>this._PostResultToDOM(responseId,true,result)).catch(err=>{console.error(`Rejection from '${component}' handler '${handler}':`,err);this._PostResultToDOM(responseId,false,""+err)});else this._PostResultToDOM(responseId,true,ret)}_PostResultToDOM(responseId,isOk,result){this._messagePort.postMessage({"type":"result",
+"responseId":responseId,"isOk":isOk,"result":result})}_OnResultFromDOM(data){const responseId=data["responseId"];const isOk=data["isOk"];const result=data["result"];const pendingPromise=this._pendingResponsePromises.get(responseId);if(isOk)pendingPromise.resolve(result);else pendingPromise.reject(result);this._pendingResponsePromises.delete(responseId)}AddDOMComponentMessageHandler(component,handler,func){let handlerMap=this._domEventHandlers.get(component);if(!handlerMap){handlerMap=new Map;this._domEventHandlers.set(component,
+handlerMap)}if(handlerMap.has(handler))throw new Error(`[Runtime] Component '${component}' already has handler '${handler}'`);handlerMap.set(handler,func)}PostComponentMessageToDOM(component,handler,data,transfer){this._messagePort.postMessage({"type":"event","component":component,"handler":handler,"data":data,"responseId":null},transfer)}PostComponentMessageToDOMAsync(component,handler,data,transfer){const responseId=this._nextDomResponseId++;const ret=new Promise((resolve,reject)=>{this._pendingResponsePromises.set(responseId,
+{resolve,reject})});this._messagePort.postMessage({"type":"event","component":component,"handler":handler,"data":data,"responseId":responseId},transfer);return ret}SendWrapperExtensionMessage(componentId,messageId,params,asyncId=-1){this.PostComponentMessageToDOM("runtime","send-wrapper-extension-message",{"componentId":componentId,"messageId":messageId,"params":params,"asyncId":asyncId})}SendWrapperExtensionMessageAsync(componentId,messageId,params){const responseId=this._nextDomResponseId++;const ret=
+new Promise((resolve,reject)=>{this._pendingResponsePromises.set(responseId,{resolve,reject})});this.SendWrapperExtensionMessage(componentId,messageId,params,responseId);return ret}_OnWrapperExtensionMessage(data){if(data["asyncId"]!==-1){const responseId=data["asyncId"];const pendingPromise=this._pendingResponsePromises.get(responseId);pendingPromise.resolve(data["params"]);this._pendingResponsePromises.delete(responseId)}else this._OnEventFromDOM({"component":"wrapper-extension:"+data["componentId"],
+"handler":data["messageId"],"data":data["params"],"responseId":null})}AddWrapperExtensionMessageHandler(componentId,messageId,func){this.AddDOMComponentMessageHandler("wrapper-extension:"+componentId,messageId,func)}HasWrapperComponentId(id){return this._pluginManager.HasWrapperComponentId(id)}PostToDebugger(data){if(!this.IsDebug())throw new Error("not in debug mode");this.PostComponentMessageToDOM("runtime","post-to-debugger",data)}async Init(opts){if(this.IsDebug())await C3Debugger.Init(this);
+else if(self.C3Debugger)self.C3Debugger.InitPreview(this);const [o]=await Promise.all([this._assetManager.FetchJson("data.json"),this._MaybeLoadOpusDecoder(),this._jobScheduler.Init()]);await this._LoadDataJson(o);await this._InitialiseCanvas(opts);if(!this.IsPreview())console.info("Made with Construct, the game and app creator :: https://www.construct.net");if(this.GetWebGLRenderer()){const webglRenderer=this.GetWebGLRenderer();console.info(`[C3 runtime] Hosted in ${this.IsInWorker()?"worker":"DOM"}, rendering with WebGL ${webglRenderer.GetWebGLVersionNumber()} [${webglRenderer.GetUnmaskedRenderer()}] (${webglRenderer.IsDesynchronized()?
+"desynchronized":"standard"} compositing)`)}else if(this.GetWebGPURenderer())console.info(`[C3 runtime] Hosted in ${this.IsInWorker()?"worker":"DOM"}, rendering with WebGPU [${this.GetWebGPURenderer().GetAdapterInfoString()}]`);if(this.GetRenderer().HasMajorPerformanceCaveat())console.warn("[C3 runtime] The renderer indicates a major performance caveat. Software rendering may be in use. This can result in significantly degraded performance.");this._isReadyToHandleEvents=true;for(const e of this._waitingToHandleEvents)this._OnEventFromDOM(e);
+C3.clearArray(this._waitingToHandleEvents);if(this._canvasManager)this._canvasManager.StartLoadingScreen();for(const f of opts["runOnStartupFunctions"])this._additionalLoadPromises.push(this._RunOnStartupFunction(f));await Promise.all([this._assetManager.WaitForAllToLoad(),...this._additionalLoadPromises]);C3.clearArray(this._additionalLoadPromises);if(this._assetManager.HasHadErrorLoading()){if(this._canvasManager)this._canvasManager.HideCordovaSplashScreen();return}if(this._canvasManager)await this._canvasManager.EndLoadingScreen();
+await this._dispatcher.dispatchEventAndWaitAsync(new C3.Event("beforeruntimestart"));await this.Start();this._messagePort.postMessage({"type":"runtime-ready"});return this}async _RunOnStartupFunction(f){try{await f(this._iRuntime)}catch(err){console.error("[C3 runtime] Error in runOnStartup function: ",err)}}async _LoadDataJson(o){const projectData=o["project"];this._projectName=projectData[0];this._projectVersion=projectData[16];this._projectUniqueId=projectData[31];this._appId=projectData[38];const loadingLogoFilename=
+projectData[39]||"loading-logo.png";this._isPixelRoundingEnabled=!!projectData[9];this._originalViewportWidth=this._viewportWidth=projectData[10];this._originalViewportHeight=this._viewportHeight=projectData[11];this._collisionEngine._InitCollisionCellSize(this._originalViewportWidth,this._originalViewportHeight);this._parallaxXorigin=this._originalViewportWidth/2;this._parallaxYorigin=this._originalViewportHeight/2;this._compositingMode=projectData[36];this._framerateMode=projectData[37];if(this._compositingMode===
+"low-latency"&&this.IsAndroidWebView()&&C3.Platform.BrowserVersionNumber<=77){console.warn("[C3 runtime] Desynchronized (low-latency) compositing is enabled, but is disabled in the Android WebView <=77 due to crbug.com/1008842. Reverting to synchronized (standard) compositing.");this._compositingMode="standard"}this._uses3dFeatures=!!projectData[40];this._sampling=projectData[14];this._usesAnyBackgroundBlending=projectData[15];this._usesAnyCrossSampling=projectData[42];this._usesAnyDepthSampling=
+projectData[17];this._usesLoaderLayout=!!projectData[18];this._loaderStyle=projectData[19];this._nextUid=projectData[21];this._pauseOnBlur=projectData[22];const assetManager=this._assetManager;assetManager._SetFileStructure(projectData[45]);assetManager._SetAudioFiles(projectData[7],projectData[25]);assetManager._SetMediaSubfolder(projectData[8]);assetManager._SetFontsSubfolder(projectData[32]);assetManager._SetIconsSubfolder(projectData[28]);assetManager._SetWebFonts(projectData[29]);if(this._loaderStyle===
+0){let url="";if(this.IsPreview()){if(assetManager._HasLocalUrlBlob(loadingLogoFilename))url=assetManager.GetLocalUrlAsBlobUrl(loadingLogoFilename)}else if(assetManager.GetFileStructure()==="flat")url=assetManager.GetIconsSubfolder()+loadingLogoFilename;else url=loadingLogoFilename;if(url)this._loadingLogoAsset=assetManager.LoadImage({url})}if(this._canvasManager){this._canvasManager.SetFullscreenMode(C3.CanvasManager._FullscreenModeNumberToString(projectData[12]));this._canvasManager.SetFullscreenScalingQuality(projectData[23]?
+"high":"low");this._canvasManager.SetMipmapsEnabled(projectData[24]!==0);this._canvasManager._SetGPUPowerPreference(projectData[34]);this._canvasManager._SetTextureAnisotropy(projectData[41]);this._canvasManager._SetWebGPUEnabled(projectData[13]);this._canvasManager._SetZAxisScale(projectData[30]);this._canvasManager._SetZDistances(projectData[46],projectData[47]);this._canvasManager._SetFieldOfView(projectData[26]);this._canvasManager._SetLimitedToWebGL1(projectData[48])}const exportToVideoOpts=
+projectData[43];if(exportToVideoOpts)await this._LoadExportToVideoData(exportToVideoOpts);this._pluginManager.CreateSystemPlugin();this._objectReferenceTable=self.C3_GetObjectRefTable();for(const pluginData of projectData[2])this._pluginManager.CreatePlugin(pluginData);this._objectReferenceTable=self.C3_GetObjectRefTable();this._LoadJsPropNameTable();for(const objectClassData of projectData[3]){const objectClass=C3.ObjectClass.Create(this,this._allObjectClasses.length,objectClassData);this._allObjectClasses.push(objectClass);
+this._objectClassesByName.set(objectClass.GetName().toLowerCase(),objectClass);this._objectClassesBySid.set(objectClass.GetSID(),objectClass)}for(const familyData of projectData[4]){const familyType=this._allObjectClasses[familyData[0]];familyType._LoadFamily(familyData)}for(const containerData of projectData[27]){const containerTypes=containerData.map(index=>this._allObjectClasses[index]);this._allContainers.push(C3.New(C3.Container,this,containerTypes))}for(const objectClass of this._allObjectClasses)objectClass._OnAfterCreate();
+for(const layoutData of projectData[5])this._layoutManager.Create(layoutData);const firstLayoutName=projectData[1];if(firstLayoutName){const firstLayout=this._layoutManager.GetLayoutByName(firstLayoutName);if(firstLayout)this._layoutManager.SetFirstLayout(firstLayout)}for(const timelineData of projectData[33])this._timelineManager.Create(timelineData);for(const transitionData of projectData[35])this._transitionManager.Create(transitionData);for(const templateInstanceData of projectData[44])this._templateManager.Create(templateInstanceData);
+if(!this._templateManager.HasTemplates()){this._templateManager.Release();this._templateManager=null}for(const flowchartData of projectData[49])this._flowchartManager.Create(flowchartData);if(!this._flowchartManager.HasFlowcharts()){this._flowchartManager.Release();this._flowchartManager=null}this._InitScriptInterfaces();for(const eventSheetData of projectData[6])this._eventSheetManager.Create(eventSheetData);this._eventSheetManager._PostInit();this._InitGlobalVariableScriptInterface();C3.clearArray(this._objectReferenceTable);
+this.FlushPendingInstances();let targetOrientation="any";const orientations=projectData[20];if(orientations===1)targetOrientation="portrait";else if(orientations===2)targetOrientation="landscape";this.PostComponentMessageToDOM("runtime","set-target-orientation",{"targetOrientation":targetOrientation})}async _LoadExportToVideoData(exportToVideoOpts){const format=exportToVideoOpts["format"];if(format==="image-sequence")this._exportToVideo=new self.C3ExportToImageSequence(this,exportToVideoOpts);else if(format===
+"image-sequence-gif")this._exportToVideo=new self.C3ExportToGIF(this,exportToVideoOpts);else if(format==="webm")this._exportToVideo=new self.C3ExportToWebMVideo(this,exportToVideoOpts);else if(format==="mp4")this._exportToVideo=new self.C3ExportToMP4Video(this,exportToVideoOpts);else;this._framerateMode="unlimited-frame";this._canvasManager.SetFullscreenMode("off");this._devicePixelRatio=1;self.devicePixelRatio=1;await this.PostComponentMessageToDOMAsync("runtime","set-exporting-to-video",{"message":this._exportToVideo.GetExportingMessageForPercent(0),
+"duration":this._exportToVideo.GetDuration()})}GetLoaderStyle(){return this._loaderStyle}IsExportToVideo(){return this._exportToVideo!==null}GetExportVideoDuration(){return this._exportToVideo.GetDuration()}GetExportVideoFramerate(){return this._exportToVideo.GetFramerate()}_InitExportToVideo(){return this._exportToVideo.Init({width:this._canvasManager.GetDeviceWidth(),height:this._canvasManager.GetDeviceHeight()})}_ExportToVideoAddFrame(){const time=this._tickCount/this.GetExportVideoFramerate();
+return this._exportToVideo.AddFrame(this._canvasManager.GetMainCanvas(),time)}_ExportToVideoAddKeyframe(){if(this._exportToVideo)this._exportToVideo.AddKeyframe()}_OnOfflineAudioRenderCompleted(e){this._exportToVideo.OnOfflineAudioRenderCompleted(e)}_ExportToVideoFinish(){return this._exportToVideo.Finish()}IsFBInstantAvailable(){return this._isFBInstantAvailable}IsLoading(){return this._isLoading}AddLoadPromise(promise){this._additionalLoadPromises.push(promise)}SetUsingCreatePromises(e){this._isUsingCreatePromises=
+!!e}AddCreatePromise(promise){if(!this._isUsingCreatePromises)return;this._additionalCreatePromises.push(promise)}GetCreatePromises(){return this._additionalCreatePromises}_GetNextFamilyIndex(){return this._familyCount++}GetFamilyCount(){return this._familyCount}_AddEffectList(el){this._allEffectLists.add(el)}_RemoveEffectList(el){this._allEffectLists.delete(el)}_GetAllEffectLists(){return this._allEffectLists}async _InitialiseCanvas(opts){if(!this._canvasManager)return;await this._canvasManager.CreateCanvas(opts);
+this._canvasManager.InitLoadingScreen(this._loaderStyle)}async _MaybeLoadOpusDecoder(){if(this._assetManager.IsAudioFormatSupported("audio/webm; codecs=opus"))return;let wasmBlob=null;let wasmBuffer=null;try{if(this.IsiOSCordova()&&this._assetManager.IsFileProtocol())wasmBuffer=await this._assetManager.CordovaFetchLocalFileAsArrayBuffer(this._opusWasmBinaryUrl);else wasmBuffer=await this._assetManager.FetchArrayBuffer(this._opusWasmBinaryUrl)}catch(err){console.info("Failed to fetch Opus decoder WASM; assuming project has no Opus audio.",
+err);return}if(wasmBuffer)this.AddJobWorkerBuffer(wasmBuffer,"opus-decoder-wasm");else this.AddJobWorkerBlob(wasmBlob,"opus-decoder-wasm");await this.AddJobWorkerScripts([this._opusWasmScriptUrl])}async _WasmDecodeWebMOpus(arrayBuffer){const result=await this.AddJob("OpusDecode",{"arrayBuffer":arrayBuffer},[arrayBuffer]);return result}async Start(){this._hasStarted=true;this._startTime=Date.now();if(this._usesLoaderLayout){for(const objectClass of this._allObjectClasses)if(!objectClass.IsFamily()&&
+!objectClass.IsOnLoaderLayout()&&objectClass.IsWorldType())objectClass.OnCreate();this._assetManager.WaitForAllToLoad().then(()=>{this._isLoading=false;this._OnLoadFinished()})}else this._isLoading=false;this._assetManager.SetInitialLoadFinished();if(this.IsDebug())C3Debugger.RuntimeInit(ife);for(const layout of this._layoutManager.GetAllLayouts())layout._CreateGlobalNonWorlds();if(this.IsExportToVideo())await this._InitExportToVideo();const firstLayout=this._layoutManager.GetFirstLayout();await firstLayout._Load(null,
+this.GetRenderer());await firstLayout._StartRunning(true);this._fpsLastTime=performance.now();if(!this._usesLoaderLayout)this._OnLoadFinished();const state=await this.PostComponentMessageToDOMAsync("runtime","before-start-ticking");if(state["isSuspended"]&&!this.IsExportToVideo())this._suspendCount++;else this.Tick()}_OnLoadFinished(){this.Trigger(C3.Plugins.System.Cnds.OnLoadFinished,null,null);this.PostComponentMessageToDOM("runtime","register-sw")}GetObjectReference(index){index=Math.floor(index);
+const objRefTable=this._objectReferenceTable;if(index<0||index>=objRefTable.length)throw new Error("invalid object reference");return objRefTable[index]}_LoadJsPropNameTable(){for(const entry of self.C3_JsPropNameTable){const propName=C3.first(Object.keys(entry));this._jsPropNameTable.push(propName)}}GetJsPropName(index){index=Math.floor(index);const jsPropNameTable=this._jsPropNameTable;if(index<0||index>=jsPropNameTable.length)throw new Error("invalid prop reference");return jsPropNameTable[index]}HasDOM(){return this._hasDom}IsHeadless(){return this._isHeadless}IsInWorker(){return this._isInWorker}GetRuntimeBaseURL(){return this._runtimeBaseUrl}GetPreviewURL(){return this._previewUrl}GetEventSheetManager(){return this._eventSheetManager}GetEventStack(){return this._eventSheetManager.GetEventStack()}GetCurrentEventStackFrame(){return this._eventSheetManager.GetCurrentEventStackFrame()}GetCurrentEvent(){return this._eventSheetManager.GetCurrentEvent()}GetCurrentCondition(){return this._eventSheetManager.GetCurrentCondition()}IsCurrentConditionFirst(){return this.GetCurrentEventStackFrame().GetConditionIndex()===
+0}GetCurrentAction(){return this._eventSheetManager.GetCurrentAction()}GetPluginManager(){return this._pluginManager}GetSystemPlugin(){return this._pluginManager.GetSystemPlugin()}GetObjectClassByIndex(i){i=Math.floor(i);if(i<0||i>=this._allObjectClasses.length)throw new RangeError("invalid index");return this._allObjectClasses[i]}GetObjectClassByName(name){return this._objectClassesByName.get(name.toLowerCase())||null}GetObjectClassBySID(sid){return this._objectClassesBySid.get(sid)||null}GetSingleGlobalObjectClassByCtor(ctor){const plugin=
+this._pluginManager.GetPluginByConstructorFunction(ctor);if(!plugin)return null;return plugin.GetSingleGlobalObjectClass()}GetAllObjectClasses(){return this._allObjectClasses}*allInstances(){for(const objectClass of this._allObjectClasses){if(objectClass.IsFamily())continue;yield*objectClass.instances()}}Dispatcher(){return this._dispatcher}UserScriptDispatcher(){return this._userScriptDispatcher}DispatchUserScriptEvent(e){e.runtime=this.GetIRuntime();const shouldTime=this.IsDebug()&&!this._eventSheetManager.IsInEventEngine();
+if(shouldTime)C3Debugger.StartMeasuringScriptTime();this._userScriptDispatcher.dispatchEvent(e);if(shouldTime)C3Debugger.AddScriptTime()}DispatchUserScriptEventAsyncWait(e){e.runtime=this.GetIRuntime();return this._userScriptDispatcher.dispatchEventAndWaitAsync(e)}GetOriginalViewportWidth(){return this._originalViewportWidth}GetOriginalViewportHeight(){return this._originalViewportHeight}SetOriginalViewportSize(w,h){if(this._originalViewportWidth===w&&this._originalViewportHeight===h)return;this._originalViewportWidth=
+w;this._originalViewportHeight=h;const layoutManager=this.GetLayoutManager();layoutManager.SetAllLayerProjectionChanged();layoutManager.SetAllLayerMVChanged()}GetViewportWidth(){return this._viewportWidth}GetViewportHeight(){return this._viewportHeight}SetViewportSize(w,h){if(this._viewportWidth===w&&this._viewportHeight===h)return;this._viewportWidth=w;this._viewportHeight=h;const layoutManager=this.GetLayoutManager();layoutManager.SetAllLayerProjectionChanged();layoutManager.SetAllLayerMVChanged()}_SetDevicePixelRatio(r){if(this.IsExportToVideo())return;
+this._devicePixelRatio=r}GetDevicePixelRatio(){return this._devicePixelRatio}GetParallaxXOrigin(){return this._parallaxXorigin}GetParallaxYOrigin(){return this._parallaxYorigin}GetCanvasManager(){return this._canvasManager}GetDrawWidth(){if(!this._canvasManager)return this._viewportWidth;return this._canvasManager.GetDrawWidth()}GetDrawHeight(){if(!this._canvasManager)return this._viewportHeight;return this._canvasManager.GetDrawHeight()}GetRenderScale(){if(!this._canvasManager)return 1;return this._canvasManager.GetRenderScale()}GetDisplayScale(){if(!this._canvasManager)return 1;
+return this._canvasManager.GetDisplayScale()}GetEffectLayerScaleParam(){if(!this._canvasManager)return 1;return this._canvasManager.GetEffectLayerScaleParam()}GetEffectDevicePixelRatioParam(){if(!this._canvasManager)return 1;return this._canvasManager.GetEffectDevicePixelRatioParam()}GetCanvasClientX(){if(!this._canvasManager)return 0;return this._canvasManager.GetCanvasClientX()}GetCanvasClientY(){if(!this._canvasManager)return 0;return this._canvasManager.GetCanvasClientY()}GetCanvasCssWidth(){if(!this._canvasManager)return 0;
+return this._canvasManager.GetCssWidth()}GetCanvasCssHeight(){if(!this._canvasManager)return 0;return this._canvasManager.GetCssHeight()}GetFullscreenMode(){if(!this._canvasManager)return"off";return this._canvasManager.GetFullscreenMode()}GetAdditionalRenderTarget(opts){if(!this._canvasManager)return null;return this._canvasManager.GetAdditionalRenderTarget(opts)}ReleaseAdditionalRenderTarget(renderTarget){if(!this._canvasManager)return;this._canvasManager.ReleaseAdditionalRenderTarget(renderTarget)}UsesAnyBackgroundBlending(){return this._usesAnyBackgroundBlending}UsesAnyCrossSampling(){return this._usesAnyCrossSampling}UsesAnyDepthSampling(){return this._usesAnyDepthSampling}GetGPUUtilisation(){if(!this._canvasManager)return NaN;
+return this._canvasManager.GetGPUUtilisation()}IsLinearSampling(){return this.GetSampling()!=="nearest"}GetFramerateMode(){return this._framerateMode}GetCompositingMode(){return this._compositingMode}GetSampling(){return this._sampling}UsesLoaderLayout(){return this._usesLoaderLayout}GetLoadingLogoAsset(){return this._loadingLogoAsset}ReleaseLoadingLogoAsset(){if(this._loadingLogoAsset){this._loadingLogoAsset.Release();this._loadingLogoAsset=null}}GetLayoutManager(){return this._layoutManager}GetMainRunningLayout(){return this._layoutManager.GetMainRunningLayout()}GetTimelineManager(){return this._timelineManager}GetTransitionManager(){return this._transitionManager}GetTemplateManager(){return this._templateManager}GetFlowchartManager(){return this._flowchartManager}GetAssetManager(){return this._assetManager}LoadImage(opts){return this._assetManager.LoadImage(opts)}CreateInstance(objectClass,
+layer,x,y,createHierarchy,templateName){if(templateName&&this._templateManager){const templateData=this._templateManager.GetTemplateData(objectClass,templateName);if(templateData){const inst=this.CreateInstanceFromData(templateData,layer,false,x,y,false,createHierarchy,undefined,createHierarchy);this._templateManager.MapInstanceToTemplateName(inst,templateName);return inst}}return this.CreateInstanceFromData(objectClass,layer,false,x,y,false,createHierarchy,undefined,createHierarchy)}CreateInstanceFromData(instData_or_objectClass,
+layer,isStartupInstance,x,y,skipSiblings,createHierarchy,previousInstance,creatingHierarchy){let instData=null;let objectClass=null;if(instData_or_objectClass instanceof C3.ObjectClass){objectClass=instData_or_objectClass;if(objectClass.IsFamily()){const members=objectClass.GetFamilyMembers();const i=Math.floor(this.Random()*members.length);objectClass=members[i]}instData=objectClass.GetDefaultInstanceData()}else{instData=instData_or_objectClass;objectClass=this.GetObjectClassByIndex(instData[1])}const isWorld=
+objectClass.GetPlugin().IsWorldType();if(this._isLoading&&isWorld&&!objectClass.IsOnLoaderLayout())return null;const originalLayer=layer;if(!isWorld)layer=null;let uid;if(isStartupInstance&&!skipSiblings&&instData&&!this._instancesByUid.has(instData[2]))uid=instData[2];else uid=this._nextUid++;const worldData=instData?instData[0]:null;const inst=C3.New(C3.Instance,{runtime:this,objectType:objectClass,layer:layer,worldData,instVarData:instData?instData[3]:null,uid:uid});this._instancesByUid.set(uid,
+inst);let wi=null;if(isWorld){wi=inst.GetWorldInfo();if(typeof x!=="undefined"&&typeof y!=="undefined"){wi.SetX(x);wi.SetY(y)}objectClass._SetAnyCollisionCellChanged(true)}if(layer){if(!creatingHierarchy)layer._AddInstance(inst,true);if(layer.GetParallaxX()!==1||layer.GetParallaxY()!==1)objectClass._SetAnyInstanceParallaxed(true);layer.GetLayout().MaybeLoadTexturesFor(objectClass)}this._objectCount++;let needsSiblingCreation=true;if(previousInstance){const previousObjectClass=previousInstance.GetObjectClass();
+if(previousObjectClass.IsInContainer()&&objectClass.IsInContainer()){const container=objectClass.GetContainer();const previousContainer=previousObjectClass.GetContainer();if(container===previousContainer)needsSiblingCreation=false}}if(objectClass.IsInContainer()&&!isStartupInstance&&!skipSiblings&&needsSiblingCreation){for(const containerType of objectClass.GetContainer().objectTypes()){if(containerType===objectClass)continue;const siblingInst=this.CreateInstanceFromData(containerType,originalLayer,
+false,wi?wi.GetX():x,wi?wi.GetY():y,true,false,undefined,creatingHierarchy);inst._AddSibling(siblingInst)}for(const s of inst.siblings()){s._AddSibling(inst);for(const s2 of inst.siblings())if(s!==s2)s._AddSibling(s2)}}if(isWorld&&!isStartupInstance&&!!createHierarchy)this._CreateChildInstancesFromData(inst,worldData,wi,layer,x,y,creatingHierarchy);if(objectClass.IsInContainer()&&!isStartupInstance&&!skipSiblings&&!!createHierarchy)for(const sibling of inst.siblings()){const swi=sibling.GetWorldInfo();
+if(!swi)continue;const siblingPlugin=sibling.GetPlugin();const sWorldData=sibling.GetObjectClass().GetDefaultInstanceData()[0];if(siblingPlugin.IsWorldType())this._CreateChildInstancesFromData(sibling,sWorldData,swi,layer,swi.GetX(),swi.GetY(),creatingHierarchy);else this._CreateChildInstancesFromData(sibling,sWorldData,swi,layer,undefined,undefined,creatingHierarchy)}if(!skipSiblings&&!!createHierarchy){if(typeof x==="undefined")x=worldData[0];if(typeof y==="undefined")y=worldData[1];const pwi=wi.GetTopParent();
+const newX=x-wi.GetX()+pwi.GetX();const newY=y-wi.GetY()+pwi.GetY();pwi.SetXY(newX,newY)}objectClass._SetIIDsStale();const instPropertyData=instData?C3.cloneArray(instData[5]):null;const behPropertyData=instData?instData[4].map(bp=>C3.cloneArray(bp)):null;const hasTilemap=isWorld&&worldData&&worldData[13];if(hasTilemap)inst._SetHasTilemap();inst._CreateSdkInstance(instPropertyData,behPropertyData);if(hasTilemap){const tilemapData=worldData[13];inst.GetSdkInstance().LoadTilemapData(tilemapData[2],
+tilemapData[0],tilemapData[1])}this._instancesPendingCreate.push(inst);this._hasPendingInstances=true;if(this.IsDebug())C3Debugger.InstanceCreated(inst);return inst}_CreateChildInstancesFromData(parentInstance,parentWorldData,parentWorldInfo,layer,x,y,creatingHierarchy){const parentZIndex=parentWorldInfo.GetSceneGraphZIndexExportData();const childrenData=parentWorldInfo.GetSceneGraphChildrenExportData();parentInstance.GetWorldInfo().SetSceneGraphZIndex(parentZIndex);if(!childrenData)return;if(typeof x===
+"undefined")x=parentWorldData[0];if(typeof y==="undefined")y=parentWorldData[1];const sceneGraphSiblings=new Set;const parentX=parentWorldData[0];const parentY=parentWorldData[1];for(const childData of childrenData){const childLayoutSID=childData[0];const childLayerIndex=childData[1];const childUID=childData[2];const childFlags=childData[3];const childIsInContainer=!!childData[4];const childZIndex=childData[5];const uniqueInstanceData=childData[6];let childInstData;if(uniqueInstanceData)childInstData=
+uniqueInstanceData;else{const layout=this._layoutManager.GetLayoutBySID(childLayoutSID);const l=layout.GetLayer(childLayerIndex);childInstData=l.GetInitialInstanceData(childUID)}const childObjectClass=this.GetObjectClassByIndex(childInstData[1]);const hasSibling=parentInstance.HasSibling(childObjectClass);const siblingProcessed=sceneGraphSiblings.has(childObjectClass);if(hasSibling&&!siblingProcessed&&childIsInContainer){const childInst=parentInstance.GetSibling(childObjectClass);const childX=x+childInstData[0][0]-
+parentX;const childY=y+childInstData[0][1]-parentY;childInst.GetWorldInfo().SetXY(childX,childY);childInst.GetWorldInfo().SetSceneGraphZIndex(childZIndex);parentInstance.AddChild(childInst,{transformX:!!(childFlags>>0&1),transformY:!!(childFlags>>1&1),transformWidth:!!(childFlags>>2&1),transformHeight:!!(childFlags>>3&1),transformAngle:!!(childFlags>>4&1),destroyWithParent:!!(childFlags>>5&1),transformZElevation:!!(childFlags>>6&1),transformOpacity:!!(childFlags>>7&1),transformVisibility:!!(childFlags>>
+8&1)});sceneGraphSiblings.add(childObjectClass)}else{const childX=x+childInstData[0][0]-parentX;const childY=y+childInstData[0][1]-parentY;const childInst=this.CreateInstanceFromData(childInstData,layer,false,childX,childY,false,true,parentInstance,creatingHierarchy);childInst.GetWorldInfo().SetSceneGraphZIndex(childZIndex);parentInstance.AddChild(childInst,{transformX:!!(childFlags>>0&1),transformY:!!(childFlags>>1&1),transformWidth:!!(childFlags>>2&1),transformHeight:!!(childFlags>>3&1),transformAngle:!!(childFlags>>
+4&1),destroyWithParent:!!(childFlags>>5&1),transformZElevation:!!(childFlags>>6&1),transformOpacity:!!(childFlags>>7&1),transformVisibility:!!(childFlags>>8&1)})}}}DestroyInstance(inst){if(this._instancesToReleaseAtEndOfTick.has(inst))return;const objectClass=inst.GetObjectClass();let s=this._instancesPendingDestroy.get(objectClass);if(s){if(s.has(inst))return;s.add(inst)}else{s=new Set;s.add(inst);this._instancesPendingDestroy.set(objectClass,s)}if(this.IsDebug())C3Debugger.InstanceDestroyed(inst);
+inst._MarkDestroyed();this._hasPendingInstances=true;if(inst.IsInContainer())for(const s of inst.siblings())this.DestroyInstance(s);for(const c of inst.children())if(c.GetDestroyWithParent())this.DestroyInstance(c);if(!this._layoutManager.IsEndingLayout()&&!this._isLoadingState){const eventSheetManager=this.GetEventSheetManager();eventSheetManager.BlockFlushingInstances(true);inst._TriggerOnDestroyed();eventSheetManager.BlockFlushingInstances(false)}inst._FireDestroyedScriptEvents(this._layoutManager.IsEndingLayout())}FlushPendingInstances(){if(!this._hasPendingInstances)return;
+this._isFlushingPendingInstances=true;this._FlushInstancesPendingCreate();this._FlushInstancesPendingDestroy();this._isFlushingPendingInstances=false;this._hasPendingInstances=false;this.UpdateRender()}_FlushInstancesPendingCreate(){for(const inst of this._instancesPendingCreate){const objectType=inst.GetObjectClass();objectType._AddInstance(inst);for(const family of objectType.GetFamilies()){family._AddInstance(inst);family._SetIIDsStale()}}C3.clearArray(this._instancesPendingCreate)}_FlushInstancesPendingDestroy(){this._dispatcher.SetDelayRemoveEventsEnabled(true);
+for(const [objectClass,s]of this._instancesPendingDestroy.entries()){this._FlushInstancesPendingDestroyForObjectClass(objectClass,s);s.clear()}this._instancesPendingDestroy.clear();this._dispatcher.SetDelayRemoveEventsEnabled(false)}_FlushInstancesPendingDestroyForObjectClass(objectClass,s){for(const inst of s){const instanceDestroyEvent=this._eventObjects["instancedestroy"];instanceDestroyEvent.instance=inst;this._dispatcher.dispatchEvent(instanceDestroyEvent);this._instancesByUid.delete(inst.GetUID());
+this._instanceTimes.delete(inst);const wi=inst.GetWorldInfo();if(wi){wi._RemoveFromCollisionCells();wi._RemoveFromRenderCells();wi._MarkDestroyed()}this._instancesToReleaseAtEndOfTick.add(inst);this._objectCount--}C3.arrayRemoveAllInSet(objectClass.GetInstances(),s);objectClass._SetIIDsStale();this._instancesToReleaseAffectedObjectClasses.add(objectClass);if(objectClass.GetInstances().length===0)objectClass._SetAnyInstanceParallaxed(false);for(const family of objectClass.GetFamilies()){C3.arrayRemoveAllInSet(family.GetInstances(),
+s);family._SetIIDsStale();this._instancesToReleaseAffectedObjectClasses.add(family)}if(objectClass.GetPlugin().IsWorldType()){const layers=new Set([...s].map(i=>i.GetWorldInfo().GetLayer()));for(const layer of layers)layer._RemoveAllInstancesInSet(s)}}_GetInstancesPendingCreate(){return this._instancesPendingCreate}*instancesPendingCreateForObjectClass(objectClass){for(const inst of this._GetInstancesPendingCreate())if(objectClass.IsFamily()){if(inst.GetObjectClass().BelongsToFamily(objectClass))yield inst}else if(inst.GetObjectClass()===
+objectClass)yield inst}_GetNewUID(){return this._nextUid++}_MapInstanceByUID(uid,inst){this._instancesByUid.set(uid,inst)}_OnRendererContextLost(){this._dispatcher.dispatchEvent(C3.New(C3.Event,"renderercontextlost"));this.SetSuspended(true);for(const objectClass of this._allObjectClasses)if(!objectClass.IsFamily()&&objectClass.HasLoadedTextures())objectClass.ReleaseTextures();const runningLayout=this.GetMainRunningLayout();if(runningLayout)runningLayout._OnRendererContextLost();C3.ImageInfo.OnRendererContextLost();
+C3.ImageAsset.OnRendererContextLost()}async _OnRendererContextRestored(){await this.GetMainRunningLayout()._Load(null,this.GetRenderer());this._dispatcher.dispatchEvent(C3.New(C3.Event,"renderercontextrestored"));this.SetSuspended(false);this.UpdateRender()}_OnVisibilityChange(e){const isHidden=e["hidden"];this.SetSuspended(isHidden);if(!isHidden)this.UpdateRender()}_OnWindowBlur(e){if(!this.IsPreview()||!this._pauseOnBlur||C3.Platform.IsMobile)return;if(!e.data["parentHasFocus"]){this.SetSuspended(true);
+this._isPausedOnBlur=true}}_OnWindowFocus(){if(!this._isPausedOnBlur)return;this.SetSuspended(false);this._isPausedOnBlur=false}_RequestAnimationFrame(){const tickCallbacks=this._tickCallbacks;if(this._framerateMode==="vsync"){if(this._rafId===-1)this._rafId=self.requestAnimationFrame(tickCallbacks.normal)}else if(this._framerateMode==="unlimited-tick"){if(this._ruafId===-1)this._ruafId=C3.RequestUnlimitedAnimationFrame(tickCallbacks.tickOnly);if(this._rafId===-1)this._rafId=self.requestAnimationFrame(tickCallbacks.renderOnly)}else if(this._ruafId===
+-1)this._ruafId=C3.RequestUnlimitedAnimationFrame(tickCallbacks.normal)}_CancelAnimationFrame(){if(this._rafId!==-1){self.cancelAnimationFrame(this._rafId);this._rafId=-1}if(this._ruafId!==-1){C3.CancelUnlimitedAnimationFrame(this._ruafId);this._ruafId=-1}}IsSuspended(){return this._suspendCount>0}SetSuspended(s){if(this.IsExportToVideo())return;const wasSuspended=this.IsSuspended();this._suspendCount+=s?1:-1;if(this._suspendCount<0)this._suspendCount=0;const isSuspended=this.IsSuspended();if(!wasSuspended&&
+isSuspended){console.log("[Construct] Suspending");this._CancelAnimationFrame();this._dispatcher.dispatchEvent(C3.New(C3.Event,"suspend"));this.Trigger(C3.Plugins.System.Cnds.OnSuspend,null,null)}else if(wasSuspended&&!isSuspended){console.log("[Construct] Resuming");const now=performance.now();this._lastTickTime=now;this._fpsLastTime=now;this._fpsFrameCount=0;this._fps=0;this._mainThreadTime=0;this._mainThreadTimeCounter=0;this._dispatcher.dispatchEvent(C3.New(C3.Event,"resume"));this.Trigger(C3.Plugins.System.Cnds.OnResume,
+null,null);if(!this.HitBreakpoint())this.Tick(now)}}_AddBehInstToTick(behSdkInst){this._behInstsToTick.Add(behSdkInst)}_AddBehInstToPostTick(behSdkInst){this._behInstsToPostTick.Add(behSdkInst)}_AddBehInstToTick2(behSdkInst){this._behInstsToTick2.Add(behSdkInst)}_RemoveBehInstToTick(behSdkInst){this._behInstsToTick.Remove(behSdkInst)}_RemoveBehInstToPostTick(behSdkInst){this._behInstsToPostTick.Remove(behSdkInst)}_RemoveBehInstToTick2(behSdkInst){this._behInstsToTick2.Remove(behSdkInst)}_BehaviorTick(){this._behInstsToTick.SetQueueingEnabled(true);
+for(const bi of this._behInstsToTick)bi.Tick();this._behInstsToTick.SetQueueingEnabled(false)}_BehaviorPostTick(){this._behInstsToPostTick.SetQueueingEnabled(true);for(const bi of this._behInstsToPostTick)bi.PostTick();this._behInstsToPostTick.SetQueueingEnabled(false)}_BehaviorTick2(){this._behInstsToTick2.SetQueueingEnabled(true);for(const bi of this._behInstsToTick2)bi.Tick2();this._behInstsToTick2.SetQueueingEnabled(false)}*_DebugBehaviorTick(){this._behInstsToTick.SetQueueingEnabled(true);for(const bi of this._behInstsToTick){const ret=
+bi.Tick();if(C3.IsIterator(ret))yield*ret}this._behInstsToTick.SetQueueingEnabled(false)}*_DebugBehaviorPostTick(){this._behInstsToPostTick.SetQueueingEnabled(true);for(const bi of this._behInstsToPostTick){const ret=bi.PostTick();if(C3.IsIterator(ret))yield*ret}this._behInstsToPostTick.SetQueueingEnabled(false)}*_DebugBehaviorTick2(){this._behInstsToTick2.SetQueueingEnabled(true);for(const bi of this._behInstsToTick2){const ret=bi.Tick2();if(C3.IsIterator(ret))yield*ret}this._behInstsToTick2.SetQueueingEnabled(false)}async Tick(timestamp,
+isDebugStep,mode){this._hasStartedTicking=true;const isBackgroundWake=mode==="background-wake";const shouldRender=mode!=="background-wake"&&mode!=="skip-render";const layoutManager=this.GetLayoutManager();const canvasManager=this.GetCanvasManager();if(!this._hasStarted||this.IsSuspended()&&!isDebugStep&&!isBackgroundWake)return;const startTime=performance.now();this._isInTick=true;this._MeasureDt(timestamp||0);const beforePreTickRet=this.Step_BeforePreTick();if(this.IsDebugging())await beforePreTickRet;
+const pretickRet=this._dispatcher.dispatchEventAndWait_AsyncOptional(this._eventObjects["pretick"]);if(pretickRet instanceof Promise)await pretickRet;const afterPreTickRet=this.Step_AfterPreTick();if(this.IsDebugging())await afterPreTickRet;if(this._NeedsHandleSaveOrLoad())await this._HandleSaveOrLoad();if(layoutManager.IsPendingChangeMainLayout())await this._MaybeChangeLayout();const runEventsRet=this.Step_RunEventsEtc();if(this.IsDebugging())await runEventsRet;const layout=layoutManager.GetMainRunningLayout();
+const pendingSetHTMLLayerCount=layout._GetPendingSetHTMLLayerCount();let needCleanUpHTMLLayers=false;if(pendingSetHTMLLayerCount!==-1){layout._ResetPendingHTMLLayerCount();if(canvasManager.GetHTMLLayerCount()!==pendingSetHTMLLayerCount){const updatePromise=this.GetCanvasManager().SetHTMLLayerCount(pendingSetHTMLLayerCount);if(this.IsInWorker()){needCleanUpHTMLLayers=true;await updatePromise}}}if(shouldRender)this.Render();if(needCleanUpHTMLLayers)this.PostComponentMessageToDOM("canvas","cleanup-html-layers");
+if(this.IsExportToVideo()){await this._ExportToVideoAddFrame();if(this.GetGameTime()>=this.GetExportVideoDuration()){this._ExportToVideoFinish();return}}if(!this.IsSuspended()&&!isBackgroundWake)this._RequestAnimationFrame();this._tickCount++;this._tickCountNoSave++;this._isInTick=false;this._mainThreadTimeCounter+=performance.now()-startTime}async Step_BeforePreTick(){const eventSheetManager=this._eventSheetManager;const isDebug=this.IsDebug();this.FlushPendingInstances();eventSheetManager.BlockFlushingInstances(true);
+this.PushCurrentLayout(this.GetMainRunningLayout());if(isDebug)C3Debugger.StartMeasuringTime();if(this.IsDebugging())await eventSheetManager.DebugRunScheduledWaits();else eventSheetManager.RunScheduledWaits();if(isDebug)C3Debugger.AddEventsTime();this.PopCurrentLayout();eventSheetManager.BlockFlushingInstances(false);this.FlushPendingInstances();eventSheetManager.BlockFlushingInstances(true)}async Step_AfterPreTick(){const isDebug=this.IsDebug();const isDebugging=this.IsDebugging();const dispatcher=
+this._dispatcher;const eventObjects=this._eventObjects;const userScriptEventObjects=this._userScriptEventObjects;if(isDebug)C3Debugger.StartMeasuringTime();if(isDebugging)await this.DebugIterateAndBreak(this._DebugBehaviorTick());else this._BehaviorTick();if(isDebugging)await this.DebugIterateAndBreak(this._DebugBehaviorPostTick());else this._BehaviorPostTick();if(isDebug)C3Debugger.AddBehaviorTickTime();if(isDebug)C3Debugger.StartMeasuringTime();if(isDebugging)await this.DebugFireGeneratorEventAndBreak(eventObjects["tick"]);
+else dispatcher.dispatchEvent(eventObjects["tick"]);if(isDebug)C3Debugger.AddPluginTickTime();this._eventSheetManager.BlockFlushingInstances(false);this.DispatchUserScriptEvent(userScriptEventObjects["tick"])}async Step_RunEventsEtc(){const eventSheetManager=this._eventSheetManager;const dispatcher=this._dispatcher;const eventObjects=this._eventObjects;const isDebug=this.IsDebug();const isDebugging=this.IsDebugging();if(isDebug)C3Debugger.StartMeasuringTime();if(isDebugging)await eventSheetManager.DebugRunEvents(this._layoutManager);
+else eventSheetManager.RunEvents(this._layoutManager);if(isDebug)C3Debugger.AddEventsTime();this._collisionEngine.ClearRegisteredCollisions();this._ReleaseInstancesAtEndOfTick();this._isLayoutFirstTick=false;eventSheetManager.BlockFlushingInstances(true);if(isDebug)C3Debugger.StartMeasuringTime();if(isDebugging)await this.DebugIterateAndBreak(this._DebugBehaviorTick2());else this._BehaviorTick2();if(isDebug)C3Debugger.AddBehaviorTickTime();if(isDebug)C3Debugger.StartMeasuringTime();if(isDebugging)await this.DebugFireGeneratorEventAndBreak(eventObjects["tick2"]);
+else dispatcher.dispatchEvent(eventObjects["tick2"]);if(isDebug)C3Debugger.AddPluginTickTime();eventSheetManager.BlockFlushingInstances(false);if(isDebugging)await eventSheetManager.RunQueuedDebugTriggersAsync()}_ReleaseInstancesAtEndOfTick(){if(this._instancesToReleaseAtEndOfTick.size===0)return;const dispatcher=this._dispatcher;dispatcher.SetDelayRemoveEventsEnabled(true);for(const objectClass of this._instancesToReleaseAffectedObjectClasses)objectClass.GetSolStack().RemoveInstances(this._instancesToReleaseAtEndOfTick);
+this._instancesToReleaseAffectedObjectClasses.clear();this._eventSheetManager.RemoveInstancesFromScheduledWaits(this._instancesToReleaseAtEndOfTick);for(const inst of this._instancesToReleaseAtEndOfTick)inst.Release();this._instancesToReleaseAtEndOfTick.clear();dispatcher.SetDelayRemoveEventsEnabled(false)}async _MaybeChangeLayout(){const layoutManager=this.GetLayoutManager();let i=0;while(layoutManager.IsPendingChangeMainLayout()&&i++<10)await this._DoChangeLayout(layoutManager.GetPendingChangeMainLayout())}_MeasureDt(timestamp){let dtRaw=
+0;if(this.IsExportToVideo()){dtRaw=1/this.GetExportVideoFramerate();this._dtRaw=dtRaw;this._dt1=dtRaw}else if(this._lastTickTime!==0){const msDiff=Math.max(timestamp-this._lastTickTime,0);dtRaw=msDiff/1E3;if(dtRaw>.5)dtRaw=0;this._dtRaw=dtRaw;const maxDt1=1/this._minimumFramerate;this._dt1=Math.min(dtRaw,maxDt1)}this._lastTickTime=timestamp;this._dt=this._dt1*this._timeScale;this._gameTime.Add(this._dt);this._gameTimeRaw.Add(dtRaw*this._timeScale);this._wallTime.Add(this._dt1);for(const [inst,instTime]of this._instanceTimes)instTime.Add(this._dt1*
+inst.GetTimeScale());if(this._canvasManager)this._canvasManager._UpdateTick();if(timestamp-this._fpsLastTime>=1E3){this._fpsLastTime+=1E3;if(timestamp-this._fpsLastTime>=1E3)this._fpsLastTime=timestamp;this._fps=this._fpsFrameCount;this._fpsFrameCount=0;this._mainThreadTime=Math.min(this._mainThreadTimeCounter/1E3,1);this._mainThreadTimeCounter=0;if(this._canvasManager)this._canvasManager._Update1sFrameRange();this._collisionEngine._Update1sStats();if(this.IsDebug())C3Debugger.Update1sPerfStats()}this._fpsFrameCount++}_SetTrackingInstanceTime(inst,
+enable){if(enable){if(!this._instanceTimes.has(inst)){const instTime=C3.New(C3.KahanSum);instTime.Copy(this._gameTime);this._instanceTimes.set(inst,instTime)}}else this._instanceTimes.delete(inst)}_GetInstanceGameTime(inst){const instTime=this._instanceTimes.get(inst);return instTime?instTime.Get():this.GetGameTime()}async _DoChangeLayout(changeToLayout){const dispatcher=this._dispatcher;const layoutManager=this.GetLayoutManager();const prevLayout=layoutManager.GetMainRunningLayout();await prevLayout._StopRunning();
+prevLayout._Unload(changeToLayout,this.GetRenderer());if(prevLayout===changeToLayout)this._eventSheetManager.ClearAllScheduledWaits();this._collisionEngine.ClearRegisteredCollisions();this._ReleaseInstancesAtEndOfTick();dispatcher.dispatchEvent(this._eventObjects["beforelayoutchange"]);C3.Asyncify.SetHighThroughputMode(true);await changeToLayout._Load(prevLayout,this.GetRenderer());C3.Asyncify.SetHighThroughputMode(false);await changeToLayout._StartRunning(false);dispatcher.dispatchEvent(this._eventObjects["layoutchange"]);
+this.UpdateRender();this._isLayoutFirstTick=true;this.FlushPendingInstances();this._ExportToVideoAddKeyframe()}UpdateRender(){this._needRender=true}GetWebGLRenderer(){if(!this._canvasManager)return null;return this._canvasManager.GetWebGLRenderer()}GetWebGPURenderer(){if(!this._canvasManager)return null;return this._canvasManager.GetWebGPURenderer()}GetRenderer(){if(!this._canvasManager)return null;return this._canvasManager.GetRenderer()}Render(){const canvasManager=this._canvasManager;if(!canvasManager||
+canvasManager.IsRendererContextLost())return;const renderer=this.GetRenderer();const supportsGPUProfiling=renderer.SupportsGPUProfiling();const isWebGLProfiling=supportsGPUProfiling&&renderer.IsWebGL();const isWebGPUProfiling=supportsGPUProfiling&&renderer.IsWebGPU();if(isWebGLProfiling)renderer.CheckForQueryResults();if(!this._needRender&&!this.IsExportToVideo()){renderer.IncrementFrameNumber();return}const layout=this._layoutManager.GetMainRunningLayout();renderer.Start();const isDebug=this.IsDebug();
+if(isDebug)C3Debugger.StartMeasuringTime();this._needRender=false;let webglFrameQuery=null;if(isWebGLProfiling){webglFrameQuery=canvasManager.GetGPUFrameTimingsBuffer().AddTimeElapsedQuery();renderer.StartQuery(webglFrameQuery)}let webgpuFrameTimings=null;if(isWebGPUProfiling){webgpuFrameTimings=renderer.StartFrameTiming((1+layout.GetLayerCount())*2);renderer.WriteTimestamp(0)}if(this.Uses3DFeatures()&&canvasManager.GetCurrentFullscreenScalingQuality()==="low")renderer.SetFixedSizeDepthBuffer(canvasManager.GetDrawWidth(),
+canvasManager.GetDrawHeight());else renderer.SetAutoSizeDepthBuffer();this._Render(this.GetRenderer(),layout);if(webglFrameQuery)renderer.EndQuery(webglFrameQuery);if(isWebGPUProfiling){renderer.WriteTimestamp(1);this._canvasManager._AddWebGPUFrameTiming(webgpuFrameTimings)}renderer.Finish();if(isDebug){C3Debugger.AddDrawCallsTime();C3Debugger.UpdateInspectHighlight()}if(canvasManager)canvasManager._MaybeTakeSnapshot()}_NeedsHTMLLayerCompositing(renderer){return this.GetCanvasManager().GetCurrentFullscreenScalingQuality()===
+"low"||renderer.IsWebGL()&&(this.UsesAnyBackgroundBlending()||this.Uses3DFeatures())}_Render(renderer,layout){renderer.SetTextureFillMode();renderer.SetAlphaBlend();renderer.SetColorRgba(1,1,1,1);renderer.SetRenderTarget(null);renderer.SetTexture(null);renderer.SetDepthEnabled(this.Uses3DFeatures());if(this._NeedsHTMLLayerCompositing(renderer))layout._MaybeStartDrawToOwnTexture(renderer);const htmlLayerCount=layout.GetHTMLLayerCount();for(let i=1;ithis.DeleteTextIconSet(iconSource);this._iconChangeHandlers.set(iconSource,changeHandler);iconSource.Dispatcher().addEventListener("animationframeimagechange",
+changeHandler)}const iconSet=this._textIconManager.GetIconSet(iconSource);if(!iconSet.HasLoaded())iconSet.LoadContent().then(()=>this.UpdateRender());return iconSet}DeleteTextIconSet(iconSource){this._textIconManager.DeleteIconSet(iconSource)}_GetTextIconSetMeta(iconSource){const icons=[];for(const animation of iconSource.GetAnimations())for(const frame of animation.GetFrames()){const imageInfo=frame.GetImageInfo();icons.push({source:frame,width:imageInfo.GetWidth(),height:imageInfo.GetHeight(),tag:frame.GetTag()})}return{icons}}async _GetTextIconSetContent(iconSource){const promiseThrottle=
+C3.New(C3.PromiseThrottle);const assetDrawablePromises=[];const assetDrawableMap=new Map;for(const animation of iconSource.GetAnimations())for(const frame of animation.GetFrames()){const imageAsset=frame.GetImageInfo().GetImageAsset();if(assetDrawableMap.has(imageAsset))continue;assetDrawableMap.set(imageAsset,null);assetDrawablePromises.push(promiseThrottle.Add(async()=>{const drawable=await imageAsset.LoadToDrawable();assetDrawableMap.set(imageAsset,drawable)}))}await Promise.all(assetDrawablePromises);
+const extractPromises=[];for(const animation of iconSource.GetAnimations())for(const frame of animation.GetFrames())extractPromises.push(promiseThrottle.Add(async()=>{const imageInfo=frame.GetImageInfo();const imageAssetDrawable=assetDrawableMap.get(imageInfo.GetImageAsset());const canvas=await imageInfo.ExtractImageToCanvas(imageAssetDrawable);const imageBitmap=await createImageBitmap(canvas);return{drawable:imageBitmap}}));const iconsArr=await Promise.all(extractPromises);for(const drawable of assetDrawableMap.values())if(drawable instanceof
+ImageBitmap&&drawable["close"])drawable["close"]();return{icons:iconsArr}}SaveToSlot(slotName){this._saveToSlotName=slotName}LoadFromSlot(slotName){this._loadFromSlotName=slotName}LoadFromJsonString(str){this._loadFromJson=str}GetLastSaveJsonString(){return this._lastSaveJson}_NeedsHandleSaveOrLoad(){return!!(this._saveToSlotName||this._loadFromSlotName||this._loadFromJson!==null)}async _HandleSaveOrLoad(){if(this._saveToSlotName){this.FlushPendingInstances();await this._DoSaveToSlot(this._saveToSlotName);
+this._ClearSaveOrLoad()}if(this._loadFromSlotName){await this._DoLoadFromSlot(this._loadFromSlotName);this._ClearSaveOrLoad();if(this.IsDebug())C3Debugger.StepIfPausedInDebugger()}if(this._loadFromJson!==null){this.FlushPendingInstances();try{await this._DoLoadFromJsonString(this._loadFromJson);this._lastSaveJson=this._loadFromJson;await this.TriggerAsync(C3.Plugins.System.Cnds.OnLoadComplete,null);this._lastSaveJson=""}catch(err){console.error("[Construct] Failed to load state from JSON string: ",
+err);await this.TriggerAsync(C3.Plugins.System.Cnds.OnLoadFailed,null)}this._ClearSaveOrLoad()}}_ClearSaveOrLoad(){this._saveToSlotName="";this._loadFromSlotName="";this._loadFromJson=null}_GetProjectStorage(){if(!this._projectStorage)this._projectStorage=localforage.createInstance({name:"c3-localstorage-"+this.GetProjectUniqueId(),description:this.GetProjectName()});return this._projectStorage}_GetSavegamesStorage(){if(!this._savegamesStorage)this._savegamesStorage=localforage.createInstance({name:"c3-savegames-"+
+this.GetProjectUniqueId(),description:this.GetProjectName()});return this._savegamesStorage}async _DoSaveToSlot(slotName){const saveJson=await this._SaveToJsonString();try{await this._GetSavegamesStorage().setItem(slotName,saveJson);console.log("[Construct] Saved state to storage ("+saveJson.length+" chars)");this._lastSaveJson=saveJson;await this.TriggerAsync(C3.Plugins.System.Cnds.OnSaveComplete,null);this._lastSaveJson=""}catch(err){console.error("[Construct] Failed to save state to storage: ",
+err);await this.TriggerAsync(C3.Plugins.System.Cnds.OnSaveFailed,null)}}async _DoLoadFromSlot(slotName){try{const loadJson=await this._GetSavegamesStorage().getItem(slotName);if(!loadJson)throw new Error("empty slot");console.log("[Construct] Loaded state from storage ("+loadJson.length+" chars)");await this._DoLoadFromJsonString(loadJson);this._lastSaveJson=loadJson;await this.TriggerAsync(C3.Plugins.System.Cnds.OnLoadComplete,null);this._lastSaveJson=""}catch(err){console.error("[Construct] Failed to load state from storage: ",
+err);await this.TriggerAsync(C3.Plugins.System.Cnds.OnLoadFailed,null)}}async _SaveToJsonString(){const o={"c3save":true,"version":1,"rt":{"time":this.GetGameTime(),"timeRaw":this.GetGameTimeRaw(),"walltime":this.GetWallTime(),"timescale":this.GetTimeScale(),"tickcount":this.GetTickCount(),"next_uid":this._nextUid,"running_layout":this.GetMainRunningLayout().GetSID(),"start_time_offset":Date.now()-this._startTime},"types":{},"layouts":{},"events":this._eventSheetManager._SaveToJson(),"timelines":this._timelineManager._SaveToJson(),
+"flowcharts":this._flowchartManager?this._flowchartManager._SaveToJson():null,"user_script_data":null};for(const objectClass of this._allObjectClasses){if(objectClass.IsFamily()||objectClass.HasNoSaveBehavior())continue;o["types"][objectClass.GetSID().toString()]=objectClass._SaveToJson()}for(const layout of this._layoutManager.GetAllLayouts())o["layouts"][layout.GetSID().toString()]=layout._SaveToJson();const saveEvent=this._CreateUserScriptEvent("save");saveEvent.saveData=null;await this.DispatchUserScriptEventAsyncWait(saveEvent);
+o["user_script_data"]=saveEvent.saveData;return JSON.stringify(o)}IsLoadingState(){return this._isLoadingState}async _DoLoadFromJsonString(jsonStr){const layoutManager=this.GetLayoutManager();const o=JSON.parse(jsonStr);if(o["c2save"])throw new Error("C2 saves are incompatible with C3 runtime");if(!o["c3save"])throw new Error("not valid C3 save data");if(o["version"]>1)throw new Error("C3 save data from future version");this.ClearIntancesNeedingAfterLoad();this._dispatcher.dispatchEvent(C3.New(C3.Event,
+"beforeload"));for(const inst of this.allInstances()){const objectClass=inst.GetObjectClass();if(objectClass.HasNoSaveBehavior())continue;inst._OnBeforeLoad()}const rt=o["rt"];this._gameTime.Set(rt["time"]);if(rt.hasOwnProperty("timeRaw"))this._gameTimeRaw.Set(rt["timeRaw"]);this._wallTime.Set(rt["walltime"]);this._timeScale=rt["timescale"];this._tickCount=rt["tickcount"];this._startTime=Date.now()-rt["start_time_offset"];const layoutSid=rt["running_layout"];this._isLoadingState=true;let changedLayout=
+false;if(layoutSid!==this.GetMainRunningLayout().GetSID()){const changeToLayout=layoutManager.GetLayoutBySID(layoutSid);if(changeToLayout){await this._DoChangeLayout(changeToLayout);changedLayout=true}else return}for(const [sidStr,data]of Object.entries(o["layouts"])){const sid=parseInt(sidStr,10);const layout=layoutManager.GetLayoutBySID(sid);if(!layout)continue;layout._LoadFromJson(data)}for(const [sidStr,data]of Object.entries(o["types"])){const sid=parseInt(sidStr,10);const objectClass=this.GetObjectClassBySID(sid);
+if(!objectClass||objectClass.IsFamily()||objectClass.HasNoSaveBehavior())continue;objectClass._LoadFromJson(data)}for(const layout of this._layoutManager.GetAllLayouts())for(const layer of layout.allLayers())layer._LoadFromJsonAfterInstances();this.FlushPendingInstances();this._RefreshUidMap();this._isLoadingState=false;if(changedLayout){for(const inst of this.allInstances())inst.SetupInitialSceneGraphConnections();for(const [sidStr,data]of Object.entries(o["types"])){const sid=parseInt(sidStr,10);
+const objectClass=this.GetObjectClassBySID(sid);if(!objectClass||objectClass.IsFamily()||objectClass.HasNoSaveBehavior())continue;objectClass._SetupSceneGraphConnectionsOnChangeOfLayout(data)}}this._nextUid=rt["next_uid"];this._eventSheetManager._LoadFromJson(o["events"]);for(const objectClass of this._allObjectClasses){if(objectClass.IsFamily()||!objectClass.IsInContainer())continue;for(const inst of objectClass.GetInstances()){const iid=inst.GetIID();for(const otherType of objectClass.GetContainer().objectTypes()){if(otherType===
+objectClass)continue;const otherInstances=otherType.GetInstances();if(iid<0||iid>=otherInstances.length)throw new Error("missing sibling instance");inst._AddSibling(otherInstances[iid])}}}this._timelineManager._LoadFromJson(o["timelines"]);if(this._flowchartManager)this._flowchartManager._LoadFromJson(o["flowcharts"]);layoutManager.SetAllLayerProjectionChanged();layoutManager.SetAllLayerMVChanged();this._dispatcher.dispatchEvent(C3.New(C3.Event,"afterload"));this.DoAfterLoad();for(const [sidStr,data]of Object.entries(o["types"])){const sid=
+parseInt(sidStr,10);const objectClass=this.GetObjectClassBySID(sid);if(objectClass)objectClass._ClearLoadInstancesJson()}const loadEvent=this._CreateUserScriptEvent("load");loadEvent.saveData=o["user_script_data"];await this.DispatchUserScriptEventAsyncWait(loadEvent);this.UpdateRender()}SortOnTmpHierarchyPosition(f,s){return f.GetWorldInfo().GetTmpHierarchyPosition()-s.GetWorldInfo().GetTmpHierarchyPosition()}AddInstanceNeedingAfterLoad(inst,data){if(!inst.GetWorldInfo())return;this._instancesNeedingAfterLoadMap.set(inst,
+data);this._instancesNeedingAfterLoadArray.push(inst)}ClearIntancesNeedingAfterLoad(){this._instancesNeedingAfterLoadMap=new WeakMap;C3.clearArray(this._instancesNeedingAfterLoadArray)}DoAfterLoad(mode="full",opts=null){this._instancesNeedingAfterLoadArray.sort(this.SortOnTmpHierarchyPosition);for(const wi of this._instancesNeedingAfterLoadArray)wi._OnAfterLoad(this._instancesNeedingAfterLoadMap.get(wi),mode,opts);for(const wi of this._instancesNeedingAfterLoadArray)wi._OnAfterLoad2(this._instancesNeedingAfterLoadMap.get(wi),
+mode,opts);this.ClearIntancesNeedingAfterLoad()}async AddJobWorkerScripts(scripts){const loadUrls=await Promise.all(scripts.map(async url=>{const isCrossOrigin=C3.IsAbsoluteURL(url)&&(new URL(url)).origin!==location.origin;const isCordovaFileProtocol=this.IsCordova()&&this._assetManager.IsFileProtocol();if(isCrossOrigin||isCordovaFileProtocol||this.IsPreview()||this.GetExportType()==="playable-ad"){const blob=await this._assetManager.FetchBlob(url);return URL.createObjectURL(blob)}else if(C3.IsRelativeURL(url))return(new URL(url,
+this._runtimeBaseUrl)).toString();else return url}));this._jobScheduler.ImportScriptsToJobWorkers(loadUrls)}AddJobWorkerBlob(blob,id){this._jobScheduler.SendBlobToJobWorkers(blob,id)}AddJobWorkerBuffer(buffer,id){this._jobScheduler.SendBufferToJobWorkers(buffer,id)}AddJob(type,params,transferables,maxWorkerNum){return this._jobScheduler.AddJob(type,params,transferables,null,null,maxWorkerNum)}BroadcastJob(type,params,transferables,maxWorkerNum){return this._jobScheduler.BroadcastJob(type,params,transferables,
+maxWorkerNum)}GetMaxNumJobWorkers(){return this._jobScheduler.GetMaxNumWorkers()}InvokeDownload(url,filename){this.PostComponentMessageToDOM("runtime","invoke-download",{"url":url,"filename":filename})}async RasterSvgImage(blob,imageWidth,imageHeight,surfaceWidth,surfaceHeight,imageBitmapOpts){surfaceWidth=surfaceWidth||imageWidth;surfaceHeight=surfaceHeight||imageHeight;if(this.IsInWorker()){const result=await this.PostComponentMessageToDOMAsync("runtime","raster-svg-image",{"blob":blob,"imageWidth":imageWidth,
+"imageHeight":imageHeight,"surfaceWidth":surfaceWidth,"surfaceHeight":surfaceHeight,"imageBitmapOpts":imageBitmapOpts});return result["imageBitmap"]}else{const canvas=await self["C3_RasterSvgImageBlob"](blob,imageWidth,imageHeight,surfaceWidth,surfaceHeight);if(imageBitmapOpts)return await self.createImageBitmap(canvas,imageBitmapOpts);else return canvas}}async GetSvgImageSize(blob){if(this.IsInWorker())return await this.PostComponentMessageToDOMAsync("runtime","get-svg-image-size",{"blob":blob});
+else return await self["C3_GetSvgImageSize"](blob)}RequestDeviceOrientationEvent(){if(this._didRequestDeviceOrientationEvent)return;this._didRequestDeviceOrientationEvent=true;this.PostComponentMessageToDOM("runtime","enable-device-orientation")}RequestDeviceMotionEvent(){if(this._didRequestDeviceMotionEvent)return;this._didRequestDeviceMotionEvent=true;this.PostComponentMessageToDOM("runtime","enable-device-motion")}Random(){return this._randomNumberCallback()}SetRandomNumberGeneratorCallback(f){this._randomNumberCallback=
+f}_GetRemotePreviewStatusInfo(){const renderer=this.GetRenderer();return{"fps":this.GetFPS(),"cpu":this.GetMainThreadTime(),"gpu":this.GetGPUUtilisation(),"layout":this.GetMainRunningLayout()?this.GetMainRunningLayout().GetName():"","renderer":renderer.IsWebGL()?renderer.GetUnmaskedRenderer():renderer.GetAdapterInfoString()}}HitBreakpoint(){if(!this.IsDebug())return false;return C3Debugger.HitBreakpoint()}DebugBreak(eventObject){if(!this.IsDebugging())return Promise.resolve();return C3Debugger.DebugBreak(eventObject)}DebugBreakNext(){if(!this.IsDebugging())return false;
+return C3Debugger.BreakNext()}SetDebugBreakpointsEnabled(e){this._breakpointsEnabled=!!e;this._UpdateDebuggingFlag()}AreDebugBreakpointsEnabled(){return this._breakpointsEnabled}IsDebugging(){return this._isDebugging}SetDebuggingEnabled(d){if(d)this._debuggingDisabled--;else this._debuggingDisabled++;this._UpdateDebuggingFlag()}_UpdateDebuggingFlag(){this._isDebugging=this.IsDebug()&&this._breakpointsEnabled&&this._debuggingDisabled===0}IsCPUProfiling(){return this.IsDebug()&&C3Debugger.IsCPUProfiling()}IsGPUProfiling(){return this.IsDebug()&&
+this.GetRenderer().SupportsGPUProfiling()&&C3Debugger.IsGPUProfiling()}async DebugIterateAndBreak(iter){if(!iter)return;for(const breakEventObject of iter)await this.DebugBreak(breakEventObject)}DebugFireGeneratorEventAndBreak(event){return this.DebugIterateAndBreak(this._dispatcher.dispatchGeneratorEvent(event))}_InvokeFunctionFromJS(e){return this._eventSheetManager._InvokeFunctionFromJS(e["name"],e["params"])}GetIRuntime(){return this._iRuntime}_CreateUserScriptEvent(name){const e=C3.New(C3.Event,
+name,false);e.runtime=this._iRuntime;return e}_InitScriptInterfaces(){const objectDescriptors={};for(const objectClass of this._allObjectClasses)objectDescriptors[objectClass.GetJsPropName()]={value:objectClass.GetIObjectClass(),enumerable:true,writable:false};const objects=Object.create(Object.prototype,objectDescriptors);this._iRuntime=new self.IRuntime(this,objects);this._userScriptEventObjects={"tick":this._CreateUserScriptEvent("tick")}}_InitGlobalVariableScriptInterface(){const globalVarDescriptors=
+{};for(const globalVar of this.GetEventSheetManager().GetAllGlobalVariables())globalVarDescriptors[globalVar.GetJsPropName()]=globalVar._GetScriptInterfaceDescriptor();this._iRuntime._InitGlobalVars(globalVarDescriptors)}_GetCommonScriptInterfaces(){return this._commonScriptInterfaces}_MapScriptInterface(interface_,class_){this._interfaceMap.set(interface_,class_)}_UnwrapScriptInterface(interface_){return this._interfaceMap.get(interface_)}_UnwrapIObjectClass(iObjectClass){if(!(iObjectClass instanceof
+self.IObjectClass))throw new TypeError("expected IObjectClass");const objectClass=this._UnwrapScriptInterface(iObjectClass);if(!objectClass||!(objectClass instanceof C3.ObjectClass))throw new Error("invalid IObjectClass");return objectClass}_UnwrapIWorldInstance(iinst){if(!(iinst instanceof self.IWorldInstance))throw new TypeError("expected IWorldInstance");const inst=this._UnwrapScriptInterface(iinst);if(!inst||!(inst instanceof C3.Instance))throw new Error("invalid IInstance");return inst}};
+self["C3_CreateRuntime"]=C3.Runtime.Create;self["C3_InitRuntime"]=(runtime,opts)=>runtime.Init(opts);
+
+}
+
+// workers/jobSchedulerRuntime.js
+{
+'use strict';const C3=self.C3;
+C3.JobSchedulerRuntime=class JobSchedulerRuntime extends C3.DefendedBase{constructor(runtime,data){super();this._runtime=runtime;this._jobPromises=new Map;this._nextJobId=0;this._inputPort=data["inputPort"];data["outputPort"].onmessage=e=>this._OnJobWorkerMessage(e);this._maxNumWorkers=data["maxNumWorkers"];this._jobWorkerCount=1;this._isCreatingWorker=false;this._hadErrorCreatingWorker=false}async Init(){}GetMaxNumWorkers(){return this._maxNumWorkers}ImportScriptsToJobWorkers(scripts){this._inputPort.postMessage({"type":"_import_scripts","scripts":scripts})}SendBlobToJobWorkers(blob,
+id){this._inputPort.postMessage({"type":"_send_blob","blob":blob,"id":id})}SendBufferToJobWorkers(buffer,id){this._inputPort.postMessage({"type":"_send_buffer","buffer":buffer,"id":id},[buffer])}AddJob(type,params,transferables,progressHandler,abortDisposable,maxWorkerNum){if(!transferables)transferables=[];if(typeof maxWorkerNum==="number"){maxWorkerNum=Math.floor(maxWorkerNum);if(maxWorkerNum<=0)throw new Error("invalid maxWorkerNum");}const jobId=this._nextJobId++;const job={"type":type,"isBroadcast":false,
+"maxWorkerNum":maxWorkerNum,"jobId":jobId,"params":params,"transferables":transferables};const promise=new Promise((resolve,reject)=>{this._jobPromises.set(jobId,{resolve:resolve,progress:progressHandler,reject:reject,cancelled:false,maxWorkerNum})});if(abortDisposable)abortDisposable.SetAction(()=>this._CancelJob(jobId));this._inputPort.postMessage(job,transferables);this._MaybeCreateExtraWorker();return promise}BroadcastJob(type,params,transferables,maxWorkerNum){if(!transferables)transferables=
+[];if(typeof maxWorkerNum==="number"){maxWorkerNum=Math.floor(maxWorkerNum);if(maxWorkerNum<=0)throw new Error("invalid maxWorkerNum");}const jobId=this._nextJobId++;const job={"type":type,"isBroadcast":true,"maxWorkerNum":maxWorkerNum,"jobId":jobId,"params":params,"transferables":transferables};this._inputPort.postMessage(job,transferables)}_CancelJob(jobId){const job=this._jobPromises.get(jobId);if(job){job.cancelled=true;job.resolve=null;job.progress=null;job.reject=null;this._inputPort.postMessage({"type":"_cancel",
+"jobId":jobId})}}_OnJobWorkerMessage(e){const msg=e.data;const type=msg["type"];const id=msg["jobId"];switch(type){case "result":this._OnJobResult(id,msg["result"]);break;case "progress":this._OnJobProgress(id,msg["progress"]);break;case "error":this._OnJobError(id,msg["error"]);break;case "ready":this._OnJobWorkerReady();break;default:throw new Error(`unknown message from worker '${type}'`);}}_OnJobResult(jobId,result){const p=this._jobPromises.get(jobId);if(!p)throw new Error("invalid job ID");
+if(!p.cancelled)p.resolve(result);this._jobPromises.delete(jobId)}_OnJobProgress(jobId,progress){const p=this._jobPromises.get(jobId);if(!p)throw new Error("invalid job ID");if(!p.cancelled&&p.progress)p.progress(progress)}_OnJobError(jobId,error){const p=this._jobPromises.get(jobId);if(!p)throw new Error("invalid job ID");if(!p.cancelled)p.reject(error);this._jobPromises.delete(jobId)}_OnJobWorkerReady(){if(!this._isCreatingWorker)return;this._isCreatingWorker=false;this._jobWorkerCount++;if(this._jobWorkerCount<
+this._maxNumWorkers)this._MaybeCreateExtraWorker();else this._inputPort.postMessage({"type":"_no_more_workers"})}_GetWorkerCountNeededForPendingJobs(){let needWorkerCount=0;const sortedJobList=[...this._jobPromises.values()].sort((a,b)=>{const an=a.maxWorkerNum||Infinity;const bn=b.maxWorkerNum||Infinity;return an-bn});for(const job of sortedJobList){const maxWorkerNum=job.maxWorkerNum||Infinity;if(needWorkerCount=
+this._maxNumWorkers||this._isCreatingWorker||this._hadErrorCreatingWorker||this._GetWorkerCountNeededForPendingJobs()<=this._jobWorkerCount)return;try{this._isCreatingWorker=true;const result=await this._runtime.PostComponentMessageToDOMAsync("runtime","create-job-worker");result["outputPort"].onmessage=e=>this._OnJobWorkerMessage(e)}catch(err){this._hadErrorCreatingWorker=true;this._isCreatingWorker=false;console.error(`[Construct] Failed to create job worker; stopping creating any more (created ${this._jobWorkerCount} so far)`,
+err)}}};
+
+}
+
+{
+self["C3_Shaders"] = {};
+
+}
+
+{
+'use strict';{const C3=self.C3;let cacheRegex=null;let lastRegex="";let lastFlags="";let regexMatches=[];let lastMatchesStr="";let lastMatchesRegex="";let lastMatchesFlags="";const forEachStack=C3.New(C3.ArrayStack);function ForEachOrdered_SortInstances(a,b){const va=a[1];const vb=b[1];if(typeof va==="number"&&typeof vb==="number")return va-vb;else{const sa=""+va;const sb=""+vb;if(sasb)return 1;else return 0}}C3.Plugins.System=class SystemPlugin extends C3.SDKPluginBase{constructor(opts){super(opts);
+this._loopStack=this._runtime.GetEventSheetManager().GetLoopStack();this._eventStack=this._runtime.GetEventSheetManager().GetEventStack();this._imagesLoadingTotal=0;this._imagesLoadingComplete=0;this._functionMaps=new Map;this._signalTags=[]}Release(){super.Release()}UpdateRender(){this._runtime.UpdateRender()}Trigger(method){this._runtime.Trigger(method,null,null)}GetRegex(regex,flags){if(!cacheRegex||regex!==lastRegex||flags!==lastFlags){cacheRegex=new RegExp(regex,flags);lastRegex=regex;lastFlags=
+flags}cacheRegex.lastIndex=0;return cacheRegex}GetRegexMatches(str,regex,flags){if(str===lastMatchesStr&®ex===lastMatchesRegex&&flags===lastMatchesFlags)return regexMatches;const cacheRegex=this.GetRegex(regex,flags);regexMatches=str.match(cacheRegex);lastMatchesStr=str;lastMatchesRegex=regex;lastMatchesFlags=flags;return regexMatches}async _LoadTexturesForObjectClasses(layout,objectClasses){if(!objectClasses.length)return;this._imagesLoadingTotal+=objectClasses.length;const promises=[];for(const oc of objectClasses)promises.push(layout.MaybeLoadTexturesFor(oc));
+await C3.PromiseAllWithProgress(promises,()=>{this._imagesLoadingComplete++});this._imagesLoadingComplete++;if(this._imagesLoadingComplete===this._imagesLoadingTotal){this._imagesLoadingComplete=0;this._imagesLoadingTotal=0;this._runtime.Trigger(C3.Plugins.System.Cnds.OnImageLoadingComplete,null,null)}}_UnloadTexturesForObjectClasses(layout,objectClasses){for(const oc of objectClasses)if(oc.GetInstanceCount()===0)layout.MaybeUnloadTexturesFor(oc)}_GetForEachStack(){return forEachStack}_Repeat(count){const eventSheetManager=
+this._runtime.GetEventSheetManager();const eventStack=eventSheetManager.GetEventStack();const oldFrame=eventStack.GetCurrentStackFrame();const currentEvent=oldFrame.GetCurrentEvent();const solModifiers=currentEvent.GetSolModifiers();const isSolModifierAfterCnds=oldFrame.IsSolModifierAfterCnds();const newFrame=eventStack.Push(currentEvent);const loopStack=eventSheetManager.GetLoopStack();const loop=loopStack.Push();loop.SetEnd(count);if(isSolModifierAfterCnds)for(let i=0;i=end&&!loop.IsStopped();--i){eventSheetManager.PushCopySol(solModifiers);loop.SetIndex(i);currentEvent.Retrigger(oldFrame,newFrame);eventSheetManager.PopSol(solModifiers)}else for(let i=start;i>=
+end&&!loop.IsStopped();--i){loop.SetIndex(i);currentEvent.Retrigger(oldFrame,newFrame)}else if(isSolModifierAfterCnds)for(let i=start;i<=end&&!loop.IsStopped();++i){eventSheetManager.PushCopySol(solModifiers);loop.SetIndex(i);currentEvent.Retrigger(oldFrame,newFrame);eventSheetManager.PopSol(solModifiers)}else for(let i=start;i<=end&&!loop.IsStopped();++i){loop.SetIndex(i);currentEvent.Retrigger(oldFrame,newFrame)}eventStack.Pop();loopStack.Pop();return false}*_DebugFor(name,start,end){const eventSheetManager=
+this._runtime.GetEventSheetManager();const eventStack=eventSheetManager.GetEventStack();const oldFrame=eventStack.GetCurrentStackFrame();const currentEvent=oldFrame.GetCurrentEvent();const solModifiers=currentEvent.GetSolModifiers();const isSolModifierAfterCnds=oldFrame.IsSolModifierAfterCnds();const newFrame=eventStack.Push(currentEvent);const loopStack=eventSheetManager.GetLoopStack();const loop=loopStack.Push();loop.SetName(name);loop.SetEnd(end);if(end=end&&!loop.IsStopped();--i){eventSheetManager.PushCopySol(solModifiers);loop.SetIndex(i);yield*currentEvent.DebugRetrigger(oldFrame,newFrame);eventSheetManager.PopSol(solModifiers)}else for(let i=start;i>=end&&!loop.IsStopped();--i){loop.SetIndex(i);yield*currentEvent.DebugRetrigger(oldFrame,newFrame)}else if(isSolModifierAfterCnds)for(let i=start;i<=end&&!loop.IsStopped();++i){eventSheetManager.PushCopySol(solModifiers);loop.SetIndex(i);yield*currentEvent.DebugRetrigger(oldFrame,newFrame);
+eventSheetManager.PopSol(solModifiers)}else for(let i=start;i<=end&&!loop.IsStopped();++i){loop.SetIndex(i);yield*currentEvent.DebugRetrigger(oldFrame,newFrame)}eventStack.Pop();loopStack.Pop();return false}_ForEach(objectClass){const sol=objectClass.GetCurrentSol();const iterInstances=sol.GetInstances();if(iterInstances.length===0)return false;const eventSheetManager=this._runtime.GetEventSheetManager();const eventStack=eventSheetManager.GetEventStack();const oldFrame=eventStack.GetCurrentStackFrame();
+const currentEvent=oldFrame.GetCurrentEvent();const solModifiers=currentEvent.GetSolModifiers();const isSolModifierAfterCnds=oldFrame.IsSolModifierAfterCnds();const newFrame=eventStack.Push(currentEvent);const loopStack=eventSheetManager.GetLoopStack();const loop=loopStack.Push();const isInContainer=objectClass.IsInContainer();const instances=forEachStack.Push();C3.shallowAssignArray(instances,iterInstances);loop.SetEnd(instances.length);if(isSolModifierAfterCnds)for(let i=0,len=instances.length;i<
+len&&!loop.IsStopped();++i){eventSheetManager.PushCopySol(solModifiers);const inst=instances[i];objectClass.GetCurrentSol().SetSinglePicked(inst);if(isInContainer)inst.SetSiblingsSinglePicked();loop.SetIndex(i);currentEvent.Retrigger(oldFrame,newFrame);eventSheetManager.PopSol(solModifiers)}else{sol._SetSelectAll(false);const solInstances=sol._GetOwnInstances();C3.clearArray(solInstances);solInstances.push(null);for(let i=0,len=instances.length;i=lastTime+thisSeconds){cndSavedData.set("Every_lastTime",lastTime+thisSeconds);if(curTime>=cndSavedData.get("Every_lastTime")+.04)cndSavedData.set("Every_lastTime",curTime);cndSavedData.set("Every_seconds",seconds);return true}else if(curTime=a&&x<=b},CompareVar(ev,cmp,val){return C3.compare(ev.GetValue(),cmp,val)},CompareBoolVar(ev){return!!ev.GetValue()},
+CompareTime(cmp,t){const gameTime=this._runtime.GetGameTime();if(cmp===0){const cnd=this._runtime.GetCurrentCondition();const cndSavedData=cnd.GetSavedDataMap();if(!cndSavedData.get("CompareTime_executed"))if(gameTime>=t){cndSavedData.set("CompareTime_executed",true);return true}return false}else return C3.compare(gameTime,cmp,t)},IsNaN(n){return isNaN(n)},AngleWithin(a1,within,a2){return C3.angleDiff(C3.toRadians(a1),C3.toRadians(a2))<=C3.toRadians(within)},IsClockwiseFrom(a1,a2){return C3.angleClockwise(C3.toRadians(a1),
+C3.toRadians(a2))},IsBetweenAngles(a,la,ua){let angle=C3.toRadians(a);let lower=C3.toRadians(la);let upper=C3.toRadians(ua);let obtuse=!C3.angleClockwise(upper,lower);if(obtuse)return!(!C3.angleClockwise(angle,lower)&&C3.angleClockwise(angle,upper));else return C3.angleClockwise(angle,lower)&&!C3.angleClockwise(angle,upper)},IsValueType(v,t){if(typeof v==="number")return t===0;else return t===1},EvaluateExpression(v){return!!v},OnSignal(tag){return tag.toLowerCase()===this._signalTags.at(-1)},PickByComparison(objectClass,
+exp,cmp,val){if(!objectClass)return false;const forEachStack=this._GetForEachStack();const tempInstances=forEachStack.Push();const sol=objectClass.GetCurrentSol();C3.shallowAssignArray(tempInstances,sol.GetInstances());if(sol.IsSelectAll())C3.clearArray(sol._GetOwnElseInstances());const cnd=this._runtime.GetCurrentCondition();let k=0;for(let i=0,len=tempInstances.length;i=instances.length)return false;const inst=instances[index];sol.PickOne(inst);objectClass.ApplySolToContainer();return true},PickRandom(objectClass){if(!objectClass)return false;const sol=objectClass.GetCurrentSol();const instances=sol.GetInstances();const index=Math.floor(this._runtime.Random()*instances.length);if(index>=instances.length)return false;const inst=instances[index];sol.PickOne(inst);objectClass.ApplySolToContainer();
+return true},PickAll(objectClass){if(!objectClass)return false;if(!objectClass.GetInstanceCount())return false;const sol=objectClass.GetCurrentSol();sol._SetSelectAll(true);objectClass.ApplySolToContainer();return true},PickOverlappingPoint(objectClass,x,y){if(!objectClass)return false;const sol=objectClass.GetCurrentSol();const instances=sol.GetInstances();const currentEvent=this._runtime.GetCurrentEvent();const isOrBlock=currentEvent.IsOrBlock();const isInverted=this._runtime.GetCurrentCondition().IsInverted();
+if(sol.IsSelectAll()){C3.shallowAssignArray(tmpPickArray,instances);sol.ClearArrays();sol._SetSelectAll(false)}else if(isOrBlock){C3.shallowAssignArray(tmpPickArray,sol._GetOwnElseInstances());C3.clearArray(sol._GetOwnElseInstances())}else{C3.shallowAssignArray(tmpPickArray,sol._GetOwnInstances());C3.clearArray(sol._GetOwnInstances())}for(let i=0,len=tmpPickArray.length;i=0;--i){const inst=instancesPendingCreate[i];if(isFamily){if(inst.GetObjectClass().BelongsToFamily(objectClass)){pick=inst;break}}else if(inst.GetObjectClass()===objectClass){pick=inst;break}}if(!pick){const instances=
+objectClass.GetInstances();if(instances.length)pick=instances.at(-1)}if(!pick)return false;const sol=objectClass.GetCurrentSol();sol.PickOne(pick);objectClass.ApplySolToContainer();return true},Repeat(count){if(this._runtime.IsDebugging())return this._DebugRepeat(count);else return this._Repeat(count)},While(){if(this._runtime.IsDebugging())return this._DebugWhile();else return this._While()},For(name,start,end){if(this._runtime.IsDebugging())return this._DebugFor(name,start,end);else return this._For(name,
+start,end)},ForEach(objectClass){if(this._runtime.IsDebugging())return this._DebugForEach(objectClass);else return this._ForEach(objectClass)},ForEachOrdered(objectClass,expression,order){if(this._runtime.IsDebugging())return this._DebugForEachOrdered(objectClass,order);else return this._ForEachOrdered(objectClass,order)},LayerVisible(layer){return layer?layer.IsVisible():false},LayerInteractive(layer){return layer?layer.IsSelfAndParentsInteractive():false},LayerIsHTML(layer){return layer?layer.IsHTMLElementsLayer():
+false},LayerEmpty(layer){return layer?!layer.GetInstanceCount():false},LayerCmpOpacity(layer,cmp,o){if(!layer)return false;return C3.compare(layer.GetOpacity()*100,cmp,o)},LayerNameExists(nameStr){const layout=this._runtime.GetMainRunningLayout();return layout?layout.HasLayerByName(nameStr):false},OnImageLoadingComplete(){return true},IsLoadingImages(){return this._imagesLoadingTotal>0},TemplateExists(objectClass,template){const templateManager=this._runtime.GetTemplateManager();if(!templateManager)return false;
+if(!template)return false;return!!templateManager.GetTemplateData(objectClass,template)}}}
+{const C3=self.C3;function SortZOrderList(a,b){const layerA=a[0];const layerB=b[0];const diff=layerA-layerB;if(diff!==0)return diff;const indexA=a[1];const indexB=b[1];return indexA-indexB}function SortInstancesByValue(a,b){return a[1]-b[1]}const tempZOrderList=[];const tempInstValues=[];const tempRect=C3.New(C3.Rect);const tempColor=C3.New(C3.Color);C3.Plugins.System.Acts={SetVar(ev,x){ev.SetValue(x)},AddVar(ev,x){if(ev.IsNumber()&&typeof x!=="number")x=parseFloat(x);ev.SetValue(ev.GetValue()+x)},
+SubVar(ev,x){if(!ev.IsNumber())return;ev.SetValue(ev.GetValue()-x)},SetBoolVar(ev,x){ev.SetValue(!!x)},ToggleBoolVar(ev){ev.SetValue(!ev.GetValue())},ResetGlobals(){this._runtime.GetEventSheetManager().ResetAllGlobalsToInitialValue()},CreateObject(objectClass,layer,x,y,createHierarchy,template){if(!objectClass||!layer)return;const inst=this._runtime.CreateInstance(objectClass,layer,x,y,createHierarchy,template);if(!inst)return;if(createHierarchy)layer.SortAndAddInstancesByZIndex(inst);const eventSheetManager=
+this._runtime.GetEventSheetManager();eventSheetManager.BlockFlushingInstances(true);inst._TriggerOnCreatedOnSelfAndRelated();eventSheetManager.BlockFlushingInstances(false);const pickMap=new Map;inst.CollectInstancesToPick(pickMap,objectClass,createHierarchy);for(const [pickObjectClass,instSet]of pickMap)pickObjectClass.GetCurrentSol().SetSetPicked(instSet)},CreateObjectByName(objectClassName,layer,x,y,createHierarchy,template){if(!objectClassName||!layer)return;const objectClass=this._runtime.GetObjectClassByName(objectClassName);
+if(!objectClass)return;C3.Plugins.System.Acts.CreateObject.call(this,objectClass,layer,x,y,createHierarchy,template)},RecreateInitialObjects(objectClass,x1,y1,x2,y2,sourceLayoutName,sourceLayerParam,offsetX,offsetY,createHierarchy){if(!objectClass)return;let sourceLayout=this._runtime.GetCurrentLayout();if(sourceLayoutName){const lookupLayout=this._runtime.GetLayoutManager().GetLayoutByName(sourceLayoutName);if(lookupLayout)sourceLayout=lookupLayout;else return}let sourceLayer=null;if(typeof sourceLayerParam!==
+"number"||sourceLayerParam>=0){sourceLayer=sourceLayout.GetLayer(sourceLayerParam);if(!sourceLayer)return}tempRect.set(x1,y1,x2,y2);const allCreatedInstances=sourceLayout.RecreateInitialObjects(objectClass,tempRect,sourceLayer,offsetX,offsetY,createHierarchy);objectClass.GetCurrentSol().SetArrayPicked(allCreatedInstances);objectClass.ApplySolToContainer()},StopLoop(){const loopStack=this._loopStack;if(!loopStack.IsInLoop())return;loopStack.GetCurrent().Stop()},SetGroupActive(groupName,a){const group=
+this._runtime.GetEventSheetManager().GetEventGroupByName(groupName);if(!group)return;if(a===0)group.SetGroupActive(false);else if(a===1)group.SetGroupActive(true);else group.SetGroupActive(!group.IsGroupActive())},SetTimescale(ts){this._runtime.SetTimeScale(ts)},SetObjectTimescale(objectClass,ts){if(ts<0)ts=0;if(!objectClass)return;const sol=objectClass.GetCurrentSol();const instances=sol.GetInstances();for(const inst of instances)inst.SetTimeScale(ts)},RestoreObjectTimescale(objectClass){if(!objectClass)return;
+const sol=objectClass.GetCurrentSol();const instances=sol.GetInstances();for(const inst of instances)inst.RestoreTimeScale()},Wait(seconds){if(seconds<0)return;this._runtime.GetEventSheetManager().AddScheduledWait().InitTimer(seconds);return true},WaitForSignal(tag){this._runtime.GetEventSheetManager().AddScheduledWait().InitSignal(tag);return true},WaitForPreviousActions(){const eventSheetManager=this._runtime.GetEventSheetManager();eventSheetManager.AddScheduledWait().InitPromise(eventSheetManager.GetPromiseForAllAsyncActions());
+return true},Signal(tag){const lowerTag=tag.toLowerCase();this._signalTags.push(lowerTag);this._runtime.Trigger(C3.Plugins.System.Cnds.OnSignal,null);this._signalTags.pop();for(const w of this._runtime.GetEventSheetManager().scheduledWaits())if(w.IsSignal()&&w.GetSignalTag()===lowerTag)w.SetSignalled()},async SnapshotCanvas(format,quality,x,y,width,height){const canvasManager=this._runtime.GetCanvasManager();if(!canvasManager)return;this.UpdateRender();await canvasManager.SnapshotCanvas(format===
+0?"image/png":"image/jpeg",quality/100,x,y,width,height);await this._runtime.TriggerAsync(C3.Plugins.System.Cnds.OnCanvasSnapshot,null)},SetCanvasSize(w,h){if(w<=0||h<=0)return;this._runtime.SetViewportSize(w,h);this._runtime.GetCurrentLayout().BoundScrolling();const canvasManager=this._runtime.GetCanvasManager();if(!canvasManager)return;if(canvasManager.GetCurrentFullscreenMode()==="off")canvasManager.SetSize(canvasManager.GetLastWidth(),canvasManager.GetLastHeight(),true);else{this._runtime.SetOriginalViewportSize(w,
+h);canvasManager.SetSize(canvasManager.GetLastWidth(),canvasManager.GetLastHeight(),true)}this._runtime.UpdateRender()},SetFullscreenQuality(q){const canvasManager=this._runtime.GetCanvasManager();if(!canvasManager)return;if(canvasManager.GetCurrentFullscreenMode()==="off")return;canvasManager.SetFullscreenScalingQuality(q!==0?"high":"low");canvasManager.SetSize(canvasManager.GetLastWidth(),canvasManager.GetLastHeight(),true)},SaveState(slot){this._runtime.SaveToSlot(slot)},LoadState(slot){this._runtime.LoadFromSlot(slot)},
+LoadStateJSON(jsonStr){this._runtime.LoadFromJsonString(jsonStr)},SetHalfFramerateMode(m){},ResetPersisted(){for(const layout of this._runtime.GetLayoutManager().GetAllLayouts())layout.ResetPersistData()},SetPixelRounding(m){this._runtime.SetPixelRoundingEnabled(m!==0)},SetMinimumFramerate(fps){this._runtime.SetMinimumFramerate(fps)},SortZOrderByInstVar(objectClass,instVar){if(!objectClass)return;const sol=objectClass.GetCurrentSol();const pickedInstances=sol.GetInstances();const zOrderList=tempZOrderList;
+const instValues=tempInstValues;const layout=this._runtime.GetCurrentLayout();const isFamily=objectClass.IsFamily();const familyIndex=objectClass.GetFamilyIndex();for(let i=0,len=pickedInstances.length;i0;if(hasAnySolModifiers)if(functionBlock.IsCopyPicked())eventSheetManager.PushCopySol(solModifiers);
+else eventSheetManager.PushCleanSol(solModifiers);const paramResults=[];const callerFunctionBlock=eventSheetManager.FindFirstFunctionBlockParent(currentEvent);if(callerFunctionBlock){const callerParameters=callerFunctionBlock.GetFunctionParameters();for(let i=forwardParams,len=callerParameters.length;in)ret=n}return ret},clamp(x,l,u){return C3.clamp(x,l,u)},distance(x1,y1,x2,y2){return C3.distanceTo(x1,y1,x2,y2)},angle(x1,y1,x2,y2){return C3.toDegrees(C3.angleTo(x1,y1,x2,y2))},lerp(a,b,x){return C3.lerp(a,b,x)},unlerp(a,b,y){return C3.unlerp(a,b,y)},qarp(a,b,c,x){return C3.qarp(a,b,c,x)},cubic(a,b,c,d,x){return C3.cubic(a,b,c,d,x)},cosp(a,b,x){return C3.cosp(a,b,x)},anglediff(a,
+b){return C3.toDegrees(C3.angleDiff(C3.toRadians(a),C3.toRadians(b)))},anglelerp(a,b,x){return C3.toDegrees(C3.angleLerp(C3.toRadians(a),C3.toRadians(b),x))},anglerotate(a,b,c){return C3.toDegrees(C3.angleRotate(C3.toRadians(a),C3.toRadians(b),C3.toRadians(c)))},setbit(n,b,v){n=n|0;b=b|0;v=v!==0?1:0;return n&~(1<=arr.length)return"";return arr[index]},tokencount(text,sep){if(typeof text!=="string"||typeof sep!=="string"||!text.length)return 0;return text.split(sep).length},find(text,searchStr){if(typeof text==="string"&&typeof searchStr==="string")return text.search(new RegExp(C3.EscapeRegex(searchStr),"i"));else return-1},findcase(text,searchStr){if(typeof text==="string"&&typeof searchStr==="string")return text.search(new RegExp(C3.EscapeRegex(searchStr),""));else return-1},replace(text,find,replace){if(typeof text===
+"string"&&typeof find==="string"&&typeof replace==="string")return text.replace(new RegExp(C3.EscapeRegex(find),"gi"),replace);else return typeof text==="string"?text:""},regexsearch(text,regex,flags){const cacheRegex=this.GetRegex(regex,flags);return text?text.search(cacheRegex):-1},regexreplace(text,regex,flags,replace){const cacheRegex=this.GetRegex(regex,flags);return text?text.replace(cacheRegex,replace):""},regexmatchcount(text,regex,flags){const matches=this.GetRegexMatches(text.toString(),
+regex,flags);return matches?matches.length:0},regexmatchat(text,regex,flags,index){index=Math.floor(index);const matches=this.GetRegexMatches(text.toString(),regex,flags);if(!matches||index<0||index>=matches.length)return"";else return matches[index]},zeropad(n,d){let s=n<0?"-":"";if(n<0)n=-n;const zeroes=d-n.toString().length;s+="0".repeat(Math.max(zeroes,0));return s+n.toString()},urlencode(s){return encodeURIComponent(s)},urldecode(s){return decodeURIComponent(s)},dt(){return this._runtime._GetDtFast()},
+timescale(){return this._runtime.GetTimeScale()},wallclocktime(){return(Date.now()-this._runtime.GetStartTime())/1E3},unixtime(){return Date.now()},time(){return this._runtime.GetGameTime()},tickcount(){return this._runtime.GetTickCount()},objectcount(){return this._runtime.GetObjectCount()},fps(){return this._runtime.GetFPS()},cpuutilisation(){return this._runtime.GetMainThreadTime()},gpuutilisation(){return this._runtime.GetGPUUtilisation()},windowwidth(){return this._runtime.GetCanvasManager().GetDeviceWidth()},
+windowheight(){return this._runtime.GetCanvasManager().GetDeviceHeight()},originalwindowwidth(){return this._runtime.GetOriginalViewportWidth()},originalwindowheight(){return this._runtime.GetOriginalViewportHeight()},originalviewportwidth(){return this._runtime.GetOriginalViewportWidth()},originalviewportheight(){return this._runtime.GetOriginalViewportHeight()},scrollx(){return this._runtime.GetCurrentLayout().GetScrollX()},scrolly(){return this._runtime.GetCurrentLayout().GetScrollY()},layoutname(){return this._runtime.GetCurrentLayout().GetName()},
+layoutscale(){return this._runtime.GetCurrentLayout().GetScale()},layoutangle(){return C3.toDegrees(this._runtime.GetCurrentLayout().GetAngle())},layoutwidth(){return this._runtime.GetCurrentLayout().GetWidth()},layoutheight(){return this._runtime.GetCurrentLayout().GetHeight()},vanishingpointx(){return this._runtime.GetCurrentLayout().GetVanishingPointX()*100},vanishingpointy(){return this._runtime.GetCurrentLayout().GetVanishingPointY()*100},viewportleft(layerParam){const layer=this._runtime.GetCurrentLayout().GetLayer(layerParam);
+return layer?layer.GetViewport3D().getLeft():0},viewporttop(layerParam){const layer=this._runtime.GetCurrentLayout().GetLayer(layerParam);return layer?layer.GetViewport3D().getTop():0},viewportright(layerParam){const layer=this._runtime.GetCurrentLayout().GetLayer(layerParam);return layer?layer.GetViewport3D().getRight():0},viewportbottom(layerParam){const layer=this._runtime.GetCurrentLayout().GetLayer(layerParam);return layer?layer.GetViewport3D().getBottom():0},viewportwidth(layerParam){const layer=
+this._runtime.GetCurrentLayout().GetLayer(layerParam);return layer?layer.GetViewport3D().width():0},viewportheight(layerParam){const layer=this._runtime.GetCurrentLayout().GetLayer(layerParam);return layer?layer.GetViewport3D().height():0},viewportmidx(layerParam){const layer=this._runtime.GetCurrentLayout().GetLayer(layerParam);if(layer){const vp=layer.GetViewport3D();return(vp.getLeft()+vp.getRight())/2}else return 0},viewportmidy(layerParam){const layer=this._runtime.GetCurrentLayout().GetLayer(layerParam);
+if(layer){const vp=layer.GetViewport3D();return(vp.getTop()+vp.getBottom())/2}else return 0},canvastolayerx(layerParam,x,y){const layer=this._runtime.GetCurrentLayout().GetLayer(layerParam);return layer?layer.CanvasCssToLayer(x,y)[0]:0},canvastolayery(layerParam,x,y){const layer=this._runtime.GetCurrentLayout().GetLayer(layerParam);return layer?layer.CanvasCssToLayer(x,y)[1]:0},layertocanvasx(layerParam,x,y){const layer=this._runtime.GetCurrentLayout().GetLayer(layerParam);return layer?layer.LayerToCanvasCss(x,
+y)[0]:0},layertocanvasy(layerParam,x,y){const layer=this._runtime.GetCurrentLayout().GetLayer(layerParam);return layer?layer.LayerToCanvasCss(x,y)[1]:0},layertolayerx(fromLayerParam,toLayerParam,x,y){const layout=this._runtime.GetCurrentLayout();const fromLayer=layout.GetLayer(fromLayerParam);const toLayer=layout.GetLayer(toLayerParam);if(!fromLayer||!toLayer||fromLayer===toLayer)return x;const [canvasX,canvasY]=fromLayer.LayerToCanvasCss(x,y);return toLayer.CanvasCssToLayer(canvasX,canvasY)[0]},
+layertolayery(fromLayerParam,toLayerParam,x,y){const layout=this._runtime.GetCurrentLayout();const fromLayer=layout.GetLayer(fromLayerParam);const toLayer=layout.GetLayer(toLayerParam);if(!fromLayer||!toLayer||fromLayer===toLayer)return y;const [canvasX,canvasY]=fromLayer.LayerToCanvasCss(x,y);return toLayer.CanvasCssToLayer(canvasX,canvasY)[1]},layerscale(layerParam){const layer=this._runtime.GetCurrentLayout().GetLayer(layerParam);return layer?layer.GetOwnScale():0},layerangle(layerParam){const layer=
+this._runtime.GetCurrentLayout().GetLayer(layerParam);return layer?C3.toDegrees(layer.GetOwnAngle()):0},layeropacity(layerParam){const layer=this._runtime.GetCurrentLayout().GetLayer(layerParam);return layer?layer.GetOpacity()*100:0},layerscalerate(layerParam){const layer=this._runtime.GetCurrentLayout().GetLayer(layerParam);return layer?layer.GetScaleRate():0},layerscrollx(layerParam){const layer=this._runtime.GetCurrentLayout().GetLayer(layerParam);return layer?layer.GetScrollX():0},layerscrolly(layerParam){const layer=
+this._runtime.GetCurrentLayout().GetLayer(layerParam);return layer?layer.GetScrollY():0},layerparallaxx(layerParam){const layer=this._runtime.GetCurrentLayout().GetLayer(layerParam);return layer?layer.GetParallaxX()*100:0},layerparallaxy(layerParam){const layer=this._runtime.GetCurrentLayout().GetLayer(layerParam);return layer?layer.GetParallaxY()*100:0},layerzelevation(layerParam){const layer=this._runtime.GetCurrentLayout().GetLayer(layerParam);return layer?layer.GetZElevation():0},layerindex(layerParam){const layer=
+this._runtime.GetCurrentLayout().GetLayer(layerParam);return layer?layer.GetIndex():-1},canvassnapshot(){const canvasManager=this._runtime.GetCanvasManager();if(!canvasManager)return"";return canvasManager.GetCanvasSnapshotUrl()},loopindex(name){const loopStack=this._loopStack;if(!loopStack.IsInLoop())return 0;if(name){const loop=loopStack.FindByName(name);return loop?loop.GetIndex():0}else return loopStack.GetCurrent().GetIndex()},savestatejson(){return this._runtime.GetLastSaveJsonString()},callmapped(name,
+str,...paramResults){const mapEntry=this._GetFunctionMap(name.toLowerCase(),false);if(!mapEntry){console.warn(`[Construct] Call mapped function: map name '${name}' not found; returning 0`);return 0}let functionBlock=mapEntry.strMap.get(str.toLowerCase());if(!functionBlock)if(mapEntry.defaultFunc)functionBlock=mapEntry.defaultFunc;else{console.warn(`[Construct] Call mapped function: no function associated with map '${name}' string '${str}'; returning 0 (consider setting a default)`);return 0}const returnType=
+functionBlock.GetReturnType();const defaultReturnValue=functionBlock.GetDefaultReturnValue();if(returnType===0){console.warn(`[Construct] Call mapped function: map '${name}' string '${str}' has no return type so cannot be called from an expression; returning 0`);return 0}if(!functionBlock.IsEnabled())return defaultReturnValue;const runtime=this._runtime;const eventSheetManager=runtime.GetEventSheetManager();const currentEvent=eventSheetManager.GetCurrentEvent();const solModifiers=currentEvent.GetSolModifiersIncludingParents();
+const hasAnySolModifiers=solModifiers.length>0;if(hasAnySolModifiers)if(functionBlock.IsCopyPicked())eventSheetManager.PushCopySol(solModifiers);else eventSheetManager.PushCleanSol(solModifiers);const calleeParameters=functionBlock.GetFunctionParameters();for(let i=paramResults.length,len=calleeParameters.length;ia.LoadAllTextures(renderer,opts)))}ReleaseTextures(){for(const a of this._animations)a.ReleaseAllTextures()}OnDynamicTextureLoadComplete(){this._UpdateAllCurrentTexture()}_UpdateAllCurrentTexture(){for(const inst of this._objectClass.instancesIncludingPendingCreate())inst.GetSdkInstance()._UpdateCurrentTexture()}FinishCondition(doPick){C3.Plugins.Sprite.FinishCollisionCondition(this,
+doPick)}BeforeRunAction(method){spawnPickStack.push({objectClass:null,createHierarchy:false,instances:[]})}_SpawnPickInstance(objectClass,inst,createHierarchy){const entry=spawnPickStack.at(-1);entry.objectClass=objectClass;entry.createHierarchy=createHierarchy;entry.instances.push(inst)}AfterRunAction(method){const entry=spawnPickStack.pop();const objectClass=entry.objectClass;const createHierarchy=entry.createHierarchy;if(!objectClass)return;const pickMap=new Map;for(const inst of entry.instances)inst.CollectInstancesToPick(pickMap,
+objectClass,createHierarchy);for(const [pickObjectClass,instSet]of pickMap)pickObjectClass.GetCurrentSol().SetSetPicked(instSet)}}}
+{const C3=self.C3;const C3X=self.C3X;const INITIALLY_VISIBLE=0;const INITIAL_ANIMATION=1;const INITIAL_FRAME=2;const ENABLE_COLLISIONS=3;const tempRect=C3.New(C3.Rect);const tempQuad=C3.New(C3.Quad);const tempVec2=C3.New(C3.Vector2);const FLAG_PLAYING_FORWARDS=1<<0;const FLAG_ANIMATION_PLAYING=1<<1;const FLAG_ANIMATION_TRIGGER=1<<2;C3.Plugins.Sprite.Instance=class SpriteInstance extends C3.SDKWorldInstanceBase{constructor(inst,properties){super(inst);let initiallyVisible=true;let initialAnimation=
+"";let initialFrame=0;let collisionEnabled=true;if(properties){initiallyVisible=!!properties[INITIALLY_VISIBLE];initialAnimation=properties[INITIAL_ANIMATION];initialFrame=properties[INITIAL_FRAME];collisionEnabled=properties[ENABLE_COLLISIONS]}this._currentAnimation=this._objectClass.GetAnimationByName(initialAnimation)||this._objectClass.GetAnimations()[0];this._currentFrameIndex=C3.clamp(initialFrame,0,this._currentAnimation.GetFrameCount()-1);this._currentAnimationFrame=this._currentAnimation.GetFrameAt(this._currentFrameIndex);
+const initialImageInfo=this._currentAnimationFrame.GetImageInfo();this._currentTexture=initialImageInfo.GetTexture();this._currentRcTex=initialImageInfo.GetTexRect();this._currentQuadTex=initialImageInfo.GetTexQuad();this.HandleRendererContextLoss();inst.SetFlag(FLAG_ANIMATION_PLAYING,true);inst.SetFlag(FLAG_PLAYING_FORWARDS,this._currentAnimation.GetSpeed()>=0);this._currentAnimationSpeed=Math.abs(this._currentAnimation.GetSpeed());this._currentAnimationRepeatTo=this._currentAnimation.GetRepeatTo();
+this._animationTimer=C3.New(C3.KahanSum);this._frameStartTime=0;this._animationRepeats=0;this._animTriggerName="";this._changeAnimFrameIndex=-1;this._changeAnimationName="";this._changeAnimationFrom=0;const wi=this.GetWorldInfo();this._bquadRef=wi.GetBoundingQuad();wi.SetVisible(initiallyVisible);wi.SetCollisionEnabled(collisionEnabled);wi.SetOriginX(this._currentAnimationFrame.GetOriginX());wi.SetOriginY(this._currentAnimationFrame.GetOriginY());wi.SetSourceCollisionPoly(this._currentAnimationFrame.GetCollisionPoly());
+wi.SetBboxChanged();if((this._objectClass.GetAnimationCount()!==1||this._objectClass.GetAnimations()[0].GetFrameCount()!==1)&&this._currentAnimationSpeed!==0)this._StartTicking()}Release(){this._currentAnimation=null;this._currentAnimationFrame=null;this._currentTexture=null;this._animationTimer=null;super.Release()}GetCurrentImageInfo(){return this._currentAnimationFrame.GetImageInfo()}IsOriginalSizeKnown(){return true}OnRendererContextLost(){this._currentTexture=null}OnRendererContextRestored(){this._UpdateCurrentTexture()}Draw(renderer){const texture=
+this._currentTexture;if(texture===null)return;renderer.SetTexture(texture);const wi=this.GetWorldInfo();if(wi.HasMesh())this._DrawMesh(wi,renderer);else this._DrawStandard(wi,renderer)}_DrawStandard(wi,renderer){let quad=this._bquadRef;if(this._runtime.IsPixelRoundingEnabled())quad=wi.PixelRoundQuad(quad);renderer.Quad4(quad,this._currentQuadTex)}_DrawMesh(wi,renderer){const transformedMesh=wi.GetTransformedMesh();if(wi.IsMeshChanged()){wi.CalculateBbox(tempRect,tempQuad,false);let quad=tempQuad;
+if(this._runtime.IsPixelRoundingEnabled())quad=wi.PixelRoundQuad(quad);transformedMesh.CalculateTransformedMesh(wi.GetSourceMesh(),quad,this._currentQuadTex);wi.SetMeshChanged(false)}transformedMesh.Draw(renderer)}GetAnimationTime(){return this._animationTimer.Get()}IsAnimationPlaying(){return this._inst.GetFlag(FLAG_ANIMATION_PLAYING)}SetAnimationPlaying(e){this._inst.SetFlag(FLAG_ANIMATION_PLAYING,e)}IsPlayingForwards(){return this._inst.GetFlag(FLAG_PLAYING_FORWARDS)}SetPlayingForwards(e){this._inst.SetFlag(FLAG_PLAYING_FORWARDS,
+e)}IsInAnimationTrigger(){return this._inst.GetFlag(FLAG_ANIMATION_TRIGGER)}SetInAnimationTrigger(e){this._inst.SetFlag(FLAG_ANIMATION_TRIGGER,e)}Tick(){if(this._changeAnimationName)this._DoChangeAnimation();if(this._changeAnimFrameIndex>=0)this._DoChangeAnimFrame();const currentAnimationSpeed=this._currentAnimationSpeed;if(!this.IsAnimationPlaying()||currentAnimationSpeed===0){this._StopTicking();return}const dt=this._runtime.GetDt(this._inst);this._animationTimer.Add(dt);const now=this.GetAnimationTime();
+const prevFrame=this._currentAnimationFrame;const currentFrameTime=prevFrame.GetDuration()/currentAnimationSpeed;if(now=frameCount)if(isPingPong){this.SetPlayingForwards(false);this._currentFrameIndex=frameCount-2}else if(isLooping)this._currentFrameIndex=repeatTo;else{this._animationRepeats++;if(this._animationRepeats>=repeatCount)this._FinishAnimation(false);else this._currentFrameIndex=repeatTo}if(this._currentFrameIndex<0)if(isPingPong){this._currentFrameIndex=1;this.SetPlayingForwards(true);if(!isLooping){this._animationRepeats++;
+if(this._animationRepeats>=repeatCount)this._FinishAnimation(true)}}else if(isLooping)this._currentFrameIndex=repeatTo;else{this._animationRepeats++;if(this._animationRepeats>=repeatCount)this._FinishAnimation(true);else this._currentFrameIndex=repeatTo}this._currentFrameIndex=C3.clamp(this._currentFrameIndex,0,frameCount-1);const nextFrame=currentAnimation.GetFrameAt(this._currentFrameIndex);if(now>this._frameStartTime+nextFrame.GetDuration()/currentAnimationSpeed)this._frameStartTime=now;this._OnFrameChanged(prevFrame,
+nextFrame)}_FinishAnimation(reverse){this._currentFrameIndex=reverse?0:this._currentAnimation.GetFrameCount()-1;this.SetAnimationPlaying(false);this._animTriggerName=this._currentAnimation.GetName();this.SetInAnimationTrigger(true);this.DispatchScriptEvent("animationend",false,{animationName:this._animTriggerName});this.Trigger(C3.Plugins.Sprite.Cnds.OnAnyAnimFinished);this.Trigger(C3.Plugins.Sprite.Cnds.OnAnimFinished);this.SetInAnimationTrigger(false);this._animationRepeats=0}_OnFrameChanged(prevFrame,
+nextFrame,opts){if(prevFrame===nextFrame)return;const wi=this.GetWorldInfo();const prevImage=prevFrame.GetImageInfo();const nextImage=nextFrame.GetImageInfo();const oldW=prevImage.GetWidth();const oldH=prevImage.GetHeight();const newW=nextImage.GetWidth();const newH=nextImage.GetHeight();if(opts&&opts.onFrameChange)opts.onFrameChange(wi,oldW,oldH,newW,newH);else{if(oldW!==newW)wi.SetWidth(wi.GetWidth()*(newW/oldW));if(oldH!==newH)wi.SetHeight(wi.GetHeight()*(newH/oldH))}wi.SetOriginX(nextFrame.GetOriginX());
+wi.SetOriginY(nextFrame.GetOriginY());wi.SetSourceCollisionPoly(nextFrame.GetCollisionPoly());wi.SetBboxChanged();this._currentAnimationFrame=nextFrame;this._currentTexture=nextImage.GetTexture();this._currentRcTex=nextImage.GetTexRect();this._currentQuadTex=nextImage.GetTexQuad();const behaviorInstances=this.GetInstance().GetBehaviorInstances();for(let i=0,len=behaviorInstances.length;i=0);if(this._currentAnimationSpeed>0)this._StartTicking()}_GetAnimSpeed(){return this.IsPlayingForwards()?this._currentAnimationSpeed:-this._currentAnimationSpeed}_SetAnimRepeatToFrame(f){f=C3.clamp(Math.floor(f),0,
+this._currentAnimation.GetFrameCount()-1);this._currentAnimationRepeatTo=f}_GetAnimRepeatToFrame(){return this._currentAnimationRepeatTo}_DoChangeAnimation(opts){const prevFrame=this._currentAnimationFrame;const animation=this._objectClass.GetAnimationByName(this._changeAnimationName);this._changeAnimationName="";if(!animation)return;if(animation===this._currentAnimation&&this.IsAnimationPlaying())return;this._currentAnimation=animation;this.SetPlayingForwards(animation.GetSpeed()>=0);this._currentAnimationSpeed=
+Math.abs(animation.GetSpeed());this._currentAnimationRepeatTo=animation.GetRepeatTo();this._currentFrameIndex=C3.clamp(this._currentFrameIndex,0,this._currentAnimation.GetFrameCount()-1);if(this._changeAnimationFrom===1)this._currentFrameIndex=0;this.SetAnimationPlaying(true);this._frameStartTime=this.GetAnimationTime();const nextFrame=this._currentAnimation.GetFrameAt(this._currentFrameIndex);this._OnFrameChanged(prevFrame,nextFrame,opts)}_DoChangeAnimFrame(){const prevFrame=this._currentAnimationFrame;
+const prevFrameIndex=this._currentFrameIndex;this._currentFrameIndex=C3.clamp(Math.floor(this._changeAnimFrameIndex),0,this._currentAnimation.GetFrameCount()-1);this._changeAnimFrameIndex=-1;if(prevFrameIndex===this._currentFrameIndex)return;const nextFrame=this._currentAnimation.GetFrameAt(this._currentFrameIndex);this._OnFrameChanged(prevFrame,nextFrame);this._frameStartTime=this.GetAnimationTime()}_UpdateCurrentTexture(){const curImageInfo=this._currentAnimationFrame.GetImageInfo();this._currentTexture=
+curImageInfo.GetTexture();this._currentRcTex=curImageInfo.GetTexRect();this._currentQuadTex=curImageInfo.GetTexQuad();this.GetWorldInfo().SetMeshChanged(true)}GetTexture(){return this._currentTexture}GetTexRect(){return this._currentRcTex}GetTexQuad(){return this._currentQuadTex}GetImagePointCount(){return this._currentAnimationFrame.GetImagePointCount()}GetImagePoint(nameOrIndex){const frame=this._currentAnimationFrame;const wi=this.GetWorldInfo();let ip=null;if(typeof nameOrIndex==="string")ip=
+frame.GetImagePointByName(nameOrIndex);else if(typeof nameOrIndex==="number")ip=frame.GetImagePointByIndex(nameOrIndex-1);else throw new TypeError("expected string or number");let ptZ=wi.GetTotalZElevation();if(!ip)return[wi.GetX(),wi.GetY(),ptZ];tempVec2.copy(ip.GetVec2());if(wi.HasMesh()){const [tx,ty,tz]=wi.GetSourceMesh().TransformPoint(tempVec2.getX(),tempVec2.getY());tempVec2.set(tx,ty);ptZ+=tz}tempVec2.offset(-frame.GetOriginX(),-frame.GetOriginY());tempVec2.scale(wi.GetWidth(),wi.GetHeight());
+tempVec2.rotate(wi.GetAngle());tempVec2.offset(wi.GetX(),wi.GetY());return[tempVec2.getX(),tempVec2.getY(),ptZ]}GetCollisionPolyPointCount(){return this.GetWorldInfo().GetTransformedCollisionPoly().pointCount()}GetCollisionPolyPoint(index){index=Math.floor(index);const wi=this.GetWorldInfo();const poly=wi.GetTransformedCollisionPoly();const pointCount=poly.pointCount();if(index===pointCount)index=0;if(index<0||index>=pointCount)return[0,0];const pointsArr=poly.pointsArr();return[pointsArr[index*2+
+0]+wi.GetX(),pointsArr[index*2+1]+wi.GetY()]}GetDebuggerProperties(){const Acts=C3.Plugins.Sprite.Acts;const prefix="plugins.sprite.debugger.animation-properties";return[{title:prefix+".title",properties:[{name:prefix+".current-animation",value:this._currentAnimation.GetName(),onedit:v=>this.CallAction(Acts.SetAnim,v,0)},{name:prefix+".current-frame",value:this._currentFrameIndex,onedit:v=>this.CallAction(Acts.SetAnimFrame,v)},{name:prefix+".is-playing",value:this.IsAnimationPlaying(),onedit:v=>v?
+this.CallAction(Acts.StartAnim,0):this.CallAction(Acts.StopAnim)},{name:prefix+".speed",value:this._currentAnimationSpeed,onedit:v=>this.CallAction(Acts.SetAnimSpeed,v)},{name:prefix+".repeats",value:this._animationRepeats,onedit:v=>this._animationRepeats=v}]}]}SaveToJson(){const o={"a":this._currentAnimation.GetSID()};if(this._frameStartTime!==0)o["fs"]=this._frameStartTime;const animTime=this.GetAnimationTime();if(animTime!==0)o["at"]=animTime;if(this._currentFrameIndex!==0)o["f"]=this._currentFrameIndex;
+if(this._currentAnimationSpeed!==0)o["cas"]=this._currentAnimationSpeed;if(this._animationRepeats!==1)o["ar"]=this._animationRepeats;if(this._currentAnimationRepeatTo!==0)o["rt"]=this._currentAnimationRepeatTo;if(!this.IsAnimationPlaying())o["ap"]=this.IsAnimationPlaying();if(!this.IsPlayingForwards())o["af"]=this.IsPlayingForwards();const wi=this.GetWorldInfo();if(wi.IsCollisionEnabled())o["ce"]=wi.IsCollisionEnabled();return o}LoadFromJson(o){const anim=this.GetObjectClass().GetAnimationBySID(o["a"]);
+if(anim)this._currentAnimation=anim;this._frameStartTime=o.hasOwnProperty("fs")?o["fs"]:0;this._animationTimer.Set(o.hasOwnProperty("at")?o["at"]:0);const frameIndex=o.hasOwnProperty("f")?o["f"]:0;this._currentFrameIndex=C3.clamp(frameIndex,0,this._currentAnimation.GetFrameCount()-1);this._currentAnimationSpeed=o.hasOwnProperty("cas")?o["cas"]:0;this._animationRepeats=o.hasOwnProperty("ar")?o["ar"]:1;const repeatToIndex=o.hasOwnProperty("rt")?o["rt"]:0;this._currentAnimationRepeatTo=C3.clamp(repeatToIndex,
+0,this._currentAnimation.GetFrameCount()-1);this.SetAnimationPlaying(o.hasOwnProperty("ap")?!!o["ap"]:true);this.SetPlayingForwards(o.hasOwnProperty("af")?!!o["af"]:true);const nextFrame=this._currentAnimation.GetFrameAt(this._currentFrameIndex);this._currentAnimationFrame=nextFrame;this._UpdateCurrentTexture();const wi=this.GetWorldInfo();wi.SetOriginX(nextFrame.GetOriginX());wi.SetOriginY(nextFrame.GetOriginY());wi.SetSourceCollisionPoly(nextFrame.GetCollisionPoly());wi.SetCollisionEnabled(!!o["ce"]);
+if(this.IsAnimationPlaying())this._StartTicking()}GetPropertyValueByIndex(index){const wi=this.GetWorldInfo();switch(index){case ENABLE_COLLISIONS:return wi.IsCollisionEnabled();case INITIAL_FRAME:return C3.clamp(this._currentFrameIndex,0,this._currentAnimation.GetFrameCount()-1);case INITIAL_ANIMATION:return this._currentAnimation.GetName()}}SetPropertyValueByIndex(index,value,opts){const wi=this.GetWorldInfo();switch(index){case ENABLE_COLLISIONS:{wi.SetCollisionEnabled(!!value);break}case INITIAL_FRAME:{this.SetAnimationPlaying(false);
+const totalFrames=this._currentAnimation.GetFrameCount()-1;const nextIndex=value=C3.clamp(value,0,totalFrames);const prevFrame=this._currentAnimation.GetFrameAt(this._currentFrameIndex);const nextFrame=this._currentAnimation.GetFrameAt(nextIndex);this._OnFrameChanged(prevFrame,nextFrame,opts);this._currentFrameIndex=C3.clamp(nextIndex,0,totalFrames);break}case INITIAL_ANIMATION:{this._changeAnimationName=value;this._DoChangeAnimation(opts);const totalFrames=this._currentAnimation.GetFrameCount();
+if(totalFrames>1&&this._currentAnimation.GetSpeed()>0)this._StartTicking();else this._StopTicking();break}}}GetScriptInterfaceClass(){return self.ISpriteInstance}};const map=new WeakMap;const ANIM_FROM_MODES=new Map([["current-frame",0],["beginning",1]]);self.ISpriteInstance=class ISpriteInstance extends self.IWorldInstance{constructor(){super();map.set(this,self.IInstance._GetInitInst().GetSdkInstance())}getImagePointCount(){return map.get(this).GetImagePointCount()}getImagePointX(nameOrIndex){return this.getImagePoint(nameOrIndex)[0]}getImagePointY(nameOrIndex){return this.getImagePoint(nameOrIndex)[1]}getImagePointZ(nameOrIndex){return this.getImagePoint(nameOrIndex)[2]}getImagePoint(nameOrIndex){if(typeof nameOrIndex!==
+"string"&&typeof nameOrIndex!=="number")throw new TypeError("expected string or number");return map.get(this).GetImagePoint(nameOrIndex)}getPolyPointCount(){return map.get(this).GetCollisionPolyPointCount()}getPolyPointX(index){C3X.RequireFiniteNumber(index);return map.get(this).GetCollisionPolyPoint(index)[0]}getPolyPointY(index){C3X.RequireFiniteNumber(index);return map.get(this).GetCollisionPolyPoint(index)[1]}getPolyPoint(index){C3X.RequireFiniteNumber(index);return map.get(this).GetCollisionPolyPoint(index)}stopAnimation(){map.get(this).SetAnimationPlaying(false)}startAnimation(from=
+"current-frame"){C3X.RequireString(from);const f=ANIM_FROM_MODES.get(from);if(typeof f==="undefined")throw new Error("invalid mode");map.get(this)._StartAnim(f)}setAnimation(name,from="beginning"){C3X.RequireString(name);C3X.RequireString(from);const f=ANIM_FROM_MODES.get(from);if(typeof f==="undefined")throw new Error("invalid mode");const inst=map.get(this);if(!inst.GetObjectClass().GetAnimationByName(name))throw new Error(`animation name "${name}" does not exist`);inst._SetAnim(name,f)}getAnimation(name){C3X.RequireString(name);
+const a=map.get(this).GetObjectClass().GetAnimationByName(name);return a?a.GetIAnimation():null}get animation(){return map.get(this)._GetCurrentAnimation().GetIAnimation()}get animationName(){return map.get(this)._GetCurrentAnimationName()}set animationFrame(frameIndex){C3X.RequireFiniteNumber(frameIndex);map.get(this)._SetAnimFrame(frameIndex)}get animationFrame(){return map.get(this)._GetAnimFrame()}set animationFrameTag(frameTag){C3X.RequireString(frameTag);map.get(this)._SetAnimFrame(frameTag)}get animationFrameTag(){return map.get(this)._GetAnimFrameTag()}set animationSpeed(s){C3X.RequireFiniteNumber(s);
+map.get(this)._SetAnimSpeed(s)}get animationSpeed(){return map.get(this)._GetAnimSpeed()}set animationRepeatToFrame(f){C3X.RequireFiniteNumber(f);map.get(this)._SetAnimRepeatToFrame(f)}get animationRepeatToFrame(){return map.get(this)._GetAnimRepeatToFrame()}get imageWidth(){return map.get(this).GetCurrentImageInfo().GetWidth()}get imageHeight(){return map.get(this).GetCurrentImageInfo().GetHeight()}getImageSize(){const imageInfo=map.get(this).GetCurrentImageInfo();return[imageInfo.GetWidth(),imageInfo.GetHeight()]}async replaceCurrentAnimationFrame(blob){C3X.RequireInstanceOf(blob,
+Blob);const sdkInst=map.get(this);const runtime=sdkInst.GetRuntime();const curImageInfo=sdkInst.GetCurrentImageInfo();const imageInfo=C3.New(C3.ImageInfo);imageInfo.LoadDynamicBlobAsset(runtime,blob);await imageInfo.LoadStaticTexture(runtime.GetRenderer(),{sampling:runtime.GetSampling()});if(sdkInst.WasReleased()){imageInfo.Release();return}curImageInfo.ReplaceWith(imageInfo);const sdkType=sdkInst.GetSdkType();sdkType._UpdateAllCurrentTexture();sdkType.GetObjectClass().Dispatcher().dispatchEvent(new C3.Event("animationframeimagechange"));
+runtime.UpdateRender()}setSolidCollisionFilter(isInclusive,tags){C3X.RequireString(tags);map.get(this).GetWorldInfo().SetSolidCollisionFilter(!!isInclusive,tags)}}}
+{const C3=self.C3;C3.Plugins.Sprite.Cnds={IsAnimPlaying(animName){return C3.equalsNoCase(this._GetCurrentAnimationName(),animName)},CompareFrame(cmp,frameNum){return C3.compare(this._currentFrameIndex,cmp,frameNum)},CompareFrameTag(cmp,frameTag){const selfTag=this._currentAnimationFrame.GetTag();return C3.compare(selfTag.toLowerCase(),cmp,frameTag.toLowerCase())},CompareAnimSpeed(cmp,x){return C3.compare(this._GetAnimSpeed(),cmp,x)},OnAnimFinished(animName){return C3.equalsNoCase(this._animTriggerName,
+animName)},OnAnyAnimFinished(){return true},OnFrameChanged(){return true},IsMirrored(){return this.GetWorldInfo().GetWidth()<0},IsFlipped(){return this.GetWorldInfo().GetHeight()<0},OnURLLoaded(){return true},OnURLFailed(){return true},IsCollisionEnabled(){return this.GetWorldInfo().IsCollisionEnabled()}}}
+{const C3=self.C3;C3.Plugins.Sprite.Acts={Spawn(objectClass,layer,imgPt,createHierarchy){if(!objectClass||!layer)return;const [imgPtX,imgPtY]=this.GetImagePoint(imgPt);const inst=this._runtime.CreateInstance(objectClass,layer,imgPtX,imgPtY,createHierarchy);if(!inst)return;if(createHierarchy)layer.SortAndAddInstancesByZIndex(inst);if(objectClass.GetPlugin().IsRotatable()){const instWi=inst.GetWorldInfo();instWi.SetAngle(this.GetWorldInfo().GetAngle());instWi.SetBboxChanged()}const eventSheetManager=
+this._runtime.GetEventSheetManager();eventSheetManager.BlockFlushingInstances(true);inst._TriggerOnCreatedOnSelfAndRelated();eventSheetManager.BlockFlushingInstances(false);if(objectClass!==this._runtime.GetCurrentAction().GetObjectClass())this._sdkType._SpawnPickInstance(objectClass,inst,createHierarchy)},StopAnim(){this.SetAnimationPlaying(false)},StartAnim(from){this._StartAnim(from)},SetAnim(animName,from){this._SetAnim(animName,from)},SetAnimFrame(frameNum){this._SetAnimFrame(frameNum)},SetAnimSpeed(s){this._SetAnimSpeed(s)},
+SetAnimRepeatToFrame(f){this._SetAnimRepeatToFrame(f)},SetMirrored(m){const wi=this.GetWorldInfo();const oldW=wi.GetWidth();const newW=Math.abs(oldW)*(m===0?-1:1);if(oldW===newW)return;wi.SetWidth(newW);wi.SetBboxChanged()},SetFlipped(f){const wi=this.GetWorldInfo();const oldH=wi.GetHeight();const newH=Math.abs(oldH)*(f===0?-1:1);if(oldH===newH)return;wi.SetHeight(newH);wi.SetBboxChanged()},SetScale(s){const frame=this._currentAnimationFrame;const imageInfo=frame.GetImageInfo();const wi=this.GetWorldInfo();
+const mirrorFactor=wi.GetWidth()<0?-1:1;const flipFactor=wi.GetHeight()<0?-1:1;const newWidth=imageInfo.GetWidth()*s*mirrorFactor;const newHeight=imageInfo.GetHeight()*s*flipFactor;if(wi.GetWidth()!==newWidth||wi.GetHeight()!==newHeight){wi.SetSize(newWidth,newHeight);wi.SetBboxChanged()}},async LoadURL(url,resize,crossOrigin){const curAnimFrame=this._currentAnimationFrame;const curImageInfo=curAnimFrame.GetImageInfo();const wi=this.GetWorldInfo();const runtime=this._runtime;const sdkType=this._sdkType;
+if(curImageInfo.GetURL()===url){if(resize===0){wi.SetSize(curImageInfo.GetWidth(),curImageInfo.GetHeight());wi.SetBboxChanged()}this.Trigger(C3.Plugins.Sprite.Cnds.OnURLLoaded);return}const imageInfo=C3.New(C3.ImageInfo);try{await imageInfo.LoadDynamicAsset(runtime,url);if(!imageInfo.IsLoaded())throw new Error("image failed to load");if(this.WasReleased()){imageInfo.Release();return}await imageInfo.LoadStaticTexture(runtime.GetRenderer(),{sampling:runtime.GetSampling()})}catch(err){console.error("Load image from URL failed: ",
+err);if(!this.WasReleased())this.Trigger(C3.Plugins.Sprite.Cnds.OnURLFailed);return}if(this.WasReleased()){imageInfo.Release();return}curImageInfo.ReplaceWith(imageInfo);sdkType._UpdateAllCurrentTexture();sdkType.GetObjectClass().Dispatcher().dispatchEvent(new C3.Event("animationframeimagechange"));runtime.UpdateRender();if(resize===0){wi.SetSize(curImageInfo.GetWidth(),curImageInfo.GetHeight());wi.SetBboxChanged()}await this.TriggerAsync(C3.Plugins.Sprite.Cnds.OnURLLoaded)},SetCollisions(e){this.GetWorldInfo().SetCollisionEnabled(e)},
+SetSolidCollisionFilter(mode,tags){this.GetWorldInfo().SetSolidCollisionFilter(mode===0,tags)},SetEffect(effect){this.GetWorldInfo().SetBlendMode(effect);this._runtime.UpdateRender()}}}
+{const C3=self.C3;C3.Plugins.Sprite.Exps={AnimationFrame(){return this._GetAnimFrame()},AnimationFrameTag(){return this._GetAnimFrameTag()},AnimationFrameCount(){return this._currentAnimation.GetFrameCount()},AnimationName(){return this._currentAnimation.GetName()},AnimationSpeed(){return this._GetAnimSpeed()},OriginalAnimationSpeed(){return this._currentAnimation.GetSpeed()},ImagePointX(imgpt){return this.GetImagePoint(imgpt)[0]},ImagePointY(imgpt){return this.GetImagePoint(imgpt)[1]},ImagePointZ(imgpt){return this.GetImagePoint(imgpt)[2]},
+ImagePointCount(){return this.GetImagePointCount()},ImageWidth(){return this.GetCurrentImageInfo().GetWidth()},ImageHeight(){return this.GetCurrentImageInfo().GetHeight()},PolyPointXAt(i){return this.GetCollisionPolyPoint(i)[0]},PolyPointYAt(i){return this.GetCollisionPolyPoint(i)[1]},PolyPointCount(){return this.GetCollisionPolyPointCount()}}};
+
+}
+
+{
+'use strict';{const C3=self.C3;C3.Plugins.Keyboard=class KeyboardPlugin extends C3.SDKPluginBase{constructor(opts){super(opts)}Release(){super.Release()}}}
+{const C3=self.C3;const C3X=self.C3X;C3.Plugins.Keyboard.Type=class KeyboardType extends C3.SDKTypeBase{constructor(objectClass){super(objectClass)}Release(){super.Release()}OnCreate(){}GetScriptInterfaceClass(){return self.IKeyboardObjectType}};let keyboardObjectType=null;function GetKeyboardSdkInstance(){return keyboardObjectType.GetSingleGlobalInstance().GetSdkInstance()}self.IKeyboardObjectType=class IKeyboardObjectType extends self.IObjectClass{constructor(objectType){super(objectType);keyboardObjectType=
+objectType;objectType.GetRuntime()._GetCommonScriptInterfaces().keyboard=this}isKeyDown(keyOrCode){const keyboardInst=GetKeyboardSdkInstance();if(typeof keyOrCode==="string")return keyboardInst.IsKeyDown(keyOrCode);else if(typeof keyOrCode==="number")return keyboardInst.IsKeyCodeDown(keyOrCode);else throw new TypeError("expected string or number");}}}
+{const C3=self.C3;C3.Plugins.Keyboard.Instance=class KeyboardInstance extends C3.SDKInstanceBase{constructor(inst,properties){super(inst);this._keysDownByString=new Set;this._keysDownByWhich=new Set;this._triggerWhich=0;this._triggerString="";this._triggerTypedKey="";const rt=this.GetRuntime().Dispatcher();this._disposables=new C3.CompositeDisposable(C3.Disposable.From(rt,"keydown",e=>this._OnKeyDown(e.data)),C3.Disposable.From(rt,"keyup",e=>this._OnKeyUp(e.data)),C3.Disposable.From(rt,"window-blur",
+()=>this._OnWindowOrKeyboardBlur()),C3.Disposable.From(rt,"keyboard-blur",()=>this._OnWindowOrKeyboardBlur()))}Release(){super.Release()}_OnKeyDown(e){const which=e["which"];const keyString=e["code"]||which.toString();const typedKey=e["key"];if(this._keysDownByString.has(keyString))return;this._keysDownByString.add(keyString);this._keysDownByWhich.add(which);this._triggerString=keyString;this._triggerWhich=which;this._triggerTypedKey=typedKey;this.Trigger(C3.Plugins.Keyboard.Cnds.OnAnyKey);this.Trigger(C3.Plugins.Keyboard.Cnds.OnKey);
+this.Trigger(C3.Plugins.Keyboard.Cnds.OnLeftRightKeyPressed);this.Trigger(C3.Plugins.Keyboard.Cnds.OnKeyCode)}_OnKeyUp(e){const which=e["which"];const keyString=e["code"]||which.toString();const typedKey=e["key"];this._keysDownByString.delete(keyString);this._keysDownByWhich.delete(which);this._triggerString=keyString;this._triggerWhich=which;this._triggerTypedKey=typedKey;this.Trigger(C3.Plugins.Keyboard.Cnds.OnAnyKeyReleased);this.Trigger(C3.Plugins.Keyboard.Cnds.OnKeyReleased);this.Trigger(C3.Plugins.Keyboard.Cnds.OnLeftRightKeyReleased);
+this.Trigger(C3.Plugins.Keyboard.Cnds.OnKeyCodeReleased)}_OnWindowOrKeyboardBlur(){for(const which of this._keysDownByWhich){this._keysDownByWhich.delete(which);this._triggerWhich=which;this.Trigger(C3.Plugins.Keyboard.Cnds.OnAnyKeyReleased);this.Trigger(C3.Plugins.Keyboard.Cnds.OnKeyReleased);this.Trigger(C3.Plugins.Keyboard.Cnds.OnKeyCodeReleased)}this._keysDownByString.clear()}IsKeyDown(str){return this._keysDownByString.has(str)}IsKeyCodeDown(which){return this._keysDownByWhich.has(which)}SaveToJson(){return{"tk":this._triggerWhich,
+"tkk":this._triggerTypedKey}}LoadFromJson(o){this._triggerWhich=o["tk"];if(o.hasOwnProperty("tkk"))this._triggerTypedKey=o["tkk"]}GetDebuggerProperties(){const prefix="plugins.keyboard";return[{title:prefix+".name",properties:[{name:prefix+".debugger.last-key-code",value:this._triggerWhich},{name:prefix+".debugger.last-key-string",value:C3.Plugins.Keyboard.Exps.StringFromKeyCode(this._triggerWhich)},{name:prefix+".debugger.last-typed-key",value:this._triggerTypedKey}]}]}}}
+{const C3=self.C3;const LEFTRIGHT_KEY_STRINGS=["ShiftLeft","ShiftRight","ControlLeft","ControlRight","AltLeft","AltRight","MetaLeft","MetaRight"];C3.Plugins.Keyboard.Cnds={IsKeyDown(which){return this._keysDownByWhich.has(which)},OnKey(which){return this._triggerWhich===which},OnAnyKey(){return true},OnAnyKeyReleased(){return true},OnKeyReleased(which){return this._triggerWhich===which},IsKeyCodeDown(which){which=Math.floor(which);return this._keysDownByWhich.has(which)},OnKeyCode(which){return this._triggerWhich===
+which},OnKeyCodeReleased(which){return this._triggerWhich===which},OnLeftRightKeyPressed(index){const keyString=LEFTRIGHT_KEY_STRINGS[index];return this._triggerString===keyString},OnLeftRightKeyReleased(index){const keyString=LEFTRIGHT_KEY_STRINGS[index];return this._triggerString===keyString},IsLeftRightKeyDown(index){const keyString=LEFTRIGHT_KEY_STRINGS[index];return this._keysDownByString.has(keyString)}}}{const C3=self.C3;C3.Plugins.Keyboard.Acts={}}
+{const C3=self.C3;function StringFromCharCode(kc){kc=Math.floor(kc);switch(kc){case 8:return"backspace";case 9:return"tab";case 13:return"enter";case 16:return"shift";case 17:return"control";case 18:return"alt";case 19:return"pause";case 20:return"capslock";case 27:return"esc";case 33:return"pageup";case 34:return"pagedown";case 35:return"end";case 36:return"home";case 37:return"\u2190";case 38:return"\u2191";case 39:return"\u2192";case 40:return"\u2193";case 45:return"insert";case 46:return"del";
+case 91:return"left window key";case 92:return"right window key";case 93:return"select";case 96:return"numpad 0";case 97:return"numpad 1";case 98:return"numpad 2";case 99:return"numpad 3";case 100:return"numpad 4";case 101:return"numpad 5";case 102:return"numpad 6";case 103:return"numpad 7";case 104:return"numpad 8";case 105:return"numpad 9";case 106:return"numpad *";case 107:return"numpad +";case 109:return"numpad -";case 110:return"numpad .";case 111:return"numpad /";case 112:return"F1";case 113:return"F2";
+case 114:return"F3";case 115:return"F4";case 116:return"F5";case 117:return"F6";case 118:return"F7";case 119:return"F8";case 120:return"F9";case 121:return"F10";case 122:return"F11";case 123:return"F12";case 144:return"numlock";case 145:return"scroll lock";case 186:return";";case 187:return"=";case 188:return",";case 189:return"-";case 190:return".";case 191:return"/";case 192:return"'";case 219:return"[";case 220:return"\\";case 221:return"]";case 222:return"#";case 223:return"`";default:return String.fromCharCode(kc)}}
+C3.Plugins.Keyboard.Exps={LastKeyCode(){return this._triggerWhich},StringFromKeyCode(kc){return StringFromCharCode(kc)},TypedKey(){return this._triggerTypedKey}}};
+
+}
+
+{
+'use strict';{const C3=self.C3;const actionPromises=[];C3.Plugins.Audio=class AudioPlugin extends C3.SDKPluginBase{constructor(opts){super(opts)}_AddActionPromise(promise){actionPromises.push(promise)}static async WaitForAllActionPromises(){await Promise.all(actionPromises);C3.clearArray(actionPromises)}Release(){super.Release()}}}
+{const C3=self.C3;const C3X=self.C3X;C3.Plugins.Audio.Type=class AudioType extends C3.SDKTypeBase{constructor(objectClass){super(objectClass)}Release(){super.Release()}OnCreate(){}GetScriptInterfaceClass(){return self.IAudioObjectType}};function GetAudioDOMInterface(){if(self["C3Audio_DOMInterface"])return self["C3Audio_DOMInterface"];else throw new Error("audio scripting API cannot be used here - make sure the project is using DOM mode, not worker mode");}self.IAudioObjectType=class IAudioObjectType extends self.IObjectClass{constructor(objectType){super(objectType)}get audioContext(){return GetAudioDOMInterface()["GetAudioContextExtern"]()}get destinationNode(){return GetAudioDOMInterface()["GetDestinationNodeExtern"]()}}}
+{const C3=self.C3;const DOM_COMPONENT_ID="audio";const LATENCY_HINTS=["interactive","balanced","playback"];C3.Plugins.Audio.Instance=class AudioInstance extends C3.SDKInstanceBase{constructor(inst,properties){super(inst,DOM_COMPONENT_ID);this._nextPlayTime=0;this._triggerTags=[];this._enableMultiTags=true;this._timeScaleMode=0;this._saveLoadMode=0;this._playInBackground=false;this._panningModel=1;this._distanceModel=1;this._listenerPos=[this._runtime.GetViewportWidth()/2,this._runtime.GetViewportHeight()/
+2,600];this._listenerForwardVec=[0,0,-1];this._listenerUpVec=[0,1,0];this._referenceDistance=600;this._maxDistance=1E4;this._rolloffFactor=1;this._listenerInst=null;this._loadListenerUid=-1;this._masterVolume=1;this._isSilent=false;this._sampleRate=0;this._audioContextState="suspended";this._outputLatency=0;this._effectCount=new Map;this._preloadTotal=0;this._preloadCount=0;this._bufferMetadata=new Map;this._remoteUrls=new Map;let latencyHint="interactive";if(properties){this._timeScaleMode=properties[0];
+this._saveLoadMode=properties[1];this._playInBackground=properties[2];latencyHint=LATENCY_HINTS[properties[3]];this._enableMultiTags=properties[4];this._panningModel=properties[5];this._distanceModel=properties[6];this._listenerPos[2]=properties[7];this._referenceDistance=properties[8];this._maxDistance=properties[9];this._rolloffFactor=properties[10]}this._lastAIState=[];this._lastFxState=[];this._lastAnalysersData=[];this.AddDOMMessageHandlers([["state",e=>this._OnUpdateState(e)],["audiocontext-state",
+e=>this._OnAudioContextStateChanged(e)],["fxstate",e=>this._OnUpdateFxState(e)],["trigger",e=>this._OnTrigger(e)],["buffer-metadata",e=>this._OnBufferMetadata(e)]]);const rt=this.GetRuntime().Dispatcher();this._disposables=new C3.CompositeDisposable(C3.Disposable.From(rt,"instancedestroy",e=>this._OnInstanceDestroyed(e.instance)),C3.Disposable.From(rt,"afterload",()=>this._OnAfterLoad()),C3.Disposable.From(rt,"suspend",()=>this._OnSuspend()),C3.Disposable.From(rt,"resume",()=>this._OnResume()));this._runtime.AddLoadPromise(this.PostToDOMAsync("create-audio-context",
+{"preloadList":this._runtime.GetAssetManager().GetAudioToPreload().map(o=>({"originalUrl":o.originalUrl,"url":o.url,"type":o.type,"fileSize":o.fileSize})),"isiOSCordova":this._runtime.IsiOSCordova(),"isSafari":C3.Platform.Browser==="Safari","timeScaleMode":this._timeScaleMode,"latencyHint":latencyHint,"panningModel":this._panningModel,"distanceModel":this._distanceModel,"refDistance":this._referenceDistance,"maxDistance":this._maxDistance,"rolloffFactor":this._rolloffFactor,"listenerPos":this._listenerPos}).then(info=>
+{this._sampleRate=info["sampleRate"];this._audioContextState=info["audioContextState"];this._outputLatency=info["outputLatency"]}));this._StartTicking()}Release(){this._listenerInst=null;super.Release()}_SplitTags(tagStr){if(this._enableMultiTags)return tagStr.split(" ").filter(s=>!!s);else return tagStr?[tagStr]:[]}_MatchTagLists(tagArr1,tagArr2){for(const t2 of tagArr2){let found=false;for(const t1 of tagArr1)if(C3.equalsNoCase(t1,t2)){found=true;break}if(!found)return false}return true}_MatchTagListToStr(tagArr,
+tagStr){return this._MatchTagLists(tagArr,this._SplitTags(tagStr))}_AddActionPromise(promise){this.GetPlugin()._AddActionPromise(promise)}_OnInstanceDestroyed(inst){if(this._listenerInst===inst)this._listenerInst=null}DbToLinearNoCap(x){return Math.pow(10,x/20)}DbToLinear(x){const v=this.DbToLinearNoCap(x);if(!isFinite(v))return 0;return Math.max(Math.min(v,1),0)}LinearToDbNoCap(x){return Math.log(x)/Math.log(10)*20}LinearToDb(x){return this.LinearToDbNoCap(Math.max(Math.min(x,1),0))}_OnSuspend(){if(this._playInBackground)return;
+this.PostToDOM("set-suspended",{"isSuspended":true})}_OnResume(){if(this._playInBackground)return;this.PostToDOM("set-suspended",{"isSuspended":false})}_OnUpdateState(e){const tickCount=e["tickCount"];this._outputLatency=e["outputLatency"];const preservePlaceholders=this._lastAIState.filter(ai=>ai.hasOwnProperty("placeholder")&&(ai["placeholder"]>tickCount||ai["placeholder"]===-1));this._lastAIState=e["audioInstances"];this._lastAnalysersData=e["analysers"];if(preservePlaceholders.length>0)C3.appendArray(this._lastAIState,
+preservePlaceholders)}_OnBufferMetadata(e){this._bufferMetadata.set(e["originalUrl"],{duration:e["duration"]})}_OnAudioContextStateChanged(e){this._audioContextState=e["audioContextState"]}GetAudioContextState(){if(this._runtime.IsExportToVideo())return"running";else return this._audioContextState}_OnUpdateFxState(e){this._lastFxState=e["fxstate"]}_GetFirstAudioStateByTags(tagStr){const tagArr=this._SplitTags(tagStr);for(const a of this._lastAIState)if(this._MatchTagLists(a["tags"],tagArr))return a;
+return null}_IsTagPlaying(tagStr){const tagArr=this._SplitTags(tagStr);return this._lastAIState.some(ai=>this._MatchTagLists(ai["tags"],tagArr)&&ai["isPlaying"])}_MaybeMarkAsPlaying(originalUrl,tagStr,isMusic,isLooping,vol){if(this._IsTagPlaying(tagStr))return null;const bufferMeta=this._bufferMetadata.get(originalUrl);const state={"tags":this._SplitTags(tagStr),"duration":bufferMeta?bufferMeta.duration:0,"volume":vol,"isPlaying":true,"playbackTime":0,"playbackRate":1,"uid":-1,"bufferOriginalUrl":originalUrl,
+"bufferUrl":"","bufferType":"","isMusic":isMusic,"isLooping":isLooping,"isMuted":false,"resumePosition":0,"pan":null,"placeholder":-1};this._lastAIState.push(state);return state}async _OnTrigger(e){const type=e["type"];this._triggerTags=e["tags"];const aiId=e["aiid"];if(type==="ended"){for(const aiState of this._lastAIState)if(aiState["aiid"]===aiId){aiState["isPlaying"]=false;break}await this.TriggerAsync(C3.Plugins.Audio.Cnds.OnEnded)}else if(type==="fade-ended")await this.TriggerAsync(C3.Plugins.Audio.Cnds.OnFadeEnded)}_MatchTriggerTag(tagStr){return this._MatchTagListToStr(this._triggerTags,
+tagStr)}Tick(){const o={"timeScale":this._runtime.GetTimeScale(),"gameTime":this._runtime.GetGameTimeRaw(),"instPans":this.GetInstancePans(),"tickCount":this._runtime.GetTickCountNoSave()};if(this._listenerInst){const wi=this._listenerInst.GetWorldInfo();this._listenerPos[0]=wi.GetX();this._listenerPos[1]=wi.GetY();o["listenerPos"]=this._listenerPos;o["listenerOrientation"]=[...this._listenerForwardVec,...this._listenerUpVec]}this.PostToDOM("tick",o)}rotatePtAround(px,py,a,ox,oy){if(a===0)return[px,
+py];const sin_a=Math.sin(a);const cos_a=Math.cos(a);px-=ox;py-=oy;const left_sin_a=px*sin_a;const top_sin_a=py*sin_a;const left_cos_a=px*cos_a;const top_cos_a=py*cos_a;px=left_cos_a-top_sin_a;py=top_cos_a+left_sin_a;px+=ox;py+=oy;return[px,py]}GetInstancePans(){return this._lastAIState.filter(ai=>ai["uid"]!==-1).map(ai=>this._runtime.GetInstanceByUID(ai["uid"])).filter(inst=>inst).map(inst=>{const wi=inst.GetWorldInfo();const layerAngle=wi.GetLayer().GetAngle();const [x,y]=this.rotatePtAround(wi.GetX(),
+wi.GetY(),-layerAngle,this._listenerPos[0],this._listenerPos[1]);return{"uid":inst.GetUID(),"x":x,"y":y,"z":wi.GetTotalZElevation(),"angle":wi.GetAngle()-layerAngle}})}GetAnalyserData(tagStr,index){for(const o of this._lastAnalysersData)if(o.index===index&&C3.equalsNoCase(o["tag"],tagStr))return o;return null}_IncrementEffectCount(tagStr){for(const tag of this._SplitTags(tagStr)){const lowerTag=tag.toLowerCase();this._effectCount.set(lowerTag,(this._effectCount.get(lowerTag)||0)+1)}}_ShouldSave(ai){if(ai.hasOwnProperty("placeholder"))return false;
+if(this._saveLoadMode===3)return false;else if(ai["isMusic"]&&this._saveLoadMode===1)return false;else if(!ai["isMusic"]&&this._saveLoadMode===2)return false;else return true}SaveToJson(){return{"isSilent":this._isSilent,"masterVolume":this._masterVolume,"listenerZ":this._listenerPos[2],"listenerForwardVec":this._listenerForwardVec,"listenerUpVec":this._listenerUpVec,"listenerUid":this._listenerInst?this._listenerInst.GetUID():-1,"remoteUrls":[...this._remoteUrls.entries()],"playing":this._lastAIState.filter(ai=>
+this._ShouldSave(ai)),"effects":this._lastFxState,"analysers":this._lastAnalysersData}}LoadFromJson(o){this._isSilent=o["isSilent"];this._masterVolume=o["masterVolume"];this._listenerPos[2]=o["listenerZ"];this._listenerInst=null;this._loadListenerUid=o["listenerUid"];if(o.hasOwnProperty("listenerForwardVec"))this._listenerForwardVec=o["listenerForwardVec"];else this._listenerForwardVec=[0,0,-1];if(o.hasOwnProperty("listenerUpVec"))this._listenerUpVec=o["listenerUpVec"];else this._listenerUpVec=[0,
+1,0];this._remoteUrls.clear();if(o["remoteUrls"])for(const [k,v]of o["remoteUrls"])this._remoteUrls.set(k,v);this._lastAIState=o["playing"];for(const a of this._lastAIState)if(a.hasOwnProperty("tag")&&!a.hasOwnProperty("tags"))a["tags"]=[a["tag"]].filter(s=>!!s);this._lastFxState=o["effects"];this._lastAnalysersData=o["analysers"]}_OnAfterLoad(){if(this._loadListenerUid!==-1){this._listenerInst=this._runtime.GetInstanceByUID(this._loadListenerUid);this._loadListenerUid=-1;if(this._listenerInst){const wi=
+this._listenerInst.GetWorldInfo();this._listenerPos[0]=wi.GetX();this._listenerPos[1]=wi.GetY()}}for(const ai of this._lastAIState){const info=this._runtime.GetAssetManager().GetProjectAudioFileUrl(ai["bufferOriginalUrl"]);if(info){ai["bufferUrl"]=info.url;ai["bufferType"]=info.type}else ai["bufferUrl"]=null}for(const fxChainData of Object.values(this._lastFxState))for(const fxData of fxChainData)if(fxData.hasOwnProperty("bufferOriginalUrl")){const info=this._runtime.GetAssetManager().GetProjectAudioFileUrl(fxData["bufferOriginalUrl"]);
+if(info){fxData["bufferUrl"]=info.url;fxData["bufferType"]=info.type}}this.PostToDOM("load-state",{"saveLoadMode":this._saveLoadMode,"timeScale":this._runtime.GetTimeScale(),"gameTime":this._runtime.GetGameTimeRaw(),"listenerPos":this._listenerPos,"listenerOrientation":[...this._listenerForwardVec,...this._listenerUpVec],"isSilent":this._isSilent,"masterVolume":this._masterVolume,"playing":this._lastAIState.filter(ai=>ai["bufferUrl"]!==null),"effects":this._lastFxState})}GetDebuggerProperties(){const fxProps=
+[];for(const [tag,fxChainData]of Object.entries(this._lastFxState))fxProps.push({name:"$"+tag,value:fxChainData.map(d=>d["type"]).join(", ")});const prefix="plugins.audio.debugger";return[{title:prefix+".tag-effects",properties:fxProps},{title:prefix+".currently-playing",properties:[{name:prefix+".currently-playing-count",value:this._lastAIState.length},...this._lastAIState.map((s,index)=>({name:"$#"+index,value:`${s["bufferOriginalUrl"]} ("${s["tags"]}") ${Math.round(s["playbackTime"]*10)/10} / ${Math.round(s["duration"]*
+10)/10}`}))]}]}}}{const C3=self.C3;C3.Plugins.Audio.Cnds={OnEnded(tagStr){return this._MatchTriggerTag(tagStr)},OnFadeEnded(tagStr){return this._MatchTriggerTag(tagStr)},PreloadsComplete(){return this._preloadCount===this._preloadTotal},AdvancedAudioSupported(){return true},IsSilent(){return this._isSilent},IsAnyPlaying(){for(const ai of this._lastAIState)if(ai["isPlaying"])return true;return false},IsTagPlaying(tagStr){return this._IsTagPlaying(tagStr)}}}
+{const C3=self.C3;const FILTER_TYPES=["lowpass","highpass","bandpass","lowshelf","highshelf","peaking","notch","allpass"];C3.Plugins.Audio.Acts={Play(file,looping,vol,stereoPan,tagStr){const ret=C3.Plugins.Audio.Acts._DoPlay.call(this,file,looping,vol,stereoPan,tagStr);this._AddActionPromise(ret);return ret},PlayFromTimeline(file,vol,tagStr,startOffset){C3.Plugins.Audio.Acts._DoPlay.call(this,file,0,vol,0,tagStr,startOffset)},async _DoPlay(file,looping,vol,stereoPan,tagStr,startOffset){if(this._isSilent)return;
+const isMusic=file[1];const info=this._runtime.GetAssetManager().GetProjectAudioFileUrl(file[0]);if(!info)return;const nextPlayTime=this._nextPlayTime;this._nextPlayTime=0;const state=this._MaybeMarkAsPlaying(file[0],tagStr,isMusic,looping!==0,this.DbToLinear(vol));try{await this.PostToDOMAsync("play",{"originalUrl":file[0],"url":info.url,"type":info.type,"isMusic":isMusic,"tags":this._SplitTags(tagStr),"isLooping":looping!==0,"vol":this.DbToLinear(vol),"stereoPan":C3.clamp(stereoPan/100,-1,1),"pos":startOffset||
+0,"off":nextPlayTime,"trueClock":!!self["C3_GetAudioContextCurrentTime"]})}finally{if(state)state["placeholder"]=this._runtime.GetTickCountNoSave()}},async PlayAtPosition(file,looping,vol,x,y,z,angle,innerAngle,outerAngle,outerGain,tagStr){if(this._isSilent)return;const isMusic=file[1];const info=this._runtime.GetAssetManager().GetProjectAudioFileUrl(file[0]);if(!info)return;const nextPlayTime=this._nextPlayTime;this._nextPlayTime=0;const state=this._MaybeMarkAsPlaying(file[0],tagStr,isMusic,looping!==
+0,this.DbToLinear(vol));try{await this.PostToDOMAsync("play",{"originalUrl":file[0],"url":info.url,"type":info.type,"isMusic":isMusic,"tags":this._SplitTags(tagStr),"isLooping":looping!==0,"vol":this.DbToLinear(vol),"pos":0,"off":nextPlayTime,"trueClock":!!self["C3_GetAudioContextCurrentTime"],"panning":{"x":x,"y":y,"z":z,"angle":C3.toRadians(angle),"innerAngle":C3.toRadians(innerAngle),"outerAngle":C3.toRadians(outerAngle),"outerGain":this.DbToLinear(outerGain)}})}finally{if(state)state["placeholder"]=
+this._runtime.GetTickCountNoSave()}},async PlayAtObject(file,looping,vol,objectClass,innerAngle,outerAngle,outerGain,tagStr){if(this._isSilent)return;if(!objectClass)return;const inst=objectClass.GetFirstPicked();if(!inst||!inst.GetWorldInfo())return;const wi=inst.GetWorldInfo();const layerAngle=wi.GetLayer().GetAngle();const [x,y]=this.rotatePtAround(wi.GetX(),wi.GetY(),-layerAngle,this._listenerPos[0],this._listenerPos[1]);const isMusic=file[1];const info=this._runtime.GetAssetManager().GetProjectAudioFileUrl(file[0]);
+if(!info)return;const nextPlayTime=this._nextPlayTime;this._nextPlayTime=0;const state=this._MaybeMarkAsPlaying(file[0],tagStr,isMusic,looping!==0,this.DbToLinear(vol));try{await this.PostToDOMAsync("play",{"originalUrl":file[0],"url":info.url,"type":info.type,"isMusic":isMusic,"tags":this._SplitTags(tagStr),"isLooping":looping!==0,"vol":this.DbToLinear(vol),"pos":0,"off":nextPlayTime,"trueClock":!!self["C3_GetAudioContextCurrentTime"],"panning":{"x":x,"y":y,"z":wi.GetTotalZElevation(),"angle":wi.GetAngle()-
+layerAngle,"innerAngle":C3.toRadians(innerAngle),"outerAngle":C3.toRadians(outerAngle),"outerGain":this.DbToLinear(outerGain),"uid":inst.GetUID()}})}finally{if(state)state["placeholder"]=this._runtime.GetTickCountNoSave()}},async PlayByName(folder,filename,looping,vol,stereoPan,tagStr){if(this._isSilent)return;const isMusic=folder===1;const info=this._runtime.GetAssetManager().GetProjectAudioFileUrl(filename)||this._remoteUrls.get(filename.toLowerCase());if(!info)return;const nextPlayTime=this._nextPlayTime;
+this._nextPlayTime=0;const state=this._MaybeMarkAsPlaying(filename,tagStr,isMusic,looping!==0,this.DbToLinear(vol));try{await this.PostToDOMAsync("play",{"originalUrl":filename,"url":info.url,"type":info.type,"isMusic":isMusic,"tags":this._SplitTags(tagStr),"isLooping":looping!==0,"vol":this.DbToLinear(vol),"stereoPan":C3.clamp(stereoPan/100,-1,1),"pos":0,"off":nextPlayTime,"trueClock":!!self["C3_GetAudioContextCurrentTime"]})}finally{if(state)state["placeholder"]=this._runtime.GetTickCountNoSave()}},
+async PlayAtPositionByName(folder,filename,looping,vol,x,y,z,angle,innerAngle,outerAngle,outerGain,tagStr){if(this._isSilent)return;const isMusic=folder===1;const info=this._runtime.GetAssetManager().GetProjectAudioFileUrl(filename)||this._remoteUrls.get(filename.toLowerCase());if(!info)return;const nextPlayTime=this._nextPlayTime;this._nextPlayTime=0;const state=this._MaybeMarkAsPlaying(filename,tagStr,isMusic,looping!==0,this.DbToLinear(vol));try{await this.PostToDOMAsync("play",{"originalUrl":filename,
+"url":info.url,"type":info.type,"isMusic":isMusic,"tags":this._SplitTags(tagStr),"isLooping":looping!==0,"vol":this.DbToLinear(vol),"pos":0,"off":nextPlayTime,"trueClock":!!self["C3_GetAudioContextCurrentTime"],"panning":{"x":x,"y":y,"z":z,"angle":C3.toRadians(angle),"innerAngle":C3.toRadians(innerAngle),"outerAngle":C3.toRadians(outerAngle),"outerGain":this.DbToLinear(outerGain)}})}finally{if(state)state["placeholder"]=this._runtime.GetTickCountNoSave()}},async PlayAtObjectByName(folder,filename,
+looping,vol,objectClass,innerAngle,outerAngle,outerGain,tagStr){if(this._isSilent)return;if(this._isSilent)return;if(!objectClass)return;const inst=objectClass.GetFirstPicked();if(!inst||!inst.GetWorldInfo())return;const wi=inst.GetWorldInfo();const layerAngle=wi.GetLayer().GetAngle();const [x,y]=this.rotatePtAround(wi.GetX(),wi.GetY(),-layerAngle,this._listenerPos[0],this._listenerPos[1]);const isMusic=folder===1;const info=this._runtime.GetAssetManager().GetProjectAudioFileUrl(filename)||this._remoteUrls.get(filename.toLowerCase());
+if(!info)return;const nextPlayTime=this._nextPlayTime;this._nextPlayTime=0;const state=this._MaybeMarkAsPlaying(filename,tagStr,isMusic,looping!==0,this.DbToLinear(vol));try{await this.PostToDOMAsync("play",{"originalUrl":filename,"url":info.url,"type":info.type,"isMusic":isMusic,"tags":this._SplitTags(tagStr),"isLooping":looping!==0,"vol":this.DbToLinear(vol),"pos":0,"off":nextPlayTime,"trueClock":!!self["C3_GetAudioContextCurrentTime"],"panning":{"x":x,"y":y,"z":wi.GetTotalZElevation(),"angle":wi.GetAngle()-
+layerAngle,"innerAngle":C3.toRadians(innerAngle),"outerAngle":C3.toRadians(outerAngle),"outerGain":this.DbToLinear(outerGain),"uid":inst.GetUID()}})}finally{if(state)state["placeholder"]=this._runtime.GetTickCountNoSave()}},SetLooping(tagStr,looping){this.PostToDOM("set-looping",{"tags":this._SplitTags(tagStr),"isLooping":looping===0})},SetMuted(tagStr,muted){this.PostToDOM("set-muted",{"tags":this._SplitTags(tagStr),"isMuted":muted===0})},SetVolume(tagStr,vol){this.PostToDOM("set-volume",{"tags":this._SplitTags(tagStr),
+"vol":this.DbToLinear(vol)})},FadeVolume(tagStr,vol,duration,ending){this.PostToDOM("fade-volume",{"tags":this._SplitTags(tagStr),"vol":this.DbToLinear(vol),"duration":duration,"stopOnEnd":ending===0})},SetStereoPan(tagStr,p){this.PostToDOM("set-stereo-pan",{"tags":this._SplitTags(tagStr),"p":C3.clamp(p/100,-1,1)})},async Preload(file){const isMusic=file[1];const info=this._runtime.GetAssetManager().GetProjectAudioFileUrl(file[0]);if(!info)return;this._preloadTotal++;await this.PostToDOMAsync("preload",
+{"originalUrl":file[0],"url":info.url,"type":info.type,"isMusic":isMusic});this._preloadCount++},async PreloadByName(folder,filename){const isMusic=folder===1;const info=this._runtime.GetAssetManager().GetProjectAudioFileUrl(filename)||this._remoteUrls.get(filename.toLowerCase());if(!info)return;this._preloadTotal++;await this.PostToDOMAsync("preload",{"originalUrl":filename,"url":info.url,"type":info.type,"isMusic":isMusic});this._preloadCount++},SetPlaybackRate(tagStr,rate){this.PostToDOM("set-playback-rate",
+{"tags":this._SplitTags(tagStr),"rate":Math.max(rate,0)})},Stop(tagStr){this.PostToDOM("stop",{"tags":this._SplitTags(tagStr)})},StopAll(){this.PostToDOM("stop-all")},SetPaused(tagStr,state){this.PostToDOM("set-paused",{"tags":this._SplitTags(tagStr),"paused":state===0})},Seek(tagStr,pos){this.PostToDOM("seek",{"tags":this._SplitTags(tagStr),"pos":pos})},SetSilent(s){if(s===2)s=this._isSilent?1:0;s=s===0;if(this._isSilent===s)return;this._isSilent=s;this.PostToDOM("set-silent",{"isSilent":s})},SetMasterVolume(vol){const mv=
+this.DbToLinear(vol);if(this._masterVolume===mv)return;this._masterVolume=mv;this.PostToDOM("set-master-volume",{"vol":mv})},AddFilterEffect(tagStr,type,freq,detune,q,gain,mix){const typeStr=FILTER_TYPES[type];this._IncrementEffectCount(tagStr);this.PostToDOM("add-effect",{"type":"filter","tags":this._SplitTags(tagStr),"params":[typeStr,freq,detune,q,gain,C3.clamp(mix/100,0,1)]})},AddDelayEffect(tagStr,delay,gain,mix){this._IncrementEffectCount(tagStr);this.PostToDOM("add-effect",{"type":"delay",
+"tags":this._SplitTags(tagStr),"params":[delay,this.DbToLinear(gain),C3.clamp(mix/100,0,1)]})},AddFlangerEffect(tagStr,delay,modulation,freq,feedback,mix){this._IncrementEffectCount(tagStr);this.PostToDOM("add-effect",{"type":"flanger","tags":this._SplitTags(tagStr),"params":[delay/1E3,modulation/1E3,freq,feedback/100,C3.clamp(mix/100,0,1)]})},AddPhaserEffect(tagStr,freq,detune,q,mod,modfreq,mix){this._IncrementEffectCount(tagStr);this.PostToDOM("add-effect",{"type":"phaser","tags":this._SplitTags(tagStr),
+"params":[freq,detune,q,mod,modfreq,C3.clamp(mix/100,0,1)]})},AddConvolutionEffect(tagStr,file,norm,mix){const info=this._runtime.GetAssetManager().GetProjectAudioFileUrl(file[0]);if(!info)return;this._IncrementEffectCount(tagStr);this.PostToDOM("add-effect",{"type":"convolution","tags":this._SplitTags(tagStr),"bufferOriginalUrl":file[0],"bufferUrl":info.url,"bufferType":info.type,"params":[norm===0,C3.clamp(mix/100,0,1)]})},AddGainEffect(tagStr,g){this._IncrementEffectCount(tagStr);this.PostToDOM("add-effect",
+{"type":"gain","tags":this._SplitTags(tagStr),"params":[this.DbToLinear(g)]})},AddStereoPanEffect(tagStr,g){this._IncrementEffectCount(tagStr);this.PostToDOM("add-effect",{"type":"stereopan","tags":this._SplitTags(tagStr),"params":[C3.clamp(g/100,-1,1)]})},AddMuteEffect(tagStr){this._IncrementEffectCount(tagStr);this.PostToDOM("add-effect",{"type":"gain","tags":this._SplitTags(tagStr),"params":[0]})},AddTremoloEffect(tagStr,freq,mix){this._IncrementEffectCount(tagStr);this.PostToDOM("add-effect",
+{"type":"tremolo","tags":this._SplitTags(tagStr),"params":[freq,C3.clamp(mix/100,0,1)]})},AddRingModEffect(tagStr,freq,mix){this._IncrementEffectCount(tagStr);this.PostToDOM("add-effect",{"type":"ringmod","tags":this._SplitTags(tagStr),"params":[freq,C3.clamp(mix/100,0,1)]})},AddDistortionEffect(tagStr,threshold,headroom,drive,makeupgain,mix){this._IncrementEffectCount(tagStr);this.PostToDOM("add-effect",{"type":"distortion","tags":this._SplitTags(tagStr),"params":[this.DbToLinearNoCap(threshold),
+this.DbToLinearNoCap(headroom),drive,this.DbToLinearNoCap(makeupgain),C3.clamp(mix/100,0,1)]})},AddCompressorEffect(tagStr,threshold,knee,ratio,attack,release){this._IncrementEffectCount(tagStr);this.PostToDOM("add-effect",{"type":"compressor","tags":this._SplitTags(tagStr),"params":[threshold,knee,ratio,attack/1E3,release/1E3]})},AddAnalyserEffect(tagStr,fftSize,smoothing){this._IncrementEffectCount(tagStr);this.PostToDOM("add-effect",{"type":"analyser","tags":this._SplitTags(tagStr),"params":[fftSize,
+smoothing]})},RemoveEffects(tagStr){const tagArr=this._SplitTags(tagStr);for(const tag of tagArr)this._effectCount.set(tag.toLowerCase(),0);this.PostToDOM("remove-effects",{"tags":tagArr});this._lastFxState={}},SetEffectParameter(tagStr,index,param,value,ramp,time){this.PostToDOM("set-effect-param",{"tags":this._SplitTags(tagStr),"index":Math.floor(index),"param":param,"value":value,"ramp":ramp,"time":time})},SetListenerObject(objectClass){if(!objectClass)return;const inst=objectClass.GetFirstPicked();
+if(!inst||!inst.GetWorldInfo())return;this._listenerInst=inst},SetListenerZ(z){this._listenerPos[2]=z},SetListenerOrientation(fx,fy,fz,ux,uy,uz){this._listenerForwardVec[0]=fx;this._listenerForwardVec[1]=fy;this._listenerForwardVec[2]=-fz;this._listenerUpVec[0]=ux;this._listenerUpVec[1]=uy;this._listenerUpVec[2]=-uz},ScheduleNextPlay(t){this._nextPlayTime=Math.max(t,0)},UnloadAudio(file){const isMusic=file[1];const info=this._runtime.GetAssetManager().GetProjectAudioFileUrl(file[0]);if(!info)return;
+this.PostToDOM("unload",{"url":info.url,"type":info.type,"isMusic":isMusic})},UnloadAudioByName(folder,filename){const isMusic=folder===1;const info=this._runtime.GetAssetManager().GetProjectAudioFileUrl(filename)||this._remoteUrls.get(filename.toLowerCase());if(!info)return;this.PostToDOM("unload",{"url":info.url,"type":info.type,"isMusic":isMusic})},UnloadAll(){this.PostToDOM("unload-all")},AddRemoteURL(url,type,name){this._remoteUrls.set(name.toLowerCase(),{url,type})}}}
+{const C3=self.C3;C3.Plugins.Audio.Exps={Duration(tagStr){const a=this._GetFirstAudioStateByTags(tagStr);return a?a["duration"]:0},PlaybackTime(tagStr){const a=this._GetFirstAudioStateByTags(tagStr);return a?a["playbackTime"]:0},PlaybackRate(tagStr){const a=this._GetFirstAudioStateByTags(tagStr);return a?a["playbackRate"]:0},Volume(tagStr){const a=this._GetFirstAudioStateByTags(tagStr);return a?this.LinearToDb(a["volume"]):0},MasterVolume(){return this.LinearToDb(this._masterVolume)},EffectCount(tag){return this._effectCount.get(tag.toLowerCase())||
+0},AnalyserFreqBinCount(tagStr,index){const o=this.GetAnalyserData(tagStr,Math.floor(index));return o?o["binCount"]:0},AnalyserFreqBinAt(tagStr,index,bin){const o=this.GetAnalyserData(tagStr,Math.floor(index));if(!o)return 0;bin=Math.floor(bin);if(bin<0||bin>=o["binCount"])return 0;return o["freqBins"][bin]},AnalyserPeakLevel(tagStr,index){const o=this.GetAnalyserData(tagStr,Math.floor(index));return o?o["peak"]:0},AnalyserRMSLevel(tagStr,index){const o=this.GetAnalyserData(tagStr,Math.floor(index));
+return o?o["rms"]:0},SampleRate(){return this._sampleRate},CurrentTime(){if(self["C3_GetAudioContextCurrentTime"])return self["C3_GetAudioContextCurrentTime"]();else return performance.now()/1E3},OutputLatency(){return this._outputLatency}}};
+
+}
+
+{
+'use strict';{const C3=self.C3;C3.Plugins.Text=class TextPlugin extends C3.SDKPluginBase{constructor(opts){super(opts)}Release(){super.Release()}}}{const C3=self.C3;C3.Plugins.Text.Type=class TextType extends C3.SDKTypeBase{constructor(objectClass){super(objectClass)}Release(){super.Release()}OnCreate(){}LoadTextures(renderer){}ReleaseTextures(){}}}
+{const C3=self.C3;const C3X=self.C3X;const TEMP_COLOR_ARRAY=[0,0,0];const TEXT=0;const ENABLE_BBCODE=1;const FONT=2;const SIZE=3;const LINE_HEIGHT=4;const BOLD=5;const ITALIC=6;const COLOR=7;const HORIZONTAL_ALIGNMENT=8;const VERTICAL_ALIGNMENT=9;const WRAPPING=10;const TEXT_DIRECTION=11;const ICON_SET=12;const INITIALLY_VISIBLE=13;const ORIGIN=14;const READ_ALOUD=15;const HORIZONTAL_ALIGNMENTS=["left","center","right"];const VERTICAL_ALIGNMENTS=["top","center","bottom"];const TEXT_DIRECTIONS=["ltr",
+"rtl"];const WORD_WRAP=0;const CHARACTER_WRAP=1;const tempRect=new C3.Rect;const tempQuad=new C3.Quad;const tempColor=new C3.Color;const tempVec2=C3.New(C3.Vector2);const BBCODE_TAG_TO_HTML=new Map([["b","strong"],["i","em"],["s","s"],["u","u"],["iconoffsety",null]]);C3.Plugins.Text.Instance=class TextInstance extends C3.SDKWorldInstanceBase{constructor(inst,properties){super(inst);this._text="";this._enableBBcode=true;this._faceName="Arial";this._ptSize=12;this._lineHeightOffset=0;this._isBold=false;
+this._isItalic=false;this._color=C3.New(C3.Color);this._horizontalAlign=0;this._verticalAlign=0;this._wrapByWord=true;this._textDirection=0;this._iconObjectClass=null;this._htmlString="";this._isHtmlStringUpToDate=false;this._readAloud=false;this._screenReaderText=null;this._typewriterStartTime=-1;this._typewriterEndTime=-1;this._typewriterLength=0;this._rendererText=C3.New(C3.Gfx.RendererText,this._runtime.GetRenderer(),{timeout:5});this._rendererText.ontextureupdate=()=>this._runtime.UpdateRender();
+this._animationframeimagechange_handler=()=>this._OnIconObjectClassImageChanged();this._pendingUpdateIconSet=false;if(properties){this._text=properties[TEXT];this._enableBBcode=!!properties[ENABLE_BBCODE];this._faceName=properties[FONT];this._ptSize=properties[SIZE];this._lineHeightOffset=properties[LINE_HEIGHT];this._isBold=!!properties[BOLD];this._isItalic=!!properties[ITALIC];this._horizontalAlign=properties[HORIZONTAL_ALIGNMENT];this._verticalAlign=properties[VERTICAL_ALIGNMENT];this._wrapByWord=
+properties[WRAPPING]===WORD_WRAP;this._textDirection=properties[TEXT_DIRECTION];this._SetIconObjectClass(this._runtime.GetObjectClassBySID(properties[ICON_SET]));const v=properties[COLOR];this._color.setRgb(v[0],v[1],v[2]);this.GetWorldInfo().SetVisible(properties[INITIALLY_VISIBLE]);this._readAloud=!!properties[READ_ALOUD]}this._UpdateTextSettings();this._UpdateScreenReaderText()}Release(){this._SetIconObjectClass(null);this._CancelTypewriter();if(this._screenReaderText){this._screenReaderText.Release();
+this._screenReaderText=null}this._rendererText.Release();this._rendererText=null;super.Release()}_UpdateTextSettings(){const rendererText=this._rendererText;rendererText.SetText(this._text);rendererText.SetBBCodeEnabled(this._enableBBcode);if(this._rendererText.IsBBCodeEnabled()&&this._iconObjectClass)this._rendererText.SetIconSet(this.GetRuntime().GetTextIconSet(this._iconObjectClass));else this._rendererText.SetIconSet(null);rendererText.SetIconSmoothing(this._runtime.GetSampling()!=="nearest");
+rendererText.SetFontName(this._faceName);rendererText.SetLineHeight(this._lineHeightOffset);rendererText.SetBold(this._isBold);rendererText.SetItalic(this._isItalic);rendererText.SetColor(this._color);rendererText.SetHorizontalAlignment(HORIZONTAL_ALIGNMENTS[this._horizontalAlign]);rendererText.SetVerticalAlignment(VERTICAL_ALIGNMENTS[this._verticalAlign]);rendererText.SetWordWrapMode(this._wrapByWord?"word":"character");rendererText.SetTextDirection(TEXT_DIRECTIONS[this._textDirection])}_UpdateTextSize(){const wi=
+this.GetWorldInfo();this._rendererText.SetFontSize(this._ptSize);this._rendererText.SetFontSizeScale(wi.GetSceneGraphScale());const layer=wi.GetLayer();const textZoom=layer.GetRenderScale()*layer.Get2DScaleFactorToZ(wi.GetTotalZElevation());if(wi.HasMesh()&&textZoom!==this._rendererText.GetZoom())wi.SetMeshChanged(true);this._rendererText.SetSize(wi.GetWidth(),wi.GetHeight(),textZoom)}_SetIconObjectClass(objectClass){if(objectClass&&(objectClass.IsFamily()||objectClass.GetPlugin().constructor!==C3.Plugins.Sprite))return;
+if(objectClass===this._iconObjectClass)return;if(this._iconObjectClass)this._iconObjectClass.Dispatcher().removeEventListener("animationframeimagechange",this._animationframeimagechange_handler);this._iconObjectClass=objectClass;if(this._iconObjectClass)this._iconObjectClass.Dispatcher().addEventListener("animationframeimagechange",this._animationframeimagechange_handler);this._UpdateTextSettings();this._isHtmlStringUpToDate=false;this._runtime.UpdateRender()}_OnIconObjectClassImageChanged(){this._runtime.DeleteTextIconSet(this._iconObjectClass);
+this._runtime.UpdateRender();this._pendingUpdateIconSet=true}_UpdateScreenReaderText(){if(this._readAloud){let text=this._text;if(this._enableBBcode)text=C3.BBString.StripAnyTags(text);if(this._screenReaderText)this._screenReaderText.SetText(text);else this._screenReaderText=C3.New(C3.ScreenReaderText,this._runtime,text)}else if(this._screenReaderText){this._screenReaderText.Release();this._screenReaderText=null}}Draw(renderer){const wi=this.GetWorldInfo();this._UpdateTextSize();if(this._pendingUpdateIconSet){this._pendingUpdateIconSet=
+false;if(this._rendererText.IsBBCodeEnabled()&&this._iconObjectClass)this._rendererText.SetIconSet(this.GetRuntime().GetTextIconSet(this._iconObjectClass))}const texture=this._rendererText.GetTexture();if(!texture)return;const layer=wi.GetLayer();if(wi.GetAngle()===0&&layer.GetAngle()===0&&wi.GetTotalZElevation()===0&&!wi.HasMesh()&&layer.RendersIn2DMode()){const quad=wi.GetBoundingQuad();const [dl,dt]=layer.LayerToDrawSurface(quad.getTlx(),quad.getTly());const [dr,db]=layer.LayerToDrawSurface(quad.getBrx(),
+quad.getBry());const offX=dl-Math.round(dl);const offY=dt-Math.round(dt);tempRect.set(dl,dt,dr,db);tempRect.offset(-offX,-offY);tempQuad.setFromRect(tempRect);const [rtWidth,rtHeight]=renderer.GetRenderTargetSize(renderer.GetRenderTarget());this._runtime.GetCanvasManager().SetDeviceTransform(renderer,rtWidth,rtHeight);renderer.SetTexture(texture);renderer.Quad3(tempQuad,this._rendererText.GetTexRect());layer._SetTransform(renderer)}else{renderer.SetTexture(texture);if(wi.HasMesh())this._DrawMesh(wi,
+renderer);else this._DrawStandard(wi,renderer)}}_DrawStandard(wi,renderer){let quad=wi.GetBoundingQuad();if(this._runtime.IsPixelRoundingEnabled())quad=this._PixelRoundQuad(quad);renderer.Quad3(quad,this._rendererText.GetTexRect())}_DrawMesh(wi,renderer){const transformedMesh=wi.GetTransformedMesh();if(wi.IsMeshChanged()){wi.CalculateBbox(tempRect,tempQuad,false);let quad=tempQuad;if(this._runtime.IsPixelRoundingEnabled())quad=this._PixelRoundQuad(quad);transformedMesh.CalculateTransformedMesh(wi.GetSourceMesh(),
+quad,this._rendererText.GetTexRect());wi.SetMeshChanged(false)}transformedMesh.Draw(renderer)}_PixelRoundQuad(quad){const offX=quad.getTlx()-Math.round(quad.getTlx());const offY=quad.getTly()-Math.round(quad.getTly());if(offX===0&&offY===0)return quad;else{tempQuad.copy(quad);tempQuad.offset(-offX,-offY);return tempQuad}}GetCurrentSurfaceSize(){const texture=this._rendererText.GetTexture();if(texture)return[texture.GetWidth(),texture.GetHeight()];else return[100,100]}GetCurrentTexRect(){return this._rendererText.GetTexRect()}IsCurrentTexRotated(){return false}SaveToJson(){const o=
+{"t":this._text,"c":this._color.toJSON(),"fn":this._faceName,"ps":this._ptSize};if(this._enableBBcode)o["bbc"]=this._enableBBcode;if(this._horizontalAlign!==0)o["ha"]=this._horizontalAlign;if(this._verticalAlign!==0)o["va"]=this._verticalAlign;if(!this._wrapByWord)o["wr"]=this._wrapByWord;if(this._lineHeightOffset!==0)o["lho"]=this._lineHeightOffset;if(this._isBold)o["b"]=this._isBold;if(this._isItalic)o["i"]=this._isItalic;if(this._typewriterEndTime!==-1)o["tw"]={"st":this._typewriterStartTime,"en":this._typewriterEndTime,
+"l":this._typewriterLength};if(this._iconObjectClass)o["ioc"]=this._iconObjectClass.GetSID();return o}LoadFromJson(o){this._CancelTypewriter();this._text=o["t"],this._color.setFromJSON(o["c"]);this._faceName=o["fn"],this._ptSize=o["ps"];this._enableBBcode=o.hasOwnProperty("bbc")?o["bbc"]:false;this._horizontalAlign=o.hasOwnProperty("ha")?o["ha"]:0;this._verticalAlign=o.hasOwnProperty("va")?o["va"]:0;this._wrapByWord=o.hasOwnProperty("wr")?o["wr"]:true;this._lineHeightOffset=o.hasOwnProperty("lho")?
+o["lho"]:0;this._isBold=o.hasOwnProperty("b")?o["b"]:false;this._isItalic=o.hasOwnProperty("i")?o["i"]:false;if(o.hasOwnProperty("tw")){const tw=o["tw"];this._typewriterStartTime=tw["st"];this._typewriterEndTime=tw["en"];this._typewriterLength=tw["l"]}if(o.hasOwnProperty("ioc")){const objectClass=this.GetRuntime().GetObjectClassBySID(o["ioc"]);if(objectClass)this._SetIconObjectClass(objectClass)}else this._SetIconObjectClass(null);this._UpdateTextSettings();this._UpdateScreenReaderText();this._isHtmlStringUpToDate=
+false;if(this._typewriterEndTime!==-1)this._StartTicking()}GetPropertyValueByIndex(index){switch(index){case TEXT:return this.GetText();case ENABLE_BBCODE:return this._enableBBcode;case FONT:return this._GetFontFace();case SIZE:return this._GetFontSize();case LINE_HEIGHT:return this._GetLineHeight();case BOLD:return this._IsBold();case ITALIC:return this._IsItalic();case COLOR:TEMP_COLOR_ARRAY[0]=this._color.getR();TEMP_COLOR_ARRAY[1]=this._color.getG();TEMP_COLOR_ARRAY[2]=this._color.getB();return TEMP_COLOR_ARRAY;
+case HORIZONTAL_ALIGNMENT:return this._GetHAlign();case VERTICAL_ALIGNMENT:return this._GetVAlign();case WRAPPING:return this._IsWrapByWord()?CHARACTER_WRAP:WORD_WRAP;case READ_ALOUD:return this._IsReadAloud()}}SetPropertyValueByIndex(index,value){switch(index){case TEXT:this._SetText(value);break;case ENABLE_BBCODE:if(this._enableBBcode===!!value)return;this._enableBBcode=!!value;this._UpdateTextSettings();break;case FONT:this._SetFontFace(value);break;case SIZE:this._SetFontSize(value);break;case LINE_HEIGHT:this._SetLineHeight(value);
+break;case BOLD:this._SetBold(value);break;case ITALIC:this._SetItalic(value);break;case COLOR:const c=this._color;const v=value;if(c.getR()===v[0]&&c.getG()===v[1]&&c.getB()===v[2])return;this._color.setRgb(v[0],v[1],v[2]);this._UpdateTextSettings();break;case HORIZONTAL_ALIGNMENT:this._SetHAlign(value);break;case VERTICAL_ALIGNMENT:this._SetVAlign(value);break;case WRAPPING:this._SetWrapByWord(value===WORD_WRAP);break}}SetPropertyColorOffsetValueByIndex(index,r,g,b){if(r===0&&g===0&&b===0)return;
+switch(index){case COLOR:this._color.addRgb(r,g,b);this._UpdateTextSettings();break}}_SetText(text){if(this._text===text)return;this._text=text;this._rendererText.SetText(text);this._UpdateScreenReaderText();this._isHtmlStringUpToDate=false;this._runtime.UpdateRender()}GetText(){return this._text}_StartTypewriter(text,duration){this._UpdateTextSize();this._SetText(text);this._typewriterStartTime=this._runtime.GetWallTime();this._typewriterEndTime=this._typewriterStartTime+duration/this.GetInstance().GetActiveTimeScale();
+this._typewriterLength=this._rendererText.GetLengthInGraphemes();this._rendererText.SetDrawMaxCharacterCount(0);this._StartTicking()}_CancelTypewriter(){this._typewriterStartTime=-1;this._typewriterEndTime=-1;this._typewriterLength=0;this._rendererText.SetDrawMaxCharacterCount(-1);this._StopTicking()}_FinishTypewriter(){if(this._typewriterEndTime===-1)return;this._CancelTypewriter();this.Trigger(C3.Plugins.Text.Cnds.OnTypewriterTextFinished);this._runtime.UpdateRender()}_SetFontFace(face){if(this._faceName===
+face)return;this._faceName=face;this._rendererText.SetFontName(face);this._runtime.UpdateRender()}_GetFontFace(){return this._faceName}_SetBold(b){b=!!b;if(this._isBold===b)return;this._isBold=b;this._rendererText.SetBold(b);this._runtime.UpdateRender()}_IsBold(){return this._isBold}_SetItalic(i){i=!!i;if(this._isItalic===i)return;this._isItalic=i;this._rendererText.SetItalic(i);this._runtime.UpdateRender()}_IsItalic(){return this._isItalic}_SetFontSize(size){if(this._ptSize===size)return;this._ptSize=
+size;this._runtime.UpdateRender()}_GetFontSize(){return this._ptSize}_SetFontColor(color){if(this._color.equalsIgnoringAlpha(color))return;this._color.copyRgb(color);this._rendererText.SetColor(this._color);this._runtime.UpdateRender()}_GetFontColor(){return this._color}_SetLineHeight(lho){if(this._lineHeightOffset===lho)return;this._lineHeightOffset=lho;this._UpdateTextSettings();this._runtime.UpdateRender()}_GetLineHeight(){return this._lineHeightOffset}_SetHAlign(h){if(this._horizontalAlign===
+h)return;this._horizontalAlign=h;this._UpdateTextSettings();this._runtime.UpdateRender()}_GetHAlign(){return this._horizontalAlign}_SetVAlign(v){if(this._verticalAlign===v)return;this._verticalAlign=v;this._UpdateTextSettings();this._runtime.UpdateRender()}_GetVAlign(){return this._verticalAlign}_SetWrapByWord(w){w=!!w;if(this._wrapByWord===w)return;this._wrapByWord=w;this._UpdateTextSettings();this._runtime.UpdateRender()}_IsWrapByWord(){return this._wrapByWord}_SetTextDirection(d){if(this._textDirection===
+d)return;this._textDirection=d;this._UpdateTextSettings();this._runtime.UpdateRender()}_GetTextDirection(){return this._textDirection}_SetReadAloud(r){this._readAloud=!!r;this._UpdateScreenReaderText()}_IsReadAloud(){return this._readAloud}_GetTextWidth(){this._UpdateTextSize();return this._rendererText.GetTextWidth()}_GetTextHeight(){this._UpdateTextSize();return this._rendererText.GetTextHeight()}_GetTagAtPosition(x,y){this._UpdateTextSize();const wi=this.GetWorldInfo();tempVec2.set(x-wi.GetX(),
+y-wi.GetY());tempVec2.rotate(-wi.GetAngle());tempVec2.offset(wi.GetWidth()*wi.GetOriginX(),wi.GetHeight()*wi.GetOriginY());tempVec2.divide(wi.GetWidth(),wi.GetHeight());tempVec2.scale(this._rendererText.GetWidth(),this._rendererText.GetHeight());const frag=this._rendererText.HitTestFragment(tempVec2.getX(),tempVec2.getY());if(frag){const fragTagStyle=frag.GetStyleTag("tag");if(fragTagStyle)return fragTagStyle.param}return""}_HasTagAtPosition(tag,x,y){const hitTag=this._GetTagAtPosition(x,y);return hitTag&&
+C3.equalsNoCase(tag,hitTag)}_GetTagPosition(tag,index){this._UpdateTextSize();index=Math.floor(index);const frag=this._rendererText.FindFragmentWithTag(tag,index);if(!frag)return null;const wi=this.GetWorldInfo();const scale=this._rendererText.GetDrawScale();const posX=frag.GetPosX();const posY=frag.GetPosY()-(frag.GetHeight()-frag.GetFontBoundingBoxDescent())*scale;const width=frag.GetWidth()*scale/this._rendererText.GetWidth()*wi.GetWidth();const height=frag.GetHeight()*scale/this._rendererText.GetHeight()*
+wi.GetHeight();tempVec2.set(posX,posY);tempVec2.divide(this._rendererText.GetWidth(),this._rendererText.GetHeight());tempVec2.scale(wi.GetWidth(),wi.GetHeight());tempVec2.offset(-wi.GetWidth()*wi.GetOriginX(),-wi.GetHeight()*wi.GetOriginY());tempVec2.rotate(wi.GetAngle());tempVec2.offset(wi.GetX(),wi.GetY());return{x:tempVec2.getX(),y:tempVec2.getY(),width,height}}_GetTagCount(tag){this._UpdateTextSize();return this._rendererText.CountFragmentsWithTag(tag)}_GetHTMLCloseTag(bbTag){let htmlTag=BBCODE_TAG_TO_HTML.get(bbTag);
+if(htmlTag===null)return"";else if(!htmlTag)htmlTag="span";return`${htmlTag||"span"}>`}_GetHTMLOpenTag(bbTag,param){let htmlTag=BBCODE_TAG_TO_HTML.get(bbTag);if(htmlTag===null)return"";else if(!htmlTag)htmlTag="span";switch(bbTag){case "color":return`<${htmlTag} style="color: ${param}">`;case "font":return`<${htmlTag} style="font-family: '${param}'">`;case "opacity":return`<${htmlTag} style="opacity: ${param}%">`;case "size":return`<${htmlTag} style="font-size: ${param}pt">`;case "background":return`<${htmlTag} style="background-color: ${param}">`;
+case "hide":return`<${htmlTag} style="visibility: hidden">`;case "class":return`<${htmlTag} class="${param}">`;case "tag":return`<${htmlTag} data-tag="${param}">`;default:return`<${htmlTag}>`}}async _UpdateHTMLString(){if(this._isHtmlStringUpToDate)return this._htmlString;const fragList=(new C3.BBString(this._text,{noEscape:true})).toFragmentList();const iconBlobUrls=new Map;let htmlStr=``;const textIconSet=this._iconObjectClass?this.GetRuntime().GetTextIconSet(this._iconObjectClass):null;if(this._iconObjectClass){const promiseThrottle=C3.New(C3.PromiseThrottle);const assetDrawablePromises=[];const assetDrawableMap=new Map;for(const frag of fragList)if(frag.IsIcon()){const textIcon=frag.GetTextIcon(textIconSet);if(textIcon){const frame=
+textIcon.GetSource();const imageAsset=frame.GetImageInfo().GetImageAsset();if(assetDrawableMap.has(imageAsset))continue;assetDrawableMap.set(imageAsset,null);assetDrawablePromises.push(promiseThrottle.Add(async()=>{const drawable=await imageAsset.LoadToDrawable();assetDrawableMap.set(imageAsset,drawable)}))}}await Promise.all(assetDrawablePromises);const blobUrlPromises=[];for(const frag of fragList)if(frag.IsIcon()){const textIcon=frag.GetTextIcon(textIconSet);if(textIcon){const frame=textIcon.GetSource();
+const imageAsset=frame.GetImageInfo().GetImageAsset();blobUrlPromises.push(promiseThrottle.Add(async()=>{const blobUrl=await frame.GetImageInfo().ExtractImageToBlobURL(assetDrawableMap.get(imageAsset));iconBlobUrls.set(textIcon,blobUrl)}))}}await Promise.all(blobUrlPromises);for(const drawable of assetDrawableMap.values())if(drawable instanceof ImageBitmap&&drawable["close"])drawable["close"]()}const openTags=new Map;for(const frag of fragList){const fragTags=frag.GetStyleMap();let revKeys=[...openTags.keys()];
+revKeys.reverse();for(const bbTag of revKeys)if(!fragTags.has(bbTag)||fragTags.get(bbTag)!==openTags.get(bbTag)){openTags.delete(bbTag);htmlStr+=this._GetHTMLCloseTag(bbTag)}for(const [bbTag,param]of fragTags)if(!openTags.has(bbTag)){openTags.set(bbTag,param);htmlStr+=this._GetHTMLOpenTag(bbTag,param)}if(frag.IsText())htmlStr+=C3.ReplaceAll(C3.EscapeHTML(frag.GetCharacterArray().join("")),"\n","
");if(frag.IsIcon()&&textIconSet){const textIcon=frag.GetTextIcon(textIconSet);if(textIcon){const blobUrl=
+iconBlobUrls.get(textIcon);if(blobUrl){const styles=[];let topStyle="0.2em";const iconOffsetYStyle=fragTags.get("iconoffsety");if(iconOffsetYStyle){let param=iconOffsetYStyle.trim();if(param.endsWith("%"))topStyle=parseFloat(param)/100+"em";else topStyle=param+"px"}styles.push(`top: ${topStyle}`);if(this._runtime.GetSampling()==="nearest")styles.push("image-rendering: pixelated");htmlStr+=``}}}}const revKeys=
+[...openTags.keys()];revKeys.reverse();for(const tag of revKeys)htmlStr+=this._GetHTMLCloseTag(tag);htmlStr+="";this._htmlString=htmlStr;this._isHtmlStringUpToDate=true;return this._htmlString}Tick(){const wallTime=this._runtime.GetWallTime();if(wallTime>=this._typewriterEndTime){this._CancelTypewriter();this.Trigger(C3.Plugins.Text.Cnds.OnTypewriterTextFinished);this._runtime.UpdateRender()}else{let displayLength=C3.relerp(this._typewriterStartTime,this._typewriterEndTime,wallTime,0,this._typewriterLength);
+displayLength=Math.floor(displayLength);if(displayLength!==this._rendererText.GetDrawMaxCharacterCount()){this._rendererText.SetDrawMaxCharacterCount(displayLength);this._runtime.UpdateRender()}}}GetDebuggerProperties(){const prefix="plugins.text";return[{title:prefix+".name",properties:[{name:prefix+".properties.text.name",value:this.GetText(),onedit:v=>this._SetText(v)},{name:prefix+".properties.font.name",value:this._GetFontFace(),onedit:v=>this._SetFontFace(v)},{name:prefix+".properties.size.name",
+value:this._GetFontSize(),onedit:v=>this._SetFontSize(v)},{name:prefix+".properties.line-height.name",value:this._GetLineHeight(),onedit:v=>this._SetLineHeight(v)},{name:prefix+".properties.bold.name",value:this._IsBold(),onedit:v=>this._SetBold(v)},{name:prefix+".properties.italic.name",value:this._IsItalic(),onedit:v=>this._SetItalic(v)}]}]}GetScriptInterfaceClass(){return self.ITextInstance}};const map=new WeakMap;const SCRIPT_HORIZONTAL_ALIGNMENTS=new Map([["left",0],["center",1],["right",2]]);
+const SCRIPT_VERTICAL_ALIGNMENTS=new Map([["top",0],["center",1],["bottom",2]]);const SCRIPT_WRAP_MODES=new Map([["word",true],["character",false]]);const SCRIPT_TEXT_DIRECTIONS=["ltr","rtl"];self.ITextInstance=class ITextInstance extends self.IWorldInstance{constructor(){super();map.set(this,self.IInstance._GetInitInst().GetSdkInstance())}get text(){return map.get(this).GetText()}set text(str){C3X.RequireString(str);const inst=map.get(this);inst._CancelTypewriter();inst._SetText(str)}typewriterText(str,
+duration){C3X.RequireString(str);C3X.RequireFiniteNumber(duration);const inst=map.get(this);inst._CancelTypewriter();inst._StartTypewriter(str,duration)}typewriterFinish(){map.get(this)._FinishTypewriter()}set fontFace(str){C3X.RequireString(str);map.get(this)._SetFontFace(str)}get fontFace(){return map.get(this)._GetFontFace()}set isBold(b){map.get(this)._SetBold(b)}get isBold(){return map.get(this)._IsBold()}set isItalic(i){map.get(this)._SetItalic(i)}get isItalic(){return map.get(this)._IsItalic()}set sizePt(pt){C3X.RequireFiniteNumber(pt);
+map.get(this)._SetFontSize(pt)}get sizePt(){return map.get(this)._GetFontSize()}set fontColor(arr){C3X.RequireArray(arr);if(arr.length<3)throw new Error("expected 3 elements");tempColor.setRgb(arr[0],arr[1],arr[2]);map.get(this)._SetFontColor(tempColor)}get fontColor(){const c=map.get(this)._GetFontColor();return[c.getR(),c.getG(),c.getB()]}set lineHeight(lho){C3X.RequireFiniteNumber(lho);map.get(this)._SetLineHeight(lho)}get lineHeight(){return map.get(this)._GetLineHeight()}set horizontalAlign(str){C3X.RequireString(str);
+const h=SCRIPT_HORIZONTAL_ALIGNMENTS.get(str);if(typeof h==="undefined")throw new Error("invalid mode");map.get(this)._SetHAlign(h)}get horizontalAlign(){return HORIZONTAL_ALIGNMENTS[map.get(this)._GetHAlign()]}set verticalAlign(str){C3X.RequireString(str);const v=SCRIPT_VERTICAL_ALIGNMENTS.get(str);if(typeof v==="undefined")throw new Error("invalid mode");map.get(this)._SetVAlign(v)}get verticalAlign(){return VERTICAL_ALIGNMENTS[map.get(this)._GetVAlign()]}set wordWrapMode(str){C3X.RequireString(str);
+const isWrapByWord=SCRIPT_WRAP_MODES.get(str);if(typeof isWrapByWord==="undefined")throw new Error("invalid mode");map.get(this)._SetWrapByWord(isWrapByWord)}get wordWrapMode(){return map.get(this)._IsWrapByWord()?"word":"character"}set textDirection(ds){C3X.RequireString(ds);const d=SCRIPT_TEXT_DIRECTIONS.indexOf(ds);if(d===-1)throw new Error("invalid text direction");map.get(this)._SetTextDirection(d)}get textDirection(){return SCRIPT_TEXT_DIRECTIONS[map.get(this)._GetTextDirection()]}set readAloud(r){map.get(this)._SetReadAloud(!!r)}get readAloud(){return map.get(this)._IsReadAloud()}get textWidth(){return map.get(this)._GetTextWidth()}get textHeight(){return map.get(this)._GetTextHeight()}getTextSize(){const inst=
+map.get(this);return[inst._GetTextWidth(),inst._GetTextHeight()]}hasTagAtPosition(tag,x,y){C3X.RequireString(tag);C3X.RequireFiniteNumber(x);C3X.RequireFiniteNumber(y);return map.get(this)._HasTagAtPosition(tag,x,y)}getTagAtPosition(x,y){C3X.RequireFiniteNumber(x);C3X.RequireFiniteNumber(y);return map.get(this)._GetTagAtPosition(x,y)}getTagPositionAndSize(tag,index=0){C3X.RequireString(tag);C3X.RequireFiniteNumber(index);return map.get(this)._GetTagPosition(tag,index)}getTagCount(tag){C3X.RequireString(tag);
+return map.get(this)._GetTagCount(tag)}changeIconSet(iObjectClass){const sdkInst=map.get(this);const objectClass=sdkInst.GetRuntime()._UnwrapIObjectClass(iObjectClass);sdkInst._SetIconObjectClass(objectClass)}getAsHtmlString(){return map.get(this)._UpdateHTMLString()}}}
+{const C3=self.C3;C3.Plugins.Text.Cnds={CompareText(str,caseSensitive){if(caseSensitive)return this._text===str;else return C3.equalsNoCase(this._text,str)},IsRunningTypewriterText(){return this._typewriterEndTime!==-1},OnTypewriterTextFinished(){return true},HasTagAtPosition(tag,x,y){return this._HasTagAtPosition(tag,x,y)}}}
+{const C3=self.C3;const tempColor=C3.New(C3.Color);C3.Plugins.Text.Acts={SetText(param){this._CancelTypewriter();if(typeof param==="number"&¶m<1E9)param=Math.round(param*1E10)/1E10;this._SetText(param.toString())},AppendText(param){this._CancelTypewriter();if(typeof param==="number"&¶m<1E9)param=Math.round(param*1E10)/1E10;param=param.toString();if(!param)return;this._SetText(this._text+param)},TypewriterText(param,duration){this._CancelTypewriter();if(typeof param==="number"&¶m<1E9)param=
+Math.round(param*1E10)/1E10;this._StartTypewriter(param.toString(),duration)},SetFontFace(face,style){let bold=false;let italic=false;switch(style){case 1:bold=true;break;case 2:italic=true;break;case 3:bold=true;italic=true;break}if(face===this._faceName&&bold===this._isBold&&italic===this._isItalic)return;this._SetFontFace(face);this._SetBold(bold);this._SetItalic(italic)},SetFontSize(size){this._SetFontSize(size)},SetFontColor(rgb){tempColor.setFromRgbValue(rgb);tempColor.clamp();this._SetFontColor(tempColor)},
+SetWebFont(familyName,cssUrl){console.warn("[Text] 'Set web font' action is deprecated and no longer has any effect")},SetEffect(effect){this.GetWorldInfo().SetBlendMode(effect);this._runtime.UpdateRender()},TypewriterFinish(){this._FinishTypewriter()},SetLineHeight(lho){this._SetLineHeight(lho)},SetHAlign(h){this._SetHAlign(h)},SetVAlign(v){this._SetVAlign(v)},SetWrapping(w){this._SetWrapByWord(w===0)},SetTextDirection(d){this._SetTextDirection(d)},ChangeIconSet(objectClass){this._SetIconObjectClass(objectClass)},
+UpdateHTML(){return this._UpdateHTMLString()},SetReadAloud(r){this._SetReadAloud(r)}}}
+{const C3=self.C3;C3.Plugins.Text.Exps={Text(){return this._text},PlainText(){if(this._enableBBcode)return C3.BBString.StripAnyTags(this._text);else return this._text},FaceName(){return this._faceName},FaceSize(){return this._ptSize},TextWidth(){return this._GetTextWidth()},TextHeight(){return this._GetTextHeight()},LineHeight(){return this._lineHeightOffset},TagAtPosition(x,y){return this._GetTagAtPosition(x,y)},TagCount(tag){return this._GetTagCount(tag)},TagX(tag,index){const ret=this._GetTagPosition(tag,
+index);return ret?ret.x:0},TagY(tag,index){const ret=this._GetTagPosition(tag,index);return ret?ret.y:0},TagWidth(tag,index){const ret=this._GetTagPosition(tag,index);return ret?ret.width:0},TagHeight(tag,index){const ret=this._GetTagPosition(tag,index);return ret?ret.height:0},AsHTML(){return this._htmlString}}};
+
+}
+
+{
+'use strict';{const C3=self.C3;C3.Plugins.Date=class DatePlugin extends C3.SDKPluginBase{constructor(opts){super(opts)}Release(){super.Release()}}}{const C3=self.C3;C3.Plugins.Date.Type=class DateType extends C3.SDKTypeBase{constructor(objectClass){super(objectClass)}Release(){super.Release()}OnCreate(){}}}{const C3=self.C3;C3.Plugins.Date.Instance=class DateInstance extends C3.SDKInstanceBase{constructor(inst,properties){super(inst)}}}
+{const C3=self.C3;const getters=[];getters[0]=[ts=>C3.Plugins.Date.Exps.GetYear(ts),ts=>C3.Plugins.Date.Exps.GetMonth(ts),ts=>C3.Plugins.Date.Exps.GetDate(ts),ts=>C3.Plugins.Date.Exps.GetDay(ts),ts=>C3.Plugins.Date.Exps.GetHours(ts),ts=>C3.Plugins.Date.Exps.GetMinutes(ts),ts=>C3.Plugins.Date.Exps.GetSeconds(ts),ts=>C3.Plugins.Date.Exps.GetMilliseconds(ts)];getters[1]=[ts=>C3.Plugins.Date.Exps.GetUTCYear(ts),ts=>C3.Plugins.Date.Exps.GetUTCMonth(ts),ts=>C3.Plugins.Date.Exps.GetUTCDate(ts),ts=>C3.Plugins.Date.Exps.GetUTCDay(ts),
+ts=>C3.Plugins.Date.Exps.GetUTCHours(ts),ts=>C3.Plugins.Date.Exps.GetUTCMinutes(ts),ts=>C3.Plugins.Date.Exps.GetUTCSeconds(ts),ts=>C3.Plugins.Date.Exps.GetUTCMilliseconds(ts)];const parse=dateString=>C3.Plugins.Date.Exps.Parse(dateString);C3.Plugins.Date.Cnds={CompareTimeStamps(first,cmp,second){return C3.compare(first,cmp,second)},CompareDateStrings(first,cmp,second){return C3.compare(parse(first),cmp,parse(second))},CompareTimestampParts(first,cmp,second,part){return C3.compare(getters[1][part](first),
+cmp,getters[1][part](second))},CompareDateStringParts(first,cmp,second,part,mode){return C3.compare(getters[mode][part](parse(first)),cmp,getters[mode][part](parse(second)))}}}{const C3=self.C3;C3.Plugins.Date.Acts={}}
+{const C3=self.C3;const Intl=self.Intl;const getters=new Map;getters.set("local",new Map([["year",ts=>(new Date(ts)).getFullYear()],["month",ts=>(new Date(ts)).getMonth()],["date",ts=>(new Date(ts)).getDate()],["day",ts=>(new Date(ts)).getDay()],["hours",ts=>(new Date(ts)).getHours()],["minutes",ts=>(new Date(ts)).getMinutes()],["seconds",ts=>(new Date(ts)).getSeconds()],["milliseconds",ts=>(new Date(ts)).getMilliseconds()]]));getters.set("universal",new Map([["year",ts=>(new Date(ts)).getUTCFullYear()],
+["month",ts=>(new Date(ts)).getUTCMonth()],["date",ts=>(new Date(ts)).getUTCDate()],["day",ts=>(new Date(ts)).getUTCDay()],["hours",ts=>(new Date(ts)).getUTCHours()],["minutes",ts=>(new Date(ts)).getUTCMinutes()],["seconds",ts=>(new Date(ts)).getUTCSeconds()],["milliseconds",ts=>(new Date(ts)).getUTCMilliseconds()]]));const setters=new Map;setters.set("local",new Map([["year",(ts,year)=>(new Date(ts)).setFullYear(year)],["month",(ts,month)=>(new Date(ts)).setMonth(month)],["date",(ts,date)=>(new Date(ts)).setDate(date)],
+["hours",(ts,hours)=>(new Date(ts)).setHours(hours)],["minutes",(ts,minutes)=>(new Date(ts)).setMinutes(minutes)],["seconds",(ts,seconds)=>(new Date(ts)).setSeconds(seconds)],["milliseconds",(ts,milliseconds)=>(new Date(ts)).setMilliseconds(milliseconds)]]));setters.set("universal",new Map([["year",(ts,year)=>(new Date(ts)).setUTCFullYear(year)],["month",(ts,month)=>(new Date(ts)).setUTCMonth(month)],["date",(ts,date)=>(new Date(ts)).setUTCDate(date)],["hours",(ts,hours)=>(new Date(ts)).setUTCHours(hours)],
+["minutes",(ts,minutes)=>(new Date(ts)).setUTCMinutes(minutes)],["seconds",(ts,seconds)=>(new Date(ts)).setUTCSeconds(seconds)],["milliseconds",(ts,milliseconds)=>(new Date(ts)).setUTCMilliseconds(milliseconds)]]));const validate_date_format_option=function(chosenOption,optionName,validOptions,optionsObject){if(validOptions.includes(chosenOption))optionsObject[optionName]=chosenOption};const validate_hour_format_option=function(hourFormat,optionsObject){if(!hourFormat)return;if(hourFormat==="12")optionsObject["hour12"]=
+true;else if(hourFormat==="24")optionsObject["hour12"]=false};const validate_locale=function(locale){try{return Intl.getCanonicalLocales(locale)}catch(err){return self.navigator.language}};const DATE_STYLES=["full","long","medium","short"];const TIME_STYLES=["full","long","medium","short"];const WEEK_DAY_FORMATS=["long","short","narrow"];const YEAR_FORMATS=["numeric","2-digit"];const MONTH_FORMATS=["numeric","2-digit","long","short","narrow"];const DAY_FORMATS=["numeric","2-digit"];const HOUR_FORMATS=
+["numeric","2-digit"];const MINUTE_FORMATS=["numeric","2-digit"];const SECOND_FORMATS=["numeric","2-digit"];C3.Plugins.Date.Exps={ToString(timeStamp){return(new Date(timeStamp)).toString()},ToDateString(timeStamp){return(new Date(timeStamp)).toDateString()},ToTimeString(timeStamp){return(new Date(timeStamp)).toTimeString()},ToLocaleString(timeStamp){return(new Date(timeStamp)).toLocaleString()},ToLocaleDateString(timeStamp){return(new Date(timeStamp)).toLocaleDateString()},ToLocaleTimeString(timeStamp){return(new Date(timeStamp)).toLocaleTimeString()},
+ToUTCString(timeStamp){return(new Date(timeStamp)).toUTCString()},Parse(dateString){return Date.parse(dateString)},Get(year,month,day,hours,minutes,seconds,milliseconds){return Date.UTC(year,month,day,hours,minutes,seconds,milliseconds)},Now(){return Date.now()},TimezoneOffset(){return(new Date(Date.now())).getTimezoneOffset()},GetYear(timeStamp){return getters.get("local").get("year")(timeStamp)},GetUTCYear(timeStamp){return getters.get("universal").get("year")(timeStamp)},GetMonth(timeStamp){return getters.get("local").get("month")(timeStamp)},
+GetUTCMonth(timeStamp){return getters.get("universal").get("month")(timeStamp)},GetDate(timeStamp){return getters.get("local").get("date")(timeStamp)},GetUTCDate(timeStamp){return getters.get("universal").get("date")(timeStamp)},GetDay(timeStamp){return getters.get("local").get("day")(timeStamp)},GetUTCDay(timeStamp){return getters.get("universal").get("day")(timeStamp)},GetHours(timeStamp){return getters.get("local").get("hours")(timeStamp)},GetUTCHours(timeStamp){return getters.get("universal").get("hours")(timeStamp)},
+GetMinutes(timeStamp){return getters.get("local").get("minutes")(timeStamp)},GetUTCMinutes(timeStamp){return getters.get("universal").get("minutes")(timeStamp)},GetSeconds(timeStamp){return getters.get("local").get("seconds")(timeStamp)},GetUTCSeconds(timeStamp){return getters.get("universal").get("seconds")(timeStamp)},GetMilliseconds(timeStamp){return getters.get("local").get("milliseconds")(timeStamp)},GetUTCMilliseconds(timeStamp){return getters.get("universal").get("milliseconds")(timeStamp)},
+ChangeYear(timeStamp,year){return setters.get("local").get("year")(timeStamp,year)},ChangeUTCYear(timeStamp,year){return setters.get("universal").get("year")(timeStamp,year)},ChangeMonth(timeStamp,month){return setters.get("local").get("month")(timeStamp,month)},ChangeUTCMonth(timeStamp,month){return setters.get("universal").get("month")(timeStamp,month)},ChangeDate(timeStamp,date){return setters.get("local").get("date")(timeStamp,date)},ChangeUTCDate(timeStamp,date){return setters.get("universal").get("date")(timeStamp,
+date)},ChangeDay(timeStamp,targetDay){const year=C3.Plugins.Date.Exps.GetYear(timeStamp);const month=C3.Plugins.Date.Exps.GetMonth(timeStamp);const date=C3.Plugins.Date.Exps.GetDate(timeStamp);const hours=C3.Plugins.Date.Exps.GetHours(timeStamp);const minutes=C3.Plugins.Date.Exps.GetMinutes(timeStamp);const seconds=C3.Plugins.Date.Exps.GetSeconds(timeStamp);const milliseconds=C3.Plugins.Date.Exps.GetMilliseconds(timeStamp);const currentDay=C3.Plugins.Date.Exps.GetDay(timeStamp);const distance=targetDay-
+currentDay;return(new Date(year,month,date+distance,hours,minutes,seconds,milliseconds)).getTime()},ChangeUTCDay(timeStamp,targetDay){const year=C3.Plugins.Date.Exps.GetUTCYear(timeStamp);const month=C3.Plugins.Date.Exps.GetUTCMonth(timeStamp);const date=C3.Plugins.Date.Exps.GetUTCDate(timeStamp);const hours=C3.Plugins.Date.Exps.GetUTCHours(timeStamp);const minutes=C3.Plugins.Date.Exps.GetUTCMinutes(timeStamp);const seconds=C3.Plugins.Date.Exps.GetUTCSeconds(timeStamp);const milliseconds=C3.Plugins.Date.Exps.GetUTCMilliseconds(timeStamp);
+const currentDay=C3.Plugins.Date.Exps.GetUTCDay(timeStamp);const distance=targetDay-currentDay;return C3.Plugins.Date.Exps.Get(year,month,date+distance,hours,minutes,seconds,milliseconds)},ChangeHours(timeStamp,hours){return setters.get("local").get("hours")(timeStamp,hours)},ChangeUTCHours(timeStamp,hours){return setters.get("universal").get("hours")(timeStamp,hours)},ChangeMinutes(timeStamp,minutes){return setters.get("local").get("minutes")(timeStamp,minutes)},ChangeUTCMinutes(timeStamp,minutes){return setters.get("universal").get("minutes")(timeStamp,
+minutes)},ChangeSeconds(timeStamp,seconds){return setters.get("local").get("seconds")(timeStamp,seconds)},ChangeUTCSeconds(timeStamp,seconds){return setters.get("universal").get("seconds")(timeStamp,seconds)},ChangeMilliseconds(timeStamp,milliseconds){return setters.get("local").get("milliseconds")(timeStamp,milliseconds)},ChangeUTCMilliseconds(timeStamp,milliseconds){return setters.get("universal").get("milliseconds")(timeStamp,milliseconds)},Difference(firstTimeStamp,secondTimeStamp){return secondTimeStamp-
+firstTimeStamp},ToTimerHours(milliseconds){return Math.trunc(C3.Plugins.Date.Exps.ToTotalHours(milliseconds))},ToTimerMinutes(milliseconds){return Math.trunc(C3.Plugins.Date.Exps.ToTotalMinutes(milliseconds))%60},ToTimerSeconds(milliseconds){return Math.trunc(C3.Plugins.Date.Exps.ToTotalSeconds(milliseconds))%60},ToTimerMilliseconds(milliseconds){return milliseconds%1E3},ToTotalHours(milliseconds){return milliseconds/(1E3*60*60)},ToTotalMinutes(milliseconds){return milliseconds/(1E3*60)},ToTotalSeconds(milliseconds){return milliseconds/
+1E3},FormatDateWithStyles(locale,timestamp,dateStyle,timeStyle,hourFormat){const l=validate_locale(locale);if(!l)return;let options={};validate_date_format_option.call(this,dateStyle,"dateStyle",DATE_STYLES,options);validate_date_format_option.call(this,timeStyle,"timeStyle",TIME_STYLES,options);validate_hour_format_option.call(this,hourFormat,options);return(new Intl.DateTimeFormat(l,options)).format(timestamp)},FormatDateWithComponents(locale,timestamp,weekday,year,month,day,hour,minute,second,
+hourFormat){const l=validate_locale(locale);if(!l)return;const options={};validate_date_format_option.call(this,weekday,"weekday",WEEK_DAY_FORMATS,options);validate_date_format_option.call(this,year,"year",YEAR_FORMATS,options);validate_date_format_option.call(this,month,"month",MONTH_FORMATS,options);validate_date_format_option.call(this,day,"day",DAY_FORMATS,options);validate_date_format_option.call(this,hour,"hour",HOUR_FORMATS,options);validate_date_format_option.call(this,minute,"minute",MINUTE_FORMATS,
+options);validate_date_format_option.call(this,second,"second",SECOND_FORMATS,options);validate_hour_format_option.call(this,hourFormat,options);return(new Intl.DateTimeFormat(l,options)).format(timestamp)}}};
+
+}
+
+{
+'use strict';{const C3=self.C3;C3.Behaviors.Pin=class PinBehavior extends C3.SDKBehaviorBase{constructor(opts){super(opts)}Release(){super.Release()}}}{const C3=self.C3;C3.Behaviors.Pin.Type=class PinType extends C3.SDKBehaviorTypeBase{constructor(behaviorType){super(behaviorType)}Release(){super.Release()}OnCreate(){}}}
+{const C3=self.C3;C3.Behaviors.Pin.Instance=class PinInstance extends C3.SDKBehaviorInstanceBase{constructor(behInst,properties){super(behInst);this._pinInst=null;this._pinUid=-1;this._mode="";this._propSet=new Set;this._pinDist=0;this._pinAngle=0;this._pinImagePoint=0;this._dx=0;this._dy=0;this._dWidth=0;this._dHeight=0;this._dAngle=0;this._dz=0;this._lastKnownAngle=0;this._destroy=false;if(properties)this._destroy=properties[0];const rt=this._runtime.Dispatcher();this._disposables=new C3.CompositeDisposable(C3.Disposable.From(rt,
+"instancedestroy",e=>this._OnInstanceDestroyed(e.instance)),C3.Disposable.From(rt,"afterload",e=>this._OnAfterLoad()))}Release(){this._pinInst=null;super.Release()}_SetPinInst(inst){if(inst){this._pinInst=inst;this._StartTicking2()}else{this._pinInst=null;this._StopTicking2()}}_Pin(objectClass,mode,propList){if(!objectClass)return;const otherInst=objectClass.GetFirstPicked(this._inst);if(!otherInst)return;this._mode=mode;this._SetPinInst(otherInst);const myWi=this._inst.GetWorldInfo();const otherWi=
+otherInst.GetWorldInfo();if(this._mode==="properties"){const propSet=this._propSet;propSet.clear();for(const p of propList)propSet.add(p);this._dx=myWi.GetX()-otherWi.GetX();this._dy=myWi.GetY()-otherWi.GetY();this._dAngle=myWi.GetAngle()-otherWi.GetAngle();this._lastKnownAngle=myWi.GetAngle();this._dz=myWi.GetZElevation()-otherWi.GetZElevation();if(propSet.has("x")&&propSet.has("y")){this._pinAngle=C3.angleTo(otherWi.GetX(),otherWi.GetY(),myWi.GetX(),myWi.GetY())-otherWi.GetAngle();this._pinDist=
+C3.distanceTo(otherWi.GetX(),otherWi.GetY(),myWi.GetX(),myWi.GetY())}if(propSet.has("width-abs"))this._dWidth=myWi.GetWidth()-otherWi.GetWidth();else if(propSet.has("width-scale"))this._dWidth=myWi.GetWidth()/otherWi.GetWidth();if(propSet.has("height-abs"))this._dHeight=myWi.GetHeight()-otherWi.GetHeight();else if(propSet.has("height-scale"))this._dHeight=myWi.GetHeight()/otherWi.GetHeight()}else this._pinDist=C3.distanceTo(otherWi.GetX(),otherWi.GetY(),myWi.GetX(),myWi.GetY())}SaveToJson(){const propSet=
+this._propSet;const mode=this._mode;const ret={"uid":this._pinInst?this._pinInst.GetUID():-1,"m":mode,"d":this._destroy};if(mode==="rope"||mode==="bar")ret["pd"]=this._pinDist;else if(mode==="properties"){ret["ps"]=[...this._propSet];if(propSet.has("imagepoint"))ret["ip"]=this._pinImagePoint;else if(propSet.has("x")&&propSet.has("y")){ret["pa"]=this._pinAngle;ret["pd"]=this._pinDist}else{if(propSet.has("x"))ret["dx"]=this._dx;if(propSet.has("y"))ret["dy"]=this._dy}if(propSet.has("angle")){ret["da"]=
+this._dAngle;ret["lka"]=this._lastKnownAngle}if(propSet.has("width-abs")||propSet.has("width-scale"))ret["dw"]=this._dWidth;if(propSet.has("height-abs")||propSet.has("height-scale"))ret["dh"]=this._dHeight;if(propSet.has("z"))ret["dz"]=this._dz}return ret}LoadFromJson(o){const mode=o["m"];const propSet=this._propSet;propSet.clear();this._pinUid=o["uid"];if(typeof mode==="number"){this._LoadFromJson_Legacy(o);return}this._mode=mode;if(o.hasOwnProperty("d"))this._destroy=!!o["d"];if(mode==="rope"||
+mode==="bar")this._pinDist=o["pd"];else if(mode==="properties"){for(const p of o["ps"])propSet.add(p);if(propSet.has("imagepoint"))this._pinImagePoint=o["ip"];else if(propSet.has("x")&&propSet.has("y")){this._pinAngle=o["pa"];this._pinDist=o["pd"]}else{if(propSet.has("x"))this._dx=o["dx"];if(propSet.has("y"))this._dy=o["dy"]}if(propSet.has("angle")){this._dAngle=o["da"];this._lastKnownAngle=o["lka"]||0}if(propSet.has("width-abs")||propSet.has("width-scale"))this._dWidth=o["dw"];if(propSet.has("height-abs")||
+propSet.has("height-scale"))this._dHeight=o["dh"];if(propSet.has("z"))this._dz=o["dz"]}}_LoadFromJson_Legacy(o){const propSet=this._propSet;const myStartAngle=o["msa"];const theirStartAngle=o["tsa"];const pinAngle=o["pa"];const pinDist=o["pd"];const mode=o["m"];switch(mode){case 0:this._mode="properties";propSet.add("x").add("y").add("angle");this._pinAngle=pinAngle;this._pinDist=pinDist;this._dAngle=myStartAngle-theirStartAngle;this._lastKnownAngle=o["lka"];break;case 1:this._mode="properties";propSet.add("x").add("y");
+this._pinAngle=pinAngle;this._pinDist=pinDist;break;case 2:this._mode="properties";propSet.add("angle");this._dAngle=myStartAngle-theirStartAngle;this._lastKnownAngle=o["lka"];break;case 3:this._mode="rope";this._pinDist=o["pd"];break;case 4:this._mode="bar";this._pinDist=o["pd"];break}}_OnAfterLoad(){if(this._pinUid===-1)this._SetPinInst(null);else{this._SetPinInst(this._runtime.GetInstanceByUID(this._pinUid));this._pinUid=-1}}_OnInstanceDestroyed(inst){if(this._pinInst===inst){this._SetPinInst(null);
+if(this._destroy)this._runtime.DestroyInstance(this._inst)}}Tick2(){const pinInst=this._pinInst;if(!pinInst)return;const pinWi=pinInst.GetWorldInfo();const myInst=this._inst;const myWi=myInst.GetWorldInfo();const mode=this._mode;let bboxChanged=false;if(mode==="rope"||mode==="bar"){const dist=C3.distanceTo(myWi.GetX(),myWi.GetY(),pinWi.GetX(),pinWi.GetY());if(dist>this._pinDist||mode==="bar"&&distthis._OnAfterLoad(e);this.GetRuntime().Dispatcher().addEventListener("afterload",this._afterLoad)}Release(){this.GetRuntime().Dispatcher().removeEventListener("afterload",this._afterLoad);this._afterLoad=null;if(this._finishingTween){this.ReleaseAndCompleteTween(this._finishingTween);this._finishingTween=null}this.ReleaseAndCompleteTweens();this._tweens=null;this.ClearDisabledList();this._disabledTweens=null;this._ReleaseWaitingTweens();this._waitingForReleaseTweens=
+null;super.Release()}SetEnabled(e){this._enabled=!!e;if(e){if(this._waitingForReleaseTweens&&this._waitingForReleaseTweens.size)this._StartTicking2()}else this._StopTicking2();for(const tween of this.AllTweens())if(e){if(this.IsInDisabledList(tween))tween.Resume()}else{if(tween.IsPlaying()||tween.IsScheduled())this.AddToDisabledList(tween);tween.Stop()}if(e)this.ClearDisabledList()}IsEnabled(){return this._enabled}AddToDisabledList(tween){this._disabledTweens.push(tween)}IsInDisabledList(tween){return this._disabledTweens.includes(tween)}ClearDisabledList(){C3.clearArray(this._disabledTweens)}GetFinishingTween(){return this._finishingTween}IsInstanceValid(){const inst=
+this.GetObjectInstance();if(!inst)return false;return!inst.IsDestroyed()}GetTween(tags,property,includeWaitingForRelease=false){const tweens=property?this.PropertyTweens(property,includeWaitingForRelease):this.AllTweens(includeWaitingForRelease);if(!tweens||!tweens.length)return;for(const tween of tweens)if(tween.HasTags(tags))return tween}GetTweenIncludingWaitingForRelease(tags,property){return this.GetTween(tags,property,true)}*GetTweens(tags,property,includeWaitingForRelease=false){const tweens=
+property?this.PropertyTweens(property,includeWaitingForRelease):this.AllTweens(includeWaitingForRelease);if(tweens&&tweens.length)for(const tween of tweens)if(tween.HasTags(tags))yield tween}*GetTweensIncludingWaitingForRelease(tags,property){yield*this.GetTweens(tags,property,true)}PropertyTweens(property,includeWaitingForRelease){if(includeWaitingForRelease){let active=this._activeTweens.get(property);let waitingForRelease=this._waitingForReleaseTweens.get(property);if(!active)active=[];if(!waitingForRelease)waitingForRelease=
+[];return active.concat(waitingForRelease).filter(t=>t).filter(t=>!t.IsReleased())}else{let active=this._activeTweens.get(property);if(!active)active=[];return active.filter(t=>t).filter(t=>!t.IsReleased())}}AllTweens(includeWaitingForRelease){if(includeWaitingForRelease){const active=[...this._activeTweens.values()].flat();const waitingForRelease=[...this._waitingForReleaseTweens.values()].flat();return active.concat(waitingForRelease).filter(t=>t).filter(t=>!t.IsReleased())}else{const active=[...this._activeTweens.values()].flat();
+return active.filter(t=>t).filter(t=>!t.IsReleased())}}AllTweensIncludingWaitingForRelease(){return this.AllTweens(true)}SaveToJson(){return{"s":false,"e":!!this._enabled,"at":this._SaveActiveTweensToJson(),"dt":this._SaveDisabledTweensToJson(),"wt":this._SaveWaitingForReleaseTweensToJson(),"ft":this._SaveFinishingTweenToJson()}}LoadFromJson(o){if(!o)return;this._activeTweensJson=o["at"];this._disabledTweensJson=o["dt"];this._waitingForReleaseTweensJson=o["wt"];this._finishingTweenName=o["ft"];this._allowMultiple=
+false;this._enabled=!!o["e"]}_OnAfterLoad(e){const timelineManager=this.GetRuntime().GetTimelineManager();this._PopulateTweenMap(this._activeTweensJson,this._activeTweens,timelineManager);if(this._disabledTweensJson){C3.clearArray(this._disabledTweens);for(const tweenName of this._disabledTweensJson)this._PopulateTweenArray(this._disabledTweens,tweenName,timelineManager)}this._PopulateTweenMap(this._waitingForReleaseTweensJson,this._waitingForReleaseTweens,timelineManager);this._finishingTween=this._GetTween(this._finishingTweenName,
+timelineManager);if(this._enabled){if(this._waitingForReleaseTweens&&this._waitingForReleaseTweens.size)this._StartTicking2()}else this._StopTicking2()}_PopulateTweenMap(restoreJson,map,timelineManager){if(!restoreJson)return;for(const property in restoreJson){let tweens=map.get(property);tweens?C3.clearArray(tweens):tweens=[];const tweensJson=restoreJson[property];for(const tweenJson of tweensJson){const success=this._PopulateTweenArray(tweens,tweenJson["name"],timelineManager);if(!success){const tween=
+C3.TweenState.Build({runtime:this.GetRuntime(),json:tweenJson});tween.AddCompletedCallback(tween=>this._FinishTriggers(tween));timelineManager.AddScheduledTimeline(tween);this._PopulateTweenArray(tweens,tween,timelineManager)}else this._LoadTweenFromJson(tweenJson["name"],tweenJson,timelineManager)}map.set(property,tweens)}}_GetTween(name,timelineManager){return timelineManager.GetScheduledOrPlayingTimelineByName(name)}_PopulateTweenArray(collection,tweenOrName,timelineManager){if(typeof tweenOrName===
+"string"){const tween=this._GetTween(tweenOrName,timelineManager);if(tween)return!!collection.push(tween)}else return!!collection.push(tweenOrName);return false}_LoadTweenFromJson(tweenOrName,tweenJson,timelineManager){if(typeof tweenOrName==="string"){const tween=this._GetTween(tweenOrName,timelineManager);if(tween)tween._LoadFromJson(tweenJson)}else tweenOrName._LoadFromJson(tweenJson)}_SaveActiveTweensToJson(){const ret={};for(const [property,tweens]of this._activeTweens)ret[property]=tweens.filter(t=>
+!t.IsReleased()).map(t=>t._SaveToJson());return ret}_SaveDisabledTweensToJson(){return this._disabledTweens.filter(t=>!t.IsReleased()).map(t=>t.GetName())}_SaveWaitingForReleaseTweensToJson(){const ret={};for(const [property,tweens]of this._waitingForReleaseTweens)ret[property]=tweens.map(tween=>tween._SaveToJson());return ret}_SaveFinishingTweenToJson(){return this._finishingTween?this._finishingTween.GetName():""}Tick2(){this._ReleaseWaitingTweens()}CreateTween(args){const propertyTracksConfig=
+NAMESPACE.Config.GetPropertyTracksConfig(args.property,args.startValue,args.endValue,args.ease,args.resultMode,this.GetObjectInstance());const tweenId=NAMESPACE.Maps.GetPropertyFromIndex(args.property);if(!NAMESPACE.Maps.IsValueId(tweenId))this.ReleaseTweens(args.property);const tween=C3.TweenState.Build({runtime:this.GetRuntime(),id:tweenId,tags:args.tags,time:args.time,instance:this.GetObjectInstance(),releaseOnComplete:!!args.releaseOnComplete,loop:!!args.loop,pingPong:!!args.pingPong,repeatCount:args.repeatCount,
+initialValueMode:args.initialValueMode,propertyTracksConfig:propertyTracksConfig});tween.AddCompletedCallback(tween=>this._FinishTriggers(tween));this._AddTween(tween,args.property);return tween}_MaybeRemoveFromActiveTweenMap(tween){const id=tween.GetId();if(this._activeTweens.has(id)){const tweenArray=this._activeTweens.get(id);if(tweenArray){const index=tweenArray.indexOf(tween);if(index!==-1)tweenArray.splice(index,1)}}}ReleaseTween(tween,complete=false){this._MaybeRemoveFromActiveTweenMap(tween);
+if(tween.IsReleased())return;if(this._IsInWaitingList(tween))return;tween.Stop(complete);this._AddToWaitingList(tween)}ReleaseTweens(indexProperty,complete=false){if(C3.IsFiniteNumber(indexProperty)){const stringProperty=NAMESPACE.Maps.GetPropertyFromIndex(indexProperty);if(!this._activeTweens.has(stringProperty))return;const tweenArray=this._activeTweens.get(stringProperty);const finishingTween=this.GetFinishingTween();for(const tween of tweenArray){if(tween===finishingTween)continue;if(tween.IsReleased())continue;
+if(this._IsInWaitingList(tween))continue;tween.Stop(complete);tween.Release()}C3.clearArray(tweenArray)}else{const finishingTween=this.GetFinishingTween();for(const tween of this.AllTweens()){if(tween===finishingTween)continue;if(tween.IsReleased())continue;if(this._IsInWaitingList(tween))continue;tween.Stop(complete);tween.Release()}for(const property of this._activeTweens.keys()){C3.clearArray(this._activeTweens.get(property));this._activeTweens.delete(property)}this._activeTweens.clear()}}ReleaseAndCompleteTween(tween){this.ReleaseTween(tween,
+true)}ReleaseAndCompleteTweens(){this.ReleaseTweens(NaN,true)}GetPropertyValueByIndex(index){switch(index){case ENABLED:return this._enabled}}SetPropertyValueByIndex(index,value){switch(index){case ENABLED:this._enabled=!!value;break}}_GetBehaviorType(tween){const instance=tween.GetInstance();const behaviorInstances=instance.GetBehaviorInstances();for(const behaviorInstance of behaviorInstances){const behaviorType=behaviorInstance.GetBehaviorType();if(behaviorType.GetInstanceSdkCtor()===this.constructor)return behaviorType}}Trigger(method,
+runtime,inst,behaviorType){if(this._runtime)return super.Trigger(method);else return runtime.Trigger(method,inst,behaviorType)}_FinishTriggers(tween){this._finishingTween=tween;NAMESPACE.Cnds.SetFinishingTween(tween);let instance;let runtime;if(!this.GetRuntime()){instance=tween.GetInstance();if(!instance)return;if(instance&&instance.IsDestroyed())return;runtime=instance.GetRuntime();const behaviorType=this._GetBehaviorType(tween);this.Trigger(NAMESPACE.Cnds.OnTweensFinished,runtime,instance,behaviorType);
+this.Trigger(NAMESPACE.Cnds.OnAnyTweensFinished,runtime,instance,behaviorType);tween.Stop()}else{instance=this._inst;runtime=this._runtime;this.Trigger(NAMESPACE.Cnds.OnTweensFinished);this.Trigger(NAMESPACE.Cnds.OnAnyTweensFinished);this.ReleaseTween(tween)}this._finishingTween=null;NAMESPACE.Cnds.SetFinishingTween(null);if(tween.GetDestroyInstanceOnComplete())runtime.DestroyInstance(instance)}_AddTween(tween,indexProperty){const stringProperty=NAMESPACE.Maps.GetPropertyFromIndex(indexProperty);
+if(!this._activeTweens.has(stringProperty))this._activeTweens.set(stringProperty,[]);const tweenArray=this._activeTweens.get(stringProperty);tweenArray.push(tween)}_AddToWaitingList(tween){const id=tween.GetId();if(!this._waitingForReleaseTweens.has(id))this._waitingForReleaseTweens.set(id,[]);this._waitingForReleaseTweens.get(id).push(tween);if(!this.IsTicking2())this._StartTicking2()}_IsInWaitingList(tween){const id=tween.GetId();if(!this._waitingForReleaseTweens.has(id))return false;return this._waitingForReleaseTweens.get(id).includes(tween)}_ReleaseWaitingTweens(){if(!this._waitingForReleaseTweens.size)return;
+for(const tweenArray of this._waitingForReleaseTweens.values()){for(const tween of tweenArray){if(tween.IsReleased())continue;tween.Release()}C3.clearArray(tweenArray)}this._waitingForReleaseTweens.clear();if(this.IsTicking2())this._StopTicking2()}GetDebuggerProperties(){const prefix="behaviors.tween";return[{title:"$"+this.GetBehaviorType().GetName(),properties:[{name:prefix+".properties.enabled.name",value:this.IsEnabled(),onedit:v=>this.SetEnabled(v)}]}]}GetScriptInterfaceClass(){return self.ITweenBehaviorInstance}}}
+{const C3=self.C3;let finishingTween=null;C3.Behaviors.Tween.Cnds={SetFinishingTween(tween){finishingTween=tween},OnTweensFinished(tags){return finishingTween.HasTags(tags)},OnAnyTweensFinished(){return true},IsPlaying(tags){const tweens=[...this.GetTweensIncludingWaitingForRelease(tags)];if(!tweens)return false;if(!tweens.length)return false;return tweens.some(C3.TweenState.IsPlaying)},IsAnyPlaying(){const tweens=[...this.AllTweensIncludingWaitingForRelease()];if(!tweens)return false;if(!tweens.length)return false;
+return tweens.some(C3.TweenState.IsPlaying)},IsPaused(tags){const tweens=[...this.GetTweensIncludingWaitingForRelease(tags)];if(!tweens)return false;if(!tweens.length)return false;return tweens.some(C3.TweenState.IsPaused)},IsAnyPaused(){const tweens=[...this.AllTweensIncludingWaitingForRelease()];if(!tweens)return false;if(!tweens.length)return false;return tweens.some(C3.TweenState.IsPaused)}}}
+{const C3=self.C3;const Ease=self.Ease;const NAMESPACE=C3.Behaviors.Tween;NAMESPACE.Acts={SetEnabled(enable){this.SetEnabled(!!enable)},async TweenOneProperty(...args){if(!this.IsEnabled()||!this.IsInstanceValid())return;const tween=this.CreateTween(NAMESPACE.TweenArguments.OneProperty(this,...args));if(tween.Play())await tween.GetPlayPromise()},async TweenTwoProperties(...args){if(!this.IsEnabled()||!this.IsInstanceValid())return;const tween=this.CreateTween(NAMESPACE.TweenArguments.TwoProperties(this,
+...args));if(tween.Play())await tween.GetPlayPromise()},async TweenValue(...args){if(!this.IsEnabled()||!this.IsInstanceValid())return;const tween=this.CreateTween(NAMESPACE.TweenArguments.ValueProperty(this,...args));if(tween.Play())await tween.GetPlayPromise()},PauseTweens(tags){if(!this.IsEnabled()||!this.IsInstanceValid())return;for(const tween of this.GetTweens(tags))tween.Stop()},PauseAllTweens(){if(!this.IsEnabled()||!this.IsInstanceValid())return;for(const tween of this.AllTweens())tween.Stop()},
+ResumeTweens(tags){if(!this.IsEnabled()||!this.IsInstanceValid())return;for(const tween of this.GetTweens(tags))tween.Resume()},ResumeAllTweens(){if(!this.IsEnabled()||!this.IsInstanceValid())return;for(const tween of this.AllTweens())tween.Resume()},StopTweens(tags){if(!this.IsEnabled()||!this.IsInstanceValid())return;for(const tween of this.GetTweens(tags))this.ReleaseTween(tween)},StopAllTweens(){if(!this.IsEnabled()||!this.IsInstanceValid())return;for(const tween of this.AllTweens())this.ReleaseTween(tween)},
+SetOnePropertyTweensEndValue(tags,property,endValue){if(!this.IsEnabled()||!this.IsInstanceValid())return;const propertyName=C3.Behaviors.Tween.Maps.GetSinglePropertyFromIndex(property);for(const tween of this.GetTweens(tags)){tween.BeforeSetEndValues([propertyName]);tween.SetEndValue(endValue,propertyName)}},SetTwoPropertiesTweensEndValue(tags,property,endValueX,endValueY){if(!this.IsEnabled()||!this.IsInstanceValid())return;const properties=C3.Behaviors.Tween.Maps.GetRealProperties(property);for(const tween of this.GetTweens(tags)){tween.BeforeSetEndValues(properties);
+tween.SetEndValue(endValueX,properties[0]);tween.SetEndValue(endValueY,properties[1])}},SetValuePropertyTweensStartValue(tags,startValue){if(!this.IsEnabled()||!this.IsInstanceValid())return;for(const tween of this.GetTweens(tags,"value"))tween.SetStartValue(startValue,"value")},SetValuePropertyTweensEndValue(tags,endValue){if(!this.IsEnabled()||!this.IsInstanceValid())return;for(const tween of this.GetTweens(tags,"value")){tween.BeforeSetEndValues(["value"]);tween.SetEndValue(endValue,"value")}},
+SetTweensEase(tags,easeIndex){if(!this.IsEnabled()||!this.IsInstanceValid())return;const ease=Ease.GetEaseFromIndex(easeIndex);for(const tween of this.GetTweens(tags))tween.SetEase(ease)},SetAllTweensEase(easeIndex){if(!this.IsEnabled()||!this.IsInstanceValid())return;const ease=Ease.GetEaseFromIndex(easeIndex);for(const tween of this.AllTweens())tween.SetEase(ease)},SetTweensTime(tags,time){if(!this.IsEnabled()||!this.IsInstanceValid())return;for(const tween of this.GetTweens(tags))tween.SetTime(time)},
+SetAllTweensTime(time){if(!this.IsEnabled()||!this.IsInstanceValid())return;for(const tween of this.AllTweens())tween.SetTime(time)},SetTweensPlaybackRate(tags,rate){if(!this.IsEnabled()||!this.IsInstanceValid())return;for(const tween of this.GetTweens(tags))tween.SetPlaybackRate(rate)},SetAllTweensPlaybackRate(rate){if(!this.IsEnabled()||!this.IsInstanceValid())return;for(const tween of this.AllTweens())tween.SetPlaybackRate(rate)},SetTweensDestroyOnComplete(tags,destroyOnComplete){if(!this.IsEnabled()||
+!this.IsInstanceValid())return;for(const tween of this.GetTweens(tags))tween.SetDestroyInstanceOnComplete(!!destroyOnComplete)},SetAllTweensDestroyOnComplete(destroyOnComplete){if(!this.IsEnabled()||!this.IsInstanceValid())return;for(const tween of this.AllTweens())tween.SetDestroyInstanceOnComplete(!!destroyOnComplete)}}}
+{const C3=self.C3;C3.Behaviors.Tween.Exps={Time(tags){const tween=this.GetTweenIncludingWaitingForRelease(tags);if(!tween)return 0;return tween.GetTime()},Progress(tags){const tween=this.GetTweenIncludingWaitingForRelease(tags);if(!tween)return 0;return tween.GetTime()/tween.GetTotalTime()},Value(tags){const tween=this.GetTweenIncludingWaitingForRelease(tags,"value");if(!tween)return 0;return tween.GetPropertyTrack("value").GetSourceAdapterValue()},Tags(){if(!this.GetFinishingTween())return"";return this.GetFinishingTween().GetStringTags()}}};
+
+}
+
+{
+'use strict';const C3=self.C3;const Ease=self.Ease;const PAIR_PROPERTIES=["position","size","scale"];const SINGLE_PROPERTIES=["offsetX","offsetY","offsetWidth","offsetHeight","offsetAngle","offsetOpacity","offsetColor","offsetZElevation","offsetScaleX","offsetScaleY"];const VALUE_PROPERTIES=["value"];const PROPERTY_INDEX_TO_NAME=[].concat(PAIR_PROPERTIES).concat(SINGLE_PROPERTIES).concat(VALUE_PROPERTIES);
+const PROPERTY_PAIR_TO_REAL_PROPERTIES={"position":["offsetX","offsetY"],"size":["offsetWidth","offsetHeight"],"scale":["offsetScaleX","offsetScaleY"]};const ALL_REAL_PROPERTIES=Object.assign({},PROPERTY_INDEX_TO_NAME.reduce((o,key)=>Object.assign({},o,{[key]:[key]}),{}),PROPERTY_PAIR_TO_REAL_PROPERTIES);
+C3.Behaviors.Tween.Maps=class Maps{constructor(){}static GetEases(){return[...Ease.GetRuntimeEaseNames()]}static GetEaseFromIndex(index){return[...Ease.GetRuntimeEaseNames()][index]}static GetPropertyFromIndex(index){return PROPERTY_INDEX_TO_NAME[index]}static GetPropertyIndexFromName(name){return PROPERTY_INDEX_TO_NAME.indexOf(name)}static GetPairPropertyFromIndex(index){return PAIR_PROPERTIES[index]}static GetSinglePropertyFromIndex(index){return SINGLE_PROPERTIES[index]}static GetValuePropertyFromIndex(index){return VALUE_PROPERTIES[index]}static GetPairProperties(pairId){return PROPERTY_PAIR_TO_REAL_PROPERTIES[pairId]}static GetRealProperties(id){if(C3.IsString(id))return ALL_REAL_PROPERTIES[id];else return ALL_REAL_PROPERTIES[PROPERTY_INDEX_TO_NAME[id]]}static IsPairId(id){return!!PROPERTY_PAIR_TO_REAL_PROPERTIES[id]}static IsColorId(id){return id===
+"offsetColor"}static IsAngleId(id){return id==="offsetAngle"}static IsOpacityId(id){return id==="offsetOpacity"}static IsValueId(id){return id==="value"}};
+
+}
+
+{
+'use strict';const C3=self.C3;const NAMESPACE=C3.Behaviors.Tween;const TWEEN_CONFIGURATIONS=new Map;
+NAMESPACE.Config=class Config{constructor(){}static GetPropertyTracksConfig(property,startValue,endValue,ease,resultMode,instance){if(TWEEN_CONFIGURATIONS.size===0)this._CreateConfigObjects();const propertyType=NAMESPACE.PropertyTypes.Pick(property);let config=TWEEN_CONFIGURATIONS.get(propertyType);if(C3.IsFiniteNumber(property))property=NAMESPACE.Maps.GetPropertyFromIndex(property);return this._GetConfig(config,property,startValue,endValue,ease,resultMode,instance)}static TransformValue(property,
+value){const configFunctionObject=C3.Behaviors.Tween.GetPropertyTracksConfig(property);return configFunctionObject.valueGetter(value)}static _CreateConfigObjects(){const types=NAMESPACE.PropertyTypes;const getters=NAMESPACE.ValueGetters;this._AddConfigObject(types.PAIR,this._GetPairConfig,getters._GetPropertyValue);this._AddConfigObject(types.COLOR,this._GetColorConfig,getters._GetColorPropertyValue);this._AddConfigObject(types.ANGLE,this._GetAngleConfig,getters._GetPropertyAngleValue);this._AddConfigObject(types.VALUE,
+this._GetValueConfig,getters._GetPropertyValue);this._AddConfigObject(types.OTHER,this._GetCommonConfig,getters._GetPropertyValue)}static _AddConfigObject(name,configGetter,valueGetter){TWEEN_CONFIGURATIONS.set(name,this._CreateConfigObject(name,configGetter,valueGetter))}static _CreateConfigObject(name,configFunc,valueGetter){return{name:name,configFunc:configFunc,valueGetter:valueGetter}}static _GetConfig(config,property,startValue,endValue,ease,resultMode,instance){return config.configFunc(property,
+config.valueGetter(startValue),config.valueGetter(endValue),ease,resultMode,instance)}static _GetPairConfig(property,startValues,endValues,ease,resultMode,instance){const properties=NAMESPACE.Maps.GetPairProperties(property);return properties.map((property,index)=>{return{sourceId:"world-instance",property:property,type:"float",valueType:"numeric",startValue:startValues[index],endValue:endValues[index],ease:NAMESPACE.Maps.GetEaseFromIndex(ease),resultMode:resultMode}})}static _GetColorConfig(property,
+startValue,endValue,ease,resultMode,instance){if(C3.Plugins.Text&&instance.GetPlugin()instanceof C3.Plugins.Text)return{sourceId:"plugin",sourceArgs:[7],property:"color",type:"color",valueType:"color",startValue:startValue,endValue:endValue,ease:NAMESPACE.Maps.GetEaseFromIndex(ease),resultMode:resultMode};else return{sourceId:"world-instance",property:property,type:"color",valueType:"color",startValue:startValue,endValue:endValue,ease:NAMESPACE.Maps.GetEaseFromIndex(ease),resultMode:resultMode}}static _GetAngleConfig(property,
+startValue,endValue,ease,resultMode,instance){return{sourceId:"world-instance",property:property,type:"angle",valueType:"angle",startValue:startValue,endValue:endValue,ease:NAMESPACE.Maps.GetEaseFromIndex(ease),resultMode:resultMode}}static _GetCommonConfig(property,startValue,endValue,ease,resultMode,instance){return{sourceId:"world-instance",property:property,type:"float",valueType:"numeric",startValue:startValue,endValue:endValue,ease:NAMESPACE.Maps.GetEaseFromIndex(ease),resultMode:resultMode}}static _GetValueConfig(property,
+startValue,endValue,ease,resultMode,instance){return{sourceId:"value",property:property,type:"float",valueType:"numeric",startValue:startValue,endValue:endValue,ease:NAMESPACE.Maps.GetEaseFromIndex(ease),resultMode:resultMode}}};
+
+}
+
+{
+'use strict';const C3=self.C3;const NAMESPACE=C3.Behaviors.Tween;const COMMON_FIXED_ARGS={resultMode:"absolute"};const COMMON_VARIABLE_ARGS=Object.assign({},COMMON_FIXED_ARGS,{tags:"",property:"",time:0,ease:0,releaseOnComplete:0,loop:false,pingPong:false,repeatCount:1});const ONE_PROPERTY_ARGS=Object.assign({},COMMON_VARIABLE_ARGS,{initialValueMode:"current-state",startValue:0,endValue:0});
+const TWO_PROPERTIES_ARGS=Object.assign({},COMMON_VARIABLE_ARGS,{initialValueMode:"current-state",startValue:[0,0],endValue:[0,0]});const COLOR_PROPERTY_ARGS=Object.assign({},COMMON_VARIABLE_ARGS,{initialValueMode:"current-state",startValue:[0,0,0],endValue:[0,0,0]});const VALUE_PROPERTY_ARGS=Object.assign({},ONE_PROPERTY_ARGS,{initialValueMode:"start-value"});const X=0;const Y=1;const R=0;const G=1;const B=2;
+NAMESPACE.TweenArguments=class TweenArguments{constructor(){}static _SetCommonProperties(argsObject,tags,time,ease,destroyOnComplete,loop,pingPong,repeatCount){argsObject.tags=tags;argsObject.time=time;argsObject.ease=ease;argsObject.releaseOnComplete=destroyOnComplete;argsObject.loop=loop;argsObject.pingPong=pingPong;argsObject.repeatCount=repeatCount}static OneProperty(inst,tags,property,endValue,time,ease,destroyOnComplete,loop,pingPong,repeatCount){const propertyName=typeof property==="string"?
+property:NAMESPACE.Maps.GetSinglePropertyFromIndex(property);const args=NAMESPACE.Maps.IsColorId(propertyName)?COLOR_PROPERTY_ARGS:ONE_PROPERTY_ARGS;this._SetCommonProperties(args,tags,time,ease,destroyOnComplete,loop,pingPong,repeatCount);if(NAMESPACE.Maps.IsColorId(propertyName)){COLOR_PROPERTY_ARGS.endValue[R]=C3.GetRValue(endValue);COLOR_PROPERTY_ARGS.endValue[G]=C3.GetGValue(endValue);COLOR_PROPERTY_ARGS.endValue[B]=C3.GetBValue(endValue);COLOR_PROPERTY_ARGS.property=NAMESPACE.Maps.GetPropertyIndexFromName(propertyName)}else if(NAMESPACE.Maps.IsOpacityId(propertyName))ONE_PROPERTY_ARGS.endValue=
+endValue/100;else ONE_PROPERTY_ARGS.endValue=endValue;args.property=NAMESPACE.Maps.GetPropertyIndexFromName(propertyName);return args}static TwoProperties(inst,tags,property,endValueX,endValueY,time,ease,destroyOnComplete,loop,pingPong,repeatCount){this._SetCommonProperties(TWO_PROPERTIES_ARGS,tags,time,ease,destroyOnComplete,loop,pingPong,repeatCount);const pairName=typeof property==="string"?property:NAMESPACE.Maps.GetPairPropertyFromIndex(property);TWO_PROPERTIES_ARGS.endValue[X]=endValueX;TWO_PROPERTIES_ARGS.endValue[Y]=
+endValueY;TWO_PROPERTIES_ARGS.property=NAMESPACE.Maps.GetPropertyIndexFromName(pairName);return TWO_PROPERTIES_ARGS}static ValueProperty(inst,tags,startValue,endValue,time,ease,destroyOnComplete,loop,pingPong,repeatCount){this._SetCommonProperties(VALUE_PROPERTY_ARGS,tags,time,ease,destroyOnComplete,loop,pingPong,repeatCount);VALUE_PROPERTY_ARGS.startValue=startValue;VALUE_PROPERTY_ARGS.endValue=endValue;VALUE_PROPERTY_ARGS.property=NAMESPACE.Maps.GetPropertyIndexFromName("value");return VALUE_PROPERTY_ARGS}};
+
+}
+
+{
+'use strict';const C3=self.C3;const NAMESPACE=C3.Behaviors.Tween;const TYPE_CHECK_OBJECTS=[];
+NAMESPACE.PropertyTypes=class PropertyTypes{constructor(){}static Pick(property){if(TYPE_CHECK_OBJECTS.length===0){const arr=TYPE_CHECK_OBJECTS;arr.push({checkFunc:NAMESPACE.Maps.IsPairId,result:this.PAIR});arr.push({checkFunc:NAMESPACE.Maps.IsColorId,result:this.COLOR});arr.push({checkFunc:NAMESPACE.Maps.IsAngleId,result:this.ANGLE});arr.push({checkFunc:NAMESPACE.Maps.IsValueId,result:this.VALUE});arr.push({checkFunc:()=>true,result:this.OTHER})}if(C3.IsFiniteNumber(property))property=C3.Behaviors.Tween.Maps.GetPropertyFromIndex(property);
+for(const propertyTypeFunctionObject of TYPE_CHECK_OBJECTS)if(propertyTypeFunctionObject.checkFunc(property))return propertyTypeFunctionObject.result}static get PAIR(){return"pair"}static get COLOR(){return"color"}static get ANGLE(){return"angle"}static get VALUE(){return"value"}static get OTHER(){return"other"}};
+
+}
+
+{
+'use strict';const C3=self.C3;const NAMESPACE=C3.Behaviors.Tween;NAMESPACE.ValueGetters=class ValueGetters{constructor(){}static _GetPropertyAngleValue(value){const r=C3.toRadians(parseFloat(value));return C3.clampAngle(r)}static _GetColorPropertyValue(value){return value.slice(0)}static _GetPropertyValue(value){return value}};
+
+}
+
+{
+'use strict';const C3=self.C3;const C3X=self.C3X;const IBehaviorInstance=self.IBehaviorInstance;const Ease=self.Ease;const NAMESPACE=C3.Behaviors.Tween;const map=new WeakMap;
+const TWEEN_PROPERTIES=new Map([["x",{name:"offsetX",type:"one"}],["y",{name:"offsetY",type:"one"}],["width",{name:"offsetWidth",type:"one"}],["height",{name:"offsetHeight",type:"one"}],["angle",{name:"offsetAngle",type:"one"}],["opacity",{name:"offsetOpacity",type:"one"}],["color",{name:"offsetColor",type:"color"}],["z-elevation",{name:"offsetZElevation",type:"one"}],["x-scale",{name:"offsetScaleX",type:"one"}],["y-scale",{name:"offsetScaleY",type:"one"}],["position",{name:"position",type:"two"}],
+["size",{name:"size",type:"two"}],["scale",{name:"scale",type:"two"}],["value",{name:"value",type:"value"}]]);function getIndexForEase(ease){C3X.RequireString(ease);const easeInternalName=Ease.ToInternal(ease);let easeIndex;if(easeInternalName)easeIndex=Ease.GetIndexForEase(easeInternalName,null);else easeIndex=Ease.GetIndexForEase(ease,null);if(easeIndex===-1)throw new Error(`invalid ease name '${ease}'`);return easeIndex}
+const TWEEN_OPTS={tags:"",destroyOnComplete:false,loop:false,pingPong:false,repeatCount:1,startValue:0};const I_TWEEN_OPTS={easeToIndexFunc:getIndexForEase};
+self.ITweenBehaviorInstance=class ITweenBehaviorInstance extends IBehaviorInstance{constructor(){super();map.set(this,IBehaviorInstance._GetInitInst().GetSdkInstance())}startTween(prop,endValue,time,ease,opts){const inst=map.get(this);if(!inst.IsEnabled()||!inst.IsInstanceValid())return null;const info=TWEEN_PROPERTIES.get(prop);if(!info)throw new Error("invalid tween property");if(info.type==="one"||info.type==="value")C3X.RequireNumber(endValue);else{C3X.RequireArray(endValue);if(info.type==="two"){C3X.RequireNumber(endValue[0]);
+C3X.RequireNumber(endValue[1])}else if(info.type==="color"){C3X.RequireNumber(endValue[0]);C3X.RequireNumber(endValue[1]);C3X.RequireNumber(endValue[2])}}if(prop==="angle")endValue=C3.toDegrees(endValue);else if(prop==="opacity")endValue*=100;else if(prop==="color")endValue=C3.PackRGBEx(endValue[0],endValue[1],endValue[2]);const easeIndex=getIndexForEase(ease);C3X.RequireFiniteNumber(time);opts=Object.assign({},TWEEN_OPTS,opts);if(info.type==="value")C3X.RequireNumber(opts.startValue);let tween;if(info.type===
+"one"||info.type==="color")tween=inst.CreateTween(NAMESPACE.TweenArguments.OneProperty(inst,opts.tags,info.name,endValue,time,easeIndex,!!opts.destroyOnComplete,!!opts.loop,!!opts.pingPong,opts.repeatCount));else if(info.type==="two")tween=inst.CreateTween(NAMESPACE.TweenArguments.TwoProperties(inst,opts.tags,info.name,endValue[0],endValue[1],time,easeIndex,!!opts.destroyOnComplete,!!opts.loop,!!opts.pingPong,opts.repeatCount));else if(info.type==="value")tween=inst.CreateTween(NAMESPACE.TweenArguments.ValueProperty(inst,
+opts.tags,opts.startValue,endValue,time,easeIndex,!!opts.destroyOnComplete,!!opts.loop,!!opts.pingPong,opts.repeatCount));if(!tween.Play())throw new Error("failed to start tween");return tween.GetITweenState(inst,I_TWEEN_OPTS)}*allTweens(){const inst=map.get(this);for(const tween of inst.AllTweens())yield tween.GetITweenState(inst,I_TWEEN_OPTS)}*tweensByTags(tags){C3X.RequireString(tags);const inst=map.get(this);for(const tween of inst.GetTweens(tags))yield tween.GetITweenState(inst,I_TWEEN_OPTS)}get isEnabled(){return map.get(this).IsEnabled()}set isEnabled(e){map.get(this).SetEnabled(e)}};
+
+}
+
+{
+'use strict';{const C3=self.C3;C3.Behaviors.TileMovement=class TileMovementBehavior extends C3.SDKBehaviorBase{constructor(opts){super(opts)}Release(){super.Release()}}}{const C3=self.C3;C3.Behaviors.TileMovement.Type=class TileMovementType extends C3.SDKBehaviorTypeBase{constructor(behaviorType){super(behaviorType)}Release(){super.Release()}OnCreate(){}}}
+{const C3=self.C3;const C3X=self.C3X;const IBehaviorInstance=self.IBehaviorInstance;const GRID_WIDTH=0;const GRID_HEIGHT=1;const GRID_OFFSET_X=2;const GRID_OFFSET_Y=3;const SPEED_X=4;const SPEED_Y=5;const ENABLED=6;const DEFAULT_CONTROLS=7;const MIN_OFFSET=.01;const PUSH_BACK_SPEED=10;const tempCandidates=[];C3.Behaviors.TileMovement.Instance=class TileMovementInstance extends C3.SDKBehaviorInstanceBase{constructor(behInst,properties){super(behInst);this._upKey=false;this._downKey=false;this._leftKey=
+false;this._rightKey=false;this._ignoreInput=false;this._simUp=false;this._simDown=false;this._simLeft=false;this._simRight=false;this._gridWidth=32;this._gridHeight=32;this._gridOffsetX=0;this._gridOffsetY=0;this._speedX=100;this._speedY=100;this._isEnabled=true;this._defaultControls=true;this._iso=false;if(properties){this._gridWidth=properties[0];this._gridHeight=properties[1];this._gridOffsetX=properties[2];this._gridOffsetY=properties[3];this._speedX=properties[4];this._speedY=properties[5];
+this._isEnabled=properties[6];this._defaultControls=properties[7];this._iso=properties[8]}this._targetX=0;this._targetY=0;this._targetGridX=0;this._targetGridY=0;this._lastX=NaN;this._lastY=NaN;this._lastX2=NaN;this._lastY2=NaN;this._collisionRect=C3.New(C3.Rect);this._disposables=null;if(this._isEnabled)this._StartTicking();if(this._defaultControls)this._BindEvents();this._ResetTarget()}Release(){this._UnBindEvents();super.Release()}_BindEvents(){if(this._disposables)return;const rt=this._runtime.Dispatcher();
+this._disposables=new C3.CompositeDisposable(C3.Disposable.From(rt,"keydown",e=>this._OnKeyDown(e.data)),C3.Disposable.From(rt,"keyup",e=>this._OnKeyUp(e.data)),C3.Disposable.From(rt,"window-blur",()=>this._OnWindowOrKeyboardBlur()),C3.Disposable.From(rt,"keyboard-blur",()=>this._OnWindowOrKeyboardBlur()))}_UnBindEvents(){if(!this._disposables)return;this._disposables.Release();this._disposables=null}_OnKeyDown(data){switch(data["key"]){case "ArrowLeft":this._leftKey=true;break;case "ArrowUp":this._upKey=
+true;break;case "ArrowRight":this._rightKey=true;break;case "ArrowDown":this._downKey=true;break}}_OnKeyUp(data){switch(data["key"]){case "ArrowLeft":this._leftKey=false;break;case "ArrowUp":this._upKey=false;break;case "ArrowRight":this._rightKey=false;break;case "ArrowDown":this._downKey=false;break}}_OnWindowOrKeyboardBlur(){this._upKey=false;this._downKey=false;this._leftKey=false;this._rightKey=false}_ResetLastPositions(){this._lastX=NaN;this._lastY=NaN;this._lastX2=NaN;this._lastY2=NaN}SaveToJson(){return{"gw":this._gridWidth,
+"gh":this._gridHeight,"ox":this._gridOffsetX,"oy":this._gridOffsetY,"sx":this._speedX,"sy":this._speedY,"x":this._targetX,"y":this._targetY,"gx":this._targetGridX,"gy":this._targetGridY,"e":this._isEnabled,"i":this._ignoreInput,"c":this._defaultControls}}LoadFromJson(o){this._gridWidth=o["gw"];this._gridHeight=o["gh"];this._gridOffsetX=o["ox"];this._gridOffsetY=o["oy"];this._speedX=o["sx"];this._speedY=o["sy"];this._targetX=o["x"];this._targetY=o["y"];this._targetGridX=o["gx"];this._targetGridY=o["gy"];
+this._isEnabled=!!o["e"];this._ignoreInput=!!o["i"];this._defaultControls=!!o["c"];if(this._isEnabled)this._StartTicking();else{this._simLeft=false;this._simRight=false;this._simUp=false;this._simDown=false;this._StopTicking()}if(this._defaultControls)this._BindEvents();else this._UnBindEvents();this._ResetLastPositions()}_GetTargetDelta(){const wi=this.GetWorldInfo();const dx=this._targetX-wi.GetX();const dy=this._targetY-wi.GetY();return[dx,dy]}IsMoving(){const [dx,dy]=this._GetTargetDelta();return Math.abs(dx)>
+0&&this._speedX!==0||Math.abs(dy)>0&&this._speedY!==0}IsMovingDirection(dir){const [dx,dy]=this._GetTargetDelta();if(dir<2&&this._speedX!==0)return dir===0?dx>0:dx<0;else if(this._speedY!==0)return dir===2?dy>0:dy<0;else return false}CanMoveTo(x,y){const wi=this.GetWorldInfo();const oldX=wi.GetX();const oldY=wi.GetY();const pos=this._WorldPosition(x,y);wi.SetX(pos[0]);wi.SetY(pos[1]);wi.SetBboxChanged();const collision=this._TestCollision();wi.SetX(oldX);wi.SetY(oldY);wi.SetBboxChanged();return!collision}CanMoveDirection(dir,
+distance){const wi=this.GetWorldInfo();const oldX=wi.GetX();const oldY=wi.GetY();let incrementX=0;let incrementY=0;switch(dir){case 0:incrementX=1;break;case 1:incrementX=-1;break;case 2:incrementY=1;break;case 3:incrementY=-1;break}distance=Math.floor(distance);if(distance<0){incrementX=-incrementX;incrementY=-incrementY;distance=-distance}let x=this._GridX(oldX,oldY);let y=this._GridY(oldX,oldY);let collision=null;for(let i=0;iPUSH_BACK_SPEED)cappedMovement=true;overlapX=Math.min(overlapX,PUSH_BACK_SPEED);if(a.getLeft()PUSH_BACK_SPEED)cappedMovement=true;overlapY=Math.min(overlapY,PUSH_BACK_SPEED);
+if(a.getTop()0){const n=Math.sign(dx);const moveLeft=n<0&&left;const moveRight=n>0&&right;if(moveLeft||moveRight)while(adx0){const n=Math.sign(dy);const moveDown=n>0&&down;const moveUp=n<0&&up;if(moveDown||moveUp)while(ady=this._gridWidth||Math.abs(this._lastY-this._lastY2)>=this._gridHeight){const [cgx,cgy]=this._GridPosition(this._lastX,this._lastY);this._UpdateTarget(Math.floor(cgx)+
+(offX>0?1:0),Math.floor(cgy)+(offY>0?1:0))}else{wi.OffsetXY(offX,offY);wi.SetBboxChanged();this._MaybePushOut()}}else{if(this._speedX!==0)if(left)this._UpdateTarget(tx-1,ty);else if(right)this._UpdateTarget(tx+1,ty);if(this._speedY!==0)if(!left&&!right&&up)this._UpdateTarget(tx,ty-1);else if(down)this._UpdateTarget(tx,ty+1)}}GetPropertyValueByIndex(index){switch(index){case GRID_WIDTH:return this._gridWidth;case GRID_HEIGHT:return this._gridHeight;case GRID_OFFSET_X:return this._gridOffsetX;case GRID_OFFSET_Y:return this._gridOffsetY;
+case SPEED_X:return this._speedX;case SPEED_Y:return this._speedY;case ENABLED:return this._isEnabled;case DEFAULT_CONTROLS:return this._defaultControls}}SetPropertyValueByIndex(index,value){switch(index){case GRID_WIDTH:this._gridWidth=value;this._TargetCurrentPositon();break;case GRID_HEIGHT:this._gridHeight=value;this._TargetCurrentPositon();break;case GRID_OFFSET_X:this._gridOffsetX=value;this._TargetCurrentPositon();break;case GRID_OFFSET_Y:this._gridOffsetY=value;this._TargetCurrentPositon();
+break;case SPEED_X:this._speedX=value;break;case SPEED_Y:this._speedY=value;break;case ENABLED:this.SetEnabled(value);break;case DEFAULT_CONTROLS:this._SetDefaultControls(value);break}}SetEnabled(e){e=!!e;if(this._isEnabled===e)return;this._isEnabled=e;if(this._isEnabled)this._StartTicking();else{this._simLeft=false;this._simRight=false;this._simUp=false;this._simDown=false;this._StopTicking()}this._ResetLastPositions()}_SetDefaultControls(d){d=!!d;if(this._defaultControls===d)return;this._defaultControls=
+d;if(this._defaultControls)this._BindEvents();else{this._UnBindEvents();this._OnWindowOrKeyboardBlur()}}GetDebuggerProperties(){const prefix="behaviors.tilemovement";const wi=this.GetWorldInfo();const gridPosition=this._GridPosition(wi.GetX(),wi.GetY());return[{title:"$"+this.GetBehaviorType().GetName(),properties:[{name:prefix+".debugger.grid-x",value:gridPosition[0],onedit:v=>{const position=this._WorldPosition(v,gridPosition[1]);wi.SetX(position[0]);wi.SetBboxChanged()}},{name:prefix+".debugger.grid-y",
+value:gridPosition[1],onedit:v=>{const position=this._WorldPosition(gridPosition[0],v);wi.SetY(position[1]);wi.SetBboxChanged()}},{name:prefix+".properties.grid-width.name",value:this._gridWidth,onedit:v=>{this._gridWidth=v;this._TargetCurrentPositon()}},{name:prefix+".properties.grid-height.name",value:this._gridHeight,onedit:v=>{this._gridHeight=v;this._TargetCurrentPositon()}},{name:prefix+".properties.grid-offset-x.name",value:this._gridOffsetX,onedit:v=>{this._gridOffsetX=v;this._TargetCurrentPositon()}},
+{name:prefix+".properties.grid-offset-y.name",value:this._gridOffsetY,onedit:v=>{this._gridOffsetY=v;this._TargetCurrentPositon()}},{name:prefix+".properties.speed-x.name",value:this._speedX,onedit:v=>this._speedX=v},{name:prefix+".properties.speed-y.name",value:this._speedY,onedit:v=>this._speedY=v},{name:prefix+".debugger.target-x",value:this._targetX,onedit:v=>{this._targetX=v;const position=this._ClampedGridPosition(this._targetX,this._targetY);this._targetGridX=position[0];this._ResetLastPositions()}},
+{name:prefix+".debugger.target-y",value:this._targetY,onedit:v=>{this._targetY=v;const position=this._ClampedGridPosition(this._targetX,this._targetY);this._targetGridY=position[1];this._ResetLastPositions()}},{name:prefix+".debugger.grid-target-x",value:this._targetGridX,onedit:v=>{this._targetGridX=v;const position=this._WorldPosition(this._targetGridX,this._targetGridY);this._targetX=position[0]}},{name:prefix+".debugger.grid-target-y",value:this._targetGridY,onedit:v=>{this._targetGridY=v;const position=
+this._WorldPosition(this._targetGridX,this._targetGridY);this._targetY=position[1]}},{name:prefix+".properties.enabled.name",value:this._isEnabled,onedit:v=>this.SetEnabled(v)},{name:prefix+".properties.default-controls.name",value:this._defaultControls,onedit:v=>this._SetDefaultControls(v)}]}]}GetScriptInterfaceClass(){return self.ITileMovementBehaviorInstance}};const map=new WeakMap;self.ITileMovementBehaviorInstance=class ITileMovementBehaviorInstance extends IBehaviorInstance{constructor(){super();
+map.set(this,IBehaviorInstance._GetInitInst().GetSdkInstance())}set isIgnoringInput(ignore){map.get(this).SetIgnoreInput(!!ignore)}get isIgnoringInput(){return map.get(this)._ignoreInput}simulateControl(dir){C3X.RequireString(dir);let ctrl=-1;switch(dir){case "left":ctrl=0;break;case "right":ctrl=1;break;case "up":ctrl=2;break;case "down":ctrl=3;break;default:throw new Error(`Invalid direction ${dir}`);}map.get(this).SimulateControl(ctrl)}set isEnabled(enable){map.get(this).SetEnabled(!!enable)}get isEnabled(){return map.get(this)._isEnabled}get isDefaultControls(){return map.get(this).GetDefaultControls()}set isDefaultControls(d){map.get(this)._SetDefaultControls(!!d)}setSpeed(x,
+y){C3X.RequireFiniteNumber(x);C3X.RequireFiniteNumber(y);map.get(this).SetSpeed(x,y)}getSpeed(){const inst=map.get(this);return[inst._speedX,inst._speedY]}setGridPosition(x,y,immediate){C3X.RequireFiniteNumber(x);C3X.RequireFiniteNumber(y);map.get(this).SetGridPosition(x,y,!!immediate)}getGridPosition(){const inst=map.get(this);const wi=inst.GetWorldInfo();const x=wi.GetX();const y=wi.GetY();return[inst._GridX(x,y),inst._GridY(x,y)]}modifyGridDimensions(width,height,x,y){C3X.RequireFiniteNumber(width);
+C3X.RequireFiniteNumber(height);C3X.RequireFiniteNumber(x);C3X.RequireFiniteNumber(y);map.get(this).SetGridDimensions(width,height,x,y)}isMoving(){return map.get(this).IsMoving()}isMovingDirection(dir){C3X.RequireString(dir);let ctrl=-1;switch(dir){case "right":ctrl=0;break;case "left":ctrl=1;break;case "down":ctrl=2;break;case "up":ctrl=3;break;default:throw new Error(`Invalid direction ${dir}`);}return map.get(this).IsMovingDirection(ctrl)}canMoveTo(x,y){C3X.RequireFiniteNumber(x);C3X.RequireFiniteNumber(y);
+return map.get(this).CanMoveTo(x,y)}canMoveDirection(dir,distance){C3X.RequireString(dir);let ctrl=-1;switch(dir){case "right":ctrl=0;break;case "left":ctrl=1;break;case "down":ctrl=2;break;case "up":ctrl=3;break;default:throw new Error(`invalid direction '${dir}'`);}return map.get(this).CanMoveDirection(ctrl,distance)}getTargetPosition(){const inst=map.get(this);return[inst._targetX,inst._targetY]}getGridTargetPosition(){const inst=map.get(this);return[inst._targetGridX,inst._targetGridY]}toGridSpace(x,
+y){C3X.RequireFiniteNumber(x);C3X.RequireFiniteNumber(y);return map.get(this)._GridPosition(x,y)}fromGridSpace(x,y){C3X.RequireFiniteNumber(x);C3X.RequireFiniteNumber(y);return map.get(this)._WorldPosition(x,y)}}}{const C3=self.C3;C3.Behaviors.TileMovement.Cnds={IsMoving(){return this.IsMoving()},IsMovingDirection(dir){return this.IsMovingDirection(dir)},IsEnabled(){return this._isEnabled},CanMoveTo(x,y){return this.CanMoveTo(x,y)},CanMoveDirection(dir,distance){return this.CanMoveDirection(dir,distance)}}}
+{const C3=self.C3;C3.Behaviors.TileMovement.Acts={SetIgnoreInput(ignore){this.SetIgnoreInput(ignore)},SimulateControl(ctrl){this.SimulateControl(ctrl)},SetEnabled(e){this.SetEnabled(e)},SetSpeed(x,y){this.SetSpeed(x,y)},SetGridPosition(x,y,immediate){this.SetGridPosition(x,y,immediate)},SetGridDimensions(width,height,x,y){this.SetGridDimensions(width,height,x,y)},SetDefaultControls(d){this._SetDefaultControls(!!d)}}}
+{const C3=self.C3;C3.Behaviors.TileMovement.Exps={GridX(){const wi=this.GetWorldInfo();return this._GridX(wi.GetX(),wi.GetY())},GridY(){const wi=this.GetWorldInfo();return this._GridY(wi.GetX(),wi.GetY())},SpeedX(){return this._speedX},SpeedY(){return this._speedY},TargetX(){return this._targetX},TargetY(){return this._targetY},GridTargetX(){return this._targetGridX},GridTargetY(){return this._targetGridY}}};
+
+}
+
+{
+'use strict';{const C3=self.C3;C3.Behaviors.bound=class BoundBehavior extends C3.SDKBehaviorBase{constructor(opts){super(opts)}Release(){super.Release()}}}{const C3=self.C3;C3.Behaviors.bound.Type=class BoundType extends C3.SDKBehaviorTypeBase{constructor(behaviorType){super(behaviorType)}Release(){super.Release()}OnCreate(){}}}
+{const C3=self.C3;const MODE=0;C3.Behaviors.bound.Instance=class BoundInstance extends C3.SDKBehaviorInstanceBase{constructor(behInst,properties){super(behInst);this._mode=0;if(properties)this._mode=properties[MODE];this._StartTicking2()}Release(){super.Release()}SaveToJson(){return{"m":this._mode}}LoadFromJson(o){this._mode=o["m"]}Tick2(){const wi=this._inst.GetWorldInfo();const bbox=wi.GetBoundingBox();const layout=wi.GetLayout();let isChanged=false;if(this._mode===0){if(wi.GetX()<0){wi.SetX(0);
+isChanged=true}if(wi.GetY()<0){wi.SetY(0);isChanged=true}if(wi.GetX()>layout.GetWidth()){wi.SetX(layout.GetWidth());isChanged=true}if(wi.GetY()>layout.GetHeight()){wi.SetY(layout.GetHeight());isChanged=true}}else{if(bbox.getLeft()<0){wi.OffsetX(-bbox.getLeft());isChanged=true}if(bbox.getTop()<0){wi.OffsetY(-bbox.getTop());isChanged=true}if(bbox.getRight()>layout.GetWidth()){wi.OffsetX(-(bbox.getRight()-layout.GetWidth()));isChanged=true}if(bbox.getBottom()>layout.GetHeight()){wi.OffsetY(-(bbox.getBottom()-
+layout.GetHeight()));isChanged=true}}if(isChanged)wi.SetBboxChanged()}GetPropertyValueByIndex(index){switch(index){case MODE:return this._mode}}SetPropertyValueByIndex(index,value){switch(index){case MODE:this._mode=value;break}}}}{const C3=self.C3;C3.Behaviors.bound.Cnds={}}{const C3=self.C3;C3.Behaviors.bound.Acts={}}{const C3=self.C3;C3.Behaviors.bound.Exps={}};
+
+}
+
+{
+'use strict';{const C3=self.C3;C3.Behaviors.solid=class SolidBehavior extends C3.SDKBehaviorBase{constructor(opts){super(opts)}Release(){super.Release()}}}{const C3=self.C3;C3.Behaviors.solid.Type=class SolidType extends C3.SDKBehaviorTypeBase{constructor(behaviorType){super(behaviorType)}Release(){super.Release()}OnCreate(){}}}
+{const C3=self.C3;const C3X=self.C3X;const IBehaviorInstance=self.IBehaviorInstance;const ENABLE=0;const TAGS=1;const EMPTY_SET=new Set;C3.Behaviors.solid.Instance=class SolidInstance extends C3.SDKBehaviorInstanceBase{constructor(behInst,properties){super(behInst);this.SetEnabled(true);if(properties){this.SetEnabled(properties[ENABLE]);this.SetTags(properties[TAGS])}}Release(){super.Release()}SetEnabled(e){this._inst._SetSolidEnabled(!!e)}IsEnabled(){return this._inst._IsSolidEnabled()}SetTags(tagList){const savedDataMap=
+this._inst.GetSavedDataMap();if(!tagList.trim()){savedDataMap.delete("solidTags");return}let solidTags=savedDataMap.get("solidTags");if(!solidTags){solidTags=new Set;savedDataMap.set("solidTags",solidTags)}solidTags.clear();for(const tag of tagList.split(" "))if(tag)solidTags.add(tag.toLowerCase())}GetTags(){return this._inst.GetSavedDataMap().get("solidTags")||EMPTY_SET}_GetTagsString(){return[...this.GetTags()].join(" ")}SaveToJson(){return{"e":this.IsEnabled()}}LoadFromJson(o){this.SetEnabled(o["e"])}GetPropertyValueByIndex(index){switch(index){case ENABLE:return this.IsEnabled()}}SetPropertyValueByIndex(index,
+value){switch(index){case ENABLE:this.SetEnabled(value);break}}GetDebuggerProperties(){return[{title:"$"+this.GetBehaviorType().GetName(),properties:[{name:"behaviors.solid.properties.enabled.name",value:this.IsEnabled(),onedit:v=>this.SetEnabled(v)},{name:"behaviors.solid.properties.tags.name",value:this._GetTagsString(),onedit:v=>this.SetTags(v)}]}]}GetScriptInterfaceClass(){return self.ISolidBehaviorInstance}};const map=new WeakMap;self.ISolidBehaviorInstance=class ISolidBehaviorInstance extends IBehaviorInstance{constructor(){super();
+map.set(this,IBehaviorInstance._GetInitInst().GetSdkInstance())}set isEnabled(e){map.get(this).SetEnabled(!!e)}get isEnabled(){return map.get(this).IsEnabled()}set tags(str){C3X.RequireString(str);map.get(this).SetTags(str)}get tags(){return map.get(this)._GetTagsString()}}}{const C3=self.C3;C3.Behaviors.solid.Cnds={IsEnabled(){return this.IsEnabled()}}}{const C3=self.C3;C3.Behaviors.solid.Acts={SetEnabled(e){this.SetEnabled(e)},SetTags(tagList){this.SetTags(tagList)}}}
+{const C3=self.C3;C3.Behaviors.solid.Exps={}};
+
+}
+
+{
+const C3 = self.C3;
+self.C3_GetObjectRefTable = function () {
+ return [
+ C3.Plugins.Sprite,
+ C3.Behaviors.Pin,
+ C3.Behaviors.Tween,
+ C3.Behaviors.TileMovement,
+ C3.Behaviors.bound,
+ C3.Plugins.Keyboard,
+ C3.Plugins.Audio,
+ C3.Behaviors.solid,
+ C3.Plugins.Text,
+ C3.Plugins.Date,
+ C3.Plugins.Keyboard.Cnds.OnKey,
+ C3.Behaviors.TileMovement.Acts.SetGridPosition,
+ C3.Behaviors.TileMovement.Exps.GridX,
+ C3.Behaviors.TileMovement.Exps.GridY,
+ C3.Plugins.Sprite.Acts.SetAngle,
+ C3.Plugins.Audio.Acts.Play,
+ C3.Plugins.System.Acts.Wait,
+ C3.Plugins.System.Cnds.OnLayoutStart,
+ C3.Behaviors.Pin.Acts.PinByProperties,
+ C3.Plugins.System.Cnds.Compare,
+ C3.Behaviors.TileMovement.Exps.GridTargetY,
+ C3.Plugins.Sprite.Acts.Destroy,
+ C3.Plugins.System.Acts.AddVar,
+ C3.Plugins.Text.Acts.SetText,
+ C3.Behaviors.TileMovement.Exps.GridTargetX,
+ C3.Plugins.Sprite.Cnds.IsOverlapping,
+ C3.Plugins.System.Acts.NextPrevLayout,
+ C3.Plugins.System.Cnds.EveryTick,
+ C3.Plugins.System.Cnds.CompareVar,
+ C3.Plugins.System.Acts.SetVar,
+ C3.Plugins.Date.Exps.GetUTCSeconds,
+ C3.Plugins.Date.Exps.Now,
+ C3.Behaviors.TileMovement.Cnds.IsMoving,
+ C3.Plugins.System.Cnds.EvaluateExpression,
+ C3.Plugins.System.Exps.random,
+ C3.Plugins.System.Acts.GoToLayout,
+ C3.ScriptsInEvents.EventSheet1_Event12,
+ C3.Plugins.Sprite.Cnds.IsBoolInstanceVarSet,
+ C3.Plugins.Sprite.Acts.SetBoolInstanceVar,
+ C3.Plugins.Sprite.Acts.SetAnim,
+ C3.Plugins.Keyboard.Cnds.OnAnyKey,
+ C3.Plugins.Audio.Acts.StopAll
+ ];
+};
+self.C3_JsPropNameTable = [
+ {Pin: 0},
+ {Rook: 0},
+ {Sprite: 0},
+ {Tween: 0},
+ {Object_Knight: 0},
+ {Object2: 0},
+ {Board: 0},
+ {TileMovement: 0},
+ {BoundToLayout: 0},
+ {Player: 0},
+ {Keyboard: 0},
+ {Audio: 0},
+ {Solid: 0},
+ {Wall_tile: 0},
+ {wall_yellow: 0},
+ {Opning_sprite: 0},
+ {Text: 0},
+ {moves: 0},
+ {wall_green: 0},
+ {Sprite2: 0},
+ {opnning_sprite: 0},
+ {Sprite3: 0},
+ {Text2: 0},
+ {Date: 0},
+ {UICombatBG: 0},
+ {UICombatBar: 0},
+ {Text3: 0},
+ {Text4: 0},
+ {overlap: 0},
+ {wall_blue: 0},
+ {coin: 0},
+ {currentTime: 0},
+ {countDownTimer: 0},
+ {showCountDown: 0},
+ {Total_moves: 0},
+ {ENCOUNTER_CHANCE: 0},
+ {Total_moves2: 0}
+];
+
+self.InstanceType = {
+ Rook: class extends self.ISpriteInstance {},
+ Sprite: class extends self.ISpriteInstance {},
+ Object_Knight: class extends self.ISpriteInstance {},
+ Object2: class extends self.ISpriteInstance {},
+ Board: class extends self.ISpriteInstance {},
+ Player: class extends self.ISpriteInstance {},
+ Keyboard: class extends self.IInstance {},
+ Audio: class extends self.IInstance {},
+ Wall_tile: class extends self.ISpriteInstance {},
+ wall_yellow: class extends self.ISpriteInstance {},
+ Opning_sprite: class extends self.ISpriteInstance {},
+ Text: class extends self.ITextInstance {},
+ moves: class extends self.ITextInstance {},
+ wall_green: class extends self.ISpriteInstance {},
+ Sprite2: class extends self.ISpriteInstance {},
+ opnning_sprite: class extends self.ISpriteInstance {},
+ Sprite3: class extends self.ISpriteInstance {},
+ Text2: class extends self.ITextInstance {},
+ Date: class extends self.IInstance {},
+ UICombatBG: class extends self.ISpriteInstance {},
+ UICombatBar: class extends self.ISpriteInstance {},
+ Text3: class extends self.ITextInstance {},
+ Text4: class extends self.ITextInstance {},
+ wall_blue: class extends self.ISpriteInstance {},
+ coin: class extends self.ISpriteInstance {}
+}
+}
+
+{
+
+const C3 = self.C3;
+
+function unaryminus(n)
+{
+ return (typeof n === "number" ? -n : n);
+}
+
+function bothNumbers(a, b)
+{
+ return typeof a === "number" && typeof b === "number";
+}
+
+function add(l, r)
+{
+ if (bothNumbers(l, r))
+ return l + r;
+ else
+ return l;
+}
+
+function subtract(l, r)
+{
+ if (bothNumbers(l, r))
+ return l - r;
+ else
+ return l;
+}
+
+function multiply(l, r)
+{
+ if (bothNumbers(l, r))
+ return l * r;
+ else
+ return l;
+}
+
+function divide(l, r)
+{
+ if (bothNumbers(l, r))
+ return l / r;
+ else
+ return l;
+}
+
+function mod(l, r)
+{
+ if (bothNumbers(l, r))
+ return l % r;
+ else
+ return l;
+}
+
+function pow(l, r)
+{
+ if (bothNumbers(l, r))
+ return Math.pow(l, r);
+ else
+ return l;
+}
+
+function and(l, r)
+{
+ if (typeof l === "string" || typeof r === "string")
+ {
+ // & with either side string does string concatenation
+ let lstr, rstr;
+
+ if (typeof l === "number")
+ lstr = (Math.round(l * 1e10) / 1e10).toString();
+ else
+ lstr = l;
+
+ if (typeof r === "number")
+ rstr = (Math.round(r * 1e10) / 1e10).toString();
+ else
+ rstr = r;
+
+ return lstr + rstr;
+ }
+ else
+ {
+ // & with neither side a string does logical AND
+ return (l && r ? 1 : 0);
+ }
+}
+
+function or(l, r)
+{
+ if (bothNumbers(l, r))
+ return (l || r ? 1 : 0);
+ else
+ return l;
+}
+
+self.C3_ExpressionFuncs = [
+ p => {
+ const n0 = p._GetNode(0);
+ return () => (n0.ExpBehavior() + 1);
+ },
+ p => {
+ const n0 = p._GetNode(0);
+ return () => n0.ExpBehavior();
+ },
+ () => 10,
+ () => -10,
+ () => 0,
+ () => "",
+ () => 0.1,
+ p => {
+ const n0 = p._GetNode(0);
+ return () => (n0.ExpBehavior() - 1);
+ },
+ () => 2,
+ () => 3,
+ () => 1,
+ p => {
+ const v0 = p._GetNode(0).GetVar();
+ return () => and("Moves: ", v0.GetValue());
+ },
+ p => {
+ const f0 = p._GetNode(0).GetBoundMethod();
+ const f1 = p._GetNode(1).GetBoundMethod();
+ return () => f0(f1());
+ },
+ p => {
+ const f0 = p._GetNode(0).GetBoundMethod();
+ return () => ((f0(15)) < (1) ? 1 : 0);
+ },
+ () => "king"
+];
+
+
+}
+
diff --git a/scripts/dispatchworker.js b/scripts/dispatchworker.js
new file mode 100644
index 0000000..74aff55
--- /dev/null
+++ b/scripts/dispatchworker.js
@@ -0,0 +1,10 @@
+'use strict';self.inputPort=null;self.jobQueue=[];self.jobWorkers=[];self.sentBlobs=[];self.sentBuffers=[];self.importedScripts=[];self.lastBroadcasts=new Map;
+class JobWorker{constructor(port,number){this._port=port;this._number=number;this._isReady=false;this._isBusy=false;this._port.onmessage=e=>this._OnMessage(e.data)}ImportScripts(scripts){this._port.postMessage({"type":"_import_scripts","scripts":scripts})}SendBlob(blob,id){this._port.postMessage({"type":"_send_blob","blob":blob,"id":id})}SendBuffer(buffer,id){this._port.postMessage({"type":"_send_buffer","buffer":buffer,"id":id})}SendJob(job){if(this._isBusy||!this._isReady)throw new Error("cannot take job");
+this._isBusy=true;this._port.postMessage(job,job["transferables"])}_InitBroadcast(job){this._port.postMessage(job,job["transferables"])}SendReady(){this._port.postMessage({"type":"_ready"})}IsReady(){return this._isReady}_OnReady(){this._isReady=true;this.MaybeStartNextJob()}IsBusy(){return this._isBusy}GetNumber(){return this._number}_OnMessage(msg){const type=msg["type"];switch(type){case "ready":this._OnReady();return;case "done":this._OnJobDone();return;default:console.error("unknown message from worker '"+
+type+"'");return}}_OnJobDone(){this._isBusy=false;this.MaybeStartNextJob()}MaybeStartNextJob(){if(this._isBusy||!this._isReady)return;const i=this._FindAvailableJob();if(i===-1)return;const job=self.jobQueue[i];const isBroadcast=job["isBroadcast"];if(isBroadcast){job["doneFlags"][this._number]=true;if(job["doneFlags"].every(x=>x))self.jobQueue.splice(i,1)}else self.jobQueue.splice(i,1);this.SendJob(job)}_FindAvailableJob(){for(let i=0,len=self.jobQueue.length;i=job["maxWorkerNum"])continue;if(!job["isBroadcast"]||this._number{const msg=e.data;const type=msg["type"];if(type==="_init"){self.inputPort=msg["in-port"];self.inputPort.onmessage=OnInputPortMessage}else if(type==="_addJobWorker")AddJobWorker(msg["port"])});
+function OnInputPortMessage(e){const msg=e.data;const type=msg["type"];if(type==="_cancel"){CancelJob(msg.jobId);return}else if(type==="_import_scripts"){const scripts=msg["scripts"];for(const w of self.jobWorkers)w.ImportScripts(scripts);self.importedScripts.push(scripts);return}else if(type==="_send_blob"){const blob=msg["blob"];const id=msg["id"];for(const w of self.jobWorkers)w.SendBlob(blob,id);self.sentBlobs.push([blob,id]);return}else if(type==="_send_buffer"){const buffer=msg["buffer"];const id=
+msg["id"];for(const w of self.jobWorkers)w.SendBuffer(buffer,id);self.sentBuffers.push([buffer,id]);return}else if(type==="_no_more_workers"){self.sentBlobs.length=0;self.sentBuffers.length=0;self.importedScripts.length=0;self.lastBroadcasts.clear();return}self.jobQueue.push(msg);if(msg["isBroadcast"]){const maxWorkerNum=msg["maxWorkerNum"];const curWorkerCount=self.jobWorkers.length;const useWorkerCount=typeof maxWorkerNum==="number"?Math.min(maxWorkerNum,curWorkerCount):curWorkerCount;msg["doneFlags"]=
+(new Array(useWorkerCount)).fill(false);msg["transferables"]=[];const broadcastKey=msg["params"]&&msg["params"]["broadcastKey"]?msg["params"]["broadcastKey"]:msg["type"];self.lastBroadcasts.delete(broadcastKey);self.lastBroadcasts.set(broadcastKey,msg)}for(const w of self.jobWorkers)w.MaybeStartNextJob()};
diff --git a/scripts/jobworker.js b/scripts/jobworker.js
new file mode 100644
index 0000000..6f5140f
--- /dev/null
+++ b/scripts/jobworker.js
@@ -0,0 +1,9 @@
+'use strict';self.dispatchPort=null;self.outputPort=null;self.workerNumber=-1;self.activeJobId=null;self.sentBlobs=new Map;self.sentBuffers=new Map;self.JobHandlers={};
+function FlipImageData(data,width,height){const stride=width*4;const tempRow=new Uint8Array(stride);const imageBuffer=data.buffer;for(let topY=0,len=Math.floor(height/2);topY{const msg=e.data;const type=msg["type"];switch(type){case "init":self.workerNumber=msg["number"];self.dispatchPort=msg["dispatch-port"];self.dispatchPort.onmessage=OnDispatchWorkerMessage;self.outputPort=msg["output-port"];return;case "terminate":self.close();return;default:console.error("unknown message '"+type+"'");return}});function SendReady(){self.dispatchPort.postMessage({"type":"ready"});self.outputPort.postMessage({"type":"ready"})}
+function SendError(isBroadcast,e){if(!isBroadcast)self.outputPort.postMessage({"type":"error","jobId":self.activeJobId,"error":e.toString()});SendDone()}function SendResult(isBroadcast,ret){if(!isBroadcast){const transferables=ret.transferables||[];self.outputPort.postMessage({"type":"result","jobId":self.activeJobId,"result":ret.result},transferables)}SendDone()}function SendDone(){self.activeJobId=null;self.dispatchPort.postMessage({"type":"done"})}
+function SendProgress(val){self.outputPort.postMessage({"type":"progress","jobId":self.activeJobId,"progress":val})}
+function OnDispatchWorkerMessage(e){const msg=e.data;const type=msg["type"];if(type==="_import_scripts"){importScripts(...msg["scripts"]);return}else if(type==="_send_blob"){self.sentBlobs.set(msg["id"],msg["blob"]);return}else if(type==="_send_buffer"){self.sentBuffers.set(msg["id"],msg["buffer"]);return}else if(type==="_ready"){SendReady();return}const jobId=msg["jobId"];const isBroadcast=msg["isBroadcast"];const params=msg["params"];let ret;self.activeJobId=jobId;if(!self.JobHandlers.hasOwnProperty(type)){console.error(`no handler for message type '${type}'`);
+return}try{ret=self.JobHandlers[type](params)}catch(e){SendError(isBroadcast,"Exception in job handler: "+e);return}if(ret&&ret.then)ret.then(asyncRet=>SendResult(isBroadcast,asyncRet)).catch(err=>SendError(isBroadcast,"Rejection in job handler: "+err));else SendResult(isBroadcast,ret)};
diff --git a/scripts/main.js b/scripts/main.js
new file mode 100644
index 0000000..fff524f
--- /dev/null
+++ b/scripts/main.js
@@ -0,0 +1,284 @@
+'use strict';{window.DOMHandler=class DOMHandler{constructor(iRuntime,componentId){this._iRuntime=iRuntime;this._componentId=componentId;this._hasTickCallback=false;this._tickCallback=()=>this.Tick()}Attach(){}PostToRuntime(handler,data,dispatchOpts,transferables){this._iRuntime.PostToRuntimeComponent(this._componentId,handler,data,dispatchOpts,transferables)}PostToRuntimeAsync(handler,data,dispatchOpts,transferables){return this._iRuntime.PostToRuntimeComponentAsync(this._componentId,handler,data,
+dispatchOpts,transferables)}_PostToRuntimeMaybeSync(name,data,dispatchOpts){if(this._iRuntime.UsesWorker())this.PostToRuntime(name,data,dispatchOpts);else this._iRuntime._GetLocalRuntime()["_OnMessageFromDOM"]({"type":"event","component":this._componentId,"handler":name,"dispatchOpts":dispatchOpts||null,"data":data,"responseId":null})}AddRuntimeMessageHandler(handler,func){this._iRuntime.AddRuntimeComponentMessageHandler(this._componentId,handler,func)}AddRuntimeMessageHandlers(list){for(const [handler,
+func]of list)this.AddRuntimeMessageHandler(handler,func)}GetRuntimeInterface(){return this._iRuntime}GetComponentID(){return this._componentId}_StartTicking(){if(this._hasTickCallback)return;this._iRuntime._AddRAFCallback(this._tickCallback);this._hasTickCallback=true}_StopTicking(){if(!this._hasTickCallback)return;this._iRuntime._RemoveRAFCallback(this._tickCallback);this._hasTickCallback=false}Tick(){}};window.RateLimiter=class RateLimiter{constructor(callback,interval){this._callback=callback;
+this._interval=interval;this._timerId=-1;this._lastCallTime=-Infinity;this._timerCallFunc=()=>this._OnTimer();this._ignoreReset=false;this._canRunImmediate=false}SetCanRunImmediate(c){this._canRunImmediate=!!c}Call(){if(this._timerId!==-1)return;const nowTime=Date.now();const timeSinceLastCall=nowTime-this._lastCallTime;const interval=this._interval;if(timeSinceLastCall>=interval&&this._canRunImmediate){this._lastCallTime=nowTime;this._RunCallback()}else this._timerId=self.setTimeout(this._timerCallFunc,
+Math.max(interval-timeSinceLastCall,4))}_RunCallback(){this._ignoreReset=true;this._callback();this._ignoreReset=false}Reset(){if(this._ignoreReset)return;this._CancelTimer();this._lastCallTime=Date.now()}_OnTimer(){this._timerId=-1;this._lastCallTime=Date.now();this._RunCallback()}_CancelTimer(){if(this._timerId!==-1){self.clearTimeout(this._timerId);this._timerId=-1}}Release(){this._CancelTimer();this._callback=null;this._timerCallFunc=null}}};
+
+
+'use strict';{class ElementState{constructor(elem){this._elem=elem;this._hadFirstUpdate=false;this._isVisibleFlag=true;this._wantHtmlIndex=-1;this._actualHtmlIndex=-1;this._htmlZIndex=-1}SetVisibleFlag(f){this._isVisibleFlag=!!f}GetVisibleFlag(){return this._isVisibleFlag}HadFirstUpdate(){return this._hadFirstUpdate}SetHadFirstUpdate(){this._hadFirstUpdate=true}GetWantHTMLIndex(){return this._wantHtmlIndex}SetWantHTMLIndex(i){this._wantHtmlIndex=i}GetActualHTMLIndex(){return this._actualHtmlIndex}SetActualHTMLIndex(i){this._actualHtmlIndex=
+i}SetHTMLZIndex(z){this._htmlZIndex=z}GetHTMLZIndex(){return this._htmlZIndex}GetElement(){return this._elem}}window.DOMElementHandler=class DOMElementHandler extends self.DOMHandler{constructor(iRuntime,componentId){super(iRuntime,componentId);this._elementMap=new Map;this._autoAttach=true;this.AddRuntimeMessageHandlers([["create",e=>this._OnCreate(e)],["destroy",e=>this._OnDestroy(e)],["set-visible",e=>this._OnSetVisible(e)],["update-position",e=>this._OnUpdatePosition(e)],["update-state",e=>this._OnUpdateState(e)],
+["focus",e=>this._OnSetFocus(e)],["set-css-style",e=>this._OnSetCssStyle(e)],["set-attribute",e=>this._OnSetAttribute(e)],["remove-attribute",e=>this._OnRemoveAttribute(e)]]);this.AddDOMElementMessageHandler("get-element",elem=>elem)}SetAutoAttach(e){this._autoAttach=!!e}AddDOMElementMessageHandler(handler,func){this.AddRuntimeMessageHandler(handler,e=>{const elementId=e["elementId"];const elem=this.GetElementById(elementId);return func(elem,e)})}_OnCreate(e){const elementId=e["elementId"];const elem=
+this.CreateElement(elementId,e);const elementState=new ElementState(elem);this._elementMap.set(elementId,elementState);elem.style.boxSizing="border-box";elem.style.display="none";elementState.SetVisibleFlag(e["isVisible"]);const focusElem=this._GetFocusElement(elem);focusElem.addEventListener("focus",e=>this._OnFocus(elementId));focusElem.addEventListener("blur",e=>this._OnBlur(elementId));const wantHtmlIndex=e["htmlIndex"];elementState.SetWantHTMLIndex(wantHtmlIndex);elementState.SetHTMLZIndex(e["htmlZIndex"]);
+if(this._autoAttach){const actualHtmlIndex=this.GetRuntimeInterface().GetAvailableHTMLIndex(wantHtmlIndex);elementState.SetActualHTMLIndex(actualHtmlIndex);const parent=this.GetRuntimeInterface().GetHTMLWrapElement(actualHtmlIndex);parent.appendChild(elem)}}CreateElement(elementId,e){throw new Error("required override");}DestroyElement(elem){}_OnDestroy(e){const elementId=e["elementId"];const elem=this.GetElementById(elementId);this.DestroyElement(elem);if(this._autoAttach)elem.parentElement.removeChild(elem);
+this._elementMap.delete(elementId)}PostToRuntimeElement(handler,elementId,data){if(!data)data={};data["elementId"]=elementId;this.PostToRuntime(handler,data)}_PostToRuntimeElementMaybeSync(handler,elementId,data){if(!data)data={};data["elementId"]=elementId;this._PostToRuntimeMaybeSync(handler,data)}_OnSetVisible(e){if(!this._autoAttach)return;const elemState=this._elementMap.get(e["elementId"]);const elem=elemState.GetElement();if(elemState.HadFirstUpdate())elem.style.display=e["isVisible"]?"":"none";
+else elemState.SetVisibleFlag(e["isVisible"])}_OnUpdatePosition(e){if(!this._autoAttach)return;const elemState=this._elementMap.get(e["elementId"]);const elem=elemState.GetElement();const iRuntime=this.GetRuntimeInterface();elem.style.left=e["left"]+"px";elem.style.top=e["top"]+"px";elem.style.width=e["width"]+"px";elem.style.height=e["height"]+"px";const fontSize=e["fontSize"];if(fontSize!==null)elem.style.fontSize=fontSize+"em";const wantHtmlIndex=e["htmlIndex"];elemState.SetWantHTMLIndex(wantHtmlIndex);
+const actualHtmlIndex=iRuntime.GetAvailableHTMLIndex(wantHtmlIndex);if(actualHtmlIndex!==elemState.GetActualHTMLIndex()){elem.remove();const parent=iRuntime.GetHTMLWrapElement(actualHtmlIndex);parent.appendChild(elem);elemState.SetActualHTMLIndex(actualHtmlIndex);iRuntime._UpdateHTMLElementsZOrder()}const htmlZIndex=e["htmlZIndex"];if(htmlZIndex!==elemState.GetHTMLZIndex()){elemState.SetHTMLZIndex(htmlZIndex);iRuntime._UpdateHTMLElementsZOrder()}if(!elemState.HadFirstUpdate()){elemState.SetHadFirstUpdate();
+if(elemState.GetVisibleFlag())elem.style.display=""}}_OnHTMLLayersChanged(){if(!this._autoAttach)return;for(const elemState of this._elementMap.values()){const wantHtmlIndex=this.GetRuntimeInterface().GetAvailableHTMLIndex(elemState.GetWantHTMLIndex());const actualHtmlIndex=elemState.GetActualHTMLIndex();if(wantHtmlIndex!==-1&&actualHtmlIndex!==-1&&wantHtmlIndex!==actualHtmlIndex){const elem=elemState.GetElement();elem.remove();const parent=this.GetRuntimeInterface().GetHTMLWrapElement(wantHtmlIndex);
+parent.appendChild(elem);elemState.SetActualHTMLIndex(wantHtmlIndex)}}}_GetAllElementStatesForZOrderUpdate(){if(!this._autoAttach)return null;return[...this._elementMap.values()]}_OnUpdateState(e){const elem=this.GetElementById(e["elementId"]);this.UpdateState(elem,e)}UpdateState(elem,e){throw new Error("required override");}_GetFocusElement(elem){return elem}_OnFocus(elementId){this.PostToRuntimeElement("elem-focused",elementId)}_OnBlur(elementId){this.PostToRuntimeElement("elem-blurred",elementId)}_OnSetFocus(e){const elem=
+this._GetFocusElement(this.GetElementById(e["elementId"]));if(e["focus"])elem.focus();else elem.blur()}_OnSetCssStyle(e){const elem=this.GetElementById(e["elementId"]);const prop=e["prop"];const val=e["val"];if(prop.startsWith("--"))elem.style.setProperty(prop,val);else elem.style[prop]=val}_OnSetAttribute(e){const elem=this.GetElementById(e["elementId"]);elem.setAttribute(e["name"],e["val"])}_OnRemoveAttribute(e){const elem=this.GetElementById(e["elementId"]);elem.removeAttribute(e["name"])}GetElementById(elementId){const elementState=
+this._elementMap.get(elementId);if(!elementState)throw new Error(`no element with id ${elementId}`);return elementState.GetElement()}}};
+
+
+'use strict';{const isiOSLike=/(iphone|ipod|ipad|macos|macintosh|mac os x)/i.test(navigator.userAgent);const isAndroid=/android/i.test(navigator.userAgent);const isSafari=/safari/i.test(navigator.userAgent)&&!/(chrome|chromium|edg\/|OPR\/|nwjs)/i.test(navigator.userAgent);let resolveCounter=0;function AddScript(url){const elem=document.createElement("script");elem.async=false;elem.type="module";if(url.isStringSrc)return new Promise(resolve=>{const resolveName="c3_resolve_"+resolveCounter;++resolveCounter;
+self[resolveName]=resolve;elem.textContent=url.str+`\n\nself["${resolveName}"]();`;document.head.appendChild(elem)});else return new Promise((resolve,reject)=>{elem.onload=resolve;elem.onerror=reject;elem.src=url;document.head.appendChild(elem)})}async function CheckSupportsWorkerMode(){if(!navigator["userActivation"]||typeof OffscreenCanvas==="undefined")return false;try{const workerScript=`
+ self.addEventListener("message", () =>
+ {
+ try {
+ const offscreenCanvas = new OffscreenCanvas(32, 32);
+ const gl = offscreenCanvas.getContext("webgl");
+ self.postMessage(!!gl);
+ }
+ catch (err)
+ {
+ console.warn("Feature detection worker error:", err);
+ self.postMessage(false);
+ }
+ });`;let isWorkerModuleSupported=false;const workerScriptBlob=new Blob([workerScript],{"type":"text/javascript"});const w=new Worker(URL.createObjectURL(workerScriptBlob),{get type(){isWorkerModuleSupported=true}});const result=await new Promise(resolve=>{w.addEventListener("message",e=>{w.terminate();resolve(e.data)});w.postMessage("")});return isWorkerModuleSupported&&result}catch(err){console.warn("Error feature detecting worker mode: ",err);return false}}let tmpAudio=new Audio;const supportedAudioFormats=
+{"audio/webm; codecs=opus":!!tmpAudio.canPlayType("audio/webm; codecs=opus"),"audio/ogg; codecs=opus":!!tmpAudio.canPlayType("audio/ogg; codecs=opus"),"audio/webm; codecs=vorbis":!!tmpAudio.canPlayType("audio/webm; codecs=vorbis"),"audio/ogg; codecs=vorbis":!!tmpAudio.canPlayType("audio/ogg; codecs=vorbis"),"audio/mp4":!!tmpAudio.canPlayType("audio/mp4"),"audio/mpeg":!!tmpAudio.canPlayType("audio/mpeg")};tmpAudio=null;async function BlobToString(blob){const arrayBuffer=await BlobToArrayBuffer(blob);
+const textDecoder=new TextDecoder("utf-8");return textDecoder.decode(arrayBuffer)}function BlobToArrayBuffer(blob){return new Promise((resolve,reject)=>{const fileReader=new FileReader;fileReader.onload=e=>resolve(e.target.result);fileReader.onerror=err=>reject(err);fileReader.readAsArrayBuffer(blob)})}const queuedArrayBufferReads=[];let activeArrayBufferReads=0;const MAX_ARRAYBUFFER_READS=8;window["RealFile"]=window["File"];const domHandlerClasses=[];const runtimeEventHandlers=new Map;const pendingResponsePromises=
+new Map;let nextResponseId=0;const runOnStartupFunctions=[];self.runOnStartup=function runOnStartup(f){if(typeof f!=="function")throw new Error("runOnStartup called without a function");runOnStartupFunctions.push(f)};const WEBVIEW_EXPORT_TYPES=new Set(["cordova","playable-ad","instant-games"]);function IsWebViewExportType(exportType){return WEBVIEW_EXPORT_TYPES.has(exportType)}let isWrapperFullscreen=false;window.RuntimeInterface=class RuntimeInterface{constructor(opts){this._useWorker=opts.useWorker;
+this._messageChannelPort=null;this._runtimeBaseUrl="";this._scriptFolder=opts.scriptFolder;this._workerScriptURLs={};this._worker=null;this._localRuntime=null;this._domHandlers=[];this._runtimeDomHandler=null;this._isFirstSizeUpdate=true;this._canvasLayers=[];this._pendingRemoveElements=[];this._pendingUpdateHTMLZOrder=false;this._updateHTMLZOrderRAFCallback=()=>this._DoUpdateHTMLElementsZOrder();this._isExportingToVideo=false;this._exportToVideoDuration=0;this._jobScheduler=null;this._rafId=-1;this._rafFunc=
+()=>this._OnRAFCallback();this._rafCallbacks=new Set;this._wrapperInitResolve=null;this._wrapperComponentIds=[];this._exportType=opts.exportType;this._isFileProtocol=location.protocol.substr(0,4)==="file";if(this._exportType==="playable-ad"||this._exportType==="instant-games")this._useWorker=false;if(this._exportType==="cordova"&&this._useWorker)if(isAndroid){const chromeVer=/Chrome\/(\d+)/i.exec(navigator.userAgent);if(!chromeVer||!(parseInt(chromeVer[1],10)>=90))this._useWorker=false}if(this.IsAnyWebView2Wrapper())self["chrome"]["webview"].addEventListener("message",
+e=>this._OnWrapperMessage(e.data));else if(this._exportType==="macos-wkwebview")self["C3WrapperOnMessage"]=msg=>this._OnWrapperMessage(msg);this._localFileBlobs=null;this._localFileStrings=null;if(this._exportType==="html5"&&!window.isSecureContext)console.warn("[Construct] Warning: the browser indicates this is not a secure context. Some features may be unavailable. Use secure (HTTPS) hosting to ensure all features are available.");this.AddRuntimeComponentMessageHandler("canvas","update-size",e=>
+this._OnUpdateCanvasSize(e));this.AddRuntimeComponentMessageHandler("canvas","set-html-layer-count",e=>this["_OnSetHTMLLayerCount"](e));this.AddRuntimeComponentMessageHandler("canvas","cleanup-html-layers",()=>this._OnCleanUpHTMLLayers());this.AddRuntimeComponentMessageHandler("runtime","cordova-fetch-local-file",e=>this._OnCordovaFetchLocalFile(e));this.AddRuntimeComponentMessageHandler("runtime","create-job-worker",e=>this._OnCreateJobWorker(e));this.AddRuntimeComponentMessageHandler("runtime",
+"send-wrapper-extension-message",e=>this._OnSendWrapperExtensionMessage(e));if(this._exportType==="cordova")document.addEventListener("deviceready",()=>this._Init(opts));else this._Init(opts)}Release(){this._CancelAnimationFrame();if(this._messageChannelPort){this._messageChannelPort.onmessage=null;this._messageChannelPort=null}if(this._worker){this._worker.terminate();this._worker=null}if(this._localRuntime){this._localRuntime.Release();this._localRuntime=null}for(const {canvas,htmlWrap}of this._canvasLayers){canvas.remove();
+htmlWrap.remove()}this._canvasLayers.length=0}GetMainCanvas(){return this._canvasLayers[0].canvas}GetAvailableHTMLIndex(index){return Math.min(index,this._canvasLayers.length-1)}GetHTMLWrapElement(index){if(index<0||index>=this._canvasLayers.length)throw new RangeError("invalid canvas layer");return this._canvasLayers[index].htmlWrap}GetRuntimeBaseURL(){return this._runtimeBaseUrl}UsesWorker(){return this._useWorker}GetExportType(){return this._exportType}IsFileProtocol(){return this._isFileProtocol}GetScriptFolder(){return this._scriptFolder}IsiOSCordova(){return isiOSLike&&
+this._exportType==="cordova"}IsiOSWebView(){const ua=navigator.userAgent;return isiOSLike&&IsWebViewExportType(this._exportType)||navigator["standalone"]||/crios\/|fxios\/|edgios\//i.test(ua)}IsAndroid(){return isAndroid}IsAndroidWebView(){return isAndroid&&IsWebViewExportType(this._exportType)}IsWindowsWebView2(){return this._exportType==="windows-webview2"||!!(this._exportType==="preview"&&window["chrome"]&&window["chrome"]["webview"]&&window["chrome"]["webview"]["postMessage"])}IsAnyWebView2Wrapper(){return this.IsWindowsWebView2()||
+this._exportType==="xbox-uwp-webview2"}async _Init(opts){if(this._useWorker){const isWorkerModeSupported=await CheckSupportsWorkerMode();if(!isWorkerModeSupported)this._useWorker=false}if(this._exportType==="macos-wkwebview")this._SendWrapperMessage({"type":"ready"});else if(this.IsAnyWebView2Wrapper()){this._SetupWebView2Polyfills();const result=await this._InitWrapper();this._wrapperComponentIds=result["registeredComponentIds"]}if(this._exportType==="playable-ad"){this._localFileBlobs=self["c3_base64files"];
+this._localFileStrings={};await this._ConvertDataUrisToBlobs();for(let i=0,len=opts.engineScripts.length;i{frameNum++;document.body.style.opacity=frameNum%2===0?"1":"0.999"})}if(opts.runtimeBaseUrl)this._runtimeBaseUrl=opts.runtimeBaseUrl;else{const origin=location.origin;this._runtimeBaseUrl=(origin==="null"?"file:///":origin)+location.pathname;const i=this._runtimeBaseUrl.lastIndexOf("/");if(i!==-1)this._runtimeBaseUrl=this._runtimeBaseUrl.substr(0,i+1)}if(opts.workerScripts)this._workerScriptURLs=opts.workerScripts;const messageChannel=new MessageChannel;this._messageChannelPort=
+messageChannel.port1;this._messageChannelPort.onmessage=e=>this["_OnMessageFromRuntime"](e.data);if(window["c3_addPortMessageHandler"])window["c3_addPortMessageHandler"](e=>this._OnMessageFromDebugger(e));this._jobScheduler=new self.JobSchedulerDOM(this);await this._jobScheduler.Init();if(typeof window["StatusBar"]==="object")window["StatusBar"]["hide"]();if(typeof window["AndroidFullScreen"]==="object")try{await new Promise((resolve,reject)=>{window["AndroidFullScreen"]["immersiveMode"](resolve,
+reject)})}catch(err){console.error("Failed to enter Android immersive mode: ",err)}if(this._useWorker)await this._InitWorker(opts,messageChannel.port2);else await this._InitDOM(opts,messageChannel.port2)}_GetWorkerURL(url){let ret;if(this._workerScriptURLs.hasOwnProperty(url))ret=this._workerScriptURLs[url];else if(url.endsWith("/workermain.js")&&this._workerScriptURLs.hasOwnProperty("workermain.js"))ret=this._workerScriptURLs["workermain.js"];else if(this._exportType==="playable-ad"&&this._localFileBlobs.hasOwnProperty(url))ret=
+this._localFileBlobs[url];else ret=url;if(ret instanceof Blob)ret=URL.createObjectURL(ret);return ret}async CreateWorker(url,baseUrl,workerOpts){if(url.startsWith("blob:"))return new Worker(url,workerOpts);if(this._exportType==="cordova"&&this._isFileProtocol){let filePath="";if(workerOpts.isC3MainWorker)filePath=url;else filePath=this._scriptFolder+url;const arrayBuffer=await this.CordovaFetchLocalFileAsArrayBuffer(filePath);const blob=new Blob([arrayBuffer],{type:"application/javascript"});return new Worker(URL.createObjectURL(blob),
+workerOpts)}const absUrl=new URL(url,baseUrl);const isCrossOrigin=location.origin!==absUrl.origin;if(isCrossOrigin){const response=await fetch(absUrl);if(!response.ok)throw new Error("failed to fetch worker script");const blob=await response.blob();return new Worker(URL.createObjectURL(blob),workerOpts)}else return new Worker(absUrl,workerOpts)}_GetWindowInnerWidth(){return Math.max(window.innerWidth,1)}_GetWindowInnerHeight(){return Math.max(window.innerHeight,1)}_GetCommonRuntimeOptions(opts){return{"runtimeBaseUrl":this._runtimeBaseUrl,
+"previewUrl":location.href,"windowInnerWidth":this._GetWindowInnerWidth(),"windowInnerHeight":this._GetWindowInnerHeight(),"devicePixelRatio":window.devicePixelRatio,"isFullscreen":RuntimeInterface.IsDocumentFullscreen(),"projectData":opts.projectData,"previewImageBlobs":window["cr_previewImageBlobs"]||this._localFileBlobs,"previewProjectFileBlobs":window["cr_previewProjectFileBlobs"],"previewProjectFileSWUrls":window["cr_previewProjectFiles"],"swClientId":window["cr_swClientId"]||"","exportType":opts.exportType,
+"isDebug":(new URLSearchParams(self.location.search)).has("debug"),"ife":!!self.ife,"jobScheduler":this._jobScheduler.GetPortData(),"supportedAudioFormats":supportedAudioFormats,"opusWasmScriptUrl":window["cr_opusWasmScriptUrl"]||this._scriptFolder+"opus.wasm.js","opusWasmBinaryUrl":window["cr_opusWasmBinaryUrl"]||this._scriptFolder+"opus.wasm.wasm","isFileProtocol":this._isFileProtocol,"isiOSCordova":this.IsiOSCordova(),"isiOSWebView":this.IsiOSWebView(),"isWindowsWebView2":this.IsWindowsWebView2(),
+"isAnyWebView2Wrapper":this.IsAnyWebView2Wrapper(),"wrapperComponentIds":this._wrapperComponentIds,"isFBInstantAvailable":typeof self["FBInstant"]!=="undefined"}}async _InitWorker(opts,port2){const workerMainUrl=this._GetWorkerURL(opts.workerMainUrl);if(this._exportType==="preview"){this._worker=new Worker("previewworker.js",{type:"module",name:"Runtime"});await new Promise((resolve,reject)=>{const messageHandler=e=>{this._worker.removeEventListener("message",messageHandler);if(e.data&&e.data["type"]===
+"ok")resolve();else reject()};this._worker.addEventListener("message",messageHandler);this._worker.postMessage({"type":"construct-worker-init","import":(new URL(workerMainUrl,this._runtimeBaseUrl)).toString()})})}else this._worker=await this.CreateWorker(workerMainUrl,this._runtimeBaseUrl,{type:"module",name:"Runtime",isC3MainWorker:true});const canvas=document.createElement("canvas");canvas.style.display="none";const offscreenCanvas=canvas["transferControlToOffscreen"]();document.body.appendChild(canvas);
+const htmlWrap=document.createElement("div");htmlWrap.className="c3htmlwrap";document.body.appendChild(htmlWrap);this._canvasLayers.push({canvas,htmlWrap});window["c3canvas"]=canvas;if(self["C3_InsertHTMLPlaceholders"])self["C3_InsertHTMLPlaceholders"]();let workerDependencyScripts=opts.workerDependencyScripts||[];let engineScripts=opts.engineScripts;workerDependencyScripts=await Promise.all(workerDependencyScripts.map(url=>this._MaybeGetCordovaScriptURL(url)));engineScripts=await Promise.all(engineScripts.map(url=>
+this._MaybeGetCordovaScriptURL(url)));if(this._exportType==="cordova")for(let i=0,len=opts.projectScripts.length;inew C(this));this._FindRuntimeDOMHandler();this._runtimeDomHandler._AddDefaultCanvasEventHandlers(canvas);this._runtimeDomHandler._AddDefaultHTMLWrapEventHandlers(htmlWrap);
+this._runtimeDomHandler._EnableWindowResizeEvent();self["c3_callFunction"]=(name,params)=>this._runtimeDomHandler._InvokeFunctionFromJS(name,params);if(this._exportType==="preview")self["goToLastErrorScript"]=()=>this.PostToRuntimeComponent("runtime","go-to-last-error-script")}async _InitDOM(opts,port2){const canvas=document.createElement("canvas");canvas.style.display="none";document.body.appendChild(canvas);const htmlWrap=document.createElement("div");htmlWrap.className="c3htmlwrap";document.body.appendChild(htmlWrap);
+this._canvasLayers.push({canvas,htmlWrap});window["c3canvas"]=canvas;if(self["C3_InsertHTMLPlaceholders"])self["C3_InsertHTMLPlaceholders"]();this._domHandlers=domHandlerClasses.map(C=>new C(this));this._FindRuntimeDOMHandler();this._runtimeDomHandler._AddDefaultCanvasEventHandlers(canvas);this._runtimeDomHandler._AddDefaultHTMLWrapEventHandlers(htmlWrap);let engineScripts=opts.engineScripts.map(url=>typeof url==="string"?(new URL(url,this._runtimeBaseUrl)).toString():url);if(Array.isArray(opts.workerDependencyScripts)){const workerDependencyScripts=
+[...opts.workerDependencyScripts].map(s=>s instanceof Blob?URL.createObjectURL(s):s);engineScripts.unshift(...workerDependencyScripts)}engineScripts=await Promise.all(engineScripts.map(url=>this._MaybeGetCordovaScriptURL(url)));await Promise.all(engineScripts.map(url=>AddScript(url)));const scriptsStatus=self["C3_ProjectScriptsStatus"];const mainProjectScript=opts.mainProjectScript;const allProjectScripts=opts.projectScripts;for(let [originalUrl,loadUrl]of allProjectScripts){if(!loadUrl)loadUrl=originalUrl;
+if(originalUrl===mainProjectScript)try{loadUrl=await this._MaybeGetCordovaScriptURL(loadUrl);await AddScript(loadUrl);if(this._exportType==="preview"&&!scriptsStatus[originalUrl])this._ReportProjectMainScriptError(originalUrl,"main script did not run to completion")}catch(err){this._ReportProjectMainScriptError(originalUrl,err)}else if(originalUrl==="scriptsInEvents.js"||originalUrl.endsWith("/scriptsInEvents.js")){loadUrl=await this._MaybeGetCordovaScriptURL(loadUrl);await AddScript(loadUrl)}}if(this._exportType===
+"preview"&&typeof self.C3.ScriptsInEvents!=="object"){this._RemoveLoadingMessage();const msg="Failed to load JavaScript code used in events. Check all your JavaScript code has valid syntax.";console.error("[C3 runtime] "+msg);alert(msg);return}const runtimeOpts=Object.assign(this._GetCommonRuntimeOptions(opts),{"isInWorker":false,"messagePort":port2,"canvas":canvas,"runOnStartupFunctions":runOnStartupFunctions});this._runtimeDomHandler._EnableWindowResizeEvent();this._OnBeforeCreateRuntime();this._localRuntime=
+self["C3_CreateRuntime"](runtimeOpts);await self["C3_InitRuntime"](this._localRuntime,runtimeOpts)}_ReportProjectMainScriptError(url,err){this._RemoveLoadingMessage();console.error(`[Preview] Failed to load project main script (${url}): `,err);alert(`Failed to load project main script (${url}). Check all your JavaScript code has valid syntax. Press F12 and check the console for error details.`)}_OnBeforeCreateRuntime(){this._RemoveLoadingMessage()}_RemoveLoadingMessage(){const loadingElem=window["cr_previewLoadingElem"];
+if(loadingElem){loadingElem.parentElement.removeChild(loadingElem);window["cr_previewLoadingElem"]=null}}async _OnCreateJobWorker(e){const outputPort=await this._jobScheduler._CreateJobWorker();return{"outputPort":outputPort,"transferables":[outputPort]}}_OnUpdateCanvasSize(e){if(this.IsExportingToVideo())return;const widthPx=e["styleWidth"]+"px";const heightPx=e["styleHeight"]+"px";const leftPx=e["marginLeft"]+"px";const topPx=e["marginTop"]+"px";for(const {canvas,htmlWrap}of this._canvasLayers){canvas.style.width=
+widthPx;canvas.style.height=heightPx;canvas.style.marginLeft=leftPx;canvas.style.marginTop=topPx;htmlWrap.style.width=widthPx;htmlWrap.style.height=heightPx;htmlWrap.style.marginLeft=leftPx;htmlWrap.style.marginTop=topPx;if(this._isFirstSizeUpdate){canvas.style.display="";htmlWrap.style.display=""}}document.documentElement.style.setProperty("--construct-scale",e["displayScale"]);this._isFirstSizeUpdate=false}["_OnSetHTMLLayerCount"](e){const count=e["count"];const immediate=e["immediate"];const widthPx=
+e["styleWidth"]+"px";const heightPx=e["styleHeight"]+"px";const leftPx=e["marginLeft"]+"px";const topPx=e["marginTop"]+"px";const addedCanvases=[];const transferables=[];if(countcount){const {canvas,htmlWrap}=this._canvasLayers.pop();htmlWrap.remove();if(this._useWorker&&!immediate)this._pendingRemoveElements.push(canvas);else canvas.remove()}else if(count>this._canvasLayers.length)for(let i=0,len=count-this._canvasLayers.length;i{const a1=a.GetActualHTMLIndex();const b1=b.GetActualHTMLIndex();if(a1!==b1)return a1-b1;const a2=a.GetHTMLZIndex();const b2=b.GetHTMLZIndex();return a2-b2});let curHtmlIndex=0;let s=0,i=0,len=allElementStates.length;for(;i=this._canvasLayers.length)return;const newChildren=arr.map(es=>es.GetElement());const newChildrenSet=new Set(newChildren);const htmlWrap=this.GetHTMLWrapElement(htmlIndex);const existingChildren=Array.from(htmlWrap.children).filter(elem=>newChildrenSet.has(elem));
+let i=0,len=Math.min(newChildren.length,existingChildren.length);for(;i{pendingResponsePromises.set(responseId,{resolve,reject})});this._messageChannelPort.postMessage({"type":"event","component":component,"handler":handler,"dispatchOpts":dispatchOpts||null,"data":data,"responseId":responseId},transferables);return ret}["_OnMessageFromRuntime"](data){const type=
+data["type"];if(type==="event")return this._OnEventFromRuntime(data);else if(type==="result")this._OnResultFromRuntime(data);else if(type==="runtime-ready")this._OnRuntimeReady();else if(type==="alert-error"){this._RemoveLoadingMessage();alert(data["message"])}else if(type==="creating-runtime")this._OnBeforeCreateRuntime();else throw new Error(`unknown message '${type}'`);}_OnEventFromRuntime(e){const component=e["component"];const handler=e["handler"];const data=e["data"];const responseId=e["responseId"];
+const handlerMap=runtimeEventHandlers.get(component);if(!handlerMap){console.warn(`[DOM] No event handlers for component '${component}'`);return}const func=handlerMap.get(handler);if(!func){console.warn(`[DOM] No handler '${handler}' for component '${component}'`);return}let ret=null;try{ret=func(data)}catch(err){console.error(`Exception in '${component}' handler '${handler}':`,err);if(responseId!==null)this._PostResultToRuntime(responseId,false,""+err);return}if(responseId===null)return ret;else if(ret&&
+ret.then)ret.then(result=>this._PostResultToRuntime(responseId,true,result)).catch(err=>{console.error(`Rejection from '${component}' handler '${handler}':`,err);this._PostResultToRuntime(responseId,false,""+err)});else this._PostResultToRuntime(responseId,true,ret)}_PostResultToRuntime(responseId,isOk,result){let transferables;if(result&&result["transferables"])transferables=result["transferables"];this._messageChannelPort.postMessage({"type":"result","responseId":responseId,"isOk":isOk,"result":result},
+transferables)}_OnResultFromRuntime(data){const responseId=data["responseId"];const isOk=data["isOk"];const result=data["result"];const pendingPromise=pendingResponsePromises.get(responseId);if(isOk)pendingPromise.resolve(result);else pendingPromise.reject(result);pendingResponsePromises.delete(responseId)}AddRuntimeComponentMessageHandler(component,handler,func){let handlerMap=runtimeEventHandlers.get(component);if(!handlerMap){handlerMap=new Map;runtimeEventHandlers.set(component,handlerMap)}if(handlerMap.has(handler))throw new Error(`[DOM] Component '${component}' already has handler '${handler}'`);
+handlerMap.set(handler,func)}static AddDOMHandlerClass(Class){if(domHandlerClasses.includes(Class))throw new Error("DOM handler already added");domHandlerClasses.push(Class)}_FindRuntimeDOMHandler(){for(const dh of this._domHandlers)if(dh.GetComponentID()==="runtime"){this._runtimeDomHandler=dh;return}throw new Error("cannot find runtime DOM handler");}_OnMessageFromDebugger(e){this.PostToRuntimeComponent("debugger","message",e)}_OnRuntimeReady(){for(const h of this._domHandlers)h.Attach()}static IsDocumentFullscreen(){return!!(document["fullscreenElement"]||
+document["webkitFullscreenElement"]||document["mozFullScreenElement"]||isWrapperFullscreen)}static _SetWrapperIsFullscreenFlag(f){isWrapperFullscreen=!!f}async GetRemotePreviewStatusInfo(){return await this.PostToRuntimeComponentAsync("runtime","get-remote-preview-status-info")}_AddRAFCallback(f){this._rafCallbacks.add(f);this._RequestAnimationFrame()}_RemoveRAFCallback(f){this._rafCallbacks.delete(f);if(this._rafCallbacks.size===0)this._CancelAnimationFrame()}_RequestAnimationFrame(){if(this._rafId===
+-1&&this._rafCallbacks.size>0)this._rafId=requestAnimationFrame(this._rafFunc)}_CancelAnimationFrame(){if(this._rafId!==-1){cancelAnimationFrame(this._rafId);this._rafId=-1}}_OnRAFCallback(){this._rafId=-1;for(const f of this._rafCallbacks)f();this._RequestAnimationFrame()}TryPlayMedia(mediaElem){this._runtimeDomHandler.TryPlayMedia(mediaElem)}RemovePendingPlay(mediaElem){this._runtimeDomHandler.RemovePendingPlay(mediaElem)}_PlayPendingMedia(){this._runtimeDomHandler._PlayPendingMedia()}SetSilent(s){this._runtimeDomHandler.SetSilent(s)}IsAudioFormatSupported(typeStr){return!!supportedAudioFormats[typeStr]}async _WasmDecodeWebMOpus(arrayBuffer){const result=
+await this.PostToRuntimeComponentAsync("runtime","opus-decode",{"arrayBuffer":arrayBuffer},null,[arrayBuffer]);return new Float32Array(result)}SetIsExportingToVideo(duration){this._isExportingToVideo=true;this._exportToVideoDuration=duration}IsExportingToVideo(){return this._isExportingToVideo}GetExportToVideoDuration(){return this._exportToVideoDuration}IsAbsoluteURL(url){return/^(?:[a-z\-]+:)?\/\//.test(url)||url.substr(0,5)==="data:"||url.substr(0,5)==="blob:"}IsRelativeURL(url){return!this.IsAbsoluteURL(url)}async _MaybeGetCordovaScriptURL(url){if(this._exportType===
+"cordova"&&(url.startsWith("file:")||this._isFileProtocol&&this.IsRelativeURL(url))){let filename=url;if(filename.startsWith(this._runtimeBaseUrl))filename=filename.substr(this._runtimeBaseUrl.length);const arrayBuffer=await this.CordovaFetchLocalFileAsArrayBuffer(filename);const blob=new Blob([arrayBuffer],{type:"application/javascript"});return URL.createObjectURL(blob)}else return url}async _OnCordovaFetchLocalFile(e){const filename=e["filename"];switch(e["as"]){case "text":return await this.CordovaFetchLocalFileAsText(filename);
+case "buffer":return await this.CordovaFetchLocalFileAsArrayBuffer(filename);default:throw new Error("unsupported type");}}_GetPermissionAPI(){const api=window["cordova"]&&window["cordova"]["plugins"]&&window["cordova"]["plugins"]["permissions"];if(typeof api!=="object")throw new Error("Permission API is not loaded");return api}_MapPermissionID(api,permission){const permissionID=api[permission];if(typeof permissionID!=="string")throw new Error("Invalid permission name");return permissionID}_HasPermission(id){const api=
+this._GetPermissionAPI();return new Promise((resolve,reject)=>api["checkPermission"](this._MapPermissionID(api,id),status=>resolve(!!status["hasPermission"]),reject))}_RequestPermission(id){const api=this._GetPermissionAPI();return new Promise((resolve,reject)=>api["requestPermission"](this._MapPermissionID(api,id),status=>resolve(!!status["hasPermission"]),reject))}async RequestPermissions(permissions){if(this.GetExportType()!=="cordova")return true;if(this.IsiOSCordova())return true;for(const id of permissions){const alreadyGranted=
+await this._HasPermission(id);if(alreadyGranted)continue;const granted=await this._RequestPermission(id);if(granted===false)return false}return true}async RequirePermissions(...permissions){if(await this.RequestPermissions(permissions)===false)throw new Error("Permission not granted");}CordovaFetchLocalFile(filename){const path=window["cordova"]["file"]["applicationDirectory"]+"www/"+filename;return new Promise((resolve,reject)=>{window["resolveLocalFileSystemURL"](path,entry=>{entry["file"](resolve,
+reject)},reject)})}async CordovaFetchLocalFileAsText(filename){const file=await this.CordovaFetchLocalFile(filename);return await BlobToString(file)}_CordovaMaybeStartNextArrayBufferRead(){if(!queuedArrayBufferReads.length)return;if(activeArrayBufferReads>=MAX_ARRAYBUFFER_READS)return;activeArrayBufferReads++;const job=queuedArrayBufferReads.shift();this._CordovaDoFetchLocalFileAsAsArrayBuffer(job.filename,job.successCallback,job.errorCallback)}CordovaFetchLocalFileAsArrayBuffer(filename){return new Promise((resolve,
+reject)=>{queuedArrayBufferReads.push({filename:filename,successCallback:result=>{activeArrayBufferReads--;this._CordovaMaybeStartNextArrayBufferRead();resolve(result)},errorCallback:err=>{activeArrayBufferReads--;this._CordovaMaybeStartNextArrayBufferRead();reject(err)}});this._CordovaMaybeStartNextArrayBufferRead()})}async _CordovaDoFetchLocalFileAsAsArrayBuffer(filename,successCallback,errorCallback){try{const file=await this.CordovaFetchLocalFile(filename);const arrayBuffer=await BlobToArrayBuffer(file);
+successCallback(arrayBuffer)}catch(err){errorCallback(err)}}_OnWrapperMessage(msg){if(msg==="entered-fullscreen"){RuntimeInterface._SetWrapperIsFullscreenFlag(true);this._runtimeDomHandler._OnFullscreenChange()}else if(msg==="exited-fullscreen"){RuntimeInterface._SetWrapperIsFullscreenFlag(false);this._runtimeDomHandler._OnFullscreenChange()}else if(typeof msg==="object"){const type=msg["type"];if(type==="wrapper-init-response"){this._wrapperInitResolve(msg);this._wrapperInitResolve=null}else if(type===
+"extension-message")this.PostToRuntimeComponent("runtime","wrapper-extension-message",msg);else console.warn("Unknown wrapper message: ",msg)}else console.warn("Unknown wrapper message: ",msg)}_OnSendWrapperExtensionMessage(data){this._SendWrapperMessage({"type":"extension-message","componentId":data["componentId"],"messageId":data["messageId"],"params":data["params"]||[],"asyncId":data["asyncId"]})}_SendWrapperMessage(o){if(this.IsAnyWebView2Wrapper())window["chrome"]["webview"]["postMessage"](JSON.stringify(o));
+else if(this._exportType==="macos-wkwebview")window["webkit"]["messageHandlers"]["C3Wrapper"]["postMessage"](JSON.stringify(o));else;}_SetupWebView2Polyfills(){window.moveTo=(x,y)=>{this._SendWrapperMessage({"type":"set-window-position","windowX":Math.ceil(x),"windowY":Math.ceil(y)})};window.resizeTo=(w,h)=>{this._SendWrapperMessage({"type":"set-window-size","windowWidth":Math.ceil(w),"windowHeight":Math.ceil(h)})}}_InitWrapper(){if(!this.IsAnyWebView2Wrapper())return Promise.resolve();return new Promise(resolve=>
+{this._wrapperInitResolve=resolve;this._SendWrapperMessage({"type":"wrapper-init"})})}async _ConvertDataUrisToBlobs(){const promises=[];for(const [filename,data]of Object.entries(this._localFileBlobs))promises.push(this._ConvertDataUriToBlobs(filename,data));await Promise.all(promises)}async _ConvertDataUriToBlobs(filename,data){if(typeof data==="object"){this._localFileBlobs[filename]=new Blob([data["str"]],{"type":data["type"]});this._localFileStrings[filename]=data["str"]}else{let blob=await this._FetchDataUri(data);
+if(!blob)blob=this._DataURIToBinaryBlobSync(data);this._localFileBlobs[filename]=blob}}async _FetchDataUri(dataUri){try{const response=await fetch(dataUri);return await response.blob()}catch(err){console.warn("Failed to fetch a data: URI. Falling back to a slower workaround. This is probably because the Content Security Policy unnecessarily blocked it. Allow data: URIs in your CSP to avoid this.",err);return null}}_DataURIToBinaryBlobSync(datauri){const o=this._ParseDataURI(datauri);return this._BinaryStringToBlob(o.data,
+o.mime_type)}_ParseDataURI(datauri){const comma=datauri.indexOf(",");if(comma<0)throw new URIError("expected comma in data: uri");const typepart=datauri.substring(5,comma);const datapart=datauri.substring(comma+1);const typearr=typepart.split(";");const mimetype=typearr[0]||"";const encoding1=typearr[1];const encoding2=typearr[2];let decodeddata;if(encoding1==="base64"||encoding2==="base64")decodeddata=atob(datapart);else decodeddata=decodeURIComponent(datapart);return{mime_type:mimetype,data:decodeddata}}_BinaryStringToBlob(binstr,
+mime_type){let len=binstr.length;let len32=len>>2;let a8=new Uint8Array(len);let a32=new Uint32Array(a8.buffer,0,len32);let i,j;for(i=0,j=0;i{const styleLink=document.createElement("link");styleLink.onload=()=>resolve(styleLink);styleLink.onerror=err=>reject(err);styleLink.rel="stylesheet";styleLink.href=cssUrl;document.head.appendChild(styleLink)})}function FetchImage(url){return new Promise((resolve,reject)=>{const img=new Image;img.onload=()=>resolve(img);img.onerror=err=>reject(err);img.src=url})}async function BlobToImage(blob){const blobUrl=
+URL.createObjectURL(blob);try{return await FetchImage(blobUrl)}finally{URL.revokeObjectURL(blobUrl)}}function BlobToString(blob){return new Promise((resolve,reject)=>{let fileReader=new FileReader;fileReader.onload=e=>resolve(e.target.result);fileReader.onerror=err=>reject(err);fileReader.readAsText(blob)})}async function BlobToSvgImage(blob,width,height){if(!/firefox/i.test(navigator.userAgent))return await BlobToImage(blob);let str=await BlobToString(blob);const parser=new DOMParser;const doc=parser.parseFromString(str,
+"image/svg+xml");const rootElem=doc.documentElement;if(rootElem.hasAttribute("width")&&rootElem.hasAttribute("height")){const widthStr=rootElem.getAttribute("width");const heightStr=rootElem.getAttribute("height");if(!widthStr.includes("%")&&!heightStr.includes("%"))return await BlobToImage(blob)}rootElem.setAttribute("width",width+"px");rootElem.setAttribute("height",height+"px");const serializer=new XMLSerializer;str=serializer.serializeToString(doc);blob=new Blob([str],{type:"image/svg+xml"});
+return await BlobToImage(blob)}function IsInContentEditable(el){do{if(el.parentNode&&el.hasAttribute("contenteditable"))return true;el=el.parentNode}while(el);return false}const keyboardInputElementTagNames=new Set(["input","textarea","datalist","select"]);function IsKeyboardInputElement(elem){return keyboardInputElementTagNames.has(elem.tagName.toLowerCase())||IsInContentEditable(elem)}const canvasOrDocTags=new Set(["canvas","body","html"]);function PreventDefaultOnCanvasOrDoc(e){if(!e.target.tagName)return;
+const tagName=e.target.tagName.toLowerCase();if(canvasOrDocTags.has(tagName))e.preventDefault()}function PreventDefaultOnHTMLWrap(e){if(!e.target.tagName)return;if(e.target.classList.contains("c3htmlwrap"))e.preventDefault()}function BlockWheelZoom(e){if(e.metaKey||e.ctrlKey)e.preventDefault()}self["C3_GetSvgImageSize"]=async function(blob){const img=await BlobToImage(blob);if(img.width>0&&img.height>0)return[img.width,img.height];else{img.style.position="absolute";img.style.left="0px";img.style.top=
+"0px";img.style.visibility="hidden";document.body.appendChild(img);const rc=img.getBoundingClientRect();document.body.removeChild(img);return[rc.width,rc.height]}};self["C3_RasterSvgImageBlob"]=async function(blob,imageWidth,imageHeight,surfaceWidth,surfaceHeight){const img=await BlobToSvgImage(blob,imageWidth,imageHeight);const canvas=document.createElement("canvas");canvas.width=surfaceWidth;canvas.height=surfaceHeight;const ctx=canvas.getContext("2d");ctx.drawImage(img,0,0,imageWidth,imageHeight);
+return canvas};let isCordovaPaused=false;document.addEventListener("pause",()=>isCordovaPaused=true);document.addEventListener("resume",()=>isCordovaPaused=false);function ParentHasFocus(){try{return window.parent&&window.parent.document.hasFocus()}catch(err){return false}}function KeyboardIsVisible(){const elem=document.activeElement;if(!elem)return false;const tagName=elem.tagName.toLowerCase();const inputTypes=new Set(["email","number","password","search","tel","text","url"]);if(tagName==="textarea")return true;
+if(tagName==="input")return inputTypes.has(elem.type.toLowerCase()||"text");return IsInContentEditable(elem)}const DOM_COMPONENT_ID="runtime";const HANDLER_CLASS=class RuntimeDOMHandler extends self.DOMHandler{constructor(iRuntime){super(iRuntime,DOM_COMPONENT_ID);this._enableWindowResizeEvent=false;this._simulatedResizeTimerId=-1;this._targetOrientation="any";this._attachedDeviceOrientationEvent=false;this._attachedDeviceMotionEvent=false;this._pageVisibilityIsHidden=false;this._screenReaderTextWrap=
+document.createElement("div");this._screenReaderTextWrap.className="c3-screen-reader-text";this._screenReaderTextWrap.setAttribute("aria-live","polite");document.body.appendChild(this._screenReaderTextWrap);this._debugHighlightElem=null;this._isExportToVideo=false;this._exportVideoProgressMessage="";this._exportVideoUpdateTimerId=-1;this._enableAndroidVKDetection=false;this._lastWindowWidth=iRuntime._GetWindowInnerWidth();this._lastWindowHeight=iRuntime._GetWindowInnerHeight();this._virtualKeyboardHeight=
+0;this._vkTranslateYOffset=0;iRuntime.AddRuntimeComponentMessageHandler("runtime","invoke-download",e=>this._OnInvokeDownload(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","load-webfonts",e=>this._OnLoadWebFonts(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","raster-svg-image",e=>this._OnRasterSvgImage(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","get-svg-image-size",e=>this._OnGetSvgImageSize(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","set-target-orientation",
+e=>this._OnSetTargetOrientation(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","register-sw",()=>this._OnRegisterSW());iRuntime.AddRuntimeComponentMessageHandler("runtime","post-to-debugger",e=>this._OnPostToDebugger(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","go-to-script",e=>this._OnPostToDebugger(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","before-start-ticking",()=>this._OnBeforeStartTicking());iRuntime.AddRuntimeComponentMessageHandler("runtime","debug-highlight",
+e=>this._OnDebugHighlight(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","enable-device-orientation",()=>this._AttachDeviceOrientationEvent());iRuntime.AddRuntimeComponentMessageHandler("runtime","enable-device-motion",()=>this._AttachDeviceMotionEvent());iRuntime.AddRuntimeComponentMessageHandler("runtime","add-stylesheet",e=>this._OnAddStylesheet(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","script-create-worker",e=>this._OnScriptCreateWorker(e));iRuntime.AddRuntimeComponentMessageHandler("runtime",
+"alert",e=>this._OnAlert(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","screen-reader-text",e=>this._OnScreenReaderTextEvent(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","hide-cordova-splash",()=>this._OnHideCordovaSplash());iRuntime.AddRuntimeComponentMessageHandler("runtime","set-exporting-to-video",e=>this._SetExportingToVideo(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","export-to-video-progress",e=>this._OnExportVideoProgress(e));iRuntime.AddRuntimeComponentMessageHandler("runtime",
+"exported-to-video",e=>this._OnExportedToVideo(e));iRuntime.AddRuntimeComponentMessageHandler("runtime","exported-to-image-sequence",e=>this._OnExportedToImageSequence(e));const allowDefaultContextMenuTagNames=new Set(["input","textarea","datalist"]);window.addEventListener("contextmenu",e=>{const t=e.target;const name=t.tagName.toLowerCase();if(!allowDefaultContextMenuTagNames.has(name)&&!IsInContentEditable(t))e.preventDefault()});window.addEventListener("selectstart",PreventDefaultOnCanvasOrDoc);
+window.addEventListener("gesturehold",PreventDefaultOnCanvasOrDoc);window.addEventListener("touchstart",PreventDefaultOnCanvasOrDoc,{"passive":false});window.addEventListener("pointerdown",PreventDefaultOnCanvasOrDoc,{"passive":false});this._mousePointerLastButtons=0;window.addEventListener("mousedown",e=>{if(e.button===1)e.preventDefault()});window.addEventListener("mousewheel",BlockWheelZoom,{"passive":false});window.addEventListener("wheel",BlockWheelZoom,{"passive":false});window.addEventListener("resize",
+()=>this._OnWindowResize());window.addEventListener("fullscreenchange",()=>this._OnFullscreenChange());window.addEventListener("webkitfullscreenchange",()=>this._OnFullscreenChange());window.addEventListener("mozfullscreenchange",()=>this._OnFullscreenChange());window.addEventListener("fullscreenerror",e=>this._OnFullscreenError(e));window.addEventListener("webkitfullscreenerror",e=>this._OnFullscreenError(e));window.addEventListener("mozfullscreenerror",e=>this._OnFullscreenError(e));if(iRuntime.IsiOSWebView()){if(window["visualViewport"]){let lastVisualViewportHeight=
+Infinity;window["visualViewport"].addEventListener("resize",()=>{const curVisualViewportHeight=window["visualViewport"].height;if(curVisualViewportHeight>lastVisualViewportHeight){document.scrollingElement.scrollTop=0;document.scrollingElement.scrollLeft=0}lastVisualViewportHeight=curVisualViewportHeight})}else window.addEventListener("focusout",()=>{if(!KeyboardIsVisible())document.scrollingElement.scrollTop=0});document.documentElement.setAttribute("ioswebview","")}this._mediaPendingPlay=new Set;
+this._mediaRemovedPendingPlay=new WeakSet;this._isSilent=false}_AddDefaultCanvasEventHandlers(canvas){canvas.addEventListener("selectstart",PreventDefaultOnCanvasOrDoc);canvas.addEventListener("gesturehold",PreventDefaultOnCanvasOrDoc);canvas.addEventListener("pointerdown",PreventDefaultOnCanvasOrDoc)}_AddDefaultHTMLWrapEventHandlers(htmlwrap){htmlwrap.addEventListener("selectstart",PreventDefaultOnHTMLWrap);htmlwrap.addEventListener("gesturehold",PreventDefaultOnHTMLWrap);htmlwrap.addEventListener("touchstart",
+PreventDefaultOnHTMLWrap)}_OnBeforeStartTicking(){self.setTimeout(()=>{this._enableAndroidVKDetection=true},1E3);if(this._iRuntime.GetExportType()==="cordova"){document.addEventListener("pause",()=>this._OnVisibilityChange(true));document.addEventListener("resume",()=>this._OnVisibilityChange(false))}else document.addEventListener("visibilitychange",()=>this._OnVisibilityChange(document.visibilityState==="hidden"));this._pageVisibilityIsHidden=!!(document.visibilityState==="hidden"||isCordovaPaused);
+return{"isSuspended":this._pageVisibilityIsHidden}}Attach(){window.addEventListener("focus",()=>this._PostRuntimeEvent("window-focus"));window.addEventListener("blur",()=>{this._PostRuntimeEvent("window-blur",{"parentHasFocus":ParentHasFocus()});this._mousePointerLastButtons=0});window.addEventListener("focusin",e=>{if(IsKeyboardInputElement(e.target))this._PostRuntimeEvent("keyboard-blur")});window.addEventListener("keydown",e=>this._OnKeyEvent("keydown",e));window.addEventListener("keyup",e=>this._OnKeyEvent("keyup",
+e));window.addEventListener("mousedown",e=>this._OnMouseEvent("mousedown",e,DISPATCH_SCRIPT_ONLY));window.addEventListener("mousemove",e=>this._OnMouseEvent("mousemove",e,DISPATCH_SCRIPT_ONLY));window.addEventListener("mouseup",e=>this._OnMouseEvent("mouseup",e,DISPATCH_SCRIPT_ONLY));window.addEventListener("dblclick",e=>this._OnMouseEvent("dblclick",e,DISPATCH_RUNTIME_AND_SCRIPT));window.addEventListener("wheel",e=>this._OnMouseWheelEvent("wheel",e,DISPATCH_RUNTIME_AND_SCRIPT));window.addEventListener("pointerdown",
+e=>{this._HandlePointerDownFocus(e);this._OnPointerEvent("pointerdown",e)});if(this._iRuntime.UsesWorker()&&typeof window["onpointerrawupdate"]!=="undefined"&&self===self.top)window.addEventListener("pointerrawupdate",e=>this._OnPointerRawUpdate(e));else window.addEventListener("pointermove",e=>this._OnPointerEvent("pointermove",e));window.addEventListener("pointerup",e=>this._OnPointerEvent("pointerup",e));window.addEventListener("pointercancel",e=>this._OnPointerEvent("pointercancel",e));const playFunc=
+()=>this._PlayPendingMedia();window.addEventListener("pointerup",playFunc,true);window.addEventListener("touchend",playFunc,true);window.addEventListener("click",playFunc,true);window.addEventListener("keydown",playFunc,true);window.addEventListener("gamepadconnected",playFunc,true);if(this._iRuntime.IsAndroid()&&!this._iRuntime.IsAndroidWebView()&&navigator["virtualKeyboard"]){navigator["virtualKeyboard"]["overlaysContent"]=true;navigator["virtualKeyboard"].addEventListener("geometrychange",()=>
+{this._OnAndroidVirtualKeyboardChange(this._GetWindowInnerHeight(),navigator["virtualKeyboard"]["boundingRect"]["height"])})}if(this._iRuntime.IsiOSWebView()){document.scrollingElement.scrollTop=0;document.scrollingElement.scrollLeft=0}}_OnAndroidVirtualKeyboardChange(windowHeight,vkHeight){document.body.style.position="";document.body.style.overflow="";document.body.style.transform="";this._vkTranslateYOffset=0;if(vkHeight>0){const activeElement=document.activeElement;if(activeElement){const rc=
+activeElement.getBoundingClientRect();const rcMidY=(rc.top+rc.bottom)/2;const targetY=(windowHeight-vkHeight)/2;let shiftY=rcMidY-targetY;if(shiftY>vkHeight)shiftY=vkHeight;if(shiftY<0)shiftY=0;if(shiftY>0){document.body.style.position="absolute";document.body.style.overflow="visible";document.body.style.transform=`translateY(${-shiftY}px)`;this._vkTranslateYOffset=shiftY}}}}_PostRuntimeEvent(name,data){this.PostToRuntime(name,data||null,DISPATCH_RUNTIME_ONLY)}_GetWindowInnerWidth(){return this._iRuntime._GetWindowInnerWidth()}_GetWindowInnerHeight(){return this._iRuntime._GetWindowInnerHeight()}_EnableWindowResizeEvent(){this._enableWindowResizeEvent=
+true;this._lastWindowWidth=this._iRuntime._GetWindowInnerWidth();this._lastWindowHeight=this._iRuntime._GetWindowInnerHeight()}_OnWindowResize(){if(this._isExportToVideo)return;if(!this._enableWindowResizeEvent)return;const width=this._GetWindowInnerWidth();const height=this._GetWindowInnerHeight();if(this._iRuntime.IsAndroidWebView())if(this._enableAndroidVKDetection)if(this._lastWindowWidth===width&&height0){this._virtualKeyboardHeight=0;this._OnAndroidVirtualKeyboardChange(height,this._virtualKeyboardHeight)}this._lastWindowWidth=width;this._lastWindowHeight=height}else{this._lastWindowWidth=width;this._lastWindowHeight=height}this.PostToRuntime("window-resize",{"innerWidth":width,"innerHeight":height,"devicePixelRatio":window.devicePixelRatio,"isFullscreen":RuntimeInterface.IsDocumentFullscreen()});if(this._iRuntime.IsiOSWebView()){if(this._simulatedResizeTimerId!==
+-1)clearTimeout(this._simulatedResizeTimerId);this._OnSimulatedResize(width,height,0)}}_ScheduleSimulatedResize(width,height,count){if(this._simulatedResizeTimerId!==-1)clearTimeout(this._simulatedResizeTimerId);this._simulatedResizeTimerId=setTimeout(()=>this._OnSimulatedResize(width,height,count),48)}_OnSimulatedResize(originalWidth,originalHeight,count){const width=this._GetWindowInnerWidth();const height=this._GetWindowInnerHeight();this._simulatedResizeTimerId=-1;if(width!=originalWidth||height!=
+originalHeight)this.PostToRuntime("window-resize",{"innerWidth":width,"innerHeight":height,"devicePixelRatio":window.devicePixelRatio,"isFullscreen":RuntimeInterface.IsDocumentFullscreen()});else if(count<10)this._ScheduleSimulatedResize(width,height,count+1)}_OnSetTargetOrientation(e){this._targetOrientation=e["targetOrientation"]}_TrySetTargetOrientation(){const orientation=this._targetOrientation;if(screen["orientation"]&&screen["orientation"]["lock"])screen["orientation"]["lock"](orientation).catch(err=>
+console.warn("[Construct] Failed to lock orientation: ",err));else try{let result=false;if(screen["lockOrientation"])result=screen["lockOrientation"](orientation);else if(screen["webkitLockOrientation"])result=screen["webkitLockOrientation"](orientation);else if(screen["mozLockOrientation"])result=screen["mozLockOrientation"](orientation);else if(screen["msLockOrientation"])result=screen["msLockOrientation"](orientation);if(!result)console.warn("[Construct] Failed to lock orientation")}catch(err){console.warn("[Construct] Failed to lock orientation: ",
+err)}}_OnFullscreenChange(){if(this._isExportToVideo)return;const isDocFullscreen=RuntimeInterface.IsDocumentFullscreen();if(isDocFullscreen&&this._targetOrientation!=="any")this._TrySetTargetOrientation();this.PostToRuntime("fullscreenchange",{"isFullscreen":isDocFullscreen,"innerWidth":this._GetWindowInnerWidth(),"innerHeight":this._GetWindowInnerHeight()})}_OnFullscreenError(e){console.warn("[Construct] Fullscreen request failed: ",e);this.PostToRuntime("fullscreenerror",{"isFullscreen":RuntimeInterface.IsDocumentFullscreen(),
+"innerWidth":this._GetWindowInnerWidth(),"innerHeight":this._GetWindowInnerHeight()})}_OnVisibilityChange(isHidden){if(this._pageVisibilityIsHidden===isHidden)return;this._pageVisibilityIsHidden=isHidden;if(isHidden)this._iRuntime._CancelAnimationFrame();else this._iRuntime._RequestAnimationFrame();this.PostToRuntime("visibilitychange",{"hidden":isHidden});if(!isHidden&&this._iRuntime.IsiOSWebView()){const resetScrollFunc=()=>{document.scrollingElement.scrollTop=0;document.scrollingElement.scrollLeft=
+0};setTimeout(resetScrollFunc,50);setTimeout(resetScrollFunc,100);setTimeout(resetScrollFunc,250);setTimeout(resetScrollFunc,500)}}_OnKeyEvent(name,e){if(e.key==="Backspace")PreventDefaultOnCanvasOrDoc(e);if(this._iRuntime.IsAnyWebView2Wrapper()){const blockKeys=["F3","F5","F7"];const blockKeysWithCtrl=["r","p","f","g","u"];if(blockKeys.includes(e.key)||e.ctrlKey&&blockKeysWithCtrl.includes(e.key))e.preventDefault()}if(this._isExportToVideo)return;const code=KEY_CODE_ALIASES.get(e.code)||e.code;this._PostToRuntimeMaybeSync(name,
+{"code":code,"key":e.key,"which":e.which,"repeat":e.repeat,"altKey":e.altKey,"ctrlKey":e.ctrlKey,"metaKey":e.metaKey,"shiftKey":e.shiftKey,"timeStamp":e.timeStamp},DISPATCH_RUNTIME_AND_SCRIPT)}_OnMouseWheelEvent(name,e,opts){if(this._isExportToVideo)return;this.PostToRuntime(name,{"clientX":e.clientX,"clientY":e.clientY+this._vkTranslateYOffset,"pageX":e.pageX,"pageY":e.pageY+this._vkTranslateYOffset,"deltaX":e.deltaX,"deltaY":e.deltaY,"deltaZ":e.deltaZ,"deltaMode":e.deltaMode,"timeStamp":e.timeStamp},
+opts)}_OnMouseEvent(name,e,opts){if(this._isExportToVideo)return;if(IsCompatibilityMouseEvent(e))return;this._PostToRuntimeMaybeSync(name,{"button":e.button,"buttons":e.buttons,"clientX":e.clientX,"clientY":e.clientY+this._vkTranslateYOffset,"pageX":e.pageX,"pageY":e.pageY+this._vkTranslateYOffset,"movementX":e.movementX||0,"movementY":e.movementY||0,"timeStamp":e.timeStamp},opts)}_OnPointerEvent(name,e){if(this._isExportToVideo)return;let lastButtons=0;if(e.pointerType==="mouse")lastButtons=this._mousePointerLastButtons;
+this._PostToRuntimeMaybeSync(name,{"pointerId":e.pointerId,"pointerType":e.pointerType,"button":e.button,"buttons":e.buttons,"lastButtons":lastButtons,"clientX":e.clientX,"clientY":e.clientY+this._vkTranslateYOffset,"pageX":e.pageX,"pageY":e.pageY+this._vkTranslateYOffset,"movementX":e.movementX||0,"movementY":e.movementY||0,"width":e.width||0,"height":e.height||0,"pressure":e.pressure||0,"tangentialPressure":e["tangentialPressure"]||0,"tiltX":e.tiltX||0,"tiltY":e.tiltY||0,"twist":e["twist"]||0,"timeStamp":e.timeStamp},
+DISPATCH_RUNTIME_AND_SCRIPT);if(e.pointerType==="mouse")this._mousePointerLastButtons=e.buttons}_OnPointerRawUpdate(e){this._OnPointerEvent("pointermove",e)}_OnTouchEvent(fireName,e){if(this._isExportToVideo)return;for(let i=0,len=e.changedTouches.length;ithis._OnDeviceOrientation(e));window.addEventListener("deviceorientationabsolute",e=>this._OnDeviceOrientationAbsolute(e))}_AttachDeviceMotionEvent(){if(this._attachedDeviceMotionEvent)return;this._attachedDeviceMotionEvent=true;window.addEventListener("devicemotion",
+e=>this._OnDeviceMotion(e))}_OnDeviceOrientation(e){if(this._isExportToVideo)return;this.PostToRuntime("deviceorientation",{"absolute":!!e["absolute"],"alpha":e["alpha"]||0,"beta":e["beta"]||0,"gamma":e["gamma"]||0,"timeStamp":e.timeStamp,"webkitCompassHeading":e["webkitCompassHeading"],"webkitCompassAccuracy":e["webkitCompassAccuracy"]},DISPATCH_RUNTIME_AND_SCRIPT)}_OnDeviceOrientationAbsolute(e){if(this._isExportToVideo)return;this.PostToRuntime("deviceorientationabsolute",{"absolute":!!e["absolute"],
+"alpha":e["alpha"]||0,"beta":e["beta"]||0,"gamma":e["gamma"]||0,"timeStamp":e.timeStamp},DISPATCH_RUNTIME_AND_SCRIPT)}_OnDeviceMotion(e){if(this._isExportToVideo)return;let accProp=null;const acc=e["acceleration"];if(acc)accProp={"x":acc["x"]||0,"y":acc["y"]||0,"z":acc["z"]||0};let withGProp=null;const withG=e["accelerationIncludingGravity"];if(withG)withGProp={"x":withG["x"]||0,"y":withG["y"]||0,"z":withG["z"]||0};let rotationRateProp=null;const rotationRate=e["rotationRate"];if(rotationRate)rotationRateProp=
+{"alpha":rotationRate["alpha"]||0,"beta":rotationRate["beta"]||0,"gamma":rotationRate["gamma"]||0};this.PostToRuntime("devicemotion",{"acceleration":accProp,"accelerationIncludingGravity":withGProp,"rotationRate":rotationRateProp,"interval":e["interval"],"timeStamp":e.timeStamp},DISPATCH_RUNTIME_AND_SCRIPT)}_OnInvokeDownload(e){const url=e["url"];const filename=e["filename"];const a=document.createElement("a");const body=document.body;a.textContent=filename;a.href=url;a.download=filename;body.appendChild(a);
+a.click();body.removeChild(a)}async _OnLoadWebFonts(e){const webfonts=e["webfonts"];await Promise.all(webfonts.map(async info=>{const fontFace=new FontFace(info.name,`url('${info.url}')`);document.fonts.add(fontFace);await fontFace.load()}))}async _OnRasterSvgImage(e){const blob=e["blob"];const imageWidth=e["imageWidth"];const imageHeight=e["imageHeight"];const surfaceWidth=e["surfaceWidth"];const surfaceHeight=e["surfaceHeight"];const imageBitmapOpts=e["imageBitmapOpts"];const canvas=await self["C3_RasterSvgImageBlob"](blob,
+imageWidth,imageHeight,surfaceWidth,surfaceHeight);let ret;if(imageBitmapOpts)ret=await createImageBitmap(canvas,imageBitmapOpts);else ret=await createImageBitmap(canvas);return{"imageBitmap":ret,"transferables":[ret]}}async _OnGetSvgImageSize(e){return await self["C3_GetSvgImageSize"](e["blob"])}async _OnAddStylesheet(e){await AddStyleSheet(e["url"])}_PlayPendingMedia(){const mediaToTryPlay=[...this._mediaPendingPlay];this._mediaPendingPlay.clear();if(!this._isSilent)for(const mediaElem of mediaToTryPlay){const playRet=
+mediaElem.play();if(playRet)playRet.catch(err=>{if(!this._mediaRemovedPendingPlay.has(mediaElem))this._mediaPendingPlay.add(mediaElem)})}}TryPlayMedia(mediaElem){if(typeof mediaElem.play!=="function")throw new Error("missing play function");this._mediaRemovedPendingPlay.delete(mediaElem);let playRet;try{playRet=mediaElem.play()}catch(err){this._mediaPendingPlay.add(mediaElem);return}if(playRet)playRet.catch(err=>{if(!this._mediaRemovedPendingPlay.has(mediaElem))this._mediaPendingPlay.add(mediaElem)})}RemovePendingPlay(mediaElem){this._mediaPendingPlay.delete(mediaElem);
+this._mediaRemovedPendingPlay.add(mediaElem)}SetSilent(s){this._isSilent=!!s}_OnHideCordovaSplash(){if(navigator["splashscreen"]&&navigator["splashscreen"]["hide"])navigator["splashscreen"]["hide"]()}_OnDebugHighlight(e){const show=e["show"];if(!show){if(this._debugHighlightElem)this._debugHighlightElem.style.display="none";return}if(!this._debugHighlightElem){this._debugHighlightElem=document.createElement("div");this._debugHighlightElem.id="inspectOutline";document.body.appendChild(this._debugHighlightElem)}const elem=
+this._debugHighlightElem;elem.style.display="";elem.style.left=e["left"]-1+"px";elem.style.top=e["top"]-1+"px";elem.style.width=e["width"]+2+"px";elem.style.height=e["height"]+2+"px";elem.textContent=e["name"]}_OnRegisterSW(){if(window["C3_RegisterSW"])window["C3_RegisterSW"]()}_OnPostToDebugger(data){if(!window["c3_postToMessagePort"])return;data["from"]="runtime";window["c3_postToMessagePort"](data)}_InvokeFunctionFromJS(name,params){return this.PostToRuntimeAsync("js-invoke-function",{"name":name,
+"params":params})}_OnScriptCreateWorker(e){const url=e["url"];const opts=e["opts"];const port2=e["port2"];const worker=new Worker(url,opts);worker.postMessage({"type":"construct-worker-init","port2":port2},[port2])}_OnAlert(e){alert(e["message"])}_OnScreenReaderTextEvent(e){const type=e["type"];if(type==="create"){const p=document.createElement("p");p.id="c3-sr-"+e["id"];p.textContent=e["text"];this._screenReaderTextWrap.appendChild(p)}else if(type==="update"){const p=document.getElementById("c3-sr-"+
+e["id"]);if(p)p.textContent=e["text"];else console.warn(`[Construct] Missing screen reader text with id ${e["id"]}`)}else if(type==="release"){const p=document.getElementById("c3-sr-"+e["id"]);if(p)p.remove();else console.warn(`[Construct] Missing screen reader text with id ${e["id"]}`)}else console.warn(`[Construct] Unknown screen reader text update '${type}'`)}_SetExportingToVideo(e){this._isExportToVideo=true;const headerElem=document.createElement("h1");headerElem.id="exportToVideoMessage";headerElem.textContent=
+e["message"];document.body.prepend(headerElem);document.body.classList.add("exportingToVideo");this.GetRuntimeInterface().GetMainCanvas().style.display="";this._iRuntime.SetIsExportingToVideo(e["duration"])}_OnExportVideoProgress(e){this._exportVideoProgressMessage=e["message"];if(this._exportVideoUpdateTimerId===-1)this._exportVideoUpdateTimerId=setTimeout(()=>this._DoUpdateExportVideoProgressMessage(),250)}_DoUpdateExportVideoProgressMessage(){this._exportVideoUpdateTimerId=-1;const headerElem=
+document.getElementById("exportToVideoMessage");if(headerElem)headerElem.textContent=this._exportVideoProgressMessage}_OnExportedToVideo(e){window.c3_postToMessagePort({"type":"exported-video","arrayBuffer":e["arrayBuffer"],"contentType":e["contentType"],"time":e["time"]})}_OnExportedToImageSequence(e){window.c3_postToMessagePort({"type":"exported-image-sequence","blobArr":e["blobArr"],"time":e["time"],"gif":e["gif"]})}};RuntimeInterface.AddDOMHandlerClass(HANDLER_CLASS)};
+
+
+'use strict';{const DISPATCH_WORKER_SCRIPT_NAME="dispatchworker.js";const JOB_WORKER_SCRIPT_NAME="jobworker.js";self.JobSchedulerDOM=class JobSchedulerDOM{constructor(runtimeInterface){this._runtimeInterface=runtimeInterface;this._baseUrl=runtimeInterface.GetRuntimeBaseURL();if(runtimeInterface.GetExportType()==="preview")this._baseUrl+="workers/";else this._baseUrl+=runtimeInterface.GetScriptFolder();this._maxNumWorkers=Math.min(navigator.hardwareConcurrency||2,16);this._dispatchWorker=null;this._jobWorkers=
+[];this._inputPort=null;this._outputPort=null}_GetWorkerScriptFolder(){if(this._runtimeInterface.GetExportType()==="playable-ad")return this._runtimeInterface.GetScriptFolder();else return""}async Init(){if(this._hasInitialised)throw new Error("already initialised");this._hasInitialised=true;const dispatchWorkerScriptUrl=this._runtimeInterface._GetWorkerURL(this._GetWorkerScriptFolder()+DISPATCH_WORKER_SCRIPT_NAME);this._dispatchWorker=await this._runtimeInterface.CreateWorker(dispatchWorkerScriptUrl,
+this._baseUrl,{name:"DispatchWorker"});const messageChannel=new MessageChannel;this._inputPort=messageChannel.port1;this._dispatchWorker.postMessage({"type":"_init","in-port":messageChannel.port2},[messageChannel.port2]);this._outputPort=await this._CreateJobWorker()}async _CreateJobWorker(){const number=this._jobWorkers.length;const jobWorkerScriptUrl=this._runtimeInterface._GetWorkerURL(this._GetWorkerScriptFolder()+JOB_WORKER_SCRIPT_NAME);const jobWorker=await this._runtimeInterface.CreateWorker(jobWorkerScriptUrl,
+this._baseUrl,{name:"JobWorker"+number});const dispatchChannel=new MessageChannel;const outputChannel=new MessageChannel;this._dispatchWorker.postMessage({"type":"_addJobWorker","port":dispatchChannel.port1},[dispatchChannel.port1]);jobWorker.postMessage({"type":"init","number":number,"dispatch-port":dispatchChannel.port2,"output-port":outputChannel.port2},[dispatchChannel.port2,outputChannel.port2]);this._jobWorkers.push(jobWorker);return outputChannel.port1}GetPortData(){return{"inputPort":this._inputPort,
+"outputPort":this._outputPort,"maxNumWorkers":this._maxNumWorkers}}GetPortTransferables(){return[this._inputPort,this._outputPort]}}};
+
+
+'use strict';{if(window["C3_Is_Supported"]){const enableWorker=false;window["c3_runtimeInterface"]=new self.RuntimeInterface({useWorker:enableWorker,workerMainUrl:"workermain.js",engineScripts:["scripts/c3runtime.js"],projectScripts:[["scripts/project/scriptsInEvents.js"]],mainProjectScript:"",scriptFolder:"scripts/",workerDependencyScripts:[],exportType:"html5"})}};
+'use strict';{const R_TO_D=180/Math.PI;const DOM_COMPONENT_ID="audio";self.AudioDOMHandler=class AudioDOMHandler extends self.DOMHandler{constructor(iRuntime){super(iRuntime,DOM_COMPONENT_ID);this._audioContext=null;this._destinationNode=null;this._hasUnblocked=false;this._hasAttachedUnblockEvents=false;this._unblockFunc=()=>this._UnblockAudioContext();this._audioBuffers=[];this._audioInstances=[];this._lastAudioInstance=null;this._lastPlayedTags=[];this._loadedAudioUrls=new Set;this._lastTickCount=
+-1;this._pendingTags=new Map;this._masterVolume=1;this._isSilent=false;this._timeScaleMode=0;this._timeScale=1;this._gameTime=0;this._panningModel="HRTF";this._distanceModel="inverse";this._refDistance=600;this._maxDistance=1E4;this._rolloffFactor=1;this._lastListenerPos=[0,0,0];this._lastListenerOrientation=[0,0,-1,0,1,0];this._playMusicAsSound=false;this._hasAnySoftwareDecodedMusic=false;this._supportsWebMOpus=this._iRuntime.IsAudioFormatSupported("audio/webm; codecs=opus");this._effects=new Map;
+this._analysers=new Set;this._isPendingPostFxState=false;this._hasStartedOfflineRender=false;this._microphoneTag="";this._microphoneSource=null;self["C3Audio_OnMicrophoneStream"]=(localMediaStream,tag)=>this._OnMicrophoneStream(localMediaStream,tag);this._destMediaStreamNode=null;self["C3Audio_GetOutputStream"]=()=>this._OnGetOutputStream();self["C3Audio_DOMInterface"]=this;this.AddRuntimeMessageHandlers([["create-audio-context",e=>this._CreateAudioContext(e)],["play",e=>this._Play(e)],["stop",e=>
+this._Stop(e)],["stop-all",()=>this._StopAll()],["set-paused",e=>this._SetPaused(e)],["set-volume",e=>this._SetVolume(e)],["fade-volume",e=>this._FadeVolume(e)],["set-master-volume",e=>this._SetMasterVolume(e)],["set-muted",e=>this._SetMuted(e)],["set-silent",e=>this._SetSilent(e)],["set-looping",e=>this._SetLooping(e)],["set-playback-rate",e=>this._SetPlaybackRate(e)],["set-stereo-pan",e=>this._SetStereoPan(e)],["seek",e=>this._Seek(e)],["preload",e=>this._Preload(e)],["unload",e=>this._Unload(e)],
+["unload-all",()=>this._UnloadAll()],["set-suspended",e=>this._SetSuspended(e)],["add-effect",e=>this._AddEffect(e)],["set-effect-param",e=>this._SetEffectParam(e)],["remove-effects",e=>this._RemoveEffects(e)],["tick",e=>this._OnTick(e)],["load-state",e=>this._OnLoadState(e)],["offline-render-audio",e=>this._OnOfflineRenderAudio(e)],["offline-render-finish",()=>this._OnOfflineRenderFinish()]])}async _CreateAudioContext(e){if(e["isiOSCordova"]||e["isSafari"])this._playMusicAsSound=true;this._timeScaleMode=
+e["timeScaleMode"];this._panningModel=["equalpower","HRTF","soundfield"][e["panningModel"]];this._distanceModel=["linear","inverse","exponential"][e["distanceModel"]];this._refDistance=e["refDistance"];this._maxDistance=e["maxDistance"];this._rolloffFactor=e["rolloffFactor"];if(this._iRuntime.IsExportingToVideo()){this._playMusicAsSound=true;const sampleRate=48E3;this._audioContext=new OfflineAudioContext({"numberOfChannels":2,"sampleRate":sampleRate,"length":Math.ceil(this._iRuntime.GetExportToVideoDuration()*
+sampleRate)})}else{const opts={"latencyHint":e["latencyHint"]};if(!this.SupportsWebMOpus())opts["sampleRate"]=48E3;if(typeof AudioContext!=="undefined")this._audioContext=new AudioContext(opts);else if(typeof webkitAudioContext!=="undefined")this._audioContext=new webkitAudioContext(opts);else throw new Error("Web Audio API not supported");this._AttachUnblockEvents();this._audioContext.onstatechange=()=>{if(this._audioContext.state!=="running")this._AttachUnblockEvents();this.PostToRuntime("audiocontext-state",
+{"audioContextState":this._audioContext.state})}}this._destinationNode=this._audioContext["createGain"]();this._destinationNode["connect"](this._audioContext["destination"]);const listenerPos=e["listenerPos"];this._lastListenerPos[0]=listenerPos[0];this._lastListenerPos[1]=listenerPos[1];this._lastListenerPos[2]=listenerPos[2];this._audioContext["listener"]["setPosition"](listenerPos[0],listenerPos[1],listenerPos[2]);this._audioContext["listener"]["setOrientation"](...this._lastListenerOrientation);
+self["C3_GetAudioContextCurrentTime"]=()=>this.GetAudioCurrentTime();try{await Promise.all(e["preloadList"].map(o=>this._GetAudioBuffer(o["originalUrl"],o["url"],o["type"],false)))}catch(err){console.error("[Construct] Preloading sounds failed: ",err)}return{"sampleRate":this._audioContext["sampleRate"],"audioContextState":this._audioContext.state,"outputLatency":this._audioContext["outputLatency"]||0}}_AttachUnblockEvents(){if(this._hasAttachedUnblockEvents)return;this._hasUnblocked=false;window.addEventListener("pointerup",
+this._unblockFunc,true);window.addEventListener("touchend",this._unblockFunc,true);window.addEventListener("click",this._unblockFunc,true);window.addEventListener("keydown",this._unblockFunc,true);this._hasAttachedUnblockEvents=true}_DetachUnblockEvents(){if(!this._hasAttachedUnblockEvents)return;this._hasUnblocked=true;window.removeEventListener("pointerup",this._unblockFunc,true);window.removeEventListener("touchend",this._unblockFunc,true);window.removeEventListener("click",this._unblockFunc,true);
+window.removeEventListener("keydown",this._unblockFunc,true);this._hasAttachedUnblockEvents=false}_UnblockAudioContext(){if(this._hasUnblocked)return;const audioContext=this._audioContext;if(audioContext["state"]==="suspended"&&audioContext["resume"])audioContext["resume"]();const buffer=audioContext["createBuffer"](1,220,22050);const source=audioContext["createBufferSource"]();source["buffer"]=buffer;source["connect"](audioContext["destination"]);source["start"](0);if(audioContext["state"]==="running")this._DetachUnblockEvents()}_MatchTagLists(tagArr1,
+tagArr2){for(const t2 of tagArr2){let found=false;for(const t1 of tagArr1)if(self.AudioDOMHandler.EqualsNoCase(t1,t2)){found=true;break}if(!found)return false}return true}GetAudioContext(){return this._audioContext}GetAudioCurrentTime(){return this._audioContext["currentTime"]}GetDestinationNode(){return this._destinationNode}["GetAudioContextExtern"](){return this.GetAudioContext()}["GetDestinationNodeExtern"](){return this.GetDestinationNode()}GetDestinationForTag(tag){const fxChain=this._effects.get(tag.toLowerCase());
+if(fxChain)return fxChain[0].GetInputNode();else return this.GetDestinationNode()}AddEffectForTag(tag,effect){tag=tag.toLowerCase();let fxChain=this._effects.get(tag);if(!fxChain){fxChain=[];this._effects.set(tag,fxChain)}effect._SetIndex(fxChain.length);effect._SetTag(tag);fxChain.push(effect);this._ReconnectEffects(tag)}_ReconnectEffects(tag){tag=tag.toLowerCase();let destNode=this.GetDestinationNode();const fxChain=this._effects.get(tag);if(fxChain&&fxChain.length){destNode=fxChain[0].GetInputNode();
+for(let i=0,len=fxChain.length;i