Browse Source

[web] port JS code to Rust

pull/9/head
Emil Ernerfeldt 4 years ago
parent
commit
0afad57d41
  1. 255
      docs/example_wasm.js
  2. BIN
      docs/example_wasm_bg.wasm
  3. 224
      docs/index.html
  4. 4
      egui/src/math.rs
  5. 3
      egui_web/Cargo.toml
  6. 157
      egui_web/src/lib.rs
  7. 91
      example_wasm/src/lib.rs

255
docs/example_wasm.js

@ -48,6 +48,26 @@ function addHeapObject(obj) {
return idx;
}
function isLikeNone(x) {
return x === undefined || x === null;
}
let cachegetFloat64Memory0 = null;
function getFloat64Memory0() {
if (cachegetFloat64Memory0 === null || cachegetFloat64Memory0.buffer !== wasm.memory.buffer) {
cachegetFloat64Memory0 = new Float64Array(wasm.memory.buffer);
}
return cachegetFloat64Memory0;
}
let cachegetInt32Memory0 = null;
function getInt32Memory0() {
if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {
cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);
}
return cachegetInt32Memory0;
}
function debugString(val) {
// primitive types
const type = typeof val;
@ -167,14 +187,6 @@ function passStringToWasm0(arg, malloc, realloc) {
WASM_VECTOR_LEN = offset;
return ptr;
}
let cachegetInt32Memory0 = null;
function getInt32Memory0() {
if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {
cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);
}
return cachegetInt32Memory0;
}
/**
* @param {string} canvas_id
* @returns {State}
@ -186,6 +198,15 @@ __exports.new_webgl_gui = function(canvas_id) {
return State.__wrap(ret);
};
/**
* @param {string} canvas_id
*/
__exports.resize_to_screen_size = function(canvas_id) {
var ptr0 = passStringToWasm0(canvas_id, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.resize_to_screen_size(ptr0, len0);
};
function _assertClass(instance, klass) {
if (!(instance instanceof klass)) {
throw new Error(`expected instance of ${klass.name}`);
@ -195,26 +216,14 @@ function _assertClass(instance, klass) {
/**
* @param {State} state
* @param {string} web_input_json
* @returns {string}
*/
__exports.run_gui = function(state, web_input_json) {
try {
_assertClass(state, State);
var ptr0 = passStringToWasm0(web_input_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.run_gui(8, state.ptr, ptr0, len0);
var r0 = getInt32Memory0()[8 / 4 + 0];
var r1 = getInt32Memory0()[8 / 4 + 1];
return getStringFromWasm0(r0, r1);
} finally {
wasm.__wbindgen_free(r0, r1);
}
_assertClass(state, State);
var ptr0 = passStringToWasm0(web_input_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
wasm.run_gui(state.ptr, ptr0, len0);
};
function isLikeNone(x) {
return x === undefined || x === null;
}
function handleError(f) {
return function () {
try {
@ -301,184 +310,228 @@ async function init(input) {
var ret = getStringFromWasm0(arg0, arg1);
return addHeapObject(ret);
};
imports.wbg.__wbg_instanceof_Window_17fdb5cd280d476d = function(arg0) {
imports.wbg.__wbg_instanceof_Window_0e8decd0a6179699 = function(arg0) {
var ret = getObject(arg0) instanceof Window;
return ret;
};
imports.wbg.__wbg_document_c26d0f423c143e0c = function(arg0) {
imports.wbg.__wbg_document_76c349f54c28c8fa = function(arg0) {
var ret = getObject(arg0).document;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
imports.wbg.__wbg_performance_781c00e4226de6c4 = function(arg0) {
imports.wbg.__wbg_location_9b266239ee5a222a = function(arg0) {
var ret = getObject(arg0).location;
return addHeapObject(ret);
};
imports.wbg.__wbg_innerWidth_17617548d79db8b4 = handleError(function(arg0) {
var ret = getObject(arg0).innerWidth;
return addHeapObject(ret);
});
imports.wbg.__wbg_innerHeight_d010431b496bbadb = handleError(function(arg0) {
var ret = getObject(arg0).innerHeight;
return addHeapObject(ret);
});
imports.wbg.__wbg_devicePixelRatio_81f8802ff64194df = function(arg0) {
var ret = getObject(arg0).devicePixelRatio;
return ret;
};
imports.wbg.__wbg_performance_7aa28f53ba322a5a = function(arg0) {
var ret = getObject(arg0).performance;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
imports.wbg.__wbg_localStorage_09146b4f48d49bc9 = handleError(function(arg0) {
imports.wbg.__wbg_localStorage_62f777b1184f4bea = handleError(function(arg0) {
var ret = getObject(arg0).localStorage;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
});
imports.wbg.__wbg_getElementById_df597d226f179219 = function(arg0, arg1, arg2) {
imports.wbg.__wbg_open_52406b79476e8f5c = handleError(function(arg0, arg1, arg2, arg3, arg4) {
var ret = getObject(arg0).open(getStringFromWasm0(arg1, arg2), getStringFromWasm0(arg3, arg4));
return isLikeNone(ret) ? 0 : addHeapObject(ret);
});
imports.wbg.__wbg_body_ca5c7fc933a74206 = function(arg0) {
var ret = getObject(arg0).body;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
imports.wbg.__wbg_getElementById_35de356b82960e7f = function(arg0, arg1, arg2) {
var ret = getObject(arg0).getElementById(getStringFromWasm0(arg1, arg2));
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
imports.wbg.__wbg_instanceof_WebGlRenderingContext_f732dd95c50b903a = function(arg0) {
imports.wbg.__wbg_getItem_5a53c566950c2181 = handleError(function(arg0, arg1, arg2, arg3) {
var ret = getObject(arg1).getItem(getStringFromWasm0(arg2, arg3));
var ptr0 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len0;
getInt32Memory0()[arg0 / 4 + 0] = ptr0;
});
imports.wbg.__wbg_setItem_6884e4d52a076b78 = handleError(function(arg0, arg1, arg2, arg3, arg4) {
getObject(arg0).setItem(getStringFromWasm0(arg1, arg2), getStringFromWasm0(arg3, arg4));
});
imports.wbg.__wbg_setProperty_3090dd7650e67dd9 = handleError(function(arg0, arg1, arg2, arg3, arg4) {
getObject(arg0).setProperty(getStringFromWasm0(arg1, arg2), getStringFromWasm0(arg3, arg4));
});
imports.wbg.__wbg_instanceof_WebGlRenderingContext_4dbaf147f8c72285 = function(arg0) {
var ret = getObject(arg0) instanceof WebGLRenderingContext;
return ret;
};
imports.wbg.__wbg_drawingBufferWidth_f6e2e679bef8d30c = function(arg0) {
imports.wbg.__wbg_drawingBufferWidth_d15574dca0dbf918 = function(arg0) {
var ret = getObject(arg0).drawingBufferWidth;
return ret;
};
imports.wbg.__wbg_drawingBufferHeight_53a875c847d3f27e = function(arg0) {
imports.wbg.__wbg_drawingBufferHeight_64716b9e5a2d23f9 = function(arg0) {
var ret = getObject(arg0).drawingBufferHeight;
return ret;
};
imports.wbg.__wbg_bufferData_a513e51e685294ae = function(arg0, arg1, arg2, arg3) {
imports.wbg.__wbg_bufferData_7c335d1d31ac7268 = function(arg0, arg1, arg2, arg3) {
getObject(arg0).bufferData(arg1 >>> 0, getObject(arg2), arg3 >>> 0);
};
imports.wbg.__wbg_texImage2D_f4f837ad2dcc6a75 = handleError(function(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10) {
imports.wbg.__wbg_texImage2D_b9580f442e65b12c = handleError(function(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10) {
getObject(arg0).texImage2D(arg1 >>> 0, arg2, arg3, arg4, arg5, arg6, arg7 >>> 0, arg8 >>> 0, arg9 === 0 ? undefined : getArrayU8FromWasm0(arg9, arg10));
});
imports.wbg.__wbg_activeTexture_ee6eed2472803dd2 = function(arg0, arg1) {
imports.wbg.__wbg_activeTexture_98659cb2d4378082 = function(arg0, arg1) {
getObject(arg0).activeTexture(arg1 >>> 0);
};
imports.wbg.__wbg_attachShader_c2f7771e6f4b91d8 = function(arg0, arg1, arg2) {
imports.wbg.__wbg_attachShader_7abea275e2bef18f = function(arg0, arg1, arg2) {
getObject(arg0).attachShader(getObject(arg1), getObject(arg2));
};
imports.wbg.__wbg_bindBuffer_f4ad79795655c1c4 = function(arg0, arg1, arg2) {
imports.wbg.__wbg_bindBuffer_213222637184d14a = function(arg0, arg1, arg2) {
getObject(arg0).bindBuffer(arg1 >>> 0, getObject(arg2));
};
imports.wbg.__wbg_bindTexture_751d66bbae4822ab = function(arg0, arg1, arg2) {
imports.wbg.__wbg_bindTexture_100465c6a2ac91a4 = function(arg0, arg1, arg2) {
getObject(arg0).bindTexture(arg1 >>> 0, getObject(arg2));
};
imports.wbg.__wbg_blendFunc_e6775dade5e99b3e = function(arg0, arg1, arg2) {
imports.wbg.__wbg_blendFunc_3a8cc938ef99e93f = function(arg0, arg1, arg2) {
getObject(arg0).blendFunc(arg1 >>> 0, arg2 >>> 0);
};
imports.wbg.__wbg_clear_42b42c27d041ce11 = function(arg0, arg1) {
imports.wbg.__wbg_clear_fca4f400fe29d8eb = function(arg0, arg1) {
getObject(arg0).clear(arg1 >>> 0);
};
imports.wbg.__wbg_clearColor_ba6ba6886092ab6a = function(arg0, arg1, arg2, arg3, arg4) {
imports.wbg.__wbg_clearColor_d2a3f875ec95af09 = function(arg0, arg1, arg2, arg3, arg4) {
getObject(arg0).clearColor(arg1, arg2, arg3, arg4);
};
imports.wbg.__wbg_compileShader_8aec8947f553f5b6 = function(arg0, arg1) {
imports.wbg.__wbg_compileShader_836d2f5f9711cad1 = function(arg0, arg1) {
getObject(arg0).compileShader(getObject(arg1));
};
imports.wbg.__wbg_createBuffer_f26187e1b465a677 = function(arg0) {
imports.wbg.__wbg_createBuffer_62053581fee0bc61 = function(arg0) {
var ret = getObject(arg0).createBuffer();
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
imports.wbg.__wbg_createProgram_10f7bf07e21fe904 = function(arg0) {
imports.wbg.__wbg_createProgram_f493c0c083100a0d = function(arg0) {
var ret = getObject(arg0).createProgram();
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
imports.wbg.__wbg_createShader_4060106dc88c8bca = function(arg0, arg1) {
imports.wbg.__wbg_createShader_21f7c586da404166 = function(arg0, arg1) {
var ret = getObject(arg0).createShader(arg1 >>> 0);
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
imports.wbg.__wbg_createTexture_d7a4df257a9410a7 = function(arg0) {
imports.wbg.__wbg_createTexture_0980984dcf341648 = function(arg0) {
var ret = getObject(arg0).createTexture();
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
imports.wbg.__wbg_drawElements_90d9e4b571f4de3d = function(arg0, arg1, arg2, arg3, arg4) {
imports.wbg.__wbg_drawElements_723792382868b794 = function(arg0, arg1, arg2, arg3, arg4) {
getObject(arg0).drawElements(arg1 >>> 0, arg2, arg3 >>> 0, arg4);
};
imports.wbg.__wbg_enable_24e0ca734ee94d76 = function(arg0, arg1) {
imports.wbg.__wbg_enable_0ffb8209df59b6e9 = function(arg0, arg1) {
getObject(arg0).enable(arg1 >>> 0);
};
imports.wbg.__wbg_enableVertexAttribArray_2e2bfba7f3a5fb74 = function(arg0, arg1) {
imports.wbg.__wbg_enableVertexAttribArray_a5f053ba5a4c63f8 = function(arg0, arg1) {
getObject(arg0).enableVertexAttribArray(arg1 >>> 0);
};
imports.wbg.__wbg_getAttribLocation_ea61e93124c45a64 = function(arg0, arg1, arg2, arg3) {
imports.wbg.__wbg_getAttribLocation_742edd714d13137e = function(arg0, arg1, arg2, arg3) {
var ret = getObject(arg0).getAttribLocation(getObject(arg1), getStringFromWasm0(arg2, arg3));
return ret;
};
imports.wbg.__wbg_getProgramInfoLog_ebcdc102c402de8d = function(arg0, arg1, arg2) {
imports.wbg.__wbg_getProgramInfoLog_29ce85a2de692138 = function(arg0, arg1, arg2) {
var ret = getObject(arg1).getProgramInfoLog(getObject(arg2));
var ptr0 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len0;
getInt32Memory0()[arg0 / 4 + 0] = ptr0;
};
imports.wbg.__wbg_getProgramParameter_02e369d0fe1637e6 = function(arg0, arg1, arg2) {
imports.wbg.__wbg_getProgramParameter_40f2b936702245fa = function(arg0, arg1, arg2) {
var ret = getObject(arg0).getProgramParameter(getObject(arg1), arg2 >>> 0);
return addHeapObject(ret);
};
imports.wbg.__wbg_getShaderInfoLog_932172511c0dfdb7 = function(arg0, arg1, arg2) {
imports.wbg.__wbg_getShaderInfoLog_de2b10efd38974b9 = function(arg0, arg1, arg2) {
var ret = getObject(arg1).getShaderInfoLog(getObject(arg2));
var ptr0 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len0;
getInt32Memory0()[arg0 / 4 + 0] = ptr0;
};
imports.wbg.__wbg_getShaderParameter_4306f019f7eb9f82 = function(arg0, arg1, arg2) {
imports.wbg.__wbg_getShaderParameter_dcc11a2ddcfa8846 = function(arg0, arg1, arg2) {
var ret = getObject(arg0).getShaderParameter(getObject(arg1), arg2 >>> 0);
return addHeapObject(ret);
};
imports.wbg.__wbg_getUniformLocation_277279212040ec65 = function(arg0, arg1, arg2, arg3) {
imports.wbg.__wbg_getUniformLocation_8d9e8ecae0d977a7 = function(arg0, arg1, arg2, arg3) {
var ret = getObject(arg0).getUniformLocation(getObject(arg1), getStringFromWasm0(arg2, arg3));
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
imports.wbg.__wbg_linkProgram_9258ef1fcd3afc43 = function(arg0, arg1) {
imports.wbg.__wbg_linkProgram_eadfa937deac04bc = function(arg0, arg1) {
getObject(arg0).linkProgram(getObject(arg1));
};
imports.wbg.__wbg_shaderSource_ef8be775578bf902 = function(arg0, arg1, arg2, arg3) {
imports.wbg.__wbg_scissor_d14e3ca37a6c3f5f = function(arg0, arg1, arg2, arg3, arg4) {
getObject(arg0).scissor(arg1, arg2, arg3, arg4);
};
imports.wbg.__wbg_shaderSource_8bde928aee653e1e = function(arg0, arg1, arg2, arg3) {
getObject(arg0).shaderSource(getObject(arg1), getStringFromWasm0(arg2, arg3));
};
imports.wbg.__wbg_texParameteri_e2db4aa7650962eb = function(arg0, arg1, arg2, arg3) {
imports.wbg.__wbg_texParameteri_909613a4b282cc0e = function(arg0, arg1, arg2, arg3) {
getObject(arg0).texParameteri(arg1 >>> 0, arg2 >>> 0, arg3);
};
imports.wbg.__wbg_uniform1i_595e085d9c3aadf2 = function(arg0, arg1, arg2) {
imports.wbg.__wbg_uniform1i_6392f03e162d29dd = function(arg0, arg1, arg2) {
getObject(arg0).uniform1i(getObject(arg1), arg2);
};
imports.wbg.__wbg_uniform2f_ecf476a0ffa61198 = function(arg0, arg1, arg2, arg3) {
imports.wbg.__wbg_uniform2f_c02c75fd5f501550 = function(arg0, arg1, arg2, arg3) {
getObject(arg0).uniform2f(getObject(arg1), arg2, arg3);
};
imports.wbg.__wbg_uniform4f_d948981d4592be6a = function(arg0, arg1, arg2, arg3, arg4, arg5) {
getObject(arg0).uniform4f(getObject(arg1), arg2, arg3, arg4, arg5);
};
imports.wbg.__wbg_useProgram_67487c5ef197884d = function(arg0, arg1) {
imports.wbg.__wbg_useProgram_c189e979d24eebd0 = function(arg0, arg1) {
getObject(arg0).useProgram(getObject(arg1));
};
imports.wbg.__wbg_vertexAttribPointer_52d124f67ddb572d = function(arg0, arg1, arg2, arg3, arg4, arg5, arg6) {
imports.wbg.__wbg_vertexAttribPointer_39d650aa12b34b0a = function(arg0, arg1, arg2, arg3, arg4, arg5, arg6) {
getObject(arg0).vertexAttribPointer(arg1 >>> 0, arg2, arg3 >>> 0, arg4 !== 0, arg5, arg6);
};
imports.wbg.__wbg_viewport_5f99aff932f780aa = function(arg0, arg1, arg2, arg3, arg4) {
imports.wbg.__wbg_viewport_eb68ba7f5198ca9c = function(arg0, arg1, arg2, arg3, arg4) {
getObject(arg0).viewport(arg1, arg2, arg3, arg4);
};
imports.wbg.__wbg_log_eb1108411ecc4a7f = function(arg0) {
imports.wbg.__wbg_log_8c015365353ccd49 = function(arg0) {
console.log(getObject(arg0));
};
imports.wbg.__wbg_now_43100dbb52857cc6 = function(arg0) {
imports.wbg.__wbg_style_08224ec396c218e8 = function(arg0) {
var ret = getObject(arg0).style;
return addHeapObject(ret);
};
imports.wbg.__wbg_hash_807752e2195bb755 = handleError(function(arg0, arg1) {
var ret = getObject(arg1).hash;
var ptr0 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len0;
getInt32Memory0()[arg0 / 4 + 0] = ptr0;
});
imports.wbg.__wbg_now_66c779566d9324ca = function(arg0) {
var ret = getObject(arg0).now();
return ret;
};
imports.wbg.__wbg_instanceof_HtmlCanvasElement_ff7be16a6a6bdf51 = function(arg0) {
imports.wbg.__wbg_instanceof_HtmlCanvasElement_0d5b3d4264830667 = function(arg0) {
var ret = getObject(arg0) instanceof HTMLCanvasElement;
return ret;
};
imports.wbg.__wbg_width_aeeb90e24b778e64 = function(arg0) {
imports.wbg.__wbg_width_56afa08c5d6a4ccc = function(arg0) {
var ret = getObject(arg0).width;
return ret;
};
imports.wbg.__wbg_height_66b10992a66b71e3 = function(arg0) {
imports.wbg.__wbg_setwidth_f14d289597bfbc0c = function(arg0, arg1) {
getObject(arg0).width = arg1 >>> 0;
};
imports.wbg.__wbg_height_8f8f429d977ce11a = function(arg0) {
var ret = getObject(arg0).height;
return ret;
};
imports.wbg.__wbg_getContext_0dcf09cb63d08f77 = handleError(function(arg0, arg1, arg2) {
imports.wbg.__wbg_setheight_560464c89bcf1ef6 = function(arg0, arg1) {
getObject(arg0).height = arg1 >>> 0;
};
imports.wbg.__wbg_getContext_36ec9e6a6037ed40 = handleError(function(arg0, arg1, arg2) {
var ret = getObject(arg0).getContext(getStringFromWasm0(arg1, arg2));
return isLikeNone(ret) ? 0 : addHeapObject(ret);
});
imports.wbg.__wbg_getItem_08cba7eaeaee125e = handleError(function(arg0, arg1, arg2, arg3) {
var ret = getObject(arg1).getItem(getStringFromWasm0(arg2, arg3));
var ptr0 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len0;
getInt32Memory0()[arg0 / 4 + 0] = ptr0;
});
imports.wbg.__wbg_setItem_535f63295c5e7cec = handleError(function(arg0, arg1, arg2, arg3, arg4) {
getObject(arg0).setItem(getStringFromWasm0(arg1, arg2), getStringFromWasm0(arg3, arg4));
});
imports.wbg.__wbg_call_1f85aaa5836dfb23 = handleError(function(arg0, arg1) {
imports.wbg.__wbg_call_79ca0d435495a83a = handleError(function(arg0, arg1) {
var ret = getObject(arg0).call(getObject(arg1));
return addHeapObject(ret);
});
@ -486,23 +539,23 @@ async function init(input) {
var ret = getObject(arg0);
return addHeapObject(ret);
};
imports.wbg.__wbg_newnoargs_8aad4a6554f38345 = function(arg0, arg1) {
imports.wbg.__wbg_newnoargs_db0587fa712f9acc = function(arg0, arg1) {
var ret = new Function(getStringFromWasm0(arg0, arg1));
return addHeapObject(ret);
};
imports.wbg.__wbg_self_c0d3a5923e013647 = handleError(function() {
imports.wbg.__wbg_self_d1b58dbab69d5bb1 = handleError(function() {
var ret = self.self;
return addHeapObject(ret);
});
imports.wbg.__wbg_window_7ee6c8be3432927d = handleError(function() {
imports.wbg.__wbg_window_de445cb18819ad4b = handleError(function() {
var ret = window.window;
return addHeapObject(ret);
});
imports.wbg.__wbg_globalThis_c6de1d938e089cf0 = handleError(function() {
imports.wbg.__wbg_globalThis_68afcb0d98f0112d = handleError(function() {
var ret = globalThis.globalThis;
return addHeapObject(ret);
});
imports.wbg.__wbg_global_c9a01ce4680907f8 = handleError(function() {
imports.wbg.__wbg_global_baed4e4fa850c0d0 = handleError(function() {
var ret = global.global;
return addHeapObject(ret);
});
@ -510,46 +563,52 @@ async function init(input) {
var ret = getObject(arg0) === undefined;
return ret;
};
imports.wbg.__wbg_buffer_eb5185aa4a8e9c62 = function(arg0) {
imports.wbg.__wbg_buffer_44855aefa83ea48c = function(arg0) {
var ret = getObject(arg0).buffer;
return addHeapObject(ret);
};
imports.wbg.__wbg_new_857f86306f3c9f8e = function(arg0) {
imports.wbg.__wbg_new_99dceb228156b8f9 = function(arg0) {
var ret = new Int16Array(getObject(arg0));
return addHeapObject(ret);
};
imports.wbg.__wbg_new_3d94e83f0a6bf252 = function(arg0) {
imports.wbg.__wbg_new_04793d2c09ba060f = function(arg0) {
var ret = new Uint8Array(getObject(arg0));
return addHeapObject(ret);
};
imports.wbg.__wbg_new_2818287a48d6df17 = function(arg0) {
imports.wbg.__wbg_new_2ea4016337a3ea43 = function(arg0) {
var ret = new Uint16Array(getObject(arg0));
return addHeapObject(ret);
};
imports.wbg.__wbg_new_470473004db6a289 = function(arg0) {
imports.wbg.__wbg_new_05020d898fee9291 = function(arg0) {
var ret = new Float32Array(getObject(arg0));
return addHeapObject(ret);
};
imports.wbg.__wbg_subarray_fde523a929c57e27 = function(arg0, arg1, arg2) {
imports.wbg.__wbg_subarray_51ef53d36c4ab7da = function(arg0, arg1, arg2) {
var ret = getObject(arg0).subarray(arg1 >>> 0, arg2 >>> 0);
return addHeapObject(ret);
};
imports.wbg.__wbg_subarray_cc54babc55409ee0 = function(arg0, arg1, arg2) {
imports.wbg.__wbg_subarray_37f4436e082c6827 = function(arg0, arg1, arg2) {
var ret = getObject(arg0).subarray(arg1 >>> 0, arg2 >>> 0);
return addHeapObject(ret);
};
imports.wbg.__wbg_subarray_709e8f734d7056df = function(arg0, arg1, arg2) {
imports.wbg.__wbg_subarray_cdadaa7a73205e8a = function(arg0, arg1, arg2) {
var ret = getObject(arg0).subarray(arg1 >>> 0, arg2 >>> 0);
return addHeapObject(ret);
};
imports.wbg.__wbg_subarray_618d0460088cd7d6 = function(arg0, arg1, arg2) {
imports.wbg.__wbg_subarray_2b50278eea0fd249 = function(arg0, arg1, arg2) {
var ret = getObject(arg0).subarray(arg1 >>> 0, arg2 >>> 0);
return addHeapObject(ret);
};
imports.wbg.__wbg_instanceof_Memory_ce2336191e545514 = function(arg0) {
imports.wbg.__wbg_instanceof_Memory_39ad4e10adf95010 = function(arg0) {
var ret = getObject(arg0) instanceof WebAssembly.Memory;
return ret;
};
imports.wbg.__wbindgen_number_get = function(arg0, arg1) {
const obj = getObject(arg1);
var ret = typeof(obj) === 'number' ? obj : undefined;
getFloat64Memory0()[arg0 / 8 + 1] = isLikeNone(ret) ? 0 : ret;
getInt32Memory0()[arg0 / 4 + 0] = !isLikeNone(ret);
};
imports.wbg.__wbindgen_boolean_get = function(arg0) {
const v = getObject(arg0);
var ret = typeof(v) === 'boolean' ? (v ? 1 : 0) : 2;

BIN
docs/example_wasm_bg.wasm

Binary file not shown.

224
docs/index.html

@ -30,6 +30,9 @@
</head>
<body>
<!-- We later make this cover the entire screen even when resized -->
<canvas id="canvas" width="1024" height="1024"></canvas>
<script>
// The `--no-modules`-generated JS from `wasm-bindgen` attempts to use
// `WebAssembly.instantiateStreaming` to instantiate the wasm module,
@ -52,79 +55,45 @@
// initialization and return to us a promise when it's done
wasm_bindgen("./example_wasm_bg.wasm")
.then(on_wasm_loaded)["catch"](console.error);
// ----------------------------------------------------------------------------
var g_wasm_app = null;
function paint_gui(canvas) {
if (g_wasm_app === null) {
g_wasm_app = wasm_bindgen.new_webgl_gui("canvas");
}
let input = {
egui: get_egui_input(canvas),
web: {
location: window.location.toString(),
location_hash: window.location.hash.toString(), // i.e. #fragment
},
}
// ----------------------------------------------------------------------------
let output = JSON.parse(wasm_bindgen.run_gui(g_wasm_app, JSON.stringify(input)));
// console.log(`output: ${JSON.stringify(output)}`);
document.body.style.cursor = from_egui_cursor(output.cursor_icon);
// console.log(`Translated ${output.cursor_icon} to ${document.body.style.cursor}`);
if (output.open_url) {
window.open(output.open_url, "_self");
}
}
var g_wasm_app = null;
function from_egui_cursor(cursor) {
if (cursor == "no_drop") { return "no-drop"; }
else if (cursor == "not_allowed") { return "not-allowed"; }
else if (cursor == "resize_horizontal") { return "ew-resize"; }
else if (cursor == "resize_ne_sw") { return "nesw-resize"; }
else if (cursor == "resize_nw_se") { return "nwse-resize"; }
else if (cursor == "resize_vertical") { return "ns-resize"; }
else if (cursor == "pointing_hand") { return "pointer"; }
// TODO: more
else {
// default, help, pointer, progress, wait, cell, crosshair, text, alias, copy, move, grab, grabbing,
return cursor;
}
}
function egui_state() {
window.g_egui_state = window.g_egui_state || {
mouse_pos: null,
mouse_down: false,
is_touch: false, // we don't know yet
scroll_delta_x: 0,
scroll_delta_y: 0,
events: [],
};
return window.g_egui_state;
};
// ----------------------------------------------------------------------------
var g_mouse_pos = null;
var g_mouse_down = false;
var g_is_touch = false; // we don't know yet
var g_scroll_delta_x = 0;
var g_scroll_delta_y = 0;
var g_events = [];
function pixels_per_point() {
return window.devicePixelRatio || 1.0;
}
function auto_resize_canvas(canvas) {
canvas.style.width = window.innerWidth + "px";
canvas.style.height = window.innerHeight + "px";
canvas.width = window.innerWidth * pixels_per_point();
canvas.height = window.innerHeight * pixels_per_point();
}
function get_egui_input() {
let state = egui_state();
function get_egui_input(canvas) {
var input = {
mouse_down: g_mouse_down,
mouse_pos: g_mouse_pos,
scroll_delta: { x: -g_scroll_delta_x, y: -g_scroll_delta_y }, // TODO: standardize scroll direction
mouse_down: state.mouse_down,
mouse_pos: state.mouse_pos,
scroll_delta: { x: -state.scroll_delta_x, y: -state.scroll_delta_y }, // TODO: standardize scroll direction
screen_size: { x: window.innerWidth, y: window.innerHeight },
pixels_per_point: pixels_per_point(),
time: window.performance.now() / 1000.0,
seconds_since_midnight: seconds_since_midnight(),
events: g_events,
events: state.events,
};
g_scroll_delta_x = 0;
g_scroll_delta_y = 0;
g_events = [];
state.scroll_delta_x = 0;
state.scroll_delta_y = 0;
state.events = [];
return input;
}
@ -147,9 +116,12 @@
const ANIMATION_FRAME = true;
function paint() {
var canvas = document.getElementById("canvas");
auto_resize_canvas(canvas);
paint_gui(canvas);
wasm_bindgen.resize_to_screen_size("canvas");
if (g_wasm_app === null) {
g_wasm_app = wasm_bindgen.new_webgl_gui("canvas");
}
let input = get_egui_input();
wasm_bindgen.run_gui(g_wasm_app, JSON.stringify(input));
}
function paint_and_schedule() {
@ -161,114 +133,126 @@
function on_wasm_loaded() {
var canvas = document.getElementById("canvas");
console.assert(canvas);
install_canvas_events(canvas, paint);
install_document_events(paint);
paint_and_schedule();
}
function install_document_events(paint) {
var invalidate = function () {
if (!ANIMATION_FRAME) {
paint();
}
};
document.addEventListener("keydown", function (event) {
var key = translate_key(event.key);
if (key) {
egui_state().events.push({ "key": { "key": key, 'pressed': true } });
} else {
egui_state().events.push({ "text": event.key });
}
invalidate();
// event.stopPropagation();
// event.preventDefault();
});
// document.addEventListener("keypress", (event)=>{
// console.log(`keypress: ${event.key} ${JSON.stringify(event)}`);
// invalidate();
// event.stopPropagation();
// event.preventDefault();
// });
document.addEventListener("keyup", function (event) {
// console.log(`keyup: ${event.key} ${JSON.stringify(event)}`);
var key = translate_key(event.key);
if (key) {
egui_state().events.push({ "key": { "key": key, 'pressed': false } });
}
invalidate();
// event.stopPropagation();
// event.preventDefault();
});
if (!ANIMATION_FRAME) {
window.addEventListener("load", invalidate);
window.addEventListener("pagehide", invalidate);
window.addEventListener("pageshow", invalidate);
window.addEventListener("resize", invalidate);
}
}
function install_canvas_events(canvas, paint) {
var invalidate = function () {
if (!ANIMATION_FRAME) {
paint();
}
};
canvas.addEventListener("mousedown", function (event) {
if (g_is_touch) { return; }
g_mouse_pos = mouse_pos_from_event(canvas, event);
g_mouse_down = true;
if (egui_state().is_touch) { return; }
egui_state().mouse_pos = mouse_pos_from_event(canvas, event);
egui_state().mouse_down = true;
invalidate();
event.stopPropagation();
event.preventDefault();
});
canvas.addEventListener("mousemove", function (event) {
if (g_is_touch) { return; }
g_mouse_pos = mouse_pos_from_event(canvas, event);
if (egui_state().is_touch) { return; }
egui_state().mouse_pos = mouse_pos_from_event(canvas, event);
invalidate();
event.stopPropagation();
event.preventDefault();
});
canvas.addEventListener("mouseup", function (event) {
if (g_is_touch) { return; }
g_mouse_pos = mouse_pos_from_event(canvas, event);
g_mouse_down = false;
if (egui_state().is_touch) { return; }
egui_state().mouse_pos = mouse_pos_from_event(canvas, event);
egui_state().mouse_down = false;
invalidate();
event.stopPropagation();
event.preventDefault();
});
canvas.addEventListener("mouseleave", function (event) {
if (g_is_touch) { return; }
g_mouse_pos = null;
if (egui_state().is_touch) { return; }
egui_state().mouse_pos = null;
invalidate();
event.stopPropagation();
event.preventDefault();
});
canvas.addEventListener("touchstart", function (event) {
g_is_touch = true;
g_mouse_pos = { x: event.touches[0].pageX, y: event.touches[0].pageY };
g_mouse_down = true;
egui_state().is_touch = true;
egui_state().mouse_pos = { x: event.touches[0].pageX, y: event.touches[0].pageY };
egui_state().mouse_down = true;
invalidate();
event.stopPropagation();
event.preventDefault();
});
canvas.addEventListener("touchmove", function (event) {
g_is_touch = true;
g_mouse_pos = { x: event.touches[0].pageX, y: event.touches[0].pageY };
egui_state().is_touch = true;
egui_state().mouse_pos = { x: event.touches[0].pageX, y: event.touches[0].pageY };
invalidate();
event.stopPropagation();
event.preventDefault();
});
canvas.addEventListener("touchend", function (event) {
g_is_touch = true;
g_mouse_down = false; // First release mouse to click...
paint();
g_mouse_pos = null; // ...remove hover effect
egui_state().is_touch = true;
egui_state().mouse_down = false; // First release mouse to click...
paint(); // ...do the clicking...
egui_state().mouse_pos = null; // ...remove hover effect
invalidate();
event.stopPropagation();
event.preventDefault();
});
canvas.addEventListener("wheel", function (event) {
g_scroll_delta_x += event.deltaX;
g_scroll_delta_y += event.deltaY;
egui_state().scroll_delta_x += event.deltaX;
egui_state().scroll_delta_y += event.deltaY;
invalidate();
event.stopPropagation();
event.preventDefault();
});
document.addEventListener("keydown", function (event) {
var key = translate_key(event.key);
if (key) {
g_events.push({ "key": { "key": key, 'pressed': true } });
} else {
g_events.push({ "text": event.key });
}
invalidate();
// event.stopPropagation();
// event.preventDefault();
});
// document.addEventListener("keypress", function (event) {
// console.log(`keypress: ${event.key} ${JSON.stringify(event)}`);
// invalidate();
// event.stopPropagation();
// event.preventDefault();
// });
document.addEventListener("keyup", function (event) {
// console.log(`keyup: ${event.key} ${JSON.stringify(event)}`);
var key = translate_key(event.key);
if (key) {
g_events.push({ "key": { "key": key, 'pressed': false } });
}
invalidate();
// event.stopPropagation();
// event.preventDefault();
});
if (!ANIMATION_FRAME) {
window.addEventListener("load", invalidate);
window.addEventListener("pagehide", invalidate);
window.addEventListener("pageshow", invalidate);
window.addEventListener("resize", invalidate);
}
paint_and_schedule();
}
function translate_key(key) {
@ -294,8 +278,6 @@
return null;
}
</script>
<!-- We later make this cover the entire screen even when resized -->
<canvas id="canvas" width="1024" height="1024"></canvas>
</body>
</html>

4
egui/src/math.rs

@ -30,6 +30,10 @@ impl Vec2 {
}
}
pub fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
pub fn splat(v: impl Into<f32>) -> Self {
let v: f32 = v.into();
Self { x: v, y: v }

3
egui_web/Cargo.toml

@ -20,9 +20,12 @@ egui = { path = "../egui", features = ["with_serde"] }
version = "0.3"
features = [
'console',
'CssStyleDeclaration',
'Document',
'Element',
'HtmlCanvasElement',
'HtmlElement',
'Location',
'Performance',
'Storage',
'WebGlBuffer',

157
egui_web/src/lib.rs

@ -3,6 +3,73 @@
pub mod webgl;
// ----------------------------------------------------------------------------
use std::sync::Arc;
use wasm_bindgen::JsValue;
pub struct State {
ctx: Arc<egui::Context>,
webgl_painter: webgl::Painter,
frame_times: egui::MovementTracker<f32>,
frame_start: Option<f64>,
}
impl State {
pub fn new(canvas_id: &str) -> Result<State, JsValue> {
let ctx = egui::Context::new();
load_memory(&ctx);
Ok(State {
ctx,
webgl_painter: webgl::Painter::new(canvas_id)?,
frame_times: egui::MovementTracker::new(1000, 1.0),
frame_start: None,
})
}
pub fn begin_frame(&mut self, raw_input: egui::RawInput) -> egui::Ui {
self.frame_start = Some(now_sec());
self.ctx.begin_frame(raw_input)
}
pub fn end_frame(&mut self) -> Result<egui::Output, JsValue> {
let frame_start = self
.frame_start
.take()
.expect("unmatched calls to begin_frame/end_frame");
let bg_color = egui::color::srgba(0, 0, 0, 0); // Use background css color.
let (output, batches) = self.ctx.end_frame();
let now = now_sec();
self.frame_times.add(now, (now - frame_start) as f32);
self.webgl_painter.paint_batches(
bg_color,
batches,
self.ctx.texture(),
self.ctx.pixels_per_point(),
)?;
save_memory(&self.ctx); // TODO: don't save every frame
Ok(output)
}
pub fn painter_debug_info(&self) -> String {
self.webgl_painter.debug_info()
}
/// excludes painting
pub fn cpu_usage(&self) -> f32 {
self.frame_times.average().unwrap_or_default()
}
pub fn fps(&self) -> f32 {
1.0 / self.frame_times.mean_time_interval().unwrap_or_default()
}
}
// ----------------------------------------------------------------------------
// Helpers to hide some of the verbosity of web_sys
@ -10,6 +77,14 @@ pub fn console_log(s: String) {
web_sys::console::log_1(&s.into());
}
pub fn screen_size() -> Option<egui::Vec2> {
let window = web_sys::window()?;
Some(egui::Vec2::new(
window.inner_width().ok()?.as_f64()? as f32,
window.inner_height().ok()?.as_f64()? as f32,
))
}
pub fn now_sec() -> f64 {
web_sys::window()
.expect("should have a Window")
@ -19,6 +94,44 @@ pub fn now_sec() -> f64 {
/ 1000.0
}
pub fn seconds_since_midnight() -> f64 {
let d = js_sys::Date::new_0();
let seconds = (d.get_hours() * 60 + d.get_minutes()) * 60 + d.get_seconds();
return seconds as f64 + 1e-3 * (d.get_milliseconds() as f64);
}
pub fn pixels_per_point() -> f32 {
let pixels_per_point = web_sys::window().unwrap().device_pixel_ratio() as f32;
if pixels_per_point > 0.0 && pixels_per_point.is_finite() {
pixels_per_point
} else {
1.0
}
}
pub fn resize_to_screen_size(canvas_id: &str) -> Option<()> {
use wasm_bindgen::JsCast;
let document = web_sys::window()?.document()?;
let canvas = document.get_element_by_id(canvas_id)?;
let canvas: web_sys::HtmlCanvasElement =
canvas.dyn_into::<web_sys::HtmlCanvasElement>().ok()?;
let screen_size = screen_size()?;
let pixels_per_point = pixels_per_point();
canvas
.style()
.set_property("width", &format!("{}px", screen_size.x))
.ok()?;
canvas
.style()
.set_property("height", &format!("{}px", screen_size.y))
.ok()?;
canvas.set_width((screen_size.x * pixels_per_point).round() as u32);
canvas.set_height((screen_size.y * pixels_per_point).round() as u32);
Some(())
}
pub fn local_storage() -> Option<web_sys::Storage> {
web_sys::window()?.local_storage().ok()?
}
@ -61,3 +174,47 @@ pub fn save_memory(ctx: &egui::Context) {
}
}
}
pub fn handle_output(output: &egui::Output) {
set_cursor_icon(output.cursor_icon);
if let Some(url) = &output.open_url {
open_url(url);
}
}
pub fn set_cursor_icon(cursor: egui::CursorIcon) -> Option<()> {
let document = web_sys::window()?.document()?;
document
.body()?
.style()
.set_property("cursor", cursor_web_name(cursor))
.ok()
}
fn cursor_web_name(cursor: egui::CursorIcon) -> &'static str {
use egui::CursorIcon::*;
match cursor {
Default => "default",
PointingHand => "pointer",
ResizeHorizontal => "ew-resize",
ResizeNeSw => "nesw-resize",
ResizeNwSe => "nwse-resize",
ResizeVertical => "ns-resize",
Text => "text",
// "no-drop"
// "not-allowed"
// default, help, pointer, progress, wait, cell, crosshair, text, alias, copy, move, grab, grabbing,
}
}
pub fn open_url(url: &str) -> Option<()> {
web_sys::window()?
.open_with_url_and_target(url, "_self")
.ok()?;
Some(())
}
/// e.g. "#fragment" part of "www.example.com/index.html#fragment"
pub fn location_hash() -> Option<String> {
web_sys::window()?.location().hash().ok()
}

91
example_wasm/src/lib.rs

@ -1,59 +1,32 @@
#![deny(warnings)]
#![warn(clippy::all)]
use std::sync::Arc;
use {
egui::{
color::srgba, examples::ExampleApp, label, widgets::Separator, Align, RawInput, TextStyle,
*,
},
egui_web::now_sec,
};
use egui::{examples::ExampleApp, label, widgets::Separator, Align, RawInput, TextStyle, *};
use wasm_bindgen::prelude::*;
#[derive(Clone, Debug, Default, serde::Deserialize)]
#[serde(default)]
struct WebInput {
egui: RawInput,
web: Web,
}
#[derive(Clone, Debug, Default, serde::Deserialize)]
#[serde(default)]
pub struct Web {
pub location: String,
/// i.e. "#fragment"
pub location_hash: String,
}
#[wasm_bindgen]
pub struct State {
egui_web: egui_web::State,
example_app: ExampleApp,
ctx: Arc<Context>,
webgl_painter: egui_web::webgl::Painter,
frame_times: egui::MovementTracker<f32>,
}
impl State {
fn new(canvas_id: &str) -> Result<State, JsValue> {
let ctx = Context::new();
egui_web::load_memory(&ctx);
Ok(State {
egui_web: egui_web::State::new(canvas_id)?,
example_app: Default::default(),
ctx,
webgl_painter: egui_web::webgl::Painter::new(canvas_id)?,
frame_times: egui::MovementTracker::new(1000, 1.0),
})
}
fn run(&mut self, web_input: WebInput) -> Result<Output, JsValue> {
let everything_start = now_sec();
fn run(&mut self, raw_input: RawInput, web_location_hash: &str) -> Result<Output, JsValue> {
let mut ui = self.egui_web.begin_frame(raw_input);
self.ui(&mut ui, web_location_hash);
self.egui_web.end_frame()
}
let mut ui = self.ctx.begin_frame(web_input.egui);
self.example_app.ui(&mut ui, &web_input.web.location_hash);
fn ui(&mut self, ui: &mut egui::Ui, web_location_hash: &str) {
self.example_app.ui(ui, web_location_hash);
let mut ui = ui.centered_column(ui.available().width().min(480.0));
ui.set_layout(Layout::vertical(Align::Min));
ui.add(label!("Egui!").text_style(TextStyle::Heading));
@ -71,40 +44,17 @@ impl State {
ui.label("WebGl painter info:");
ui.indent("webgl region id", |ui| {
ui.label(self.webgl_painter.debug_info());
ui.label(self.egui_web.painter_debug_info());
});
ui.add(
label!(
"CPU usage: {:.2} ms (excludes painting)",
1e3 * self.frame_times.average().unwrap_or_default()
)
.text_style(TextStyle::Monospace),
);
ui.add(
label!(
"FPS: {:.1}",
1.0 / self.frame_times.mean_time_interval().unwrap_or_default()
1e3 * self.egui_web.cpu_usage()
)
.text_style(TextStyle::Monospace),
);
let bg_color = srgba(0, 0, 0, 0); // Use background css color.
let (output, batches) = self.ctx.end_frame();
let now = now_sec();
self.frame_times.add(now, (now - everything_start) as f32);
self.webgl_painter.paint_batches(
bg_color,
batches,
self.ctx.texture(),
self.ctx.pixels_per_point(),
)?;
egui_web::save_memory(&self.ctx); // TODO: don't save every frame
Ok(output)
ui.add(label!("FPS: {:.1}", self.egui_web.fps()).text_style(TextStyle::Monospace));
}
}
@ -114,9 +64,16 @@ pub fn new_webgl_gui(canvas_id: &str) -> Result<State, JsValue> {
}
#[wasm_bindgen]
pub fn run_gui(state: &mut State, web_input_json: &str) -> Result<String, JsValue> {
pub fn resize_to_screen_size(canvas_id: &str) {
egui_web::resize_to_screen_size(canvas_id);
}
#[wasm_bindgen]
pub fn run_gui(state: &mut State, web_input_json: &str) -> Result<(), JsValue> {
// TODO: nicer interface than JSON
let web_input: WebInput = serde_json::from_str(web_input_json).unwrap();
let output = state.run(web_input)?;
Ok(serde_json::to_string(&output).unwrap())
let raw_input: RawInput = serde_json::from_str(web_input_json).unwrap();
let web_location_hash = egui_web::location_hash().unwrap_or_default();
let output = state.run(raw_input, &web_location_hash)?;
egui_web::handle_output(&output);
Ok(())
}

Loading…
Cancel
Save