runtime.js 52 KB

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