odin.js 61 KB

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