odin.js 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993
  1. "use strict";
  2. (function() {
  3. function getElement(name) {
  4. if (name) {
  5. return document.getElementById(name);
  6. }
  7. return undefined;
  8. }
  9. function stripNewline(str) {
  10. return str.replace(/\n/, ' ')
  11. }
  12. class WasmMemoryInterface {
  13. constructor() {
  14. this.memory = null;
  15. this.exports = null;
  16. this.listenerMap = {};
  17. // Size (in bytes) of the integer type, should be 4 on `js_wasm32` and 8 on `js_wasm64p32`
  18. this.intSize = 4;
  19. }
  20. setIntSize(size) {
  21. this.intSize = size;
  22. }
  23. setMemory(memory) {
  24. this.memory = memory;
  25. }
  26. setExports(exports) {
  27. this.exports = exports;
  28. }
  29. get mem() {
  30. return new DataView(this.memory.buffer);
  31. }
  32. loadF32Array(addr, len) {
  33. let array = new Float32Array(this.memory.buffer, addr, len);
  34. return array;
  35. }
  36. loadF64Array(addr, len) {
  37. let array = new Float64Array(this.memory.buffer, addr, len);
  38. return array;
  39. }
  40. loadU32Array(addr, len) {
  41. let array = new Uint32Array(this.memory.buffer, addr, len);
  42. return array;
  43. }
  44. loadI32Array(addr, len) {
  45. let array = new Int32Array(this.memory.buffer, addr, len);
  46. return array;
  47. }
  48. loadU8(addr) { return this.mem.getUint8 (addr); }
  49. loadI8(addr) { return this.mem.getInt8 (addr); }
  50. loadU16(addr) { return this.mem.getUint16 (addr, true); }
  51. loadI16(addr) { return this.mem.getInt16 (addr, true); }
  52. loadU32(addr) { return this.mem.getUint32 (addr, true); }
  53. loadI32(addr) { return this.mem.getInt32 (addr, true); }
  54. loadU64(addr) {
  55. const lo = this.mem.getUint32(addr + 0, true);
  56. const hi = this.mem.getUint32(addr + 4, true);
  57. return lo + hi*4294967296;
  58. };
  59. loadI64(addr) {
  60. const lo = this.mem.getUint32(addr + 0, true);
  61. const hi = this.mem.getInt32 (addr + 4, true);
  62. return lo + hi*4294967296;
  63. };
  64. loadF32(addr) { return this.mem.getFloat32(addr, true); }
  65. loadF64(addr) { return this.mem.getFloat64(addr, true); }
  66. loadInt(addr) {
  67. if (this.intSize == 8) {
  68. return this.loadI64(addr);
  69. } else if (this.intSize == 4) {
  70. return this.loadI32(addr);
  71. } else {
  72. throw new Error('Unhandled `intSize`, expected `4` or `8`');
  73. }
  74. };
  75. loadUint(addr) {
  76. if (this.intSize == 8) {
  77. return this.loadU64(addr);
  78. } else if (this.intSize == 4) {
  79. return this.loadU32(addr);
  80. } else {
  81. throw new Error('Unhandled `intSize`, expected `4` or `8`');
  82. }
  83. };
  84. loadPtr(addr) { return this.loadU32(addr); }
  85. loadB32(addr) {
  86. return this.loadU32(addr) != 0;
  87. }
  88. loadBytes(ptr, len) {
  89. return new Uint8Array(this.memory.buffer, ptr, Number(len));
  90. }
  91. loadString(ptr, len) {
  92. const bytes = this.loadBytes(ptr, Number(len));
  93. return new TextDecoder().decode(bytes);
  94. }
  95. loadCstring(ptr) {
  96. const start = this.loadPtr(ptr);
  97. if (start == 0) {
  98. return null;
  99. }
  100. let len = 0;
  101. for (; this.mem.getUint8(start+len) != 0; len += 1) {}
  102. return this.loadString(start, len);
  103. }
  104. storeU8(addr, value) { this.mem.setUint8 (addr, value); }
  105. storeI8(addr, value) { this.mem.setInt8 (addr, value); }
  106. storeU16(addr, value) { this.mem.setUint16 (addr, value, true); }
  107. storeI16(addr, value) { this.mem.setInt16 (addr, value, true); }
  108. storeU32(addr, value) { this.mem.setUint32 (addr, value, true); }
  109. storeI32(addr, value) { this.mem.setInt32 (addr, value, true); }
  110. storeU64(addr, value) {
  111. this.mem.setUint32(addr + 0, Number(value), true);
  112. let div = 4294967296;
  113. if (typeof value == 'bigint') {
  114. div = BigInt(div);
  115. }
  116. this.mem.setUint32(addr + 4, Math.floor(Number(value / div)), true);
  117. }
  118. storeI64(addr, value) {
  119. this.mem.setUint32(addr + 0, Number(value), true);
  120. let div = 4294967296;
  121. if (typeof value == 'bigint') {
  122. div = BigInt(div);
  123. }
  124. this.mem.setInt32(addr + 4, Math.floor(Number(value / div)), true);
  125. }
  126. storeF32(addr, value) { this.mem.setFloat32(addr, value, true); }
  127. storeF64(addr, value) { this.mem.setFloat64(addr, value, true); }
  128. storeInt(addr, value) {
  129. if (this.intSize == 8) {
  130. this.storeI64(addr, value);
  131. } else if (this.intSize == 4) {
  132. this.storeI32(addr, value);
  133. } else {
  134. throw new Error('Unhandled `intSize`, expected `4` or `8`');
  135. }
  136. }
  137. storeUint(addr, value) {
  138. if (this.intSize == 8) {
  139. this.storeU64(addr, value);
  140. } else if (this.intSize == 4) {
  141. this.storeU32(addr, value);
  142. } else {
  143. throw new Error('Unhandled `intSize`, expected `4` or `8`');
  144. }
  145. }
  146. // Returned length might not be the same as `value.length` if non-ascii strings are given.
  147. storeString(addr, value) {
  148. const src = new TextEncoder().encode(value);
  149. const dst = new Uint8Array(this.memory.buffer, addr, src.length);
  150. dst.set(src);
  151. return src.length;
  152. }
  153. };
  154. class WebGLInterface {
  155. constructor(wasmMemoryInterface) {
  156. this.wasmMemoryInterface = wasmMemoryInterface;
  157. this.ctxElement = null;
  158. this.ctx = null;
  159. this.ctxVersion = 1.0;
  160. this.counter = 1;
  161. this.lastError = 0;
  162. this.buffers = [];
  163. this.mappedBuffers = {};
  164. this.programs = [];
  165. this.framebuffers = [];
  166. this.renderbuffers = [];
  167. this.textures = [];
  168. this.uniforms = [];
  169. this.shaders = [];
  170. this.vaos = [];
  171. this.contexts = [];
  172. this.currentContext = null;
  173. this.offscreenCanvases = {};
  174. this.timerQueriesEXT = [];
  175. this.queries = [];
  176. this.samplers = [];
  177. this.transformFeedbacks = [];
  178. this.syncs = [];
  179. this.programInfos = {};
  180. }
  181. get mem() {
  182. return this.wasmMemoryInterface
  183. }
  184. setCurrentContext(element, contextSettings) {
  185. if (!element) {
  186. return false;
  187. }
  188. if (this.ctxElement == element) {
  189. return true;
  190. }
  191. contextSettings = contextSettings ?? {};
  192. this.ctx = element.getContext("webgl2", contextSettings) || element.getContext("webgl", contextSettings);
  193. if (!this.ctx) {
  194. return false;
  195. }
  196. this.ctxElement = element;
  197. if (this.ctx.getParameter(0x1F02).indexOf("WebGL 2.0") !== -1) {
  198. this.ctxVersion = 2.0;
  199. } else {
  200. this.ctxVersion = 1.0;
  201. }
  202. return true;
  203. }
  204. assertWebGL2() {
  205. if (this.ctxVersion < 2) {
  206. throw new Error("WebGL2 procedure called in a canvas without a WebGL2 context");
  207. }
  208. }
  209. getNewId(table) {
  210. for (var ret = this.counter++, i = table.length; i < ret; i++) {
  211. table[i] = null;
  212. }
  213. return ret;
  214. }
  215. recordError(errorCode) {
  216. this.lastError || (this.lastError = errorCode);
  217. }
  218. populateUniformTable(program) {
  219. let p = this.programs[program];
  220. this.programInfos[program] = {
  221. uniforms: {},
  222. maxUniformLength: 0,
  223. maxAttributeLength: -1,
  224. maxUniformBlockNameLength: -1,
  225. };
  226. for (let ptable = this.programInfos[program], utable = ptable.uniforms, numUniforms = this.ctx.getProgramParameter(p, this.ctx.ACTIVE_UNIFORMS), i = 0; i < numUniforms; ++i) {
  227. let u = this.ctx.getActiveUniform(p, i);
  228. let name = u.name;
  229. if (ptable.maxUniformLength = Math.max(ptable.maxUniformLength, name.length + 1), name.indexOf("]", name.length - 1) !== -1) {
  230. name = name.slice(0, name.lastIndexOf("["));
  231. }
  232. let loc = this.ctx.getUniformLocation(p, name);
  233. if (loc !== null) {
  234. let id = this.getNewId(this.uniforms);
  235. utable[name] = [u.size, id], this.uniforms[id] = loc;
  236. for (let j = 1; j < u.size; ++j) {
  237. let n = name + "[" + j + "]";
  238. let loc = this.ctx.getUniformLocation(p, n);
  239. let id = this.getNewId(this.uniforms);
  240. this.uniforms[id] = loc;
  241. }
  242. }
  243. }
  244. }
  245. getSource(shader, strings_ptr, strings_length) {
  246. const stringSize = this.mem.intSize*2;
  247. let source = "";
  248. for (let i = 0; i < strings_length; i++) {
  249. let ptr = this.mem.loadPtr(strings_ptr + i*stringSize);
  250. let len = this.mem.loadPtr(strings_ptr + i*stringSize + 4);
  251. let str = this.mem.loadString(ptr, len);
  252. source += str;
  253. }
  254. return source;
  255. }
  256. getWebGL1Interface() {
  257. return {
  258. SetCurrentContextById: (name_ptr, name_len) => {
  259. let name = this.mem.loadString(name_ptr, name_len);
  260. let element = getElement(name);
  261. return this.setCurrentContext(element, {alpha: true, antialias: true, depth: true, premultipliedAlpha: true});
  262. },
  263. CreateCurrentContextById: (name_ptr, name_len, attributes) => {
  264. let name = this.mem.loadString(name_ptr, name_len);
  265. let element = getElement(name);
  266. let contextSettings = {
  267. alpha: !(attributes & (1<<0)),
  268. antialias: !(attributes & (1<<1)),
  269. depth: !(attributes & (1<<2)),
  270. failIfMajorPerformanceCaveat: !!(attributes & (1<<3)),
  271. premultipliedAlpha: !(attributes & (1<<4)),
  272. preserveDrawingBuffer: !!(attributes & (1<<5)),
  273. stencil: !!(attributes & (1<<6)),
  274. desynchronized: !!(attributes & (1<<7)),
  275. };
  276. return this.setCurrentContext(element, contextSettings);
  277. },
  278. GetCurrentContextAttributes: () => {
  279. if (!this.ctx) {
  280. return 0;
  281. }
  282. let attrs = this.ctx.getContextAttributes();
  283. let res = 0;
  284. if (!attrs.alpha) res |= 1<<0;
  285. if (!attrs.antialias) res |= 1<<1;
  286. if (!attrs.depth) res |= 1<<2;
  287. if (attrs.failIfMajorPerformanceCaveat) res |= 1<<3;
  288. if (!attrs.premultipliedAlpha) res |= 1<<4;
  289. if (attrs.preserveDrawingBuffer) res |= 1<<5;
  290. if (attrs.stencil) res |= 1<<6;
  291. if (attrs.desynchronized) res |= 1<<7;
  292. return res;
  293. },
  294. DrawingBufferWidth: () => this.ctx.drawingBufferWidth,
  295. DrawingBufferHeight: () => this.ctx.drawingBufferHeight,
  296. IsExtensionSupported: (name_ptr, name_len) => {
  297. let name = this.mem.loadString(name_ptr, name_len);
  298. let extensions = this.ctx.getSupportedExtensions();
  299. return extensions.indexOf(name) !== -1
  300. },
  301. GetError: () => {
  302. let err = this.lastError;
  303. this.recordError(0);
  304. if (err) {
  305. return err;
  306. }
  307. return this.ctx.getError();
  308. },
  309. GetWebGLVersion: (major_ptr, minor_ptr) => {
  310. let version = this.ctx.getParameter(0x1F02);
  311. if (version.indexOf("WebGL 2.0") !== -1) {
  312. this.mem.storeI32(major_ptr, 2);
  313. this.mem.storeI32(minor_ptr, 0);
  314. return;
  315. }
  316. this.mem.storeI32(major_ptr, 1);
  317. this.mem.storeI32(minor_ptr, 0);
  318. },
  319. GetESVersion: (major_ptr, minor_ptr) => {
  320. let version = this.ctx.getParameter(0x1F02);
  321. if (version.indexOf("OpenGL ES 3.0") !== -1) {
  322. this.mem.storeI32(major_ptr, 3);
  323. this.mem.storeI32(minor_ptr, 0);
  324. return;
  325. }
  326. this.mem.storeI32(major_ptr, 2);
  327. this.mem.storeI32(minor_ptr, 0);
  328. },
  329. ActiveTexture: (x) => {
  330. this.ctx.activeTexture(x);
  331. },
  332. AttachShader: (program, shader) => {
  333. this.ctx.attachShader(this.programs[program], this.shaders[shader]);
  334. },
  335. BindAttribLocation: (program, index, name_ptr, name_len) => {
  336. let name = this.mem.loadString(name_ptr, name_len);
  337. this.ctx.bindAttribLocation(this.programs[program], index, name)
  338. },
  339. BindBuffer: (target, buffer) => {
  340. let bufferObj = buffer ? this.buffers[buffer] : null;
  341. if (target == 35051) {
  342. this.ctx.currentPixelPackBufferBinding = buffer;
  343. } else {
  344. if (target == 35052) {
  345. this.ctx.currentPixelUnpackBufferBinding = buffer;
  346. }
  347. this.ctx.bindBuffer(target, bufferObj)
  348. }
  349. },
  350. BindFramebuffer: (target, framebuffer) => {
  351. this.ctx.bindFramebuffer(target, framebuffer ? this.framebuffers[framebuffer] : null)
  352. },
  353. BindTexture: (target, texture) => {
  354. this.ctx.bindTexture(target, texture ? this.textures[texture] : null)
  355. },
  356. BlendColor: (red, green, blue, alpha) => {
  357. this.ctx.blendColor(red, green, blue, alpha);
  358. },
  359. BlendEquation: (mode) => {
  360. this.ctx.blendEquation(mode);
  361. },
  362. BlendFunc: (sfactor, dfactor) => {
  363. this.ctx.blendFunc(sfactor, dfactor);
  364. },
  365. BlendFuncSeparate: (srcRGB, dstRGB, srcAlpha, dstAlpha) => {
  366. this.ctx.blendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
  367. },
  368. BufferData: (target, size, data, usage) => {
  369. if (data) {
  370. this.ctx.bufferData(target, this.mem.loadBytes(data, size), usage);
  371. } else {
  372. this.ctx.bufferData(target, size, usage);
  373. }
  374. },
  375. BufferSubData: (target, offset, size, data) => {
  376. if (data) {
  377. this.ctx.bufferSubData(target, offset, this.mem.loadBytes(data, size));
  378. } else {
  379. this.ctx.bufferSubData(target, offset, null);
  380. }
  381. },
  382. Clear: (x) => {
  383. this.ctx.clear(x);
  384. },
  385. ClearColor: (r, g, b, a) => {
  386. this.ctx.clearColor(r, g, b, a);
  387. },
  388. ClearDepth: (x) => {
  389. this.ctx.clearDepth(x);
  390. },
  391. ClearStencil: (x) => {
  392. this.ctx.clearStencil(x);
  393. },
  394. ColorMask: (r, g, b, a) => {
  395. this.ctx.colorMask(!!r, !!g, !!b, !!a);
  396. },
  397. CompileShader: (shader) => {
  398. this.ctx.compileShader(this.shaders[shader]);
  399. },
  400. CompressedTexImage2D: (target, level, internalformat, width, height, border, imageSize, data) => {
  401. if (data) {
  402. this.ctx.compressedTexImage2D(target, level, internalformat, width, height, border, this.mem.loadBytes(data, imageSize));
  403. } else {
  404. this.ctx.compressedTexImage2D(target, level, internalformat, width, height, border, null);
  405. }
  406. },
  407. CompressedTexSubImage2D: (target, level, xoffset, yoffset, width, height, format, imageSize, data) => {
  408. if (data) {
  409. this.ctx.compressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, this.mem.loadBytes(data, imageSize));
  410. } else {
  411. this.ctx.compressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, null);
  412. }
  413. },
  414. CopyTexImage2D: (target, level, internalformat, x, y, width, height, border) => {
  415. this.ctx.copyTexImage2D(target, level, internalformat, x, y, width, height, border);
  416. },
  417. CopyTexSubImage2D: (target, level, xoffset, yoffset, x, y, width, height) => {
  418. this.ctx.copyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);
  419. },
  420. CreateBuffer: () => {
  421. let buffer = this.ctx.createBuffer();
  422. if (!buffer) {
  423. this.recordError(1282);
  424. return 0;
  425. }
  426. let id = this.getNewId(this.buffers);
  427. buffer.name = id
  428. this.buffers[id] = buffer;
  429. return id;
  430. },
  431. CreateFramebuffer: () => {
  432. let buffer = this.ctx.createFramebuffer();
  433. let id = this.getNewId(this.framebuffers);
  434. buffer.name = id
  435. this.framebuffers[id] = buffer;
  436. return id;
  437. },
  438. CreateProgram: () => {
  439. let program = this.ctx.createProgram();
  440. let id = this.getNewId(this.programs);
  441. program.name = id;
  442. this.programs[id] = program;
  443. return id;
  444. },
  445. CreateRenderbuffer: () => {
  446. let buffer = this.ctx.createRenderbuffer();
  447. let id = this.getNewId(this.renderbuffers);
  448. buffer.name = id;
  449. this.renderbuffers[id] = buffer;
  450. return id;
  451. },
  452. CreateShader: (shaderType) => {
  453. let shader = this.ctx.createShader(shaderType);
  454. let id = this.getNewId(this.shaders);
  455. shader.name = id;
  456. this.shaders[id] = shader;
  457. return id;
  458. },
  459. CreateTexture: () => {
  460. let texture = this.ctx.createTexture();
  461. if (!texture) {
  462. this.recordError(1282)
  463. return 0;
  464. }
  465. let id = this.getNewId(this.textures);
  466. texture.name = id;
  467. this.textures[id] = texture;
  468. return id;
  469. },
  470. CullFace: (mode) => {
  471. this.ctx.cullFace(mode);
  472. },
  473. DeleteBuffer: (id) => {
  474. let obj = this.buffers[id];
  475. if (obj && id != 0) {
  476. this.ctx.deleteBuffer(obj);
  477. this.buffers[id] = null;
  478. }
  479. },
  480. DeleteFramebuffer: (id) => {
  481. let obj = this.framebuffers[id];
  482. if (obj && id != 0) {
  483. this.ctx.deleteFramebuffer(obj);
  484. this.framebuffers[id] = null;
  485. }
  486. },
  487. DeleteProgram: (id) => {
  488. let obj = this.programs[id];
  489. if (obj && id != 0) {
  490. this.ctx.deleteProgram(obj);
  491. this.programs[id] = null;
  492. }
  493. },
  494. DeleteRenderbuffer: (id) => {
  495. let obj = this.renderbuffers[id];
  496. if (obj && id != 0) {
  497. this.ctx.deleteRenderbuffer(obj);
  498. this.renderbuffers[id] = null;
  499. }
  500. },
  501. DeleteShader: (id) => {
  502. let obj = this.shaders[id];
  503. if (obj && id != 0) {
  504. this.ctx.deleteShader(obj);
  505. this.shaders[id] = null;
  506. }
  507. },
  508. DeleteTexture: (id) => {
  509. let obj = this.textures[id];
  510. if (obj && id != 0) {
  511. this.ctx.deleteTexture(obj);
  512. this.textures[id] = null;
  513. }
  514. },
  515. DepthFunc: (func) => {
  516. this.ctx.depthFunc(func);
  517. },
  518. DepthMask: (flag) => {
  519. this.ctx.depthMask(!!flag);
  520. },
  521. DepthRange: (zNear, zFar) => {
  522. this.ctx.depthRange(zNear, zFar);
  523. },
  524. DetachShader: (program, shader) => {
  525. this.ctx.detachShader(this.programs[program], this.shaders[shader]);
  526. },
  527. Disable: (cap) => {
  528. this.ctx.disable(cap);
  529. },
  530. DisableVertexAttribArray: (index) => {
  531. this.ctx.disableVertexAttribArray(index);
  532. },
  533. DrawArrays: (mode, first, count) => {
  534. this.ctx.drawArrays(mode, first, count);
  535. },
  536. DrawElements: (mode, count, type, indices) => {
  537. this.ctx.drawElements(mode, count, type, indices);
  538. },
  539. Enable: (cap) => {
  540. this.ctx.enable(cap);
  541. },
  542. EnableVertexAttribArray: (index) => {
  543. this.ctx.enableVertexAttribArray(index);
  544. },
  545. Finish: () => {
  546. this.ctx.finish();
  547. },
  548. Flush: () => {
  549. this.ctx.flush();
  550. },
  551. FramebufferRenderbuffer: (target, attachment, renderbuffertarget, renderbuffer) => {
  552. this.ctx.framebufferRenderbuffer(target, attachment, renderbuffertarget, this.renderbuffers[renderbuffer]);
  553. },
  554. FramebufferTexture2D: (target, attachment, textarget, texture, level) => {
  555. this.ctx.framebufferTexture2D(target, attachment, textarget, this.textures[texture], level);
  556. },
  557. FrontFace: (mode) => {
  558. this.ctx.frontFace(mode);
  559. },
  560. GenerateMipmap: (target) => {
  561. this.ctx.generateMipmap(target);
  562. },
  563. GetAttribLocation: (program, name_ptr, name_len) => {
  564. let name = this.mem.loadString(name_ptr, name_len);
  565. return this.ctx.getAttribLocation(this.programs[program], name);
  566. },
  567. GetParameter: (pname) => {
  568. return this.ctx.getParameter(pname);
  569. },
  570. GetProgramParameter: (program, pname) => {
  571. return this.ctx.getProgramParameter(this.programs[program], pname)
  572. },
  573. GetProgramInfoLog: (program, buf_ptr, buf_len, length_ptr) => {
  574. let log = this.ctx.getProgramInfoLog(this.programs[program]);
  575. if (log === null) {
  576. log = "(unknown error)";
  577. }
  578. if (buf_len > 0 && buf_ptr) {
  579. let n = Math.min(buf_len, log.length);
  580. log = log.substring(0, n);
  581. this.mem.loadBytes(buf_ptr, buf_len).set(new TextEncoder().encode(log))
  582. this.mem.storeInt(length_ptr, n);
  583. }
  584. },
  585. GetShaderInfoLog: (shader, buf_ptr, buf_len, length_ptr) => {
  586. let log = this.ctx.getShaderInfoLog(this.shaders[shader]);
  587. if (log === null) {
  588. log = "(unknown error)";
  589. }
  590. if (buf_len > 0 && buf_ptr) {
  591. let n = Math.min(buf_len, log.length);
  592. log = log.substring(0, n);
  593. this.mem.loadBytes(buf_ptr, buf_len).set(new TextEncoder().encode(log))
  594. this.mem.storeInt(length_ptr, n);
  595. }
  596. },
  597. GetShaderiv: (shader, pname, p) => {
  598. if (p) {
  599. if (pname == 35716) {
  600. let log = this.ctx.getShaderInfoLog(this.shaders[shader]);
  601. if (log === null) {
  602. log = "(unknown error)";
  603. }
  604. this.mem.storeInt(p, log.length+1);
  605. } else if (pname == 35720) {
  606. let source = this.ctx.getShaderSource(this.shaders[shader]);
  607. let sourceLength = (source === null || source.length == 0) ? 0 : source.length+1;
  608. this.mem.storeInt(p, sourceLength);
  609. } else {
  610. let param = this.ctx.getShaderParameter(this.shaders[shader], pname);
  611. this.mem.storeI32(p, param);
  612. }
  613. } else {
  614. this.recordError(1281);
  615. }
  616. },
  617. GetUniformLocation: (program, name_ptr, name_len) => {
  618. let name = this.mem.loadString(name_ptr, name_len);
  619. let arrayOffset = 0;
  620. if (name.indexOf("]", name.length - 1) !== -1) {
  621. let ls = name.lastIndexOf("["),
  622. arrayIndex = name.slice(ls + 1, -1);
  623. if (arrayIndex.length > 0 && (arrayOffset = parseInt(arrayIndex)) < 0) {
  624. return -1;
  625. }
  626. name = name.slice(0, ls)
  627. }
  628. var ptable = this.programInfos[program];
  629. if (!ptable) {
  630. return -1;
  631. }
  632. var uniformInfo = ptable.uniforms[name];
  633. return (uniformInfo && arrayOffset < uniformInfo[0]) ? uniformInfo[1] + arrayOffset : -1
  634. },
  635. GetVertexAttribOffset: (index, pname) => {
  636. return this.ctx.getVertexAttribOffset(index, pname);
  637. },
  638. Hint: (target, mode) => {
  639. this.ctx.hint(target, mode);
  640. },
  641. IsBuffer: (buffer) => this.ctx.isBuffer(this.buffers[buffer]),
  642. IsEnabled: (cap) => this.ctx.isEnabled(cap),
  643. IsFramebuffer: (framebuffer) => this.ctx.isFramebuffer(this.framebuffers[framebuffer]),
  644. IsProgram: (program) => this.ctx.isProgram(this.programs[program]),
  645. IsRenderbuffer: (renderbuffer) => this.ctx.isRenderbuffer(this.renderbuffers[renderbuffer]),
  646. IsShader: (shader) => this.ctx.isShader(this.shaders[shader]),
  647. IsTexture: (texture) => this.ctx.isTexture(this.textures[texture]),
  648. LineWidth: (width) => {
  649. this.ctx.lineWidth(width);
  650. },
  651. LinkProgram: (program) => {
  652. this.ctx.linkProgram(this.programs[program]);
  653. this.programInfos[program] = null;
  654. this.populateUniformTable(program);
  655. },
  656. PixelStorei: (pname, param) => {
  657. this.ctx.pixelStorei(pname, param);
  658. },
  659. PolygonOffset: (factor, units) => {
  660. this.ctx.polygonOffset(factor, units);
  661. },
  662. ReadnPixels: (x, y, width, height, format, type, bufSize, data) => {
  663. this.ctx.readPixels(x, y, width, height, format, type, this.mem.loadBytes(data, bufSize));
  664. },
  665. RenderbufferStorage: (target, internalformat, width, height) => {
  666. this.ctx.renderbufferStorage(target, internalformat, width, height);
  667. },
  668. SampleCoverage: (value, invert) => {
  669. this.ctx.sampleCoverage(value, !!invert);
  670. },
  671. Scissor: (x, y, width, height) => {
  672. this.ctx.scissor(x, y, width, height);
  673. },
  674. ShaderSource: (shader, strings_ptr, strings_length) => {
  675. let source = this.getSource(shader, strings_ptr, strings_length);
  676. this.ctx.shaderSource(this.shaders[shader], source);
  677. },
  678. StencilFunc: (func, ref, mask) => {
  679. this.ctx.stencilFunc(func, ref, mask);
  680. },
  681. StencilFuncSeparate: (face, func, ref, mask) => {
  682. this.ctx.stencilFuncSeparate(face, func, ref, mask);
  683. },
  684. StencilMask: (mask) => {
  685. this.ctx.stencilMask(mask);
  686. },
  687. StencilMaskSeparate: (face, mask) => {
  688. this.ctx.stencilMaskSeparate(face, mask);
  689. },
  690. StencilOp: (fail, zfail, zpass) => {
  691. this.ctx.stencilOp(fail, zfail, zpass);
  692. },
  693. StencilOpSeparate: (face, fail, zfail, zpass) => {
  694. this.ctx.stencilOpSeparate(face, fail, zfail, zpass);
  695. },
  696. TexImage2D: (target, level, internalformat, width, height, border, format, type, size, data) => {
  697. if (data) {
  698. this.ctx.texImage2D(target, level, internalformat, width, height, border, format, type, this.mem.loadBytes(data, size));
  699. } else {
  700. this.ctx.texImage2D(target, level, internalformat, width, height, border, format, type, null);
  701. }
  702. },
  703. TexParameterf: (target, pname, param) => {
  704. this.ctx.texParameterf(target, pname, param);
  705. },
  706. TexParameteri: (target, pname, param) => {
  707. this.ctx.texParameteri(target, pname, param);
  708. },
  709. TexSubImage2D: (target, level, xoffset, yoffset, width, height, format, type, size, data) => {
  710. this.ctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, this.mem.loadBytes(data, size));
  711. },
  712. Uniform1f: (location, v0) => { this.ctx.uniform1f(this.uniforms[location], v0); },
  713. Uniform2f: (location, v0, v1) => { this.ctx.uniform2f(this.uniforms[location], v0, v1); },
  714. Uniform3f: (location, v0, v1, v2) => { this.ctx.uniform3f(this.uniforms[location], v0, v1, v2); },
  715. Uniform4f: (location, v0, v1, v2, v3) => { this.ctx.uniform4f(this.uniforms[location], v0, v1, v2, v3); },
  716. Uniform1i: (location, v0) => { this.ctx.uniform1i(this.uniforms[location], v0); },
  717. Uniform2i: (location, v0, v1) => { this.ctx.uniform2i(this.uniforms[location], v0, v1); },
  718. Uniform3i: (location, v0, v1, v2) => { this.ctx.uniform3i(this.uniforms[location], v0, v1, v2); },
  719. Uniform4i: (location, v0, v1, v2, v3) => { this.ctx.uniform4i(this.uniforms[location], v0, v1, v2, v3); },
  720. UniformMatrix2fv: (location, addr) => {
  721. let array = this.mem.loadF32Array(addr, 2*2);
  722. this.ctx.uniformMatrix2fv(this.uniforms[location], false, array);
  723. },
  724. UniformMatrix3fv: (location, addr) => {
  725. let array = this.mem.loadF32Array(addr, 3*3);
  726. this.ctx.uniformMatrix3fv(this.uniforms[location], false, array);
  727. },
  728. UniformMatrix4fv: (location, addr) => {
  729. let array = this.mem.loadF32Array(addr, 4*4);
  730. this.ctx.uniformMatrix4fv(this.uniforms[location], false, array);
  731. },
  732. UseProgram: (program) => {
  733. if (program) this.ctx.useProgram(this.programs[program]);
  734. },
  735. ValidateProgram: (program) => {
  736. if (program) this.ctx.validateProgram(this.programs[program]);
  737. },
  738. VertexAttrib1f: (index, x) => {
  739. this.ctx.vertexAttrib1f(index, x);
  740. },
  741. VertexAttrib2f: (index, x, y) => {
  742. this.ctx.vertexAttrib2f(index, x, y);
  743. },
  744. VertexAttrib3f: (index, x, y, z) => {
  745. this.ctx.vertexAttrib3f(index, x, y, z);
  746. },
  747. VertexAttrib4f: (index, x, y, z, w) => {
  748. this.ctx.vertexAttrib4f(index, x, y, z, w);
  749. },
  750. VertexAttribPointer: (index, size, type, normalized, stride, ptr) => {
  751. this.ctx.vertexAttribPointer(index, size, type, !!normalized, stride, ptr);
  752. },
  753. Viewport: (x, y, w, h) => {
  754. this.ctx.viewport(x, y, w, h);
  755. },
  756. };
  757. }
  758. getWebGL2Interface() {
  759. return {
  760. /* Buffer objects */
  761. CopyBufferSubData: (readTarget, writeTarget, readOffset, writeOffset, size) => {
  762. this.assertWebGL2();
  763. this.ctx.copyBufferSubData(readTarget, writeTarget, readOffset, writeOffset, size);
  764. },
  765. GetBufferSubData: (target, srcByteOffset, dst_buffer_ptr, dst_buffer_len, dstOffset, length) => {
  766. this.assertWebGL2();
  767. this.ctx.getBufferSubData(target, srcByteOffset, this.mem.loadBytes(dst_buffer_ptr, dst_buffer_len), dstOffset, length);
  768. },
  769. /* Framebuffer objects */
  770. BlitFramebuffer: (srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter) => {
  771. this.assertWebGL2();
  772. this.ctx.blitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
  773. },
  774. FramebufferTextureLayer: (target, attachment, texture, level, layer) => {
  775. this.assertWebGL2();
  776. this.ctx.framebufferTextureLayer(target, attachment, this.textures[texture], level, layer);
  777. },
  778. InvalidateFramebuffer: (target, attachments_ptr, attachments_len) => {
  779. this.assertWebGL2();
  780. let attachments = this.mem.loadU32Array(attachments_ptr, attachments_len);
  781. this.ctx.invalidateFramebuffer(target, attachments);
  782. },
  783. InvalidateSubFramebuffer: (target, attachments_ptr, attachments_len, x, y, width, height) => {
  784. this.assertWebGL2();
  785. let attachments = this.mem.loadU32Array(attachments_ptr, attachments_len);
  786. this.ctx.invalidateSubFramebuffer(target, attachments, x, y, width, height);
  787. },
  788. ReadBuffer: (src) => {
  789. this.assertWebGL2();
  790. this.ctx.readBuffer(src);
  791. },
  792. /* Renderbuffer objects */
  793. RenderbufferStorageMultisample: (target, samples, internalformat, width, height) => {
  794. this.assertWebGL2();
  795. this.ctx.renderbufferStorageMultisample(target, samples, internalformat, width, height);
  796. },
  797. /* Texture objects */
  798. TexStorage3D: (target, levels, internalformat, width, height, depth) => {
  799. this.assertWebGL2();
  800. this.ctx.texStorage3D(target, levels, internalformat, width, height, depth);
  801. },
  802. TexImage3D: (target, level, internalformat, width, height, depth, border, format, type, size, data) => {
  803. this.assertWebGL2();
  804. if (data) {
  805. this.ctx.texImage3D(target, level, internalformat, width, height, depth, border, format, type, this.mem.loadBytes(data, size));
  806. } else {
  807. this.ctx.texImage3D(target, level, internalformat, width, height, depth, border, format, type, null);
  808. }
  809. },
  810. TexSubImage3D: (target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, size, data) => {
  811. this.assertWebGL2();
  812. this.ctx.texSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, this.mem.loadBytes(data, size));
  813. },
  814. CompressedTexImage3D: (target, level, internalformat, width, height, depth, border, imageSize, data) => {
  815. this.assertWebGL2();
  816. if (data) {
  817. this.ctx.compressedTexImage3D(target, level, internalformat, width, height, depth, border, this.mem.loadBytes(data, imageSize));
  818. } else {
  819. this.ctx.compressedTexImage3D(target, level, internalformat, width, height, depth, border, null);
  820. }
  821. },
  822. CompressedTexSubImage3D: (target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data) => {
  823. this.assertWebGL2();
  824. if (data) {
  825. this.ctx.compressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, this.mem.loadBytes(data, imageSize));
  826. } else {
  827. this.ctx.compressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, null);
  828. }
  829. },
  830. CopyTexSubImage3D: (target, level, xoffset, yoffset, zoffset, x, y, width, height) => {
  831. this.assertWebGL2();
  832. this.ctx.copyTexSubImage3D(target, level, xoffset, yoffset, zoffset, x, y, width, height);
  833. },
  834. /* Programs and shaders */
  835. GetFragDataLocation: (program, name_ptr, name_len) => {
  836. this.assertWebGL2();
  837. return this.ctx.getFragDataLocation(this.programs[program], this.mem.loadString(name_ptr, name_len));
  838. },
  839. /* Uniforms */
  840. Uniform1ui: (location, v0) => {
  841. this.assertWebGL2();
  842. this.ctx.uniform1ui(this.uniforms[location], v0);
  843. },
  844. Uniform2ui: (location, v0, v1) => {
  845. this.assertWebGL2();
  846. this.ctx.uniform2ui(this.uniforms[location], v0, v1);
  847. },
  848. Uniform3ui: (location, v0, v1, v2) => {
  849. this.assertWebGL2();
  850. this.ctx.uniform3ui(this.uniforms[location], v0, v1, v2);
  851. },
  852. Uniform4ui: (location, v0, v1, v2, v3) => {
  853. this.assertWebGL2();
  854. this.ctx.uniform4ui(this.uniforms[location], v0, v1, v2, v3);
  855. },
  856. UniformMatrix3x2fv: (location, addr) => {
  857. this.assertWebGL2();
  858. let array = this.mem.loadF32Array(addr, 3*2);
  859. this.ctx.uniformMatrix3x2fv(this.uniforms[location], false, array);
  860. },
  861. UniformMatrix4x2fv: (location, addr) => {
  862. this.assertWebGL2();
  863. let array = this.mem.loadF32Array(addr, 4*2);
  864. this.ctx.uniformMatrix4x2fv(this.uniforms[location], false, array);
  865. },
  866. UniformMatrix2x3fv: (location, addr) => {
  867. this.assertWebGL2();
  868. let array = this.mem.loadF32Array(addr, 2*3);
  869. this.ctx.uniformMatrix2x3fv(this.uniforms[location], false, array);
  870. },
  871. UniformMatrix4x3fv: (location, addr) => {
  872. this.assertWebGL2();
  873. let array = this.mem.loadF32Array(addr, 4*3);
  874. this.ctx.uniformMatrix4x3fv(this.uniforms[location], false, array);
  875. },
  876. UniformMatrix2x4fv: (location, addr) => {
  877. this.assertWebGL2();
  878. let array = this.mem.loadF32Array(addr, 2*4);
  879. this.ctx.uniformMatrix2x4fv(this.uniforms[location], false, array);
  880. },
  881. UniformMatrix3x4fv: (location, addr) => {
  882. this.assertWebGL2();
  883. let array = this.mem.loadF32Array(addr, 3*4);
  884. this.ctx.uniformMatrix3x4fv(this.uniforms[location], false, array);
  885. },
  886. /* Vertex attribs */
  887. VertexAttribI4i: (index, x, y, z, w) => {
  888. this.assertWebGL2();
  889. this.ctx.vertexAttribI4i(index, x, y, z, w);
  890. },
  891. VertexAttribI4ui: (index, x, y, z, w) => {
  892. this.assertWebGL2();
  893. this.ctx.vertexAttribI4ui(index, x, y, z, w);
  894. },
  895. VertexAttribIPointer: (index, size, type, stride, offset) => {
  896. this.assertWebGL2();
  897. this.ctx.vertexAttribIPointer(index, size, type, stride, offset);
  898. },
  899. /* Writing to the drawing buffer */
  900. VertexAttribDivisor: (index, divisor) => {
  901. this.assertWebGL2();
  902. this.ctx.vertexAttribDivisor(index, divisor);
  903. },
  904. DrawArraysInstanced: (mode, first, count, instanceCount) => {
  905. this.assertWebGL2();
  906. this.ctx.drawArraysInstanced(mode, first, count, instanceCount);
  907. },
  908. DrawElementsInstanced: (mode, count, type, offset, instanceCount) => {
  909. this.assertWebGL2();
  910. this.ctx.drawElementsInstanced(mode, count, type, offset, instanceCount);
  911. },
  912. DrawRangeElements: (mode, start, end, count, type, offset) => {
  913. this.assertWebGL2();
  914. this.ctx.drawRangeElements(mode, start, end, count, type, offset);
  915. },
  916. /* Multiple Render Targets */
  917. DrawBuffers: (buffers_ptr, buffers_len) => {
  918. this.assertWebGL2();
  919. let array = this.mem.loadU32Array(buffers_ptr, buffers_len);
  920. this.ctx.drawBuffers(array);
  921. },
  922. ClearBufferfv: (buffer, drawbuffer, values_ptr, values_len) => {
  923. this.assertWebGL2();
  924. let array = this.mem.loadF32Array(values_ptr, values_len);
  925. this.ctx.clearBufferfv(buffer, drawbuffer, array);
  926. },
  927. ClearBufferiv: (buffer, drawbuffer, values_ptr, values_len) => {
  928. this.assertWebGL2();
  929. let array = this.mem.loadI32Array(values_ptr, values_len);
  930. this.ctx.clearBufferiv(buffer, drawbuffer, array);
  931. },
  932. ClearBufferuiv: (buffer, drawbuffer, values_ptr, values_len) => {
  933. this.assertWebGL2();
  934. let array = this.mem.loadU32Array(values_ptr, values_len);
  935. this.ctx.clearBufferuiv(buffer, drawbuffer, array);
  936. },
  937. ClearBufferfi: (buffer, drawbuffer, depth, stencil) => {
  938. this.assertWebGL2();
  939. this.ctx.clearBufferfi(buffer, drawbuffer, depth, stencil);
  940. },
  941. /* Query Objects */
  942. CreateQuery: () => {
  943. this.assertWebGL2();
  944. let query = this.ctx.createQuery();
  945. let id = this.getNewId(this.queries);
  946. query.name = id;
  947. this.queries[id] = query;
  948. return id;
  949. },
  950. DeleteQuery: (id) => {
  951. this.assertWebGL2();
  952. let obj = this.queries[id];
  953. if (obj && id != 0) {
  954. this.ctx.deleteQuery(obj);
  955. this.queries[id] = null;
  956. }
  957. },
  958. IsQuery: (query) => {
  959. this.assertWebGL2();
  960. return this.ctx.isQuery(this.queries[query]);
  961. },
  962. BeginQuery: (target, query) => {
  963. this.assertWebGL2();
  964. this.ctx.beginQuery(target, this.queries[query])
  965. },
  966. EndQuery: (target) => {
  967. this.assertWebGL2();
  968. this.ctx.endQuery(target);
  969. },
  970. GetQuery: (target, pname) => {
  971. this.assertWebGL2();
  972. let query = this.ctx.getQuery(target, pname);
  973. if (!query) {
  974. return 0;
  975. }
  976. if (this.queries.indexOf(query) !== -1) {
  977. return query.name;
  978. }
  979. let id = this.getNewId(this.queries);
  980. query.name = id;
  981. this.queries[id] = query;
  982. return id;
  983. },
  984. /* Sampler Objects */
  985. CreateSampler: () => {
  986. this.assertWebGL2();
  987. let sampler = this.ctx.createSampler();
  988. let id = this.getNewId(this.samplers);
  989. sampler.name = id;
  990. this.samplers[id] = sampler;
  991. return id;
  992. },
  993. DeleteSampler: (id) => {
  994. this.assertWebGL2();
  995. let obj = this.samplers[id];
  996. if (obj && id != 0) {
  997. this.ctx.deleteSampler(obj);
  998. this.samplers[id] = null;
  999. }
  1000. },
  1001. IsSampler: (sampler) => {
  1002. this.assertWebGL2();
  1003. return this.ctx.isSampler(this.samplers[sampler]);
  1004. },
  1005. BindSampler: (unit, sampler) => {
  1006. this.assertWebGL2();
  1007. this.ctx.bindSampler(unit, this.samplers[sampler]);
  1008. },
  1009. SamplerParameteri: (sampler, pname, param) => {
  1010. this.assertWebGL2();
  1011. this.ctx.samplerParameteri(this.samplers[sampler], pname, param);
  1012. },
  1013. SamplerParameterf: (sampler, pname, param) => {
  1014. this.assertWebGL2();
  1015. this.ctx.samplerParameterf(this.samplers[sampler], pname, param);
  1016. },
  1017. /* Sync objects */
  1018. FenceSync: (condition, flags) => {
  1019. this.assertWebGL2();
  1020. let sync = this.ctx.fenceSync(condition, flags);
  1021. let id = this.getNewId(this.syncs);
  1022. sync.name = id;
  1023. this.syncs[id] = sync;
  1024. return id;
  1025. },
  1026. IsSync: (sync) => {
  1027. this.assertWebGL2();
  1028. return this.ctx.isSync(this.syncs[sync]);
  1029. },
  1030. DeleteSync: (id) => {
  1031. this.assertWebGL2();
  1032. let obj = this.syncs[id];
  1033. if (obj && id != 0) {
  1034. this.ctx.deleteSampler(obj);
  1035. this.syncs[id] = null;
  1036. }
  1037. },
  1038. ClientWaitSync: (sync, flags, timeout) => {
  1039. this.assertWebGL2();
  1040. return this.ctx.clientWaitSync(this.syncs[sync], flags, timeout);
  1041. },
  1042. WaitSync: (sync, flags, timeout) => {
  1043. this.assertWebGL2();
  1044. this.ctx.waitSync(this.syncs[sync], flags, timeout) ;
  1045. },
  1046. /* Transform Feedback */
  1047. CreateTransformFeedback: () => {
  1048. this.assertWebGL2();
  1049. let transformFeedback = this.ctx.createTransformFeedback();
  1050. let id = this.getNewId(this.transformFeedbacks);
  1051. transformFeedback.name = id;
  1052. this.transformFeedbacks[id] = transformFeedback;
  1053. return id;
  1054. },
  1055. DeleteTransformFeedback: (id) => {
  1056. this.assertWebGL2();
  1057. let obj = this.transformFeedbacks[id];
  1058. if (obj && id != 0) {
  1059. this.ctx.deleteTransformFeedback(obj);
  1060. this.transformFeedbacks[id] = null;
  1061. }
  1062. },
  1063. IsTransformFeedback: (tf) => {
  1064. this.assertWebGL2();
  1065. return this.ctx.isTransformFeedback(this.transformFeedbacks[tf]);
  1066. },
  1067. BindTransformFeedback: (target, tf) => {
  1068. this.assertWebGL2();
  1069. this.ctx.bindTransformFeedback(target, this.transformFeedbacks[tf]);
  1070. },
  1071. BeginTransformFeedback: (primitiveMode) => {
  1072. this.assertWebGL2();
  1073. this.ctx.beginTransformFeedback(primitiveMode);
  1074. },
  1075. EndTransformFeedback: () => {
  1076. this.assertWebGL2();
  1077. this.ctx.endTransformFeedback();
  1078. },
  1079. TransformFeedbackVaryings: (program, varyings_ptr, varyings_len, bufferMode) => {
  1080. this.assertWebGL2();
  1081. const stringSize = this.mem.intSize*2;
  1082. let varyings = [];
  1083. for (let i = 0; i < varyings_len; i++) {
  1084. let ptr = this.mem.loadPtr(varyings_ptr + i*stringSize + 0*4);
  1085. let len = this.mem.loadPtr(varyings_ptr + i*stringSize + 1*4);
  1086. varyings.push(this.mem.loadString(ptr, len));
  1087. }
  1088. this.ctx.transformFeedbackVaryings(this.programs[program], varyings, bufferMode);
  1089. },
  1090. PauseTransformFeedback: () => {
  1091. this.assertWebGL2();
  1092. this.ctx.pauseTransformFeedback();
  1093. },
  1094. ResumeTransformFeedback: () => {
  1095. this.assertWebGL2();
  1096. this.ctx.resumeTransformFeedback();
  1097. },
  1098. /* Uniform Buffer Objects and Transform Feedback Buffers */
  1099. BindBufferBase: (target, index, buffer) => {
  1100. this.assertWebGL2();
  1101. this.ctx.bindBufferBase(target, index, this.buffers[buffer]);
  1102. },
  1103. BindBufferRange: (target, index, buffer, offset, size) => {
  1104. this.assertWebGL2();
  1105. this.ctx.bindBufferRange(target, index, this.buffers[buffer], offset, size);
  1106. },
  1107. GetUniformBlockIndex: (program, uniformBlockName_ptr, uniformBlockName_len) => {
  1108. this.assertWebGL2();
  1109. return this.ctx.getUniformBlockIndex(this.programs[program], this.mem.loadString(uniformBlockName_ptr, uniformBlockName_len));
  1110. },
  1111. // any getActiveUniformBlockParameter(WebGLProgram program, GLuint uniformBlockIndex, GLenum pname);
  1112. GetActiveUniformBlockName: (program, uniformBlockIndex, buf_ptr, buf_len, length_ptr) => {
  1113. this.assertWebGL2();
  1114. let name = this.ctx.getActiveUniformBlockName(this.programs[program], uniformBlockIndex);
  1115. let n = Math.min(buf_len, name.length);
  1116. name = name.substring(0, n);
  1117. this.mem.loadBytes(buf_ptr, buf_len).set(new TextEncoder().encode(name))
  1118. this.mem.storeInt(length_ptr, n);
  1119. },
  1120. UniformBlockBinding: (program, uniformBlockIndex, uniformBlockBinding) => {
  1121. this.assertWebGL2();
  1122. this.ctx.uniformBlockBinding(this.programs[program], uniformBlockIndex, uniformBlockBinding);
  1123. },
  1124. /* Vertex Array Objects */
  1125. CreateVertexArray: () => {
  1126. this.assertWebGL2();
  1127. let vao = this.ctx.createVertexArray();
  1128. let id = this.getNewId(this.vaos);
  1129. vao.name = id;
  1130. this.vaos[id] = vao;
  1131. return id;
  1132. },
  1133. DeleteVertexArray: (id) => {
  1134. this.assertWebGL2();
  1135. let obj = this.vaos[id];
  1136. if (obj && id != 0) {
  1137. this.ctx.deleteVertexArray(obj);
  1138. this.vaos[id] = null;
  1139. }
  1140. },
  1141. IsVertexArray: (vertexArray) => {
  1142. this.assertWebGL2();
  1143. return this.ctx.isVertexArray(this.vaos[vertexArray]);
  1144. },
  1145. BindVertexArray: (vertexArray) => {
  1146. this.assertWebGL2();
  1147. this.ctx.bindVertexArray(this.vaos[vertexArray]);
  1148. },
  1149. };
  1150. }
  1151. };
  1152. function odinSetupDefaultImports(wasmMemoryInterface, consoleElement, memory, eventQueue, event_temp) {
  1153. const MAX_INFO_CONSOLE_LINES = 512;
  1154. let infoConsoleLines = new Array();
  1155. let currentLine = {};
  1156. currentLine[false] = "";
  1157. currentLine[true] = "";
  1158. let prevIsError = false;
  1159. const writeToConsole = (line, isError) => {
  1160. if (!line) {
  1161. return;
  1162. }
  1163. const println = (text, forceIsError) => {
  1164. let style = [
  1165. "color: #eee",
  1166. "background-color: #d20",
  1167. "padding: 2px 4px",
  1168. "border-radius: 2px",
  1169. ].join(";");
  1170. let doIsError = isError;
  1171. if (forceIsError !== undefined) {
  1172. doIsError = forceIsError;
  1173. }
  1174. if (doIsError) {
  1175. console.log("%c"+text, style);
  1176. } else {
  1177. console.log(text);
  1178. }
  1179. };
  1180. // Print to console
  1181. if (line == "\n") {
  1182. println(currentLine[isError]);
  1183. currentLine[isError] = "";
  1184. } else if (!line.includes("\n")) {
  1185. currentLine[isError] = currentLine[isError].concat(line);
  1186. } else {
  1187. let lines = line.split("\n");
  1188. let printLast = lines.length > 1 && line.endsWith("\n");
  1189. println(currentLine[isError].concat(lines[0]));
  1190. currentLine[isError] = "";
  1191. for (let i = 1; i < lines.length-1; i++) {
  1192. println(lines[i]);
  1193. }
  1194. let last = lines[lines.length-1];
  1195. if (printLast) {
  1196. println(last);
  1197. } else {
  1198. currentLine[isError] = last;
  1199. }
  1200. }
  1201. if (prevIsError != isError) {
  1202. if (prevIsError) {
  1203. println(currentLine[prevIsError], prevIsError);
  1204. currentLine[prevIsError] = "";
  1205. }
  1206. }
  1207. prevIsError = isError;
  1208. // HTML based console
  1209. if (!consoleElement) {
  1210. return;
  1211. }
  1212. const wrap = (x) => {
  1213. if (isError) {
  1214. return '<span style="color:#f21">'+x+'</span>';
  1215. }
  1216. return x;
  1217. };
  1218. if (line == "\n") {
  1219. infoConsoleLines.push(line);
  1220. } else if (!line.includes("\n")) {
  1221. let prevLine = "";
  1222. if (infoConsoleLines.length > 0) {
  1223. prevLine = infoConsoleLines.pop();
  1224. }
  1225. infoConsoleLines.push(prevLine.concat(wrap(line)));
  1226. } else {
  1227. let lines = line.split("\n");
  1228. let lastHasNewline = lines.length > 1 && line.endsWith("\n");
  1229. let prevLine = "";
  1230. if (infoConsoleLines.length > 0) {
  1231. prevLine = infoConsoleLines.pop();
  1232. }
  1233. infoConsoleLines.push(prevLine.concat(wrap(lines[0]).concat("\n")));
  1234. for (let i = 1; i < lines.length-1; i++) {
  1235. infoConsoleLines.push(wrap(lines[i]).concat("\n"));
  1236. }
  1237. let last = lines[lines.length-1];
  1238. if (lastHasNewline) {
  1239. infoConsoleLines.push(last.concat("\n"));
  1240. } else {
  1241. infoConsoleLines.push(last);
  1242. }
  1243. }
  1244. if (infoConsoleLines.length > MAX_INFO_CONSOLE_LINES) {
  1245. infoConsoleLines.shift(MAX_INFO_CONSOLE_LINES);
  1246. }
  1247. let data = "";
  1248. for (let i = 0; i < infoConsoleLines.length; i++) {
  1249. data = data.concat(infoConsoleLines[i]);
  1250. }
  1251. let info = consoleElement;
  1252. info.innerHTML = data;
  1253. info.scrollTop = info.scrollHeight;
  1254. };
  1255. let webglContext = new WebGLInterface(wasmMemoryInterface);
  1256. const env = {};
  1257. if (memory) {
  1258. env.memory = memory;
  1259. }
  1260. return {
  1261. env,
  1262. "odin_env": {
  1263. write: (fd, ptr, len) => {
  1264. const str = wasmMemoryInterface.loadString(ptr, len);
  1265. if (fd == 1) {
  1266. writeToConsole(str, false);
  1267. return;
  1268. } else if (fd == 2) {
  1269. writeToConsole(str, true);
  1270. return;
  1271. } else {
  1272. throw new Error("Invalid fd to 'write'" + stripNewline(str));
  1273. }
  1274. },
  1275. trap: () => { throw new Error() },
  1276. alert: (ptr, len) => { alert(wasmMemoryInterface.loadString(ptr, len)) },
  1277. abort: () => { Module.abort() },
  1278. evaluate: (str_ptr, str_len) => { eval.call(null, wasmMemoryInterface.loadString(str_ptr, str_len)); },
  1279. // return a bigint to be converted to i64
  1280. time_now: () => BigInt(Date.now()),
  1281. tick_now: () => performance.now(),
  1282. time_sleep: (duration_ms) => {
  1283. if (duration_ms > 0) {
  1284. // TODO(bill): Does this even make any sense?
  1285. }
  1286. },
  1287. sqrt: Math.sqrt,
  1288. sin: Math.sin,
  1289. cos: Math.cos,
  1290. pow: Math.pow,
  1291. fmuladd: (x, y, z) => x*y + z,
  1292. ln: Math.log,
  1293. exp: Math.exp,
  1294. ldexp: (x, exp) => x * Math.pow(2, exp),
  1295. rand_bytes: (ptr, len) => {
  1296. const view = new Uint8Array(wasmMemoryInterface.memory.buffer, ptr, len)
  1297. crypto.getRandomValues(view)
  1298. },
  1299. },
  1300. "odin_dom": {
  1301. init_event_raw: (ep) => {
  1302. const W = wasmMemoryInterface.intSize;
  1303. let offset = ep;
  1304. let off = (amount, alignment) => {
  1305. if (alignment === undefined) {
  1306. alignment = Math.min(amount, W);
  1307. }
  1308. if (offset % alignment != 0) {
  1309. offset += alignment - (offset%alignment);
  1310. }
  1311. let x = offset;
  1312. offset += amount;
  1313. return x;
  1314. };
  1315. let align = (alignment) => {
  1316. const modulo = offset & (alignment-1);
  1317. if (modulo != 0) {
  1318. offset += alignment - modulo
  1319. }
  1320. };
  1321. let wmi = wasmMemoryInterface;
  1322. if (!event_temp.data) {
  1323. return;
  1324. }
  1325. let e = event_temp.data.event;
  1326. wmi.storeU32(off(4), event_temp.data.name_code);
  1327. if (e.target == document) {
  1328. wmi.storeU32(off(4), 1);
  1329. } else if (e.target == window) {
  1330. wmi.storeU32(off(4), 2);
  1331. } else {
  1332. wmi.storeU32(off(4), 0);
  1333. }
  1334. if (e.currentTarget == document) {
  1335. wmi.storeU32(off(4), 1);
  1336. } else if (e.currentTarget == window) {
  1337. wmi.storeU32(off(4), 2);
  1338. } else {
  1339. wmi.storeU32(off(4), 0);
  1340. }
  1341. align(W);
  1342. wmi.storeI32(off(W), event_temp.data.id_ptr);
  1343. wmi.storeUint(off(W), event_temp.data.id_len);
  1344. align(8);
  1345. wmi.storeF64(off(8), e.timeStamp*1e-3);
  1346. wmi.storeU8(off(1), e.eventPhase);
  1347. let options = 0;
  1348. if (!!e.bubbles) { options |= 1<<0; }
  1349. if (!!e.cancelable) { options |= 1<<1; }
  1350. if (!!e.composed) { options |= 1<<2; }
  1351. wmi.storeU8(off(1), options);
  1352. wmi.storeU8(off(1), !!e.isComposing);
  1353. wmi.storeU8(off(1), !!e.isTrusted);
  1354. align(8);
  1355. if (e instanceof WheelEvent) {
  1356. wmi.storeF64(off(8), e.deltaX);
  1357. wmi.storeF64(off(8), e.deltaY);
  1358. wmi.storeF64(off(8), e.deltaZ);
  1359. wmi.storeU32(off(4), e.deltaMode);
  1360. } else if (e instanceof MouseEvent) {
  1361. wmi.storeI64(off(8), e.screenX);
  1362. wmi.storeI64(off(8), e.screenY);
  1363. wmi.storeI64(off(8), e.clientX);
  1364. wmi.storeI64(off(8), e.clientY);
  1365. wmi.storeI64(off(8), e.offsetX);
  1366. wmi.storeI64(off(8), e.offsetY);
  1367. wmi.storeI64(off(8), e.pageX);
  1368. wmi.storeI64(off(8), e.pageY);
  1369. wmi.storeI64(off(8), e.movementX);
  1370. wmi.storeI64(off(8), e.movementY);
  1371. wmi.storeU8(off(1), !!e.ctrlKey);
  1372. wmi.storeU8(off(1), !!e.shiftKey);
  1373. wmi.storeU8(off(1), !!e.altKey);
  1374. wmi.storeU8(off(1), !!e.metaKey);
  1375. wmi.storeI16(off(2), e.button);
  1376. wmi.storeU16(off(2), e.buttons);
  1377. } else if (e instanceof KeyboardEvent) {
  1378. // Note: those strings are constructed
  1379. // on the native side from buffers that
  1380. // are filled later, so skip them
  1381. const keyPtr = off(W*2, W);
  1382. const codePtr = off(W*2, W);
  1383. wmi.storeU8(off(1), e.location);
  1384. wmi.storeU8(off(1), !!e.ctrlKey);
  1385. wmi.storeU8(off(1), !!e.shiftKey);
  1386. wmi.storeU8(off(1), !!e.altKey);
  1387. wmi.storeU8(off(1), !!e.metaKey);
  1388. wmi.storeU8(off(1), !!e.repeat);
  1389. wmi.storeInt(off(W, W), e.key.length)
  1390. wmi.storeInt(off(W, W), e.code.length)
  1391. wmi.storeString(off(16, 1), e.key);
  1392. wmi.storeString(off(16, 1), e.code);
  1393. } else if (e.type === 'scroll') {
  1394. wmi.storeF64(off(8, 8), window.scrollX);
  1395. wmi.storeF64(off(8, 8), window.scrollY);
  1396. } else if (e.type === 'visibilitychange') {
  1397. wmi.storeU8(off(1), !document.hidden);
  1398. } else if (e instanceof GamepadEvent) {
  1399. const idPtr = off(W*2, W);
  1400. const mappingPtr = off(W*2, W);
  1401. wmi.storeI32(off(W, W), e.gamepad.index);
  1402. wmi.storeU8(off(1), !!e.gamepad.connected);
  1403. wmi.storeF64(off(8, 8), e.gamepad.timestamp);
  1404. wmi.storeInt(off(W, W), e.gamepad.buttons.length);
  1405. wmi.storeInt(off(W, W), e.gamepad.axes.length);
  1406. for (let i = 0; i < 64; i++) {
  1407. if (i < e.gamepad.buttons.length) {
  1408. let b = e.gamepad.buttons[i];
  1409. wmi.storeF64(off(8, 8), b.value);
  1410. wmi.storeU8(off(1), !!b.pressed);
  1411. wmi.storeU8(off(1), !!b.touched);
  1412. } else {
  1413. off(16, 8);
  1414. }
  1415. }
  1416. for (let i = 0; i < 16; i++) {
  1417. if (i < e.gamepad.axes.length) {
  1418. let a = e.gamepad.axes[i];
  1419. wmi.storeF64(off(8, 8), a);
  1420. } else {
  1421. off(8, 8);
  1422. }
  1423. }
  1424. wmi.storeInt(off(W, W), e.gamepad.id.length)
  1425. wmi.storeInt(off(W, W), e.gamepad.mapping.length)
  1426. wmi.storeString(off(64, 1), e.gamepad.id);
  1427. wmi.storeString(off(64, 1), e.gamepad.mapping);
  1428. }
  1429. },
  1430. add_event_listener: (id_ptr, id_len, name_ptr, name_len, name_code, data, callback, use_capture) => {
  1431. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1432. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1433. let element = getElement(id);
  1434. if (element == undefined) {
  1435. return false;
  1436. }
  1437. let listener = (e) => {
  1438. let event_data = {};
  1439. event_data.id_ptr = id_ptr;
  1440. event_data.id_len = id_len;
  1441. event_data.event = e;
  1442. event_data.name_code = name_code;
  1443. eventQueue.push({event_data: event_data, data: data, callback: callback});
  1444. };
  1445. wasmMemoryInterface.listenerMap[{data: data, callback: callback}] = listener;
  1446. element.addEventListener(name, listener, !!use_capture);
  1447. return true;
  1448. },
  1449. add_window_event_listener: (name_ptr, name_len, name_code, data, callback, use_capture) => {
  1450. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1451. let element = window;
  1452. let listener = (e) => {
  1453. let event_data = {};
  1454. event_data.id_ptr = 0;
  1455. event_data.id_len = 0;
  1456. event_data.event = e;
  1457. event_data.name_code = name_code;
  1458. eventQueue.push({event_data: event_data, data: data, callback: callback});
  1459. };
  1460. wasmMemoryInterface.listenerMap[{data: data, callback: callback}] = listener;
  1461. element.addEventListener(name, listener, !!use_capture);
  1462. return true;
  1463. },
  1464. remove_event_listener: (id_ptr, id_len, name_ptr, name_len, data, callback) => {
  1465. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1466. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1467. let element = getElement(id);
  1468. if (element == undefined) {
  1469. return false;
  1470. }
  1471. let listener = wasmMemoryInterface.listenerMap[{data: data, callback: callback}];
  1472. if (listener == undefined) {
  1473. return false;
  1474. }
  1475. element.removeEventListener(name, listener);
  1476. return true;
  1477. },
  1478. remove_window_event_listener: (name_ptr, name_len, data, callback) => {
  1479. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1480. let element = window;
  1481. let key = {data: data, callback: callback};
  1482. let listener = wasmMemoryInterface.listenerMap[key];
  1483. if (!listener) {
  1484. return false;
  1485. }
  1486. wasmMemoryInterface.listenerMap[key] = undefined;
  1487. element.removeEventListener(name, listener);
  1488. return true;
  1489. },
  1490. event_stop_propagation: () => {
  1491. if (event_temp.data && event_temp.data.event) {
  1492. event_temp.data.event.stopPropagation();
  1493. }
  1494. },
  1495. event_stop_immediate_propagation: () => {
  1496. if (event_temp.data && event_temp.data.event) {
  1497. event_temp.data.event.stopImmediatePropagation();
  1498. }
  1499. },
  1500. event_prevent_default: () => {
  1501. if (event_temp.data && event_temp.data.event) {
  1502. event_temp.data.event.preventDefault();
  1503. }
  1504. },
  1505. dispatch_custom_event: (id_ptr, id_len, name_ptr, name_len, options_bits) => {
  1506. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1507. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1508. let options = {
  1509. bubbles: (options_bits & (1<<0)) !== 0,
  1510. cancelable: (options_bits & (1<<1)) !== 0,
  1511. composed: (options_bits & (1<<2)) !== 0,
  1512. };
  1513. let element = getElement(id);
  1514. if (element) {
  1515. element.dispatchEvent(new Event(name, options));
  1516. return true;
  1517. }
  1518. return false;
  1519. },
  1520. get_gamepad_state: (gamepad_id, ep) => {
  1521. let index = gamepad_id;
  1522. let gps = navigator.getGamepads();
  1523. if (0 <= index && index < gps.length) {
  1524. let gamepad = gps[index];
  1525. if (!gamepad) {
  1526. return false;
  1527. }
  1528. const W = wasmMemoryInterface.intSize;
  1529. let offset = ep;
  1530. let off = (amount, alignment) => {
  1531. if (alignment === undefined) {
  1532. alignment = Math.min(amount, W);
  1533. }
  1534. if (offset % alignment != 0) {
  1535. offset += alignment - (offset%alignment);
  1536. }
  1537. let x = offset;
  1538. offset += amount;
  1539. return x;
  1540. };
  1541. let align = (alignment) => {
  1542. const modulo = offset & (alignment-1);
  1543. if (modulo != 0) {
  1544. offset += alignment - modulo
  1545. }
  1546. };
  1547. let wmi = wasmMemoryInterface;
  1548. const idPtr = off(W*2, W);
  1549. const mappingPtr = off(W*2, W);
  1550. wmi.storeI32(off(W), gamepad.index);
  1551. wmi.storeU8(off(1), !!gamepad.connected);
  1552. wmi.storeF64(off(8), gamepad.timestamp);
  1553. wmi.storeInt(off(W), gamepad.buttons.length);
  1554. wmi.storeInt(off(W), gamepad.axes.length);
  1555. for (let i = 0; i < 64; i++) {
  1556. if (i < gamepad.buttons.length) {
  1557. let b = gamepad.buttons[i];
  1558. wmi.storeF64(off(8, 8), b.value);
  1559. wmi.storeU8(off(1), !!b.pressed);
  1560. wmi.storeU8(off(1), !!b.touched);
  1561. } else {
  1562. off(16, 8);
  1563. }
  1564. }
  1565. for (let i = 0; i < 16; i++) {
  1566. if (i < gamepad.axes.length) {
  1567. wmi.storeF64(off(8, 8), gamepad.axes[i]);
  1568. } else {
  1569. off(8, 8);
  1570. }
  1571. }
  1572. wmi.storeInt(off(W, W), gamepad.id.length)
  1573. wmi.storeInt(off(W, W), gamepad.mapping.length)
  1574. wmi.storeString(off(64, 1), gamepad.id);
  1575. wmi.storeString(off(64, 1), gamepad.mapping);
  1576. return true;
  1577. }
  1578. return false;
  1579. },
  1580. get_element_value_f64: (id_ptr, id_len) => {
  1581. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1582. let element = getElement(id);
  1583. return element ? element.value : 0;
  1584. },
  1585. get_element_value_string: (id_ptr, id_len, buf_ptr, buf_len) => {
  1586. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1587. let element = getElement(id);
  1588. if (element) {
  1589. let str = element.value;
  1590. if (buf_len > 0 && buf_ptr) {
  1591. let n = Math.min(buf_len, str.length);
  1592. str = str.substring(0, n);
  1593. this.mem.loadBytes(buf_ptr, buf_len).set(new TextEncoder().encode(str))
  1594. return n;
  1595. }
  1596. }
  1597. return 0;
  1598. },
  1599. get_element_value_string_length: (id_ptr, id_len) => {
  1600. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1601. let element = getElement(id);
  1602. if (element) {
  1603. return element.value.length;
  1604. }
  1605. return 0;
  1606. },
  1607. get_element_min_max: (ptr_array2_f64, id_ptr, id_len) => {
  1608. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1609. let element = getElement(id);
  1610. if (element) {
  1611. let values = wasmMemoryInterface.loadF64Array(ptr_array2_f64, 2);
  1612. values[0] = element.min;
  1613. values[1] = element.max;
  1614. }
  1615. },
  1616. set_element_value_f64: (id_ptr, id_len, value) => {
  1617. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1618. let element = getElement(id);
  1619. if (element) {
  1620. element.value = value;
  1621. }
  1622. },
  1623. set_element_value_string: (id_ptr, id_len, value_ptr, value_len) => {
  1624. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1625. let value = wasmMemoryInterface.loadString(value_ptr, value_len);
  1626. let element = getElement(id);
  1627. if (element) {
  1628. element.value = value;
  1629. }
  1630. },
  1631. set_element_style: (id_ptr, id_len, key_ptr, key_len, value_ptr, value_len) => {
  1632. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1633. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1634. let value = wasmMemoryInterface.loadString(value_ptr, value_len);
  1635. let element = getElement(id);
  1636. if (element) {
  1637. element.style[key] = value;
  1638. }
  1639. },
  1640. get_element_key_f64: (id_ptr, id_len, key_ptr, key_len) => {
  1641. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1642. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1643. let element = getElement(id);
  1644. return element ? element[key] : 0;
  1645. },
  1646. get_element_key_string: (id_ptr, id_len, key_ptr, key_len, buf_ptr, buf_len) => {
  1647. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1648. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1649. let element = getElement(id);
  1650. if (element) {
  1651. let str = element[key];
  1652. if (buf_len > 0 && buf_ptr) {
  1653. let n = Math.min(buf_len, str.length);
  1654. str = str.substring(0, n);
  1655. this.mem.loadBytes(buf_ptr, buf_len).set(new TextEncoder().encode(str))
  1656. return n;
  1657. }
  1658. }
  1659. return 0;
  1660. },
  1661. get_element_key_string_length: (id_ptr, id_len, key_ptr, key_len) => {
  1662. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1663. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1664. let element = getElement(id);
  1665. if (element && element[key]) {
  1666. return element[key].length;
  1667. }
  1668. return 0;
  1669. },
  1670. set_element_key_f64: (id_ptr, id_len, key_ptr, key_len, value) => {
  1671. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1672. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1673. let element = getElement(id);
  1674. if (element) {
  1675. element[key] = value;
  1676. }
  1677. },
  1678. set_element_key_string: (id_ptr, id_len, key_ptr, key_len, value_ptr, value_len) => {
  1679. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1680. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1681. let value = wasmMemoryInterface.loadString(value_ptr, value_len);
  1682. let element = getElement(id);
  1683. if (element) {
  1684. element[key] = value;
  1685. }
  1686. },
  1687. get_bounding_client_rect: (rect_ptr, id_ptr, id_len) => {
  1688. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1689. let element = getElement(id);
  1690. if (element) {
  1691. let values = wasmMemoryInterface.loadF64Array(rect_ptr, 4);
  1692. let rect = element.getBoundingClientRect();
  1693. values[0] = rect.left;
  1694. values[1] = rect.top;
  1695. values[2] = rect.right - rect.left;
  1696. values[3] = rect.bottom - rect.top;
  1697. }
  1698. },
  1699. window_get_rect: (rect_ptr) => {
  1700. let values = wasmMemoryInterface.loadF64Array(rect_ptr, 4);
  1701. values[0] = window.screenX;
  1702. values[1] = window.screenY;
  1703. values[2] = window.screen.width;
  1704. values[3] = window.screen.height;
  1705. },
  1706. window_get_scroll: (pos_ptr) => {
  1707. let values = wasmMemoryInterface.loadF64Array(pos_ptr, 2);
  1708. values[0] = window.scrollX;
  1709. values[1] = window.scrollY;
  1710. },
  1711. window_set_scroll: (x, y) => {
  1712. window.scroll(x, y);
  1713. },
  1714. device_pixel_ratio: () => {
  1715. return window.devicePixelRatio;
  1716. },
  1717. },
  1718. "webgl": webglContext.getWebGL1Interface(),
  1719. "webgl2": webglContext.getWebGL2Interface(),
  1720. };
  1721. };
  1722. /**
  1723. * @param {string} wasmPath - Path to the WASM module to run
  1724. * @param {?HTMLPreElement} consoleElement - Optional console/pre element to append output to, in addition to the console
  1725. * @param {any} extraForeignImports - Imports, in addition to the default runtime to provide the module
  1726. * @param {?WasmMemoryInterface} wasmMemoryInterface - Optional memory to use instead of the defaults
  1727. * @param {?int} intSize - Size (in bytes) of the integer type, should be 4 on `js_wasm32` and 8 on `js_wasm64p32`
  1728. */
  1729. async function runWasm(wasmPath, consoleElement, extraForeignImports, wasmMemoryInterface, intSize = 4) {
  1730. if (!wasmMemoryInterface) {
  1731. wasmMemoryInterface = new WasmMemoryInterface();
  1732. }
  1733. wasmMemoryInterface.setIntSize(intSize);
  1734. let eventQueue = new Array();
  1735. let event_temp = {};
  1736. let imports = odinSetupDefaultImports(wasmMemoryInterface, consoleElement, wasmMemoryInterface.memory, eventQueue, event_temp);
  1737. let exports = {};
  1738. if (extraForeignImports !== undefined) {
  1739. imports = {
  1740. ...imports,
  1741. ...extraForeignImports,
  1742. };
  1743. }
  1744. const response = await fetch(wasmPath);
  1745. const file = await response.arrayBuffer();
  1746. const wasm = await WebAssembly.instantiate(file, imports);
  1747. exports = wasm.instance.exports;
  1748. wasmMemoryInterface.setExports(exports);
  1749. if (exports.memory) {
  1750. if (wasmMemoryInterface.memory) {
  1751. console.warn("WASM module exports memory, but `runWasm` was given an interface with existing memory too");
  1752. }
  1753. wasmMemoryInterface.setMemory(exports.memory);
  1754. }
  1755. exports._start();
  1756. // Define a `@export step :: proc(delta_time: f64) -> (keep_going: bool) {`
  1757. // in your app and it will get called every frame.
  1758. // return `false` to stop the execution of the module.
  1759. if (exports.step) {
  1760. const odin_ctx = exports.default_context_ptr();
  1761. let prevTimeStamp = undefined;
  1762. function step(currTimeStamp) {
  1763. if (prevTimeStamp == undefined) {
  1764. prevTimeStamp = currTimeStamp;
  1765. }
  1766. const dt = (currTimeStamp - prevTimeStamp)*0.001;
  1767. prevTimeStamp = currTimeStamp;
  1768. while (eventQueue.length > 0) {
  1769. let e = eventQueue.shift()
  1770. event_temp.data = e.event_data;
  1771. exports.odin_dom_do_event_callback(e.data, e.callback, odin_ctx);
  1772. }
  1773. event_temp.data = null;
  1774. if (!exports.step(dt, odin_ctx)) {
  1775. exports._end();
  1776. return;
  1777. }
  1778. window.requestAnimationFrame(step);
  1779. }
  1780. window.requestAnimationFrame(step);
  1781. } else {
  1782. exports._end();
  1783. }
  1784. return;
  1785. };
  1786. window.odin = {
  1787. // Interface Types
  1788. WasmMemoryInterface: WasmMemoryInterface,
  1789. WebGLInterface: WebGLInterface,
  1790. // Functions
  1791. setupDefaultImports: odinSetupDefaultImports,
  1792. runWasm: runWasm,
  1793. };
  1794. })();