runtime.js 49 KB

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