use super::*;
#[must_use]
pub fn web_system_theme() -> ThemeMode {
let Some(win) = window() else {
return ThemeMode::Light;
};
let matches_dark: bool = win
.match_media(WEB_DARK_MEDIA_QUERY)
.ok()
.flatten()
.map(|mql: MediaQueryList| mql.matches())
.unwrap_or(false);
if matches_dark {
ThemeMode::Dark
} else {
ThemeMode::Light
}
}
#[must_use]
pub fn web_device_pixel_ratio() -> f32 {
window()
.map(|width_val: Window| {
let raw: f64 = width_val.device_pixel_ratio();
if raw.is_finite() && raw > 0.0 {
(raw as f32).clamp(WEB_DPR_MIN, WEB_DPR_MAX)
} else {
1.0
}
})
.unwrap_or(1.0)
}
#[must_use]
pub(crate) fn web_open_external_url(url: &str) -> bool {
let Some(win) = window() else {
return false;
};
win.open_with_url_and_target_and_features(url, WEB_OPEN_TARGET_BLANK, WEB_OPEN_FEATURES_SAFE)
.is_ok()
}
pub(crate) fn web_webview_open(url: &str, title: &str) -> bool {
let Some(doc) = window().and_then(|win: Window| win.document()) else {
return false;
};
let iframe_el: Element = if let Some(existing) = doc.get_element_by_id(WEB_WEBVIEW_IFRAME_ID) {
existing
} else {
let Ok(created) = doc.create_element(WEB_TAG_IFRAME) else {
return false;
};
drop(created.set_attribute(WEB_ATTR_ID, WEB_WEBVIEW_IFRAME_ID));
drop(created.set_attribute(WEB_ATTR_REFERRER_POLICY, WEB_REFERRER_POLICY_STRICT));
drop(created.set_attribute(WEB_ATTR_STYLE, WEB_WEBVIEW_HIDDEN_STYLE));
let Some(body_el) = doc.body() else {
return false;
};
if body_el.append_child(&created).is_err() {
return false;
}
created
};
drop(iframe_el.set_attribute(WEB_ATTR_TITLE, title));
iframe_el.set_attribute(WEB_ATTR_SRC, url).is_ok()
}
pub(crate) fn web_webview_frame(
left_px: f32,
top_px: f32,
width_px: f32,
height_px: f32,
alpha_val: f32,
) -> bool {
let Some(doc) = window().and_then(|win: Window| win.document()) else {
return false;
};
let Some(iframe_el) = doc.get_element_by_id(WEB_WEBVIEW_IFRAME_ID) else {
return false;
};
let is_empty_rect: bool = width_px < 1.0 || height_px < 1.0;
if is_empty_rect || alpha_val <= 0.005 {
return iframe_el
.set_attribute(WEB_ATTR_STYLE, WEB_WEBVIEW_HIDDEN_STYLE)
.is_ok();
}
let pointer_css: &str = if alpha_val >= 0.98 { "auto" } else { "none" };
let inline_css: String = format!(
"position:fixed;left:{left_px:.2}px;top:{top_px:.2}px;width:{width_px:.2}px;height:{height_px:.2}px;border:0;z-index:20;background:#ffffff;display:block;pointer-events:{pointer_css};opacity:{alpha_val:.3};"
);
iframe_el.set_attribute(WEB_ATTR_STYLE, &inline_css).is_ok()
}
pub(crate) fn web_webview_reload(url: &str) -> bool {
let Some(doc) = window().and_then(|win: Window| win.document()) else {
return false;
};
let Some(iframe_el) = doc.get_element_by_id(WEB_WEBVIEW_IFRAME_ID) else {
return false;
};
iframe_el.set_attribute(WEB_ATTR_SRC, url).is_ok()
}
pub(crate) fn web_webview_close() -> bool {
let Some(doc) = window().and_then(|win: Window| win.document()) else {
return false;
};
let Some(iframe_el) = doc.get_element_by_id(WEB_WEBVIEW_IFRAME_ID) else {
return false;
};
iframe_el.remove();
true
}
#[must_use]
pub(crate) fn web_query_viewport_css_size(
win: &Window,
doc: &Document,
fallback_w: f64,
fallback_h: f64,
) -> (f64, f64) {
if let Ok(vv) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT))
&& !vv.is_null()
&& !vv.is_undefined()
{
let vv_scale: f64 = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_SCALE))
.ok()
.and_then(|item_val: JsValue| item_val.as_f64())
.filter(|tex_v: &f64| tex_v.is_finite() && *tex_v > 0.0)
.unwrap_or(1.0);
if vv_scale <= WEB_PINCH_ZOOM_THRESHOLD {
let vw: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_WIDTH))
.ok()
.and_then(|bary_v: JsValue| bary_v.as_f64())
.filter(|sample_val: &f64| sample_val.is_finite() && *sample_val >= 64.0);
let vh: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_HEIGHT))
.ok()
.and_then(|item_val_primary: JsValue| item_val_primary.as_f64())
.filter(|item_val_secondary: &f64| {
item_val_secondary.is_finite() && *item_val_secondary >= 64.0
});
if let (Some(width_val), Some(height_val)) = (vw, vh) {
return (width_val, height_val);
}
}
}
if let Some(root) = doc.document_element() {
let cw: f64 = f64::from(root.client_width());
let ch: f64 = f64::from(root.client_height());
if cw >= 64.0 && ch >= 64.0 {
return (cw, ch);
}
}
let span_width: f64 = win
.inner_width()
.ok()
.and_then(|item_val_next: JsValue| item_val_next.as_f64())
.filter(|item_val_alt: &f64| item_val_alt.is_finite() && *item_val_alt >= 64.0)
.unwrap_or(fallback_w.max(64.0));
let span_height: f64 = win
.inner_height()
.ok()
.and_then(|item_val_inner: JsValue| item_val_inner.as_f64())
.filter(|item_val_local: &f64| item_val_local.is_finite() && *item_val_local >= 64.0)
.unwrap_or(fallback_h.max(64.0));
(span_width, span_height)
}
fn web_write_clipboard_exec_command(doc: &Document, text: &str) -> bool {
let Some(body) = doc.body() else {
return false;
};
let prev_active: Option<HtmlElement> = doc
.active_element()
.and_then(|el: Element| el.dyn_into::<HtmlElement>().ok());
let Ok(ta_el) = doc.create_element(WEB_TAG_TEXTAREA) else {
return false;
};
drop(ta_el.set_attribute(WEB_ATTR_READONLY, ""));
drop(ta_el.set_attribute(WEB_ATTR_COPY_PROXY, WEB_COPY_PROXY_FLAG));
drop(ta_el.set_attribute(WEB_ATTR_STYLE, WEB_COPY_PROXY_STYLE));
let _: Result<bool, JsValue> = Reflect::set(
ta_el.as_ref(),
&JsValue::from_str(WEB_PROP_VALUE),
&JsValue::from_str(text),
);
if body.append_child(&ta_el).is_err() {
return false;
}
if let Ok(ta_html) = ta_el.clone().dyn_into::<HtmlElement>() {
drop(ta_html.focus());
}
if let Ok(sel_val) = Reflect::get(ta_el.as_ref(), &JsValue::from_str(WEB_METHOD_SELECT))
&& let Ok(sel_fn) = sel_val.dyn_into::<Function>()
{
drop(sel_fn.call0(ta_el.as_ref()));
}
if let Ok(rng_val) = Reflect::get(
ta_el.as_ref(),
&JsValue::from_str(WEB_METHOD_SET_SELECTION_RANGE),
) && let Ok(rng_fn) = rng_val.dyn_into::<Function>()
{
let utf16_len: f64 = text.encode_utf16().count() as f64;
drop(rng_fn.call2(
ta_el.as_ref(),
&JsValue::from_f64(0.0),
&JsValue::from_f64(utf16_len),
));
}
let copied: bool = Reflect::get(doc.as_ref(), &JsValue::from_str(WEB_METHOD_EXEC_COMMAND))
.ok()
.and_then(|item_val: JsValue| item_val.dyn_into::<Function>().ok())
.and_then(|factor_val: Function| {
factor_val
.call1(doc.as_ref(), &JsValue::from_str(WEB_CMD_COPY))
.ok()
})
.and_then(|res: JsValue| res.as_bool())
.unwrap_or(false);
drop(body.remove_child(&ta_el));
if let Some(prev) = prev_active {
drop(prev.focus());
}
copied
}
pub(crate) fn web_write_clipboard(text: &str) -> bool {
let Some(win) = window() else {
return false;
};
let exec_ok: bool = win
.document()
.map(|doc: Document| web_write_clipboard_exec_command(&doc, text))
.unwrap_or(false);
let nav: Navigator = win.navigator();
let mut async_ok: bool = false;
if let Ok(clip) = Reflect::get(nav.as_ref(), &JsValue::from_str(WEB_PROP_CLIPBOARD))
&& !clip.is_null()
&& !clip.is_undefined()
&& let Ok(write_val) = Reflect::get(&clip, &JsValue::from_str(WEB_METHOD_WRITE_TEXT))
&& let Ok(write_fn) = write_val.dyn_into::<Function>()
&& let Ok(promise_val) = write_fn.call1(&clip, &JsValue::from_str(text))
{
async_ok = true;
if let Ok(catch_val) = Reflect::get(&promise_val, &JsValue::from_str(WEB_METHOD_CATCH))
&& let Ok(catch_fn) = catch_val.dyn_into::<Function>()
{
let noop: Function = Function::new_no_args(WEB_JS_NOOP_BODY);
drop(catch_fn.call1(&promise_val, &noop));
}
}
exec_ok || async_ok
}
#[must_use]
pub(crate) fn web_document_hidden() -> bool {
window()
.and_then(|width_val: Window| width_val.document())
.map(|delta_val: Document| delta_val.hidden())
.unwrap_or(false)
}
#[must_use]
pub(crate) fn web_navigator_online() -> bool {
window()
.map(|width_val: Window| width_val.navigator().on_line())
.unwrap_or(true)
}
#[must_use]
pub(crate) fn web_navigator_locale() -> String {
window()
.and_then(|width_val: Window| width_val.navigator().language())
.filter(|text_value: &String| !text_value.trim().is_empty())
.unwrap_or_else(|| DEFAULT_SYSTEM_LOCALE.to_string())
}
#[must_use]
fn web_read_css_px_prop(style_decl: &JsValue, get_prop_fn: &Function, prop_name: &str) -> f32 {
let Ok(raw_val) = get_prop_fn.call1(style_decl, &JsValue::from_str(prop_name)) else {
return 0.0;
};
let Some(text) = raw_val.as_string() else {
return 0.0;
};
parse_css_safe_area_px(&text)
}
fn web_ensure_safe_area_probe(doc: &Document) -> Option<Element> {
if let Some(existing) = doc.get_element_by_id(WEB_SAFE_PROBE_ID) {
return Some(existing);
}
let probe: Element = doc.create_element(WEB_TAG_DIV).ok()?;
drop(probe.set_attribute(WEB_ATTR_ID, WEB_SAFE_PROBE_ID));
drop(probe.set_attribute(WEB_ATTR_STYLE, WEB_SAFE_PROBE_STYLE));
let parent: Element = doc
.body()
.map(|blue_val: HtmlElement| blue_val.into())
.or_else(|| doc.document_element())?;
drop(parent.append_child(probe.as_ref()));
Some(probe)
}
#[must_use]
pub fn web_query_safe_area_insets() -> SafeAreaInsets {
let Some(win) = window() else {
return SafeAreaInsets::default();
};
let Some(doc): Option<Document> = win.document() else {
return SafeAreaInsets::default();
};
let Ok(get_style_val) = Reflect::get(
win.as_ref(),
&JsValue::from_str(WEB_METHOD_GET_COMPUTED_STYLE),
) else {
return SafeAreaInsets::default();
};
let Ok(get_style_fn) = get_style_val.dyn_into::<Function>() else {
return SafeAreaInsets::default();
};
let mut probe_insets: SafeAreaInsets = SafeAreaInsets::default();
if let Some(probe) = web_ensure_safe_area_probe(&doc)
&& let Ok(style_decl) = get_style_fn.call1(win.as_ref(), probe.as_ref())
&& let Ok(get_prop_val) = Reflect::get(
&style_decl,
&JsValue::from_str(WEB_METHOD_GET_PROPERTY_VALUE),
)
&& let Ok(get_prop_fn) = get_prop_val.dyn_into::<Function>()
{
probe_insets = SafeAreaInsets::new(
web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_PADDING_TOP),
web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_PADDING_RIGHT),
web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_PADDING_BOTTOM),
web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_PADDING_LEFT),
);
}
if probe_insets != SafeAreaInsets::default() {
return probe_insets;
}
let Some(root): Option<Element> = doc.document_element() else {
return SafeAreaInsets::default();
};
let Ok(style_decl) = get_style_fn.call1(win.as_ref(), root.as_ref()) else {
return SafeAreaInsets::default();
};
let Ok(get_prop_val) = Reflect::get(
&style_decl,
&JsValue::from_str(WEB_METHOD_GET_PROPERTY_VALUE),
) else {
return SafeAreaInsets::default();
};
let Ok(get_prop_fn) = get_prop_val.dyn_into::<Function>() else {
return SafeAreaInsets::default();
};
let top: f32 = web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_SAFE_TOP);
let right: f32 = web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_SAFE_RIGHT);
let bottom: f32 = web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_SAFE_BOTTOM);
let left: f32 = web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_SAFE_LEFT);
SafeAreaInsets::new(top, right, bottom, left)
}
#[must_use]
pub fn web_has_webgpu() -> bool {
let Some(win) = window() else {
return false;
};
let nav: Navigator = win.navigator();
Reflect::get(nav.as_ref(), &JsValue::from_str(WEB_PROP_GPU))
.map(|val: JsValue| !val.is_undefined() && !val.is_null())
.unwrap_or(false)
}
#[must_use]
pub fn web_attach_resize_observer(
canvas: &HtmlCanvasElement,
callback: &Function,
) -> Option<Object> {
let win: Window = window()?;
let ctor_val: JsValue =
Reflect::get(win.as_ref(), &JsValue::from_str(WEB_CTOR_RESIZE_OBSERVER)).ok()?;
let ctor_fn: Function = ctor_val.dyn_into::<Function>().ok()?;
let args_obj: Object = Object::new();
let _: bool = Reflect::set(
args_obj.as_ref(),
&JsValue::from_str(WEB_REFLECT_ARG0_KEY),
callback.as_ref(),
)
.ok()?;
let ro_val: JsValue = Reflect::construct(&ctor_fn, &Object::values(&args_obj)).ok()?;
let observe_val: JsValue =
Reflect::get(&ro_val, &JsValue::from_str(WEB_METHOD_OBSERVE)).ok()?;
let observe_fn: Function = observe_val.dyn_into::<Function>().ok()?;
let _: JsValue = observe_fn.call1(&ro_val, canvas.as_ref()).ok()?;
ro_val.dyn_into::<Object>().ok()
}
pub fn web_disconnect_resize_observer(observer: &Object) {
if let Ok(disc_val) = Reflect::get(observer.as_ref(), &JsValue::from_str(WEB_METHOD_DISCONNECT))
&& let Ok(disc_fn) = disc_val.dyn_into::<Function>()
{
drop(disc_fn.call0(observer.as_ref()));
}
}
#[must_use]
fn web_gl2_context_options() -> Object {
let opts: Object = Object::new();
let _: Result<bool, JsValue> = Reflect::set(
opts.as_ref(),
&JsValue::from_str(WEB_GL_OPT_ALPHA),
&JsValue::from_bool(false),
);
let _: Result<bool, JsValue> = Reflect::set(
opts.as_ref(),
&JsValue::from_str(WEB_GL_OPT_ANTIALIAS),
&JsValue::from_bool(false),
);
let _: Result<bool, JsValue> = Reflect::set(
opts.as_ref(),
&JsValue::from_str(WEB_GL_OPT_DEPTH),
&JsValue::from_bool(false),
);
let _: Result<bool, JsValue> = Reflect::set(
opts.as_ref(),
&JsValue::from_str(WEB_GL_OPT_DESYNCHRONIZED),
&JsValue::from_bool(false),
);
let _: Result<bool, JsValue> = Reflect::set(
opts.as_ref(),
&JsValue::from_str(WEB_GL_OPT_POWER_PREF),
&JsValue::from_str(WEB_GL_OPT_HIGH_PERFORMANCE),
);
let _: Result<bool, JsValue> = Reflect::set(
opts.as_ref(),
&JsValue::from_str(WEB_GL_OPT_PRESERVE_DRAWING),
&JsValue::from_bool(false),
);
opts
}
fn web_configure_gl2_unpack_state(gl: &WebGl2RenderingContext) {
gl.pixel_storei(WebGl2RenderingContext::UNPACK_ALIGNMENT, 4);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_FLIP_Y_WEBGL, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
gl.pixel_storei(
WebGl2RenderingContext::UNPACK_COLORSPACE_CONVERSION_WEBGL,
WebGl2RenderingContext::NONE as i32,
);
}
fn web_init_gl2_direct_pipeline(gl: &WebGl2RenderingContext) -> Option<WebGl2DirectPipeline> {
let vs: WebGlShader = gl.create_shader(WebGl2RenderingContext::VERTEX_SHADER)?;
gl.shader_source(&vs, WEB_GL2_DIRECT_VERT_SHADER);
gl.compile_shader(&vs);
let fs: WebGlShader = gl.create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)?;
gl.shader_source(&fs, WEB_GL2_DIRECT_FRAG_SHADER);
gl.compile_shader(&fs);
let prog: WebGlProgram = gl.create_program()?;
gl.attach_shader(&prog, &vs);
gl.attach_shader(&prog, &fs);
gl.link_program(&prog);
let view_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&prog, WEB_GL2_UNIFORM_VIEW);
let rect_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&prog, WEB_GL2_DIRECT_UNIFORM_RECT);
let color_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&prog, WEB_GL2_DIRECT_UNIFORM_COLOR);
Some(WebGl2DirectPipeline {
program: prog,
view_loc,
rect_loc,
color_loc,
})
}
#[must_use]
fn web_query_gl2_max_texture_size(gl: &WebGl2RenderingContext) -> u32 {
let max_tex: u32 = gl
.get_parameter(WebGl2RenderingContext::MAX_TEXTURE_SIZE)
.ok()
.and_then(|val: JsValue| val.as_f64())
.map(|val: f64| val.max(1024.0) as u32)
.unwrap_or(WEB_TILED_BLIT_CHUNK_DIM);
let max_rb: u32 = gl
.get_parameter(WebGl2RenderingContext::MAX_RENDERBUFFER_SIZE)
.ok()
.and_then(|val: JsValue| val.as_f64())
.map(|val: f64| val.max(1024.0) as u32)
.unwrap_or(max_tex);
max_tex.min(max_rb).max(1024)
}
#[must_use]
fn web_probe_webgpu_available(win: &Window) -> bool {
let nav: Navigator = win.navigator();
Reflect::get(nav.as_ref(), &JsValue::from_str(WEB_PROP_GPU))
.ok()
.map(|val: JsValue| !val.is_null() && !val.is_undefined())
.unwrap_or(false)
}
fn web_create_gl2_seeded_texture(
gl: &WebGl2RenderingContext,
bind_texture_fn: Option<&Function>,
internal_format: i32,
upload_format: u32,
seed_pixel: &[u8],
) -> Option<JsValue> {
let tex: JsValue = Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_CREATE_TEXTURE))
.ok()
.and_then(|item_val: JsValue| item_val.dyn_into::<Function>().ok())
.and_then(|create_fn: Function| create_fn.call0(gl.as_ref()).ok())
.filter(|val: &JsValue| !val.is_null() && !val.is_undefined())?;
let target_val: JsValue = JsValue::from_f64(WebGl2RenderingContext::TEXTURE_2D as f64);
if let Some(bind_fn) = bind_texture_fn {
drop(bind_fn.call2(gl.as_ref(), &target_val, &tex));
}
gl.tex_parameteri(
WebGl2RenderingContext::TEXTURE_2D,
WebGl2RenderingContext::TEXTURE_MIN_FILTER,
WebGl2RenderingContext::LINEAR as i32,
);
gl.tex_parameteri(
WebGl2RenderingContext::TEXTURE_2D,
WebGl2RenderingContext::TEXTURE_MAG_FILTER,
WebGl2RenderingContext::LINEAR as i32,
);
gl.tex_parameteri(
WebGl2RenderingContext::TEXTURE_2D,
WebGl2RenderingContext::TEXTURE_WRAP_S,
WebGl2RenderingContext::CLAMP_TO_EDGE as i32,
);
gl.tex_parameteri(
WebGl2RenderingContext::TEXTURE_2D,
WebGl2RenderingContext::TEXTURE_WRAP_T,
WebGl2RenderingContext::CLAMP_TO_EDGE as i32,
);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_ALIGNMENT, 1);
let view: Uint8Array = unsafe { Uint8Array::view(seed_pixel) };
let _: Result<(), JsValue> = gl
.tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_array_buffer_view(
WebGl2RenderingContext::TEXTURE_2D,
0,
internal_format,
1,
1,
0,
upload_format,
WebGl2RenderingContext::UNSIGNED_BYTE,
Some(view.as_ref()),
);
Some(tex)
}
fn web_init_gl2_instanced_pipeline(gl: &WebGl2RenderingContext) -> Option<WebGl2InstancedPipeline> {
let program: WebGlProgram = webgl2_compile_ui_program(gl)?;
let linked: bool = gl
.get_program_parameter(&program, WebGl2RenderingContext::LINK_STATUS)
.as_bool()
.unwrap_or(false);
if !linked {
return None;
}
let vao: WebGlVertexArrayObject = gl.create_vertex_array()?;
let quad_vbo: WebGlBuffer = gl.create_buffer()?;
let instance_vbo: WebGlBuffer = gl.create_buffer()?;
gl.bind_vertex_array(Some(&vao));
gl.bind_buffer(WebGl2RenderingContext::ARRAY_BUFFER, Some(&quad_vbo));
let quad_bytes: &[u8] = unsafe {
from_raw_parts(
WEB_GL2_UNIT_QUAD_VERTS.as_ptr().cast::<u8>(),
size_of::<[f32; 12]>(),
)
};
let quad_view: Uint8Array = unsafe { Uint8Array::view(quad_bytes) };
gl.buffer_data_with_array_buffer_view(
WebGl2RenderingContext::ARRAY_BUFFER,
quad_view.as_ref(),
WebGl2RenderingContext::STATIC_DRAW,
);
gl.enable_vertex_attrib_array(0);
gl.vertex_attrib_pointer_with_i32(0, 2, WebGl2RenderingContext::FLOAT, false, 8, 0);
gl.vertex_attrib_divisor(0, 0);
gl.bind_buffer(WebGl2RenderingContext::ARRAY_BUFFER, Some(&instance_vbo));
gl.buffer_data_with_i32(
WebGl2RenderingContext::ARRAY_BUFFER,
WEB_GL2_INITIAL_INSTANCE_VBO_BYTES as i32,
WebGl2RenderingContext::STREAM_DRAW,
);
let attribs: [Gles3InstanceAttribSpec; 5] = gles3_ui_instance_attribs();
for spec in attribs.iter() {
gl.enable_vertex_attrib_array(spec.get_location());
if spec.get_is_integer() {
gl.vertex_attrib_i_pointer_with_i32(
spec.get_location(),
spec.get_components(),
WebGl2RenderingContext::UNSIGNED_INT,
spec.get_stride(),
spec.get_byte_offset() as i32,
);
} else {
gl.vertex_attrib_pointer_with_i32(
spec.get_location(),
spec.get_components(),
WebGl2RenderingContext::FLOAT,
false,
spec.get_stride(),
spec.get_byte_offset() as i32,
);
}
gl.vertex_attrib_divisor(spec.get_location(), 1);
}
gl.bind_vertex_array(None);
gl.use_program(Some(&program));
if let Some(loc) = gl.get_uniform_location(&program, WEB_GL2_UBER_UNIFORM_GLYPH_R8) {
gl.uniform1i(Some(&loc), 0);
}
if let Some(loc) = gl.get_uniform_location(&program, WEB_GL2_UBER_UNIFORM_GLYPH_RGBA8) {
gl.uniform1i(Some(&loc), 1);
}
if let Some(loc) = gl.get_uniform_location(&program, WEB_GL2_UBER_UNIFORM_IMAGE_TEX) {
gl.uniform1i(Some(&loc), 2);
}
if let Some(loc) = gl.get_uniform_location(&program, WEB_GL2_UBER_UNIFORM_EXTERNAL_TEX) {
gl.uniform1i(Some(&loc), 3);
}
let viewport_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&program, WEB_GL2_UBER_UNIFORM_VIEWPORT);
let scroll_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&program, WEB_GL2_UBER_UNIFORM_SCROLL);
let tile_origin_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&program, WEB_GL2_UBER_UNIFORM_TILE_ORIGIN);
let blur_program: Option<WebGlProgram> = web_compile_gl2_program(
gl,
GLSL_ES3_BACKDROP_BLUR_VERTEX_SHADER,
GLSL_ES3_BACKDROP_BLUR_FRAGMENT_SHADER,
);
let (blur_texel_loc, blur_offset_loc, blur_mode_loc): (
Option<WebGlUniformLocation>,
Option<WebGlUniformLocation>,
Option<WebGlUniformLocation>,
) = if let Some(bprog) = blur_program.as_ref() {
gl.use_program(Some(bprog));
if let Some(loc) = gl.get_uniform_location(bprog, WEB_GL2_BLUR_UNIFORM_TEX) {
gl.uniform1i(Some(&loc), 0);
}
(
gl.get_uniform_location(bprog, WEB_GL2_BLUR_UNIFORM_TEXEL),
gl.get_uniform_location(bprog, WEB_GL2_BLUR_UNIFORM_OFFSET),
gl.get_uniform_location(bprog, WEB_GL2_BLUR_UNIFORM_MODE),
)
} else {
(None, None, None)
};
gl.use_program(Some(&program));
let bind_texture_fn: Option<Function> =
Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_BIND_TEXTURE))
.ok()
.and_then(|val: JsValue| val.dyn_into::<Function>().ok());
let zero_r8: [u8; 1] = [0];
let zero_rgba8: [u8; 4] = [0, 0, 0, 0];
gl.active_texture(WebGl2RenderingContext::TEXTURE0);
let glyph_r8_tex: Option<JsValue> = web_create_gl2_seeded_texture(
gl,
bind_texture_fn.as_ref(),
WebGl2RenderingContext::R8 as i32,
WebGl2RenderingContext::RED,
&zero_r8,
);
gl.active_texture(WebGl2RenderingContext::TEXTURE1);
let glyph_rgba8_tex: Option<JsValue> = web_create_gl2_seeded_texture(
gl,
bind_texture_fn.as_ref(),
WebGl2RenderingContext::RGBA8 as i32,
WebGl2RenderingContext::RGBA,
&zero_rgba8,
);
gl.active_texture(WebGl2RenderingContext::TEXTURE2);
let image_atlas_tex: Option<JsValue> = web_create_gl2_seeded_texture(
gl,
bind_texture_fn.as_ref(),
WebGl2RenderingContext::RGBA8 as i32,
WebGl2RenderingContext::RGBA,
&zero_rgba8,
);
gl.active_texture(WebGl2RenderingContext::TEXTURE3);
let external_tex: Option<JsValue> = web_create_gl2_seeded_texture(
gl,
bind_texture_fn.as_ref(),
WebGl2RenderingContext::RGBA8 as i32,
WebGl2RenderingContext::RGBA,
&zero_rgba8,
);
let max_tex_dim: u32 = web_query_gl2_max_texture_size(gl);
Some(WebGl2InstancedPipeline {
program,
vao,
instance_vbo,
instance_vbo_cap_bytes: WEB_GL2_INITIAL_INSTANCE_VBO_BYTES,
viewport_loc,
scroll_loc,
tile_origin_loc,
bind_texture_fn,
glyph_r8_tex,
glyph_r8_w: 1,
glyph_r8_h: 1,
glyph_rgba8_tex,
image_atlas_tex,
image_atlas_w: 1,
image_atlas_h: 1,
external_tex,
max_tex_dim,
blur_program,
blur_texel_loc,
blur_offset_loc,
blur_mode_loc,
blur_scene_fbo: None,
blur_scene_tex: None,
blur_half_fbo: None,
blur_half_tex: None,
blur_full_fbo: None,
blur_full_tex: None,
blur_dims: (0, 0),
scene_gl: None,
synced_glyph_r8_rev: 0,
synced_image_rgba8_rev: 0,
})
}
fn web_init_gl2_blit_pipeline(gl: &WebGl2RenderingContext) -> Option<WebGl2BlitPipeline> {
let vs: WebGlShader = gl.create_shader(WebGl2RenderingContext::VERTEX_SHADER)?;
gl.shader_source(&vs, WEB_GL2_BLIT_VERT_SHADER);
gl.compile_shader(&vs);
let fs: WebGlShader = gl.create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)?;
gl.shader_source(&fs, WEB_GL2_BLIT_FRAG_SHADER);
gl.compile_shader(&fs);
let prog: WebGlProgram = gl.create_program()?;
gl.attach_shader(&prog, &vs);
gl.attach_shader(&prog, &fs);
gl.link_program(&prog);
gl.use_program(Some(&prog));
if let Some(loc) = gl.get_uniform_location(&prog, WEB_GL2_UNIFORM_TEX) {
gl.uniform1i(Some(&loc), 0);
}
let view_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&prog, WEB_GL2_UNIFORM_VIEW);
web_configure_gl2_unpack_state(gl);
let bind_texture_fn: Option<Function> =
Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_BIND_TEXTURE))
.ok()
.and_then(|val: JsValue| val.dyn_into::<Function>().ok());
let texture: Option<JsValue> =
Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_CREATE_TEXTURE))
.ok()
.and_then(|item_val: JsValue| item_val.dyn_into::<Function>().ok())
.and_then(|factor_val: Function| factor_val.call0(gl.as_ref()).ok())
.filter(|blend_factor: &JsValue| {
!blend_factor.is_null() && !blend_factor.is_undefined()
});
if let Some(tex) = texture.as_ref() {
let target: JsValue = JsValue::from_f64(WebGl2RenderingContext::TEXTURE_2D as f64);
if let Some(bind_fn) = bind_texture_fn.as_ref() {
drop(bind_fn.call2(gl.as_ref(), &target, tex));
}
gl.tex_parameteri(
WebGl2RenderingContext::TEXTURE_2D,
WebGl2RenderingContext::TEXTURE_MIN_FILTER,
WebGl2RenderingContext::LINEAR as i32,
);
gl.tex_parameteri(
WebGl2RenderingContext::TEXTURE_2D,
WebGl2RenderingContext::TEXTURE_MAG_FILTER,
WebGl2RenderingContext::LINEAR as i32,
);
gl.tex_parameteri(
WebGl2RenderingContext::TEXTURE_2D,
WebGl2RenderingContext::TEXTURE_WRAP_S,
WebGl2RenderingContext::CLAMP_TO_EDGE as i32,
);
gl.tex_parameteri(
WebGl2RenderingContext::TEXTURE_2D,
WebGl2RenderingContext::TEXTURE_WRAP_T,
WebGl2RenderingContext::CLAMP_TO_EDGE as i32,
);
}
let max_tex_dim: u32 = web_query_gl2_max_texture_size(gl);
Some(WebGl2BlitPipeline {
program: prog,
texture,
view_loc,
bind_texture_fn,
max_tex_dim,
})
}
fn web_invoke_promise_method(target: &JsValue, method: &str) -> bool {
let Ok(func_val) = Reflect::get(target, &JsValue::from_str(method)) else {
return false;
};
let Ok(func) = func_val.dyn_into::<Function>() else {
return false;
};
if let Ok(ret) = func.call0(target)
&& let Ok(promise) = ret.dyn_into::<Promise>()
{
WEB_PROMISE_NOOP_REJECT.with(|callback_fn: &Closure<dyn FnMut(JsValue)>| {
let _: Promise = promise.catch(callback_fn);
});
}
true
}
#[must_use]
fn web_doc_has_fullscreen_element(doc: &Document) -> bool {
if doc.fullscreen_element().is_some() {
return true;
}
Reflect::get(
doc.as_ref(),
&JsValue::from_str(WEB_PROP_WEBKIT_FULLSCREEN_ELEMENT),
)
.ok()
.map(|item_val: JsValue| !item_val.is_null() && !item_val.is_undefined())
.unwrap_or(false)
}
pub fn web_set_fullscreen(enabled: bool) {
let Some(doc) = window().and_then(|width_val: Window| width_val.document()) else {
return;
};
let is_fs: bool = web_doc_has_fullscreen_element(&doc);
if enabled {
if !is_fs
&& let Some(root) = doc.document_element()
&& !web_invoke_promise_method(root.as_ref(), WEB_METHOD_REQUEST_FULLSCREEN)
{
let _: bool =
web_invoke_promise_method(root.as_ref(), WEB_METHOD_WEBKIT_REQUEST_FULLSCREEN);
}
} else if is_fs && !web_invoke_promise_method(doc.as_ref(), WEB_METHOD_EXIT_FULLSCREEN) {
let _: bool = web_invoke_promise_method(doc.as_ref(), WEB_METHOD_WEBKIT_EXIT_FULLSCREEN);
}
}
fn web_ensure_reset_stylesheet(doc: &Document) {
if doc.get_element_by_id(WEB_RESET_STYLE_ID).is_some() {
return;
}
let Ok(style_el) = doc.create_element(WEB_STYLE_TAG) else {
return;
};
drop(style_el.set_attribute(WEB_ATTR_ID, WEB_RESET_STYLE_ID));
style_el.set_text_content(Some(WEB_RESET_STYLE_CSS));
if let Ok(Some(head)) = doc.query_selector(WEB_HEAD_SELECTOR) {
drop(head.append_child(&style_el));
} else if let Some(root) = doc.document_element() {
drop(root.append_child(&style_el));
}
}
pub(crate) fn web_create_canvas(
config: &WindowConfig,
dpr: f32,
reuse_existing: bool,
) -> Result<WebCanvasSurface, PlatformError> {
let win: Window = window()
.ok_or_else(|| PlatformError::InitializationFailed(ERR_WEB_WINDOW_MISSING.to_string()))?;
let doc: Document = win
.document()
.ok_or_else(|| PlatformError::InitializationFailed(ERR_WEB_WINDOW_MISSING.to_string()))?;
doc.set_title(config.get_title());
web_ensure_reset_stylesheet(&doc);
let mut existing_canvas: Option<HtmlCanvasElement> = None;
if reuse_existing
&& let Ok(Some(found)) = doc.query_selector(WEB_CANVAS_TAG)
&& let Ok(existing) = found.dyn_into::<HtmlCanvasElement>()
{
existing_canvas = Some(existing);
}
let (canvas, needs_append): (HtmlCanvasElement, bool) = match existing_canvas {
Some(existing) => (existing, false),
None => {
let el: Element = doc.create_element(WEB_CANVAS_TAG).map_err(|_: JsValue| {
PlatformError::InitializationFailed(ERR_WEB_CANVAS_CREATE.to_string())
})?;
let created: HtmlCanvasElement =
el.dyn_into::<HtmlCanvasElement>().map_err(|_: Element| {
PlatformError::InitializationFailed(ERR_WEB_CANVAS_CREATE.to_string())
})?;
(created, true)
}
};
let (win_w, win_h): (f64, f64) = web_query_viewport_css_size(
&win,
&doc,
config.get_width() as f64,
config.get_height() as f64,
);
let safe_dpr: f64 = f64::from(dpr.clamp(WEB_DPR_MIN, WEB_DPR_MAX));
let phys_w: u32 = (win_w * safe_dpr)
.round()
.clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
let phys_h: u32 = (win_h * safe_dpr)
.round()
.clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
canvas.set_width(phys_w);
canvas.set_height(phys_h);
let css_style: String =
format!("{WEB_CANVAS_STYLE_PREFIX}{WEB_CURSOR_DEFAULT}{WEB_CANVAS_STYLE_SUFFIX}");
drop(canvas.set_attribute(WEB_ATTR_STYLE, &css_style));
drop(canvas.set_attribute(WEB_ATTR_CANVAS_ROLE, WEB_CANVAS_ROLE_ACTIVE));
drop(canvas.set_attribute(WEB_ATTR_TABINDEX, WEB_ATTR_TABINDEX_ZERO));
if let Some(body) = doc.body() {
drop(body.set_attribute(WEB_ATTR_STYLE, WEB_BODY_STYLE));
if needs_append {
drop(body.append_child(&canvas));
}
}
let render_mode: RenderMode = config.get_render().get_mode();
let prefer_direct: bool = config.get_render().get_direct_gpu_present();
let webgpu_available: bool = web_probe_webgpu_available(&win);
if render_mode != RenderMode::Software {
let gl_opts: Object = web_gl2_context_options();
if let Ok(Some(raw_gl)) =
canvas.get_context_with_context_options(WEB_CONTEXT_WEBGL2, gl_opts.as_ref())
&& let Ok(gl2) = raw_gl.dyn_into::<WebGl2RenderingContext>()
{
let gl2_instanced: Option<WebGl2InstancedPipeline> =
web_init_gl2_instanced_pipeline(&gl2);
let direct: Option<WebGl2DirectPipeline> = web_init_gl2_direct_pipeline(&gl2);
let (
gl2_direct_program,
gl2_direct_view_loc,
gl2_direct_rect_loc,
gl2_direct_color_loc,
): (
Option<WebGlProgram>,
Option<WebGlUniformLocation>,
Option<WebGlUniformLocation>,
Option<WebGlUniformLocation>,
) = match direct {
Some(delta_val) => (
Some(delta_val.program),
delta_val.view_loc,
delta_val.rect_loc,
delta_val.color_loc,
),
None => (None, None, None, None),
};
let pipeline: Option<WebGl2BlitPipeline> = web_init_gl2_blit_pipeline(&gl2);
let (gl2_program, gl2_texture, gl2_view_loc, gl2_bind_texture_fn, gl2_max_tex_dim): (
Option<WebGlProgram>,
Option<JsValue>,
Option<WebGlUniformLocation>,
Option<Function>,
u32,
) = match pipeline {
Some(point_val) => (
Some(point_val.program),
point_val.texture,
point_val.view_loc,
point_val.bind_texture_fn,
point_val.max_tex_dim,
),
None => (None, None, None, None, web_query_gl2_max_texture_size(&gl2)),
};
let pres_mode: WebPresentationMode = if prefer_direct && gl2_instanced.is_some() {
WebPresentationMode::GpuDirect
} else {
WebPresentationMode::GpuUpload
};
return Ok(WebCanvasSurface {
canvas,
context_kind: WebCanvasContextKind::WebGl2,
presentation_mode: pres_mode,
webgpu_ctx: None,
webgpu_available,
gl2: Some(gl2),
gl2_instanced,
gl2_direct_program,
gl2_direct_view_loc,
gl2_direct_rect_loc,
gl2_direct_color_loc,
gl2_program,
gl2_texture,
gl2_view_loc,
gl2_bind_texture_fn,
gl2_max_tex_dim,
ctx2d: None,
});
}
}
let raw_ctx: Object = canvas
.get_context(WEB_CONTEXT_2D)
.map_err(|_: JsValue| PlatformError::SurfaceError(ERR_WEB_CONTEXT_2D_MISSING.to_string()))?
.ok_or_else(|| PlatformError::SurfaceError(ERR_WEB_CONTEXT_2D_MISSING.to_string()))?;
let ctx2d: CanvasRenderingContext2d = raw_ctx
.dyn_into::<CanvasRenderingContext2d>()
.map_err(|_: Object| PlatformError::SurfaceError(ERR_WEB_CONTEXT_2D_MISSING.to_string()))?;
Ok(WebCanvasSurface {
canvas,
context_kind: WebCanvasContextKind::Canvas2d,
presentation_mode: WebPresentationMode::Software,
webgpu_ctx: None,
webgpu_available,
gl2: None,
gl2_instanced: None,
gl2_direct_program: None,
gl2_direct_view_loc: None,
gl2_direct_rect_loc: None,
gl2_direct_color_loc: None,
gl2_program: None,
gl2_texture: None,
gl2_view_loc: None,
gl2_bind_texture_fn: None,
gl2_max_tex_dim: WEB_TILED_BLIT_CHUNK_DIM,
ctx2d: Some(ctx2d),
})
}
pub(crate) fn web_create_independent_standby_canvas(
parent_el: Option<&Element>,
target_mode: WebPresentationMode,
phys_w: u32,
phys_h: u32,
) -> Result<WebCanvasSurface, PlatformError> {
let win: Window = window()
.ok_or_else(|| PlatformError::InitializationFailed(ERR_WEB_WINDOW_MISSING.to_string()))?;
let doc: Document = win
.document()
.ok_or_else(|| PlatformError::InitializationFailed(ERR_WEB_WINDOW_MISSING.to_string()))?;
let el: Element = doc.create_element(WEB_CANVAS_TAG).map_err(|_: JsValue| {
PlatformError::InitializationFailed(ERR_WEB_CANVAS_CREATE.to_string())
})?;
let canvas: HtmlCanvasElement = el.dyn_into::<HtmlCanvasElement>().map_err(|_: Element| {
PlatformError::InitializationFailed(ERR_WEB_CANVAS_CREATE.to_string())
})?;
canvas.set_width(phys_w.max(1));
canvas.set_height(phys_h.max(1));
drop(canvas.set_attribute(WEB_ATTR_STYLE, WEB_STANDBY_CANVAS_STYLE));
drop(canvas.set_attribute(WEB_ATTR_CANVAS_ROLE, WEB_CANVAS_ROLE_STANDBY));
drop(canvas.set_attribute(WEB_ATTR_TABINDEX, WEB_ATTR_TABINDEX_ZERO));
if let Some(container) = parent_el {
drop(container.append_child(&canvas));
} else if let Some(body) = doc.body() {
drop(body.append_child(&canvas));
}
match target_mode {
WebPresentationMode::GpuDirect | WebPresentationMode::GpuUpload => {
let gl_opts: Object = web_gl2_context_options();
let raw_gl: Object = canvas
.get_context_with_context_options(WEB_CONTEXT_WEBGL2, gl_opts.as_ref())
.map_err(|_: JsValue| {
canvas.remove();
PlatformError::SurfaceError(ERR_WEB_GL2_CONTEXT_MISSING.to_string())
})?
.ok_or_else(|| {
canvas.remove();
PlatformError::SurfaceError(ERR_WEB_GL2_CONTEXT_MISSING.to_string())
})?;
let gl2: WebGl2RenderingContext =
raw_gl
.dyn_into::<WebGl2RenderingContext>()
.map_err(|_: Object| {
canvas.remove();
PlatformError::SurfaceError(ERR_WEB_GL2_CONTEXT_MISSING.to_string())
})?;
let gl2_instanced: Option<WebGl2InstancedPipeline> =
web_init_gl2_instanced_pipeline(&gl2);
let direct: Option<WebGl2DirectPipeline> = web_init_gl2_direct_pipeline(&gl2);
let (
gl2_direct_program,
gl2_direct_view_loc,
gl2_direct_rect_loc,
gl2_direct_color_loc,
): (
Option<WebGlProgram>,
Option<WebGlUniformLocation>,
Option<WebGlUniformLocation>,
Option<WebGlUniformLocation>,
) = match direct {
Some(delta_val) => (
Some(delta_val.program),
delta_val.view_loc,
delta_val.rect_loc,
delta_val.color_loc,
),
None => (None, None, None, None),
};
let pipeline: Option<WebGl2BlitPipeline> = web_init_gl2_blit_pipeline(&gl2);
let (gl2_program, gl2_texture, gl2_view_loc, gl2_bind_texture_fn, gl2_max_tex_dim): (
Option<WebGlProgram>,
Option<JsValue>,
Option<WebGlUniformLocation>,
Option<Function>,
u32,
) = match pipeline {
Some(point_val) => (
Some(point_val.program),
point_val.texture,
point_val.view_loc,
point_val.bind_texture_fn,
point_val.max_tex_dim,
),
None => (None, None, None, None, web_query_gl2_max_texture_size(&gl2)),
};
if target_mode == WebPresentationMode::GpuDirect
&& gl2_instanced.is_none()
&& gl2_direct_program.is_none()
{
canvas.remove();
return Err(PlatformError::SurfaceError(
ERR_WEB_GL2_DIRECT_MISSING.to_string(),
));
}
Ok(WebCanvasSurface {
canvas,
context_kind: WebCanvasContextKind::WebGl2,
presentation_mode: target_mode,
webgpu_ctx: None,
webgpu_available: web_probe_webgpu_available(&win),
gl2: Some(gl2),
gl2_instanced,
gl2_direct_program,
gl2_direct_view_loc,
gl2_direct_rect_loc,
gl2_direct_color_loc,
gl2_program,
gl2_texture,
gl2_view_loc,
gl2_bind_texture_fn,
gl2_max_tex_dim,
ctx2d: None,
})
}
WebPresentationMode::Software => {
let raw_ctx: Object = canvas
.get_context(WEB_CONTEXT_2D)
.map_err(|_: JsValue| {
canvas.remove();
PlatformError::SurfaceError(ERR_WEB_CONTEXT_2D_MISSING.to_string())
})?
.ok_or_else(|| {
canvas.remove();
PlatformError::SurfaceError(ERR_WEB_CONTEXT_2D_MISSING.to_string())
})?;
let ctx2d: CanvasRenderingContext2d = raw_ctx
.dyn_into::<CanvasRenderingContext2d>()
.map_err(|_: Object| {
canvas.remove();
PlatformError::SurfaceError(ERR_WEB_CONTEXT_2D_MISSING.to_string())
})?;
Ok(WebCanvasSurface {
canvas,
context_kind: WebCanvasContextKind::Canvas2d,
presentation_mode: WebPresentationMode::Software,
webgpu_ctx: None,
webgpu_available: web_probe_webgpu_available(&win),
gl2: None,
gl2_instanced: None,
gl2_direct_program: None,
gl2_direct_view_loc: None,
gl2_direct_rect_loc: None,
gl2_direct_color_loc: None,
gl2_program: None,
gl2_texture: None,
gl2_view_loc: None,
gl2_bind_texture_fn: None,
gl2_max_tex_dim: WEB_TILED_BLIT_CHUNK_DIM,
ctx2d: Some(ctx2d),
})
}
}
}
#[must_use]
pub(crate) fn web_batches_support_gl2_direct(batches: &[GpuBatch]) -> bool {
for batch_entry in batches.iter() {
for primitive_item in batch_entry.get_primitives().iter() {
if primitive_item.prim_kind() != PrimKind::RoundedRect
|| primitive_item.get_radii_border() != [0, 0, 0, 0]
|| primitive_item.get_extra_param() != 0
{
return false;
}
}
}
true
}
pub(crate) fn web_draw_gl2_direct_batches(
gl: &WebGl2RenderingContext,
program: &WebGlProgram,
uniform_locs: &WebGl2DirectUniforms<'_>,
surface_dims: (u32, u32),
clear_color: Color,
batches: &[GpuBatch],
) -> u32 {
let view_loc: Option<&WebGlUniformLocation> = uniform_locs.view_loc;
let rect_loc: Option<&WebGlUniformLocation> = uniform_locs.rect_loc;
let color_loc: Option<&WebGlUniformLocation> = uniform_locs.color_loc;
let (width, height): (u32, u32) = surface_dims;
let draw_w: i32 = width.max(1) as i32;
let draw_h: i32 = height.max(1) as i32;
gl.viewport(0, 0, draw_w, draw_h);
gl.enable(WebGl2RenderingContext::BLEND);
gl.blend_func(
WebGl2RenderingContext::SRC_ALPHA,
WebGl2RenderingContext::ONE_MINUS_SRC_ALPHA,
);
gl.clear_color(
f32::from(clear_color.get_red()) / 255.0,
f32::from(clear_color.get_green()) / 255.0,
f32::from(clear_color.get_blue()) / 255.0,
f32::from(clear_color.get_alpha()) / 255.0,
);
gl.clear(WebGl2RenderingContext::COLOR_BUFFER_BIT);
gl.use_program(Some(program));
if let Some(loc) = view_loc {
gl.uniform2f(Some(loc), draw_w as f32, draw_h as f32);
}
let mut drawn: u32 = 0;
for batch in batches.iter() {
for prim in batch.get_primitives().iter() {
let rect: [f32; 4] = prim.get_rect();
let packed: u32 = prim.get_color_rgba();
let red_val: f32 = f32::from((packed & 0xFF) as u8) / 255.0;
let green_val: f32 = f32::from(((packed >> 8) & 0xFF) as u8) / 255.0;
let blue_val: f32 = f32::from(((packed >> 16) & 0xFF) as u8) / 255.0;
let alpha_val: f32 = f32::from(((packed >> 24) & 0xFF) as u8) / 255.0;
if let Some(loc) = rect_loc {
gl.uniform4f(Some(loc), rect[0], rect[1], rect[2], rect[3]);
}
if let Some(loc) = color_loc {
gl.uniform4f(Some(loc), red_val, green_val, blue_val, alpha_val);
}
gl.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, 6);
drawn = drawn.saturating_add(1);
}
}
drawn
}
fn web_sync_gl2_glyph_r8_atlas(
gl: &WebGl2RenderingContext,
pipe: &mut WebGl2InstancedPipeline,
atlas: &DirectGpuAtlasUpload,
dirty_rects: &[PixelDirtyRect],
) {
let atlas_w: u32 = atlas.get_width();
let atlas_h: u32 = atlas.get_height();
let pixels: &[u8] = atlas.get_pixels().as_slice();
if atlas_w == 0
|| atlas_h == 0
|| pixels.len() < (atlas_w as usize).saturating_mul(atlas_h as usize)
{
return;
}
let Some(tex) = pipe.glyph_r8_tex.as_ref() else {
return;
};
let target_val: JsValue = JsValue::from_f64(WebGl2RenderingContext::TEXTURE_2D as f64);
gl.active_texture(WebGl2RenderingContext::TEXTURE0);
if let Some(bind_fn) = pipe.bind_texture_fn.as_ref() {
drop(bind_fn.call2(gl.as_ref(), &target_val, tex));
}
gl.pixel_storei(WebGl2RenderingContext::UNPACK_ALIGNMENT, 1);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_FLIP_Y_WEBGL, 0);
let dims_changed: bool = pipe.glyph_r8_w != atlas_w || pipe.glyph_r8_h != atlas_h;
if dims_changed || dirty_rects.is_empty() {
gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, 0);
let view: Uint8Array = unsafe { Uint8Array::view(pixels) };
let _: Result<(), JsValue> = gl
.tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_array_buffer_view(
WebGl2RenderingContext::TEXTURE_2D,
0,
WebGl2RenderingContext::R8 as i32,
atlas_w as i32,
atlas_h as i32,
0,
WebGl2RenderingContext::RED,
WebGl2RenderingContext::UNSIGNED_BYTE,
Some(view.as_ref()),
);
pipe.glyph_r8_w = atlas_w;
pipe.glyph_r8_h = atlas_h;
return;
}
gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, atlas_w as i32);
let view: Uint8Array = unsafe { Uint8Array::view(pixels) };
for dirty in dirty_rects.iter() {
let rx: u32 = dirty.get_x().min(atlas_w);
let ry: u32 = dirty.get_y().min(atlas_h);
let rw: u32 = dirty.get_width().min(atlas_w.saturating_sub(rx));
let rh: u32 = dirty.get_height().min(atlas_h.saturating_sub(ry));
if rw == 0 || rh == 0 {
continue;
}
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, rx as i32);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, ry as i32);
let _: Result<(), JsValue> = gl
.tex_sub_image_2d_with_i32_and_i32_and_u32_and_type_and_opt_array_buffer_view(
WebGl2RenderingContext::TEXTURE_2D,
0,
rx as i32,
ry as i32,
rw as i32,
rh as i32,
WebGl2RenderingContext::RED,
WebGl2RenderingContext::UNSIGNED_BYTE,
Some(view.as_ref()),
);
}
gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, 0);
}
fn web_compile_gl2_program(
gl: &WebGl2RenderingContext,
vs_src: &str,
fs_src: &str,
) -> Option<WebGlProgram> {
let vs: WebGlShader = gl.create_shader(WebGl2RenderingContext::VERTEX_SHADER)?;
gl.shader_source(&vs, vs_src);
gl.compile_shader(&vs);
if !gl
.get_shader_parameter(&vs, WebGl2RenderingContext::COMPILE_STATUS)
.as_bool()
.unwrap_or(false)
{
return None;
}
let fs: WebGlShader = gl.create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)?;
gl.shader_source(&fs, fs_src);
gl.compile_shader(&fs);
if !gl
.get_shader_parameter(&fs, WebGl2RenderingContext::COMPILE_STATUS)
.as_bool()
.unwrap_or(false)
{
return None;
}
let prog: WebGlProgram = gl.create_program()?;
gl.attach_shader(&prog, &vs);
gl.attach_shader(&prog, &fs);
gl.link_program(&prog);
if !gl
.get_program_parameter(&prog, WebGl2RenderingContext::LINK_STATUS)
.as_bool()
.unwrap_or(false)
{
return None;
}
Some(prog)
}
fn web_create_gl2_fbo_target(
gl: &WebGl2RenderingContext,
width: u32,
height: u32,
) -> Option<(WebGlFramebuffer, WebGlTexture)> {
let fbo: WebGlFramebuffer = gl.create_framebuffer()?;
let tex: WebGlTexture = gl.create_texture()?;
gl.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(&tex));
gl.tex_parameteri(
WebGl2RenderingContext::TEXTURE_2D,
WebGl2RenderingContext::TEXTURE_MIN_FILTER,
WebGl2RenderingContext::LINEAR as i32,
);
gl.tex_parameteri(
WebGl2RenderingContext::TEXTURE_2D,
WebGl2RenderingContext::TEXTURE_MAG_FILTER,
WebGl2RenderingContext::LINEAR as i32,
);
gl.tex_parameteri(
WebGl2RenderingContext::TEXTURE_2D,
WebGl2RenderingContext::TEXTURE_WRAP_S,
WebGl2RenderingContext::CLAMP_TO_EDGE as i32,
);
gl.tex_parameteri(
WebGl2RenderingContext::TEXTURE_2D,
WebGl2RenderingContext::TEXTURE_WRAP_T,
WebGl2RenderingContext::CLAMP_TO_EDGE as i32,
);
let _: Result<(), JsValue> = gl
.tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_array_buffer_view(
WebGl2RenderingContext::TEXTURE_2D,
0,
WebGl2RenderingContext::RGBA8 as i32,
width.max(1) as i32,
height.max(1) as i32,
0,
WebGl2RenderingContext::RGBA,
WebGl2RenderingContext::UNSIGNED_BYTE,
None,
);
gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, Some(&fbo));
gl.framebuffer_texture_2d(
WebGl2RenderingContext::FRAMEBUFFER,
WebGl2RenderingContext::COLOR_ATTACHMENT0,
WebGl2RenderingContext::TEXTURE_2D,
Some(&tex),
0,
);
gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, None);
Some((fbo, tex))
}
fn web_ensure_gl2_blur_targets(
gl: &WebGl2RenderingContext,
pipe: &mut WebGl2InstancedPipeline,
width: u32,
height: u32,
) -> bool {
let w: u32 = width.max(1);
let h: u32 = height.max(1);
if pipe.blur_dims == (w, h)
&& pipe.blur_scene_fbo.is_some()
&& pipe.blur_half_fbo.is_some()
&& pipe.blur_full_fbo.is_some()
{
return true;
}
if let Some(fbo) = pipe.blur_scene_fbo.take() {
gl.delete_framebuffer(Some(&fbo));
}
if let Some(tex) = pipe.blur_scene_tex.take() {
gl.delete_texture(Some(&tex));
}
if let Some(fbo) = pipe.blur_half_fbo.take() {
gl.delete_framebuffer(Some(&fbo));
}
if let Some(tex) = pipe.blur_half_tex.take() {
gl.delete_texture(Some(&tex));
}
if let Some(fbo) = pipe.blur_full_fbo.take() {
gl.delete_framebuffer(Some(&fbo));
}
if let Some(tex) = pipe.blur_full_tex.take() {
gl.delete_texture(Some(&tex));
}
let hw: u32 = (w / 2).max(1);
let hh: u32 = (h / 2).max(1);
let (Some((sfbo, stex)), Some((hfbo, htex)), Some((ffbo, ftex))) = (
web_create_gl2_fbo_target(gl, w, h),
web_create_gl2_fbo_target(gl, hw, hh),
web_create_gl2_fbo_target(gl, w, h),
) else {
pipe.blur_dims = (0, 0);
return false;
};
pipe.blur_scene_fbo = Some(sfbo);
pipe.blur_scene_tex = Some(stex);
pipe.blur_half_fbo = Some(hfbo);
pipe.blur_half_tex = Some(htex);
pipe.blur_full_fbo = Some(ffbo);
pipe.blur_full_tex = Some(ftex);
pipe.blur_dims = (w, h);
true
}
fn web_init_gl2_scene_pipeline(gl: &WebGl2RenderingContext) -> Option<WebGl2ScenePipeline> {
let ocean_program: WebGlProgram =
web_compile_gl2_program(gl, WEB_GL2_SCENE_FULLSCREEN_VERT, WEB_GL2_SCENE_OCEAN_FRAG)?;
gl.use_program(Some(&ocean_program));
if let Some(loc) = gl.get_uniform_location(&ocean_program, WEB_GL2_SCENE_UNIFORM_WAKE_TEX) {
gl.uniform1i(Some(&loc), 0);
}
let ocean_time_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&ocean_program, WEB_GL2_SCENE_UNIFORM_OCEAN_TIME);
let ocean_roll_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&ocean_program, WEB_GL2_SCENE_UNIFORM_OCEAN_ROLL);
let ocean_sun_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&ocean_program, WEB_GL2_SCENE_UNIFORM_OCEAN_SUN);
let boat_program: WebGlProgram =
web_compile_gl2_program(gl, WEB_GL2_SCENE_BOAT_VERT, WEB_GL2_SCENE_BOAT_FRAG)?;
let boat_vao: WebGlVertexArrayObject = gl.create_vertex_array()?;
let boat_vbo: WebGlBuffer = gl.create_buffer()?;
gl.bind_vertex_array(Some(&boat_vao));
gl.bind_buffer(WebGl2RenderingContext::ARRAY_BUFFER, Some(&boat_vbo));
gl.enable_vertex_attrib_array(0);
gl.vertex_attrib_pointer_with_i32(0, 4, WebGl2RenderingContext::FLOAT, false, 32, 0);
gl.enable_vertex_attrib_array(1);
gl.vertex_attrib_pointer_with_i32(1, 4, WebGl2RenderingContext::FLOAT, false, 32, 16);
gl.bind_vertex_array(None);
let sky3d_program: WebGlProgram =
web_compile_gl2_program(gl, WEB_GL2_SCENE_FULLSCREEN_VERT, WEB_GL2_SCENE_3D_SKY_FRAG)?;
let sky3d_cam_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&sky3d_program, WEB_GL2_SCENE_UNIFORM_CAM_POS);
let sky3d_sun_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&sky3d_program, WEB_GL2_SCENE_UNIFORM_SUN_COL);
let sky3d_hor_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&sky3d_program, WEB_GL2_SCENE_UNIFORM_SKY_HOR);
let sky3d_zen_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&sky3d_program, WEB_GL2_SCENE_UNIFORM_SKY_ZEN);
let mesh3d_program: WebGlProgram =
web_compile_gl2_program(gl, WEB_GL2_SCENE_3D_MESH_VERT, WEB_GL2_SCENE_3D_MESH_FRAG)?;
let mesh3d_vp_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&mesh3d_program, WEB_GL2_SCENE_UNIFORM_VIEW_PROJ);
let mesh3d_cam_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&mesh3d_program, WEB_GL2_SCENE_UNIFORM_CAM_POS);
let mesh3d_sun_fog_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&mesh3d_program, WEB_GL2_SCENE_UNIFORM_SUN_FOG);
let mesh3d_sun_col_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&mesh3d_program, WEB_GL2_SCENE_UNIFORM_SUN_COL);
let mesh3d_hor_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&mesh3d_program, WEB_GL2_SCENE_UNIFORM_SKY_HOR);
let mesh3d_zen_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&mesh3d_program, WEB_GL2_SCENE_UNIFORM_SKY_ZEN);
let mesh3d_vao: WebGlVertexArrayObject = gl.create_vertex_array()?;
let mesh3d_vert_vbo: WebGlBuffer = gl.create_buffer()?;
let mesh3d_inst_vbo: WebGlBuffer = gl.create_buffer()?;
gl.bind_vertex_array(Some(&mesh3d_vao));
gl.bind_buffer(WebGl2RenderingContext::ARRAY_BUFFER, Some(&mesh3d_vert_vbo));
for attr_idx in 0u32..3u32 {
gl.enable_vertex_attrib_array(attr_idx);
gl.vertex_attrib_pointer_with_i32(
attr_idx,
4,
WebGl2RenderingContext::FLOAT,
false,
48,
(attr_idx * 16) as i32,
);
gl.vertex_attrib_divisor(attr_idx, 0);
}
gl.bind_buffer(WebGl2RenderingContext::ARRAY_BUFFER, Some(&mesh3d_inst_vbo));
for slot in 0u32..6u32 {
let loc: u32 = 3 + slot;
gl.enable_vertex_attrib_array(loc);
gl.vertex_attrib_pointer_with_i32(
loc,
4,
WebGl2RenderingContext::FLOAT,
false,
96,
(slot * 16) as i32,
);
gl.vertex_attrib_divisor(loc, 1);
}
gl.bind_vertex_array(None);
let (scene_fbo, scene_color_tex): (WebGlFramebuffer, WebGlTexture) =
web_create_gl2_fbo_target(gl, 64, 64)?;
let scene_depth_rbo: WebGlRenderbuffer = gl.create_renderbuffer()?;
gl.bind_renderbuffer(WebGl2RenderingContext::RENDERBUFFER, Some(&scene_depth_rbo));
gl.renderbuffer_storage(
WebGl2RenderingContext::RENDERBUFFER,
WebGl2RenderingContext::DEPTH_COMPONENT24,
64,
64,
);
gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, Some(&scene_fbo));
gl.framebuffer_renderbuffer(
WebGl2RenderingContext::FRAMEBUFFER,
WebGl2RenderingContext::DEPTH_ATTACHMENT,
WebGl2RenderingContext::RENDERBUFFER,
Some(&scene_depth_rbo),
);
gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, None);
let wake_tex: WebGlTexture = gl.create_texture()?;
gl.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(&wake_tex));
gl.tex_parameteri(
WebGl2RenderingContext::TEXTURE_2D,
WebGl2RenderingContext::TEXTURE_MIN_FILTER,
WebGl2RenderingContext::LINEAR as i32,
);
gl.tex_parameteri(
WebGl2RenderingContext::TEXTURE_2D,
WebGl2RenderingContext::TEXTURE_MAG_FILTER,
WebGl2RenderingContext::LINEAR as i32,
);
gl.tex_parameteri(
WebGl2RenderingContext::TEXTURE_2D,
WebGl2RenderingContext::TEXTURE_WRAP_S,
WebGl2RenderingContext::CLAMP_TO_EDGE as i32,
);
gl.tex_parameteri(
WebGl2RenderingContext::TEXTURE_2D,
WebGl2RenderingContext::TEXTURE_WRAP_T,
WebGl2RenderingContext::CLAMP_TO_EDGE as i32,
);
Some(WebGl2ScenePipeline {
ocean_program,
ocean_time_loc,
ocean_roll_loc,
ocean_sun_loc,
boat_program,
boat_vao,
boat_vbo,
boat_vbo_cap: 0,
sky3d_program,
sky3d_cam_loc,
sky3d_sun_loc,
sky3d_hor_loc,
sky3d_zen_loc,
mesh3d_program,
mesh3d_vp_loc,
mesh3d_cam_loc,
mesh3d_sun_fog_loc,
mesh3d_sun_col_loc,
mesh3d_hor_loc,
mesh3d_zen_loc,
mesh3d_vao,
mesh3d_vert_vbo,
mesh3d_vert_rev: 0,
mesh3d_vert_cap: 0,
mesh3d_inst_vbo,
mesh3d_inst_cap: 0,
mesh3d_inst_base_off: 0,
scene_fbo,
scene_color_tex,
scene_depth_rbo,
scene_dims: (64, 64),
wake_tex,
wake_dims: (0, 0),
})
}
#[must_use]
fn web_scene_pass_tile_uv_bounds(
submission: &GpuFrameSubmission,
tile_origin: (f32, f32),
draw_dims: (i32, i32),
) -> Option<[f32; 4]> {
let tile_x0: f32 = tile_origin.0;
let tile_y0: f32 = tile_origin.1;
let tile_x1: f32 = tile_x0 + (draw_dims.0.max(1) as f32);
let tile_y1: f32 = tile_y0 + (draw_dims.1.max(1) as f32);
let mut found: bool = false;
let mut min_u: f32 = 1.0;
let mut min_v: f32 = 1.0;
let mut max_u: f32 = 0.0;
let mut max_v: f32 = 0.0;
for batch in submission.get_batches().iter() {
for prim in batch.get_primitives().iter() {
if prim.prim_kind() != PrimKind::ExternalGpuSurface {
continue;
}
let rect: [f32; 4] = prim.get_rect();
let clip: [f32; 4] = prim.get_clip_rect();
let qw: f32 = rect[2];
let qh: f32 = rect[3];
if qw <= 0.0 || qh <= 0.0 {
continue;
}
let qx0: f32 = rect[0];
let qy0: f32 = rect[1];
let qx1: f32 = qx0 + qw;
let qy1: f32 = qy0 + qh;
let vx0: f32 = qx0.max(clip[0]).max(tile_x0);
let vy0: f32 = qy0.max(clip[1]).max(tile_y0);
let vx1: f32 = qx1.min(clip[2]).min(tile_x1);
let vy1: f32 = qy1.min(clip[3]).min(tile_y1);
if vx1 <= vx0 || vy1 <= vy0 {
continue;
}
let u0: f32 = ((vx0 - qx0) / qw).clamp(0.0, 1.0);
let v0: f32 = ((vy0 - qy0) / qh).clamp(0.0, 1.0);
let u1: f32 = ((vx1 - qx0) / qw).clamp(0.0, 1.0);
let v1: f32 = ((vy1 - qy0) / qh).clamp(0.0, 1.0);
if u1 <= u0 || v1 <= v0 {
continue;
}
min_u = min_u.min(u0);
min_v = min_v.min(v0);
max_u = max_u.max(u1);
max_v = max_v.max(v1);
found = true;
}
}
if found {
Some([min_u, min_v, max_u, max_v])
} else {
None
}
}
#[must_use]
fn web_tile_has_backdrop_blur(
submission: &GpuFrameSubmission,
tile_origin: (f32, f32),
draw_dims: (i32, i32),
) -> bool {
let tile_x0: f32 = tile_origin.0;
let tile_y0: f32 = tile_origin.1;
let tile_x1: f32 = tile_x0 + (draw_dims.0.max(1) as f32);
let tile_y1: f32 = tile_y0 + (draw_dims.1.max(1) as f32);
for batch in submission.get_batches().iter() {
for prim in batch.get_primitives().iter() {
if prim.prim_kind() != PrimKind::BackdropBlur {
continue;
}
let rect: [f32; 4] = prim.get_rect();
let clip: [f32; 4] = prim.get_clip_rect();
let vx0: f32 = rect[0].max(clip[0]).max(tile_x0);
let vy0: f32 = rect[1].max(clip[1]).max(tile_y0);
let vx1: f32 = (rect[0] + rect[2]).min(clip[2]).min(tile_x1);
let vy1: f32 = (rect[1] + rect[3]).min(clip[3]).min(tile_y1);
if vx1 > vx0 && vy1 > vy0 {
return true;
}
}
}
false
}
pub(crate) fn web_sync_canvas_tiled_attr(
canvas: Option<&HtmlCanvasElement>,
active_tile_grid: &mut (u32, u32),
columns: u32,
rows: u32,
) {
let next_grid: (u32, u32) = (columns.max(1), rows.max(1));
if *active_tile_grid == next_grid {
return;
}
if let Some(el) = canvas {
if next_grid.0 > 1 || next_grid.1 > 1 {
let label: String = format!("{}x{}", next_grid.0, next_grid.1);
drop(el.set_attribute(WEB_ATTR_DATA_TILED, &label));
} else {
drop(el.remove_attribute(WEB_ATTR_DATA_TILED));
}
}
*active_tile_grid = next_grid;
}
fn web_execute_gl2_scene_pass(
gl: &WebGl2RenderingContext,
scene: &mut WebGl2ScenePipeline,
max_tex_dim: u32,
pass: &DirectGpuScenePass,
uv_bounds: [f32; 4],
) {
let max_dim: u32 = max_tex_dim.clamp(256, WEB_GL2_MAX_SINGLE_SURFACE_DIM);
let (req_w, req_h): (u32, u32) = match pass {
DirectGpuScenePass::OceanFluid(ocean) => (
ocean.get_target_width().clamp(64, max_dim),
ocean.get_target_height().clamp(64, max_dim),
),
DirectGpuScenePass::World3d(world) => (
world.get_target_width().clamp(64, max_dim),
world.get_target_height().clamp(64, max_dim),
),
};
if scene.scene_dims != (req_w, req_h) {
gl.bind_texture(
WebGl2RenderingContext::TEXTURE_2D,
Some(&scene.scene_color_tex),
);
let _: Result<(), JsValue> = gl
.tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_array_buffer_view(
WebGl2RenderingContext::TEXTURE_2D,
0,
WebGl2RenderingContext::RGBA8 as i32,
req_w as i32,
req_h as i32,
0,
WebGl2RenderingContext::RGBA,
WebGl2RenderingContext::UNSIGNED_BYTE,
None,
);
gl.bind_renderbuffer(
WebGl2RenderingContext::RENDERBUFFER,
Some(&scene.scene_depth_rbo),
);
gl.renderbuffer_storage(
WebGl2RenderingContext::RENDERBUFFER,
WebGl2RenderingContext::DEPTH_COMPONENT24,
req_w as i32,
req_h as i32,
);
scene.scene_dims = (req_w, req_h);
}
gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, Some(&scene.scene_fbo));
let [u0, v0_top, u1, v1_bot]: [f32; 4] = uv_bounds;
let has_full_uv: bool = u0 <= 0.0005 && v0_top <= 0.0005 && u1 >= 0.9995 && v1_bot >= 0.9995;
let use_scissor: bool = !has_full_uv;
if use_scissor {
let fbo_w_f: f32 = req_w as f32;
let fbo_h_f: f32 = req_h as f32;
let fbo_w_i: i32 = req_w as i32;
let fbo_h_i: i32 = req_h as i32;
let sc_x0: i32 =
((u0 * fbo_w_f).floor() as i32 - WEB_GL2_SCENE_SCISSOR_PAD_PX).clamp(0, fbo_w_i);
let sc_x1: i32 =
((u1 * fbo_w_f).ceil() as i32 + WEB_GL2_SCENE_SCISSOR_PAD_PX).clamp(0, fbo_w_i);
let sc_y0: i32 = (((1.0 - v1_bot) * fbo_h_f).floor() as i32 - WEB_GL2_SCENE_SCISSOR_PAD_PX)
.clamp(0, fbo_h_i);
let sc_y1: i32 = (((1.0 - v0_top) * fbo_h_f).ceil() as i32 + WEB_GL2_SCENE_SCISSOR_PAD_PX)
.clamp(0, fbo_h_i);
let sc_w: i32 = sc_x1 - sc_x0;
let sc_h: i32 = sc_y1 - sc_y0;
if sc_w <= 0 || sc_h <= 0 {
gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, None);
return;
}
gl.enable(WebGl2RenderingContext::SCISSOR_TEST);
gl.scissor(sc_x0, sc_y0, sc_w, sc_h);
} else {
gl.disable(WebGl2RenderingContext::SCISSOR_TEST);
}
gl.viewport(0, 0, req_w as i32, req_h as i32);
match pass {
DirectGpuScenePass::OceanFluid(ocean) => {
let wake_w: u32 = ocean.get_wake_width().max(1);
let wake_h: u32 = ocean.get_wake_height().max(1);
let wake_bytes: &[u8] = ocean.get_wake_rgba8().as_slice();
let req_wake: usize = (wake_w as usize)
.saturating_mul(wake_h as usize)
.saturating_mul(4);
if wake_bytes.len() >= req_wake
&& (scene.wake_dims != (wake_w, wake_h) || ocean.get_has_active_wake())
{
gl.active_texture(WebGl2RenderingContext::TEXTURE0);
gl.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(&scene.wake_tex));
web_configure_gl2_unpack_state(gl);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, 0);
let view: Uint8Array = unsafe { Uint8Array::view(wake_bytes) };
if scene.wake_dims != (wake_w, wake_h) {
let _: Result<(), JsValue> = gl
.tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_array_buffer_view(
WebGl2RenderingContext::TEXTURE_2D,
0,
WebGl2RenderingContext::RGBA8 as i32,
wake_w as i32,
wake_h as i32,
0,
WebGl2RenderingContext::RGBA,
WebGl2RenderingContext::UNSIGNED_BYTE,
Some(view.as_ref()),
);
scene.wake_dims = (wake_w, wake_h);
} else {
let _: Result<(), JsValue> = gl
.tex_sub_image_2d_with_i32_and_i32_and_u32_and_type_and_opt_array_buffer_view(
WebGl2RenderingContext::TEXTURE_2D,
0,
0,
0,
wake_w as i32,
wake_h as i32,
WebGl2RenderingContext::RGBA,
WebGl2RenderingContext::UNSIGNED_BYTE,
Some(view.as_ref()),
);
}
}
gl.disable(WebGl2RenderingContext::DEPTH_TEST);
gl.disable(WebGl2RenderingContext::BLEND);
gl.use_program(Some(&scene.ocean_program));
gl.active_texture(WebGl2RenderingContext::TEXTURE0);
gl.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(&scene.wake_tex));
let boat_uv: [f32; 2] = ocean.get_boat_uv();
let sun: [f32; 3] = ocean.get_sun_dir();
if let Some(loc) = scene.ocean_time_loc.as_ref() {
gl.uniform4f(
Some(loc),
ocean.get_sim_time(),
ocean.get_agitation(),
ocean.get_horizon_v(),
ocean.get_aspect(),
);
}
if let Some(loc) = scene.ocean_roll_loc.as_ref() {
gl.uniform4f(
Some(loc),
ocean.get_roll_cos(),
ocean.get_roll_sin(),
boat_uv[0],
boat_uv[1],
);
}
if let Some(loc) = scene.ocean_sun_loc.as_ref() {
gl.uniform4f(
Some(loc),
sun[0],
sun[1],
sun[2],
if ocean.get_has_active_wake() {
1.0
} else {
0.0
},
);
}
gl.bind_vertex_array(None);
gl.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, 3);
let boat_verts: &[GpuOceanBoatVertex] = ocean.get_boat_vertices().as_slice();
if !boat_verts.is_empty() {
let byte_len: usize = size_of_val(boat_verts);
let raw: &[u8] =
unsafe { from_raw_parts(boat_verts.as_ptr().cast::<u8>(), byte_len) };
let view: Uint8Array = unsafe { Uint8Array::view(raw) };
gl.enable(WebGl2RenderingContext::BLEND);
gl.blend_func_separate(
WebGl2RenderingContext::SRC_ALPHA,
WebGl2RenderingContext::ONE_MINUS_SRC_ALPHA,
WebGl2RenderingContext::ONE,
WebGl2RenderingContext::ONE_MINUS_SRC_ALPHA,
);
gl.use_program(Some(&scene.boat_program));
gl.bind_vertex_array(Some(&scene.boat_vao));
gl.bind_buffer(WebGl2RenderingContext::ARRAY_BUFFER, Some(&scene.boat_vbo));
if byte_len > scene.boat_vbo_cap {
let cap: usize = byte_len.max(1024).next_power_of_two();
gl.buffer_data_with_i32(
WebGl2RenderingContext::ARRAY_BUFFER,
cap as i32,
WebGl2RenderingContext::STREAM_DRAW,
);
scene.boat_vbo_cap = cap;
}
gl.buffer_sub_data_with_i32_and_array_buffer_view(
WebGl2RenderingContext::ARRAY_BUFFER,
0,
view.as_ref(),
);
gl.draw_arrays(
WebGl2RenderingContext::TRIANGLES,
0,
boat_verts.len() as i32,
);
gl.bind_vertex_array(None);
}
}
DirectGpuScenePass::World3d(world) => {
let cam: [f32; 4] = world.get_camera_pos();
let sun_fog: [f32; 4] = world.get_sun_dir_fog();
let sun_col: [f32; 4] = world.get_sun_color_ambient();
let sky_hor: [f32; 4] = world.get_sky_horizon_tod();
let sky_zen: [f32; 4] = world.get_sky_zenith_aspect();
gl.disable(WebGl2RenderingContext::BLEND);
gl.depth_mask(true);
gl.clear_depth(1.0);
gl.clear_color(0.04, 0.05, 0.09, 1.0);
gl.clear(
WebGl2RenderingContext::COLOR_BUFFER_BIT | WebGl2RenderingContext::DEPTH_BUFFER_BIT,
);
gl.disable(WebGl2RenderingContext::DEPTH_TEST);
gl.depth_mask(false);
gl.use_program(Some(&scene.sky3d_program));
if let Some(loc) = scene.sky3d_cam_loc.as_ref() {
gl.uniform4f(Some(loc), cam[0], cam[1], cam[2], cam[3]);
}
if let Some(loc) = scene.sky3d_sun_loc.as_ref() {
gl.uniform4f(Some(loc), sun_col[0], sun_col[1], sun_col[2], sun_col[3]);
}
if let Some(loc) = scene.sky3d_hor_loc.as_ref() {
gl.uniform4f(Some(loc), sky_hor[0], sky_hor[1], sky_hor[2], sky_hor[3]);
}
if let Some(loc) = scene.sky3d_zen_loc.as_ref() {
gl.uniform4f(Some(loc), sky_zen[0], sky_zen[1], sky_zen[2], sky_zen[3]);
}
gl.bind_vertex_array(None);
gl.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, 3);
let verts: &[GpuWorld3dVertex] = world.get_mesh_buffer().get_vertices().as_slice();
let insts: &[GpuWorld3dInstance] = world.get_instances().as_slice();
if !verts.is_empty() && !insts.is_empty() {
let mesh_rev: u64 = world.get_mesh_buffer().get_revision();
gl.bind_vertex_array(Some(&scene.mesh3d_vao));
if scene.mesh3d_vert_rev != mesh_rev || scene.mesh3d_vert_cap == 0 {
let vbytes: usize = size_of_val(verts);
let raw_v: &[u8] =
unsafe { from_raw_parts(verts.as_ptr().cast::<u8>(), vbytes) };
let vview: Uint8Array = unsafe { Uint8Array::view(raw_v) };
gl.bind_buffer(
WebGl2RenderingContext::ARRAY_BUFFER,
Some(&scene.mesh3d_vert_vbo),
);
if vbytes > scene.mesh3d_vert_cap {
let cap: usize = vbytes.max(4096).next_power_of_two();
gl.buffer_data_with_i32(
WebGl2RenderingContext::ARRAY_BUFFER,
cap as i32,
WebGl2RenderingContext::STATIC_DRAW,
);
scene.mesh3d_vert_cap = cap;
}
gl.buffer_sub_data_with_i32_and_array_buffer_view(
WebGl2RenderingContext::ARRAY_BUFFER,
0,
vview.as_ref(),
);
scene.mesh3d_vert_rev = mesh_rev;
}
let ibytes: usize = size_of_val(insts);
let raw_i: &[u8] = unsafe { from_raw_parts(insts.as_ptr().cast::<u8>(), ibytes) };
let iview: Uint8Array = unsafe { Uint8Array::view(raw_i) };
gl.bind_buffer(
WebGl2RenderingContext::ARRAY_BUFFER,
Some(&scene.mesh3d_inst_vbo),
);
if ibytes > scene.mesh3d_inst_cap {
let cap: usize = ibytes.max(4096).next_power_of_two();
gl.buffer_data_with_i32(
WebGl2RenderingContext::ARRAY_BUFFER,
cap as i32,
WebGl2RenderingContext::STREAM_DRAW,
);
scene.mesh3d_inst_cap = cap;
}
gl.buffer_sub_data_with_i32_and_array_buffer_view(
WebGl2RenderingContext::ARRAY_BUFFER,
0,
iview.as_ref(),
);
gl.enable(WebGl2RenderingContext::DEPTH_TEST);
gl.depth_func(WebGl2RenderingContext::LESS);
gl.depth_mask(true);
gl.use_program(Some(&scene.mesh3d_program));
let vp: [f32; 16] = world.get_view_proj();
gl.uniform_matrix4fv_with_f32_array(scene.mesh3d_vp_loc.as_ref(), false, &vp);
if let Some(loc) = scene.mesh3d_cam_loc.as_ref() {
gl.uniform4f(Some(loc), cam[0], cam[1], cam[2], cam[3]);
}
if let Some(loc) = scene.mesh3d_sun_fog_loc.as_ref() {
gl.uniform4f(Some(loc), sun_fog[0], sun_fog[1], sun_fog[2], sun_fog[3]);
}
if let Some(loc) = scene.mesh3d_sun_col_loc.as_ref() {
gl.uniform4f(Some(loc), sun_col[0], sun_col[1], sun_col[2], sun_col[3]);
}
if let Some(loc) = scene.mesh3d_hor_loc.as_ref() {
gl.uniform4f(Some(loc), sky_hor[0], sky_hor[1], sky_hor[2], sky_hor[3]);
}
if let Some(loc) = scene.mesh3d_zen_loc.as_ref() {
gl.uniform4f(Some(loc), sky_zen[0], sky_zen[1], sky_zen[2], sky_zen[3]);
}
for batch in world.get_draw_batches().iter() {
if batch.get_vertex_count() == 0 || batch.get_instance_count() == 0 {
continue;
}
let base_byte_off: i32 = (batch.get_instance_start() as i32).saturating_mul(96);
if scene.mesh3d_inst_base_off != base_byte_off {
for slot in 0u32..6u32 {
gl.vertex_attrib_pointer_with_i32(
3 + slot,
4,
WebGl2RenderingContext::FLOAT,
false,
96,
base_byte_off + (slot as i32) * 16,
);
}
scene.mesh3d_inst_base_off = base_byte_off;
}
gl.draw_arrays_instanced(
WebGl2RenderingContext::TRIANGLES,
batch.get_vertex_start() as i32,
batch.get_vertex_count() as i32,
batch.get_instance_count() as i32,
);
}
gl.bind_vertex_array(None);
gl.disable(WebGl2RenderingContext::DEPTH_TEST);
}
}
}
if use_scissor {
gl.disable(WebGl2RenderingContext::SCISSOR_TEST);
}
gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, None);
}
fn web_create_gl2_tile_canvas(
parent_canvas: Option<&HtmlCanvasElement>,
tile_w: u32,
tile_h: u32,
) -> Option<WebGl2TileCanvas> {
let win: Window = window()?;
let doc: Document = win.document()?;
let el: Element = doc.create_element(WEB_CANVAS_TAG).ok()?;
let canvas: HtmlCanvasElement = el.dyn_into::<HtmlCanvasElement>().ok()?;
canvas.set_width(tile_w.max(1));
canvas.set_height(tile_h.max(1));
drop(canvas.set_attribute(WEB_ATTR_CANVAS_ROLE, WEB_CANVAS_ROLE_TILE));
if let Some(parent) =
parent_canvas.and_then(|main_el: &HtmlCanvasElement| main_el.parent_element())
{
drop(parent.append_child(&canvas));
} else if let Some(body) = doc.body() {
drop(body.append_child(&canvas));
}
let gl_opts: Object = web_gl2_context_options();
let raw_gl: Object = canvas
.get_context_with_context_options(WEB_CONTEXT_WEBGL2, gl_opts.as_ref())
.ok()
.flatten()?;
let gl2: WebGl2RenderingContext = raw_gl.dyn_into::<WebGl2RenderingContext>().ok()?;
let instanced: WebGl2InstancedPipeline = web_init_gl2_instanced_pipeline(&gl2)?;
Some(WebGl2TileCanvas {
canvas,
gl2,
instanced,
last_style_geom: (u32::MAX, u32::MAX, 0, 0, 0, 0),
})
}
fn web_sync_gl2_image_rgba8_atlas(
gl: &WebGl2RenderingContext,
pipe: &mut WebGl2InstancedPipeline,
atlas: &DirectGpuAtlasUpload,
dirty_rects: &[PixelDirtyRect],
) {
let atlas_w: u32 = atlas.get_width();
let atlas_h: u32 = atlas.get_height();
let pixels: &[u8] = atlas.get_pixels().as_slice();
let required: usize = (atlas_w as usize)
.saturating_mul(atlas_h as usize)
.saturating_mul(4);
if atlas_w == 0 || atlas_h == 0 || pixels.len() < required {
return;
}
let Some(tex) = pipe.image_atlas_tex.as_ref() else {
return;
};
let target_val: JsValue = JsValue::from_f64(WebGl2RenderingContext::TEXTURE_2D as f64);
gl.active_texture(WebGl2RenderingContext::TEXTURE2);
if let Some(bind_fn) = pipe.bind_texture_fn.as_ref() {
drop(bind_fn.call2(gl.as_ref(), &target_val, tex));
}
web_configure_gl2_unpack_state(gl);
let dims_changed: bool = pipe.image_atlas_w != atlas_w || pipe.image_atlas_h != atlas_h;
if dims_changed || dirty_rects.is_empty() {
gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, 0);
let view: Uint8Array = unsafe { Uint8Array::view(pixels) };
let _: Result<(), JsValue> = gl
.tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_array_buffer_view(
WebGl2RenderingContext::TEXTURE_2D,
0,
WebGl2RenderingContext::RGBA8 as i32,
atlas_w as i32,
atlas_h as i32,
0,
WebGl2RenderingContext::RGBA,
WebGl2RenderingContext::UNSIGNED_BYTE,
Some(view.as_ref()),
);
pipe.image_atlas_w = atlas_w;
pipe.image_atlas_h = atlas_h;
return;
}
gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, atlas_w as i32);
let view: Uint8Array = unsafe { Uint8Array::view(pixels) };
for dirty in dirty_rects.iter() {
let rx: u32 = dirty.get_x().min(atlas_w);
let ry: u32 = dirty.get_y().min(atlas_h);
let rw: u32 = dirty.get_width().min(atlas_w.saturating_sub(rx));
let rh: u32 = dirty.get_height().min(atlas_h.saturating_sub(ry));
if rw == 0 || rh == 0 {
continue;
}
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, rx as i32);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, ry as i32);
let _: Result<(), JsValue> = gl
.tex_sub_image_2d_with_i32_and_i32_and_u32_and_type_and_opt_array_buffer_view(
WebGl2RenderingContext::TEXTURE_2D,
0,
rx as i32,
ry as i32,
rw as i32,
rh as i32,
WebGl2RenderingContext::RGBA,
WebGl2RenderingContext::UNSIGNED_BYTE,
Some(view.as_ref()),
);
}
gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, 0);
}
fn web_draw_gl2_instanced_on_surface(
gl: &WebGl2RenderingContext,
pipe: &mut WebGl2InstancedPipeline,
submission: &GpuFrameSubmission,
draw_dims: (i32, i32),
tile_origin: (f32, f32),
glyph_cache: (Option<&DirectGpuAtlasUpload>, u64, bool),
image_cache: (Option<&DirectGpuAtlasUpload>, u64, bool),
) -> (usize, u32) {
let (draw_w, draw_h): (i32, i32) = draw_dims;
let (tile_ox, tile_oy): (f32, f32) = tile_origin;
let (glyph_snap, glyph_rev, glyph_incoming): (Option<&DirectGpuAtlasUpload>, u64, bool) =
glyph_cache;
let (image_snap, image_rev, image_incoming): (Option<&DirectGpuAtlasUpload>, u64, bool) =
image_cache;
if glyph_rev > 0
&& pipe.synced_glyph_r8_rev != glyph_rev
&& let Some(glyph_atlas) = glyph_snap
{
let incremental_ok: bool = glyph_incoming
&& pipe.synced_glyph_r8_rev > 0
&& pipe.synced_glyph_r8_rev.wrapping_add(1) == glyph_rev;
let dirty_slice: &[PixelDirtyRect] = if incremental_ok {
submission.get_glyph_dirty_rects().as_slice()
} else {
&[]
};
web_sync_gl2_glyph_r8_atlas(gl, pipe, glyph_atlas, dirty_slice);
pipe.synced_glyph_r8_rev = glyph_rev;
}
if image_rev > 0
&& pipe.synced_image_rgba8_rev != image_rev
&& let Some(image_atlas) = image_snap
{
let incremental_ok: bool = image_incoming
&& pipe.synced_image_rgba8_rev > 0
&& pipe.synced_image_rgba8_rev.wrapping_add(1) == image_rev;
let dirty_slice: &[PixelDirtyRect] = if incremental_ok {
submission.get_image_dirty_rects().as_slice()
} else {
&[]
};
web_sync_gl2_image_rgba8_atlas(gl, pipe, image_atlas, dirty_slice);
pipe.synced_image_rgba8_rev = image_rev;
}
let mut active_scene_tex: Option<WebGlTexture> = None;
if let Some(scene_pass) = submission.gpu_scene_pass_ref()
&& let Some(uv_bounds) = web_scene_pass_tile_uv_bounds(submission, tile_origin, draw_dims)
{
if pipe.scene_gl.is_none() {
pipe.scene_gl = web_init_gl2_scene_pipeline(gl);
}
if let Some(scene_gl) = pipe.scene_gl.as_mut() {
web_execute_gl2_scene_pass(gl, scene_gl, pipe.max_tex_dim, scene_pass, uv_bounds);
active_scene_tex = Some(scene_gl.scene_color_tex.clone());
}
}
let has_blur_batches: bool = pipe.blur_program.is_some()
&& web_tile_has_backdrop_blur(submission, tile_origin, draw_dims);
let use_blur_fbo: bool =
has_blur_batches && web_ensure_gl2_blur_targets(gl, pipe, draw_w as u32, draw_h as u32);
if use_blur_fbo {
gl.bind_framebuffer(
WebGl2RenderingContext::FRAMEBUFFER,
pipe.blur_scene_fbo.as_ref(),
);
} else {
gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, None);
}
let target_val: JsValue = JsValue::from_f64(WebGl2RenderingContext::TEXTURE_2D as f64);
if let Some(bind_fn) = pipe.bind_texture_fn.as_ref() {
if let Some(tex) = pipe.glyph_r8_tex.as_ref() {
gl.active_texture(WebGl2RenderingContext::TEXTURE0);
drop(bind_fn.call2(gl.as_ref(), &target_val, tex));
}
if let Some(tex) = pipe.glyph_rgba8_tex.as_ref() {
gl.active_texture(WebGl2RenderingContext::TEXTURE1);
drop(bind_fn.call2(gl.as_ref(), &target_val, tex));
}
if let Some(tex) = pipe.image_atlas_tex.as_ref() {
gl.active_texture(WebGl2RenderingContext::TEXTURE2);
drop(bind_fn.call2(gl.as_ref(), &target_val, tex));
}
if let Some(scene_tex) = active_scene_tex.as_ref() {
gl.active_texture(WebGl2RenderingContext::TEXTURE3);
gl.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(scene_tex));
} else if let Some(tex) = pipe.external_tex.as_ref() {
gl.active_texture(WebGl2RenderingContext::TEXTURE3);
drop(bind_fn.call2(gl.as_ref(), &target_val, tex));
}
}
let clear_color: Color = submission.get_clear_color();
gl.viewport(0, 0, draw_w, draw_h);
gl.disable(WebGl2RenderingContext::DEPTH_TEST);
gl.enable(WebGl2RenderingContext::BLEND);
gl.blend_func_separate(
WebGl2RenderingContext::SRC_ALPHA,
WebGl2RenderingContext::ONE_MINUS_SRC_ALPHA,
WebGl2RenderingContext::ONE,
WebGl2RenderingContext::ONE_MINUS_SRC_ALPHA,
);
gl.clear_color(
f32::from(clear_color.get_red()) / 255.0,
f32::from(clear_color.get_green()) / 255.0,
f32::from(clear_color.get_blue()) / 255.0,
f32::from(clear_color.get_alpha()) / 255.0,
);
gl.clear(WebGl2RenderingContext::COLOR_BUFFER_BIT);
gl.use_program(Some(&pipe.program));
if let Some(loc) = pipe.viewport_loc.as_ref() {
gl.uniform2f(Some(loc), draw_w as f32, draw_h as f32);
}
if let Some(loc) = pipe.scroll_loc.as_ref() {
gl.uniform2f(Some(loc), 0.0, 0.0);
}
if let Some(loc) = pipe.tile_origin_loc.as_ref() {
gl.uniform2f(Some(loc), tile_ox, tile_oy);
}
gl.bind_vertex_array(Some(&pipe.vao));
gl.bind_buffer(
WebGl2RenderingContext::ARRAY_BUFFER,
Some(&pipe.instance_vbo),
);
let mut draw_calls: usize = 0;
let mut total_primitives: u32 = 0;
let half_w: i32 = (draw_w / 2).max(1);
let half_h: i32 = (draw_h / 2).max(1);
for batch in submission.get_batches().iter() {
let prims: &[GpuPrimitiveInstance] = batch.get_primitives().as_slice();
if prims.is_empty() {
continue;
}
let is_blur_batch: bool = use_blur_fbo
&& prims.iter().any(|prim_item: &GpuPrimitiveInstance| {
prim_item.prim_kind() == PrimKind::BackdropBlur
});
if is_blur_batch
&& let (
Some(bprog),
Some(sfbo),
Some(stex),
Some(hfbo),
Some(htex),
Some(ffbo),
Some(ftex),
) = (
pipe.blur_program.as_ref(),
pipe.blur_scene_fbo.as_ref(),
pipe.blur_scene_tex.as_ref(),
pipe.blur_half_fbo.as_ref(),
pipe.blur_half_tex.as_ref(),
pipe.blur_full_fbo.as_ref(),
pipe.blur_full_tex.as_ref(),
)
{
gl.disable(WebGl2RenderingContext::BLEND);
gl.bind_vertex_array(None);
gl.use_program(Some(bprog));
gl.active_texture(WebGl2RenderingContext::TEXTURE0);
gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, Some(hfbo));
gl.viewport(0, 0, half_w, half_h);
gl.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(stex));
if let Some(loc) = pipe.blur_texel_loc.as_ref() {
gl.uniform2f(
Some(loc),
1.0 / (draw_w.max(1) as f32),
1.0 / (draw_h.max(1) as f32),
);
}
if let Some(loc) = pipe.blur_offset_loc.as_ref() {
gl.uniform1f(Some(loc), 2.5);
}
if let Some(loc) = pipe.blur_mode_loc.as_ref() {
gl.uniform1i(Some(loc), 0);
}
gl.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, 3);
gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, Some(ffbo));
gl.viewport(0, 0, draw_w, draw_h);
gl.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(htex));
if let Some(loc) = pipe.blur_texel_loc.as_ref() {
gl.uniform2f(Some(loc), 1.0 / (half_w as f32), 1.0 / (half_h as f32));
}
if let Some(loc) = pipe.blur_mode_loc.as_ref() {
gl.uniform1i(Some(loc), 1);
}
gl.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, 3);
draw_calls = draw_calls.saturating_add(2);
gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, Some(sfbo));
gl.viewport(0, 0, draw_w, draw_h);
gl.enable(WebGl2RenderingContext::BLEND);
if let (Some(bind_fn), Some(r8_tex)) =
(pipe.bind_texture_fn.as_ref(), pipe.glyph_r8_tex.as_ref())
{
gl.active_texture(WebGl2RenderingContext::TEXTURE0);
drop(bind_fn.call2(gl.as_ref(), &target_val, r8_tex));
}
gl.active_texture(WebGl2RenderingContext::TEXTURE3);
gl.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(ftex));
gl.use_program(Some(&pipe.program));
gl.bind_vertex_array(Some(&pipe.vao));
gl.bind_buffer(
WebGl2RenderingContext::ARRAY_BUFFER,
Some(&pipe.instance_vbo),
);
}
let byte_len: usize = prims.len().saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
let raw_bytes: &[u8] = unsafe { from_raw_parts(prims.as_ptr().cast::<u8>(), byte_len) };
let view: Uint8Array = unsafe { Uint8Array::view(raw_bytes) };
if byte_len > pipe.instance_vbo_cap_bytes {
let next_cap: usize = byte_len.next_power_of_two();
gl.buffer_data_with_i32(
WebGl2RenderingContext::ARRAY_BUFFER,
next_cap as i32,
WebGl2RenderingContext::STREAM_DRAW,
);
pipe.instance_vbo_cap_bytes = next_cap;
}
gl.buffer_sub_data_with_i32_and_array_buffer_view(
WebGl2RenderingContext::ARRAY_BUFFER,
0,
view.as_ref(),
);
gl.draw_arrays_instanced(WebGl2RenderingContext::TRIANGLES, 0, 6, prims.len() as i32);
draw_calls = draw_calls.saturating_add(1);
total_primitives = total_primitives.saturating_add(prims.len() as u32);
if is_blur_batch {
gl.active_texture(WebGl2RenderingContext::TEXTURE3);
if let Some(scene_tex) = active_scene_tex.as_ref() {
gl.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(scene_tex));
} else if let (Some(bind_fn), Some(ext_tex)) =
(pipe.bind_texture_fn.as_ref(), pipe.external_tex.as_ref())
{
drop(bind_fn.call2(gl.as_ref(), &target_val, ext_tex));
}
}
}
gl.bind_vertex_array(None);
if use_blur_fbo && let Some(sfbo) = pipe.blur_scene_fbo.as_ref() {
gl.bind_framebuffer(WebGl2RenderingContext::READ_FRAMEBUFFER, Some(sfbo));
gl.bind_framebuffer(WebGl2RenderingContext::DRAW_FRAMEBUFFER, None);
gl.blit_framebuffer(
0,
0,
draw_w,
draw_h,
0,
0,
draw_w,
draw_h,
WebGl2RenderingContext::COLOR_BUFFER_BIT,
WebGl2RenderingContext::NEAREST,
);
gl.bind_framebuffer(WebGl2RenderingContext::FRAMEBUFFER, None);
}
(draw_calls, total_primitives)
}
pub(crate) fn web_draw_gl2_instanced_submission(
rec: &mut WebWindowRecord,
submission: &GpuFrameSubmission,
) -> Result<Option<(usize, u32)>, PlatformError> {
let WebWindowRecord {
canvas,
gl2,
gl2_instanced,
tiled_canvases,
active_tile_grid,
cached_glyph_r8_atlas,
cached_glyph_r8_rev,
cached_image_rgba8_atlas,
cached_image_rgba8_rev,
..
} = rec;
let (Some(gl), Some(pipe)) = (gl2.as_ref(), gl2_instanced.as_mut()) else {
return Ok(None);
};
let glyph_incoming: bool = submission.glyph_atlas_r8_ref().is_some();
if let Some(atlas) = submission.glyph_atlas_r8_ref() {
*cached_glyph_r8_atlas = Some(atlas.clone());
*cached_glyph_r8_rev = cached_glyph_r8_rev.wrapping_add(1).max(1);
}
let image_incoming: bool = submission.image_atlas_rgba8_ref().is_some();
if let Some(atlas) = submission.image_atlas_rgba8_ref() {
*cached_image_rgba8_atlas = Some(atlas.clone());
*cached_image_rgba8_rev = cached_image_rgba8_rev.wrapping_add(1).max(1);
}
let glyph_cache: (Option<&DirectGpuAtlasUpload>, u64, bool) = (
cached_glyph_r8_atlas.as_ref(),
*cached_glyph_r8_rev,
glyph_incoming,
);
let image_cache: (Option<&DirectGpuAtlasUpload>, u64, bool) = (
cached_image_rgba8_atlas.as_ref(),
*cached_image_rgba8_rev,
image_incoming,
);
let req_w: u32 = submission.get_width().max(1);
let req_h: u32 = submission.get_height().max(1);
let max_single_dim: u32 = pipe.max_tex_dim.clamp(256, WEB_GL2_MAX_SINGLE_SURFACE_DIM);
let max_single_area: u64 = u64::from(max_single_dim)
.saturating_mul(u64::from(max_single_dim))
.max(65_536);
let mut tile_limit: Option<(u32, u64)> = if req_w > max_single_dim || req_h > max_single_dim {
Some((max_single_dim, max_single_area))
} else {
None
};
if tile_limit.is_none() {
if let Some(el) = canvas.as_ref() {
if el.width() != req_w {
el.set_width(req_w);
}
if el.height() != req_h {
el.set_height(req_h);
}
}
let draw_w: i32 = gl.drawing_buffer_width();
let draw_h: i32 = gl.drawing_buffer_height();
if draw_w == (req_w as i32) && draw_h == (req_h as i32) {
if !tiled_canvases.is_empty() {
for tile_rec in tiled_canvases.drain(..) {
tile_rec.canvas.remove();
}
}
web_sync_canvas_tiled_attr(canvas.as_ref(), active_tile_grid, 1, 1);
let (draws, prims): (usize, u32) = web_draw_gl2_instanced_on_surface(
gl,
pipe,
submission,
(draw_w, draw_h),
(0.0, 0.0),
glyph_cache,
image_cache,
);
return Ok(Some((draws, prims)));
}
let actual_w: u32 = (draw_w.max(256) as u32).min(max_single_dim);
let actual_h: u32 = (draw_h.max(256) as u32).min(max_single_dim);
let clamped_w: bool = draw_w < (req_w as i32);
let clamped_h: bool = draw_h < (req_h as i32);
let safe_axis: u32 = if clamped_w && clamped_h {
actual_w.max(actual_h).min(max_single_dim).max(256)
} else if clamped_w {
actual_w.max(256)
} else if clamped_h {
actual_h.max(256)
} else {
actual_w.min(actual_h).max(256)
};
let safe_area: u64 = u64::from(actual_w)
.saturating_mul(u64::from(actual_h))
.max(65_536);
tile_limit = Some((safe_axis, safe_area));
}
let (max_tile_axis, max_tile_area): (u32, u64) =
tile_limit.unwrap_or((max_single_dim, max_single_area));
let plan: TiledSurfacePlan =
ViewportMetrics::from_exact(f64::from(req_w), f64::from(req_h), req_w, req_h, 1.0)
.plan_tiled_surface(SurfaceTileLimit::new(max_tile_axis, max_tile_area));
let tiles: &[SurfaceTileRect] = plan.get_tiles().as_slice();
if tiles.is_empty() {
return Ok(None);
}
while tiled_canvases.len() > tiles.len() {
if let Some(extra) = tiled_canvases.pop() {
extra.canvas.remove();
}
}
for tile in tiles.iter().skip(tiled_canvases.len()) {
let Some(created) = web_create_gl2_tile_canvas(
canvas.as_ref(),
tile.get_physical_width(),
tile.get_physical_height(),
) else {
for existing in tiled_canvases.drain(..) {
existing.canvas.remove();
}
web_sync_canvas_tiled_attr(canvas.as_ref(), active_tile_grid, 1, 1);
return Ok(None);
};
tiled_canvases.push(created);
}
web_sync_canvas_tiled_attr(
canvas.as_ref(),
active_tile_grid,
plan.get_columns(),
plan.get_rows(),
);
let inv_req_w: f64 = 100.0 / f64::from(req_w);
let inv_req_h: f64 = 100.0 / f64::from(req_h);
let mut total_draws: usize = 0;
let mut total_prims: u32 = 0;
for (tile, tile_rec) in tiles.iter().zip(tiled_canvases.iter_mut()) {
let tw: u32 = tile.get_physical_width().max(1);
let th: u32 = tile.get_physical_height().max(1);
if tile_rec.canvas.width() != tw {
tile_rec.canvas.set_width(tw);
}
if tile_rec.canvas.height() != th {
tile_rec.canvas.set_height(th);
}
let tile_geom: (u32, u32, u32, u32, u32, u32) = (
tile.get_physical_x(),
tile.get_physical_y(),
tw,
th,
req_w,
req_h,
);
if tile_rec.last_style_geom != tile_geom {
let left_pct: f64 = f64::from(tile.get_physical_x()) * inv_req_w;
let top_pct: f64 = f64::from(tile.get_physical_y()) * inv_req_h;
let width_pct: f64 = f64::from(tw) * inv_req_w;
let height_pct: f64 = f64::from(th) * inv_req_h;
let tile_style: String = format!(
"{WEB_TILE_CANVAS_STYLE_PREFIX}left:{left_pct:.4}%;top:{top_pct:.4}%;width:{width_pct:.4}%;height:{height_pct:.4}%;"
);
drop(tile_rec.canvas.set_attribute(WEB_ATTR_STYLE, &tile_style));
tile_rec.last_style_geom = tile_geom;
}
let draw_w: i32 = tile_rec.gl2.drawing_buffer_width().max(1);
let draw_h: i32 = tile_rec.gl2.drawing_buffer_height().max(1);
let (draws, prims): (usize, u32) = web_draw_gl2_instanced_on_surface(
&tile_rec.gl2,
&mut tile_rec.instanced,
submission,
(draw_w, draw_h),
(tile.get_physical_x() as f32, tile.get_physical_y() as f32),
glyph_cache,
image_cache,
);
total_draws = total_draws.saturating_add(draws);
total_prims = total_prims.saturating_add(prims);
}
Ok(Some((total_draws, total_prims)))
}
fn web_pack_rgba_subrect_into(
framebuffer: &Framebuffer,
x0: u32,
y0: u32,
width: u32,
height: u32,
out: &mut Vec<u8>,
) {
let fb_w: usize = framebuffer.get_width() as usize;
let src: &[u8] = framebuffer.get_pixels().as_slice();
let row_bytes: usize = (width as usize) * 4;
let needed: usize = row_bytes * (height as usize);
out.clear();
if out.capacity() < needed {
out.reserve(needed - out.capacity());
}
for row in y0..(y0 + height) {
let start: usize = ((row as usize) * fb_w + (x0 as usize)) * 4;
let end: usize = start + row_bytes;
if end <= src.len() {
out.extend_from_slice(&src[start..end]);
}
}
}
pub(crate) fn web_present_gl2_region(
rec: &mut WebWindowRecord,
framebuffer: &Framebuffer,
damage: DamageRegion,
) -> Result<Option<u64>, PlatformError> {
let WebWindowRecord {
canvas,
gl2,
gl2_program,
gl2_texture,
gl2_view_loc,
gl2_bind_texture_fn,
gl2_max_tex_dim,
gl2_tex_width,
gl2_tex_height,
active_tile_grid,
..
} = rec;
let (Some(gl), Some(program), Some(texture)) =
(gl2.as_ref(), gl2_program.as_ref(), gl2_texture.as_ref())
else {
return Ok(None);
};
let fb_w: u32 = framebuffer.get_width();
let fb_h: u32 = framebuffer.get_height();
if fb_w == 0 || fb_h == 0 {
return Ok(Some(0));
}
let pixels: &[u8] = framebuffer.get_pixels().as_slice();
let required_bytes: usize = (fb_w as usize)
.saturating_mul(fb_h as usize)
.saturating_mul(4);
if pixels.len() < required_bytes {
return Err(PlatformError::SurfaceError(
ERR_WEB_PRESENT_FAILED.to_string(),
));
}
let max_tex_dim: u32 = (*gl2_max_tex_dim).max(1024);
if fb_w > max_tex_dim || fb_h > max_tex_dim {
return Ok(None);
}
let mut drawing_resized: bool =
gl.drawing_buffer_width() != (fb_w as i32) || gl.drawing_buffer_height() != (fb_h as i32);
if drawing_resized && let Some(el) = canvas.as_ref() {
if el.width() != fb_w {
el.set_width(fb_w);
}
if el.height() != fb_h {
el.set_height(fb_h);
}
drawing_resized = true;
}
if gl.drawing_buffer_width() != (fb_w as i32) || gl.drawing_buffer_height() != (fb_h as i32) {
return Ok(None);
}
web_sync_canvas_tiled_attr(canvas.as_ref(), active_tile_grid, 1, 1);
let tex_dims_changed: bool = *gl2_tex_width != fb_w || *gl2_tex_height != fb_h;
let resolved_rect: Option<Rect> = damage.resolve(fb_w, fb_h);
if resolved_rect.is_none() && !drawing_resized && !tex_dims_changed {
return Ok(Some(0));
}
let target_val: JsValue = JsValue::from_f64(WebGl2RenderingContext::TEXTURE_2D as f64);
gl.active_texture(WebGl2RenderingContext::TEXTURE0);
if let Some(bind_fn) = gl2_bind_texture_fn.as_ref() {
drop(bind_fn.call2(gl.as_ref(), &target_val, texture));
}
web_configure_gl2_unpack_state(gl);
let surface_dirty: bool = drawing_resized || tex_dims_changed;
let needs_full_upload: bool = damage.get_full_damage() || surface_dirty;
let mut upload_bytes: u64 = 0;
if needs_full_upload {
gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, 0);
let view: Uint8Array = unsafe { Uint8Array::view(pixels) };
if tex_dims_changed {
gl.tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_array_buffer_view(
WebGl2RenderingContext::TEXTURE_2D,
0,
WebGl2RenderingContext::RGBA8 as i32,
fb_w as i32,
fb_h as i32,
0,
WebGl2RenderingContext::RGBA,
WebGl2RenderingContext::UNSIGNED_BYTE,
Some(view.as_ref()),
)
.map_err(|_: JsValue| {
PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
})?;
*gl2_tex_width = fb_w;
*gl2_tex_height = fb_h;
} else {
gl.tex_sub_image_2d_with_i32_and_i32_and_u32_and_type_and_opt_array_buffer_view(
WebGl2RenderingContext::TEXTURE_2D,
0,
0,
0,
fb_w as i32,
fb_h as i32,
WebGl2RenderingContext::RGBA,
WebGl2RenderingContext::UNSIGNED_BYTE,
Some(view.as_ref()),
)
.map_err(|_: JsValue| {
PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
})?;
}
upload_bytes = required_bytes as u64;
} else if let Some(rect) = resolved_rect {
let x0: u32 = (rect.get_x().floor().max(0.0) as u32).min(fb_w);
let y0: u32 = (rect.get_y().floor().max(0.0) as u32).min(fb_h);
let x1: u32 = (rect.right().ceil().max(0.0) as u32).min(fb_w);
let y1: u32 = (rect.bottom().ceil().max(0.0) as u32).min(fb_h);
if x1 > x0 && y1 > y0 {
let rw: u32 = x1 - x0;
let rh: u32 = y1 - y0;
gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, fb_w as i32);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, x0 as i32);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, y0 as i32);
let view: Uint8Array = unsafe { Uint8Array::view(pixels) };
let upload_res: Result<(), JsValue> = gl
.tex_sub_image_2d_with_i32_and_i32_and_u32_and_type_and_opt_array_buffer_view(
WebGl2RenderingContext::TEXTURE_2D,
0,
x0 as i32,
y0 as i32,
rw as i32,
rh as i32,
WebGl2RenderingContext::RGBA,
WebGl2RenderingContext::UNSIGNED_BYTE,
Some(view.as_ref()),
);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, 0);
upload_res.map_err(|_: JsValue| {
PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
})?;
upload_bytes = u64::from(rw)
.saturating_mul(u64::from(rh))
.saturating_mul(4);
}
}
let draw_w: i32 = gl.drawing_buffer_width().max(1);
let draw_h: i32 = gl.drawing_buffer_height().max(1);
gl.viewport(0, 0, draw_w, draw_h);
gl.use_program(Some(program));
if let Some(loc) = gl2_view_loc.as_ref() {
gl.uniform2f(Some(loc), draw_w as f32, draw_h as f32);
}
gl.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, 3);
Ok(Some(upload_bytes))
}
pub(crate) fn web_present_image_data_region(
canvas: Option<&HtmlCanvasElement>,
ctx2d: &CanvasRenderingContext2d,
framebuffer: &Framebuffer,
damage: DamageRegion,
) -> Result<u64, PlatformError> {
let fb_w: u32 = framebuffer.get_width();
let fb_h: u32 = framebuffer.get_height();
let mut backing_resized: bool = false;
if let Some(el) = canvas {
if el.width() != fb_w {
el.set_width(fb_w);
backing_resized = true;
}
if el.height() != fb_h {
el.set_height(fb_h);
backing_resized = true;
}
}
let effective_damage: DamageRegion = if backing_resized {
DamageRegion::full()
} else {
damage
};
let Some(rect) = effective_damage.resolve(fb_w, fb_h) else {
return Ok(0);
};
if effective_damage.get_full_damage()
&& fb_w <= WEB_TILED_BLIT_CHUNK_DIM
&& fb_h <= WEB_TILED_BLIT_CHUNK_DIM
{
let pixels: &[u8] = framebuffer.get_pixels().as_slice();
let clamped: Clamped<&[u8]> = Clamped(pixels);
let img: ImageData = ImageData::new_with_u8_clamped_array_and_sh(clamped, fb_w, fb_h)
.map_err(|_: JsValue| {
PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
})?;
ctx2d.put_image_data(&img, 0.0, 0.0).map_err(|_: JsValue| {
PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
})?;
Ok(pixels.len() as u64)
} else {
let (x0, y0, x1, y1): (u32, u32, u32, u32) = if effective_damage.get_full_damage() {
(0, 0, fb_w, fb_h)
} else {
(
(rect.get_x().floor().max(0.0) as u32).min(fb_w),
(rect.get_y().floor().max(0.0) as u32).min(fb_h),
(rect.right().ceil().max(0.0) as u32).min(fb_w),
(rect.bottom().ceil().max(0.0) as u32).min(fb_h),
)
};
if x1 <= x0 || y1 <= y0 {
return Ok(0);
}
let mut total_copied: u64 = 0;
let mut tile_y: u32 = y0;
while tile_y < y1 {
let tile_h: u32 = (y1 - tile_y).min(WEB_TILED_BLIT_CHUNK_DIM);
let mut tile_x: u32 = x0;
while tile_x < x1 {
let tile_w: u32 = (x1 - tile_x).min(WEB_TILED_BLIT_CHUNK_DIM);
let (img, copied_bytes): (ImageData, u64) = WEB_SUBRECT_SCRATCH.with(
|cell: &RefCell<Vec<u8>>| -> Result<(ImageData, u64), PlatformError> {
let Ok(mut sub) = cell.try_borrow_mut() else {
return Err(PlatformError::SurfaceError(
ERR_WEB_PRESENT_FAILED.to_string(),
));
};
web_pack_rgba_subrect_into(
framebuffer,
tile_x,
tile_y,
tile_w,
tile_h,
&mut sub,
);
let copied_bytes: u64 = sub.len() as u64;
let clamped: Clamped<&[u8]> = Clamped(sub.as_slice());
let img_res: Result<ImageData, JsValue> =
ImageData::new_with_u8_clamped_array_and_sh(clamped, tile_w, tile_h);
drop(sub);
let img: ImageData = img_res.map_err(|_: JsValue| {
PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
})?;
Ok((img, copied_bytes))
},
)?;
ctx2d
.put_image_data(&img, tile_x as f64, tile_y as f64)
.map_err(|_: JsValue| {
PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
})?;
total_copied = total_copied.saturating_add(copied_bytes);
tile_x = tile_x.saturating_add(tile_w);
}
tile_y = tile_y.saturating_add(tile_h);
}
Ok(total_copied)
}
}
fn web_read_opt_f32(target: &JsValue, key: &str) -> Option<f32> {
let val: JsValue = Reflect::get(target, &JsValue::from_str(key)).ok()?;
let num: f64 = val.as_f64()?;
if num.is_finite() {
Some(num as f32)
} else {
None
}
}
fn web_read_vec3_prop(event_val: &JsValue, prop: &str) -> Option<[f32; 3]> {
let sub: JsValue = Reflect::get(event_val, &JsValue::from_str(prop)).ok()?;
if sub.is_null() || sub.is_undefined() {
return None;
}
let ox: Option<f32> = web_read_opt_f32(&sub, WEB_PROP_AXIS_X);
let oy: Option<f32> = web_read_opt_f32(&sub, WEB_PROP_AXIS_Y);
let oz: Option<f32> = web_read_opt_f32(&sub, WEB_PROP_AXIS_Z);
if ox.is_none() && oy.is_none() && oz.is_none() {
return None;
}
Some([ox.unwrap_or(0.0), oy.unwrap_or(0.0), oz.unwrap_or(0.0)])
}
fn web_read_rotation_rate_rad(event_val: &JsValue) -> [f32; 3] {
let Ok(sub) = Reflect::get(event_val, &JsValue::from_str(WEB_PROP_ROTATION_RATE)) else {
return [0.0, 0.0, 0.0];
};
if sub.is_null() || sub.is_undefined() {
return [0.0, 0.0, 0.0];
}
let alpha_dps: f32 = web_read_opt_f32(&sub, WEB_PROP_ALPHA).unwrap_or(0.0);
let beta_dps: f32 = web_read_opt_f32(&sub, WEB_PROP_BETA).unwrap_or(0.0);
let gamma_dps: f32 = web_read_opt_f32(&sub, WEB_PROP_GAMMA).unwrap_or(0.0);
[
beta_dps * WEB_DEG_TO_RAD,
gamma_dps * WEB_DEG_TO_RAD,
alpha_dps * WEB_DEG_TO_RAD,
]
}
#[must_use]
pub fn web_screen_orientation_angle_deg() -> i32 {
let Some(win) = window() else {
return 0;
};
if let Ok(screen_val) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_SCREEN))
&& !screen_val.is_null()
&& !screen_val.is_undefined()
&& let Ok(orient_val) = Reflect::get(&screen_val, &JsValue::from_str(WEB_PROP_ORIENTATION))
&& !orient_val.is_null()
&& !orient_val.is_undefined()
&& let Some(angle) = web_read_opt_f32(&orient_val, WEB_PROP_ANGLE)
{
return angle.round() as i32;
}
if let Some(legacy_angle) = web_read_opt_f32(win.as_ref(), WEB_PROP_ORIENTATION) {
return legacy_angle.round() as i32;
}
0
}
#[must_use]
fn web_monotonic_now_ns() -> u64 {
window()
.and_then(|win: Window| win.performance())
.map(|perf: Performance| (perf.now().max(0.0) * 1_000_000.0) as u64)
.unwrap_or(0)
}
fn web_handle_device_orientation(event: &Event) {
let ev_val: &JsValue = event.as_ref();
let Some(beta_deg) = web_read_opt_f32(ev_val, WEB_PROP_BETA) else {
return;
};
let Some(gamma_deg) = web_read_opt_f32(ev_val, WEB_PROP_GAMMA) else {
return;
};
let alpha_deg: f32 = web_read_opt_f32(ev_val, WEB_PROP_ALPHA).unwrap_or(0.0);
let blue_val: f32 = beta_deg * WEB_DEG_TO_RAD;
let green_val: f32 = gamma_deg * WEB_DEG_TO_RAD;
let yaw_rad: f32 = alpha_deg * WEB_DEG_TO_RAD;
let g_dev: [f32; 3] = [
STANDARD_GRAVITY_MPS2 * blue_val.cos() * green_val.sin(),
-STANDARD_GRAVITY_MPS2 * blue_val.sin(),
-STANDARD_GRAVITY_MPS2 * blue_val.cos() * green_val.cos(),
];
let angle_deg: i32 = web_screen_orientation_angle_deg();
let ts_ns: u64 = web_monotonic_now_ns();
WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
if let Ok(mut node_style) = cell.try_borrow_mut() {
node_style.set_orient_gravity_dev(Some(g_dev));
node_style.set_last_yaw_rad(yaw_rad);
if !node_style.get_has_motion_event() {
let mut sample: DeviceMotionSample = DeviceMotionSample::from_device_axes(
g_dev,
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
angle_deg,
ts_ns,
);
sample.set_yaw_rad(yaw_rad);
node_style.set_pending_sample(sample);
node_style.set_has_pending_sample(true);
}
}
});
}
#[inline(always)]
#[must_use]
fn web_apply_sensor_deadzone(item_val: f32, dz: f32) -> f32 {
if !item_val.is_finite() {
return 0.0;
}
let abs_v: f32 = item_val.abs();
if abs_v <= dz {
0.0
} else {
item_val.signum() * (abs_v - dz)
}
}
fn web_handle_device_motion(event: &Event) {
let ev_val: &JsValue = event.as_ref();
let accel_incl: Option<[f32; 3]> = web_read_vec3_prop(ev_val, WEB_PROP_ACCEL_INCLUDING_GRAVITY);
let accel_lin: Option<[f32; 3]> = web_read_vec3_prop(ev_val, WEB_PROP_ACCELERATION);
let raw_gyro: [f32; 3] = web_read_rotation_rate_rad(ev_val);
let gyro_dev: [f32; 3] = [
web_apply_sensor_deadzone(raw_gyro[0], WEB_GYRO_DEADZONE_RAD_S),
web_apply_sensor_deadzone(raw_gyro[1], WEB_GYRO_DEADZONE_RAD_S),
web_apply_sensor_deadzone(raw_gyro[2], WEB_GYRO_DEADZONE_RAD_S),
];
let angle_deg: i32 = web_screen_orientation_angle_deg();
let ts_ns: u64 = web_monotonic_now_ns();
WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
if let Ok(mut node_style) = cell.try_borrow_mut() {
let first_motion: bool = !node_style.get_has_motion_event();
let mut g_dev_opt: Option<[f32; 3]> = None;
let mut lin_dev: [f32; 3] = [0.0, 0.0, 0.0];
if let Some(ag) = accel_incl {
node_style.set_has_motion_event(true);
let (raw_g_unsmoothed, raw_lin): ([f32; 3], [f32; 3]) = if let Some(al) = accel_lin
{
([ag[0] - al[0], ag[1] - al[1], ag[2] - al[2]], al)
} else {
let prev: [f32; 3] = node_style.get_filtered_gravity_dev().unwrap_or(ag);
let alpha_val: f32 = WEB_GRAVITY_LPF_ALPHA;
let filt: [f32; 3] = [
prev[0] * (1.0 - alpha_val) + ag[0] * alpha_val,
prev[1] * (1.0 - alpha_val) + ag[1] * alpha_val,
prev[2] * (1.0 - alpha_val) + ag[2] * alpha_val,
];
node_style.set_filtered_gravity_dev(Some(filt));
(filt, [ag[0] - filt[0], ag[1] - filt[1], ag[2] - filt[2]])
};
let prev_g: [f32; 3] = node_style
.get_filtered_gravity_dev()
.unwrap_or(raw_g_unsmoothed);
let dg2: f32 = (raw_g_unsmoothed[0] - prev_g[0]).powi(2)
+ (raw_g_unsmoothed[1] - prev_g[1]).powi(2)
+ (raw_g_unsmoothed[2] - prev_g[2]).powi(2);
let lpf_a: f32 = if dg2 < 0.09 { 0.18 } else { 0.65 };
let raw_g: [f32; 3] = [
prev_g[0] * (1.0 - lpf_a) + raw_g_unsmoothed[0] * lpf_a,
prev_g[1] * (1.0 - lpf_a) + raw_g_unsmoothed[1] * lpf_a,
prev_g[2] * (1.0 - lpf_a) + raw_g_unsmoothed[2] * lpf_a,
];
node_style.set_filtered_gravity_dev(Some(raw_g));
if let Some(og) = node_style.get_orient_gravity_dev() {
let dot: f32 = raw_g[0] * og[0] + raw_g[1] * og[1] + raw_g[2] * og[2];
if dot > WEB_GRAVITY_SIGN_DOT_THRESHOLD {
node_style.set_gravity_sign(1.0);
} else if dot < -WEB_GRAVITY_SIGN_DOT_THRESHOLD {
node_style.set_gravity_sign(-1.0);
}
} else if first_motion && raw_g[1].abs() > 4.2 {
node_style.set_gravity_sign(if raw_g[1] < 0.0 { 1.0 } else { -1.0 });
}
let source_val: f32 = node_style.get_gravity_sign();
g_dev_opt = Some([
raw_g[0] * source_val,
raw_g[1] * source_val,
raw_g[2] * source_val,
]);
let lin_sign: f32 = if source_val > 0.0 { -1.0 } else { 1.0 };
lin_dev = [
web_apply_sensor_deadzone(
raw_lin[0] * lin_sign,
WEB_LINEAR_ACCEL_DEADZONE_MPS2,
),
web_apply_sensor_deadzone(
raw_lin[1] * lin_sign,
WEB_LINEAR_ACCEL_DEADZONE_MPS2,
),
web_apply_sensor_deadzone(
raw_lin[2] * lin_sign,
WEB_LINEAR_ACCEL_DEADZONE_MPS2,
),
];
} else if let Some(og) = node_style.get_orient_gravity_dev() {
g_dev_opt = Some(og);
if let Some(al) = accel_lin {
lin_dev = [
web_apply_sensor_deadzone(al[0], WEB_LINEAR_ACCEL_DEADZONE_MPS2),
web_apply_sensor_deadzone(al[1], WEB_LINEAR_ACCEL_DEADZONE_MPS2),
web_apply_sensor_deadzone(al[2], WEB_LINEAR_ACCEL_DEADZONE_MPS2),
];
}
}
if let Some(g_dev) = g_dev_opt {
let mut sample: DeviceMotionSample = DeviceMotionSample::from_device_axes(
g_dev, lin_dev, gyro_dev, angle_deg, ts_ns,
);
sample.set_yaw_rad(node_style.get_last_yaw_rad());
node_style.set_pending_sample(sample);
node_style.set_has_pending_sample(true);
}
}
});
}
pub fn web_attach_device_motion_listeners() -> bool {
let already: bool = WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
cell.try_borrow()
.map(|node_style: Ref<'_, WebDeviceMotionState>| node_style.get_listeners_attached())
.unwrap_or(false)
});
if already {
return true;
}
let Some(win) = window() else {
return false;
};
let on_motion: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(|ui_event: Event| {
web_handle_device_motion(&ui_event);
}) as Box<dyn FnMut(Event)>);
let motion_ok: bool = win
.add_event_listener_with_callback(
WEB_EVENT_DEVICE_MOTION,
on_motion.as_ref().unchecked_ref(),
)
.is_ok();
on_motion.forget();
let on_orient: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(|dispatched_event: Event| {
web_handle_device_orientation(&dispatched_event);
}) as Box<dyn FnMut(Event)>);
let orient_ok: bool = win
.add_event_listener_with_callback(
WEB_EVENT_DEVICE_ORIENTATION,
on_orient.as_ref().unchecked_ref(),
)
.is_ok();
on_orient.forget();
let attached: bool = motion_ok || orient_ok;
if attached {
WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
if let Ok(mut active_style) = cell.try_borrow_mut() {
active_style.set_listeners_attached(true);
}
});
}
attached
}
#[must_use]
pub fn web_take_pending_device_motion() -> Option<DeviceMotionSample> {
WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
cell.try_borrow_mut()
.ok()
.and_then(|mut node_style: RefMut<'_, WebDeviceMotionState>| {
if node_style.get_has_pending_sample() {
node_style.set_has_pending_sample(false);
Some(node_style.get_pending_sample())
} else {
None
}
})
})
}
fn web_try_request_ctor_permission(win: &Window, ctor_name: &str) -> bool {
let Ok(ctor_val) = Reflect::get(win.as_ref(), &JsValue::from_str(ctor_name)) else {
return false;
};
if ctor_val.is_null() || ctor_val.is_undefined() {
return false;
}
let Ok(req_val) = Reflect::get(&ctor_val, &JsValue::from_str(WEB_METHOD_REQUEST_PERMISSION))
else {
return false;
};
let Ok(req_fn) = req_val.dyn_into::<Function>() else {
return false;
};
if let Ok(ret) = req_fn.call0(&ctor_val)
&& let Ok(promise) = ret.dyn_into::<Promise>()
{
let on_granted: Closure<dyn FnMut(JsValue)> = Closure::wrap(Box::new(|res: JsValue| {
if res.as_string().as_deref() == Some(WEB_PERMISSION_GRANTED) {
let _: bool = web_attach_device_motion_listeners();
}
})
as Box<dyn FnMut(JsValue)>);
let chained: Promise = promise.then(&on_granted);
on_granted.forget();
WEB_PROMISE_NOOP_REJECT.with(|callback_fn: &Closure<dyn FnMut(JsValue)>| {
let _: Promise = chained.catch(callback_fn);
});
return true;
}
false
}
pub(crate) fn web_request_motion_permission_impl() -> bool {
let Some(win) = window() else {
return false;
};
let motion_req: bool = web_try_request_ctor_permission(&win, WEB_CTOR_DEVICE_MOTION_EVENT);
let orient_req: bool = web_try_request_ctor_permission(&win, WEB_CTOR_DEVICE_ORIENTATION_EVENT);
if motion_req || orient_req {
return true;
}
web_attach_device_motion_listeners()
}
fn web_rasterize_loaded_img(doc: &Document, img: &Element, url: &str) -> Option<ImageBuffer> {
let raw_w: u32 = Reflect::get(img.as_ref(), &JsValue::from_str(WEB_PROP_NATURAL_WIDTH))
.ok()
.and_then(|item_val: JsValue| item_val.as_f64())
.map(|item_count: f64| item_count.round().max(0.0) as u32)
.unwrap_or(0);
let raw_h: u32 = Reflect::get(img.as_ref(), &JsValue::from_str(WEB_PROP_NATURAL_HEIGHT))
.ok()
.and_then(|tex_v: JsValue| tex_v.as_f64())
.map(|node_entry: f64| node_entry.round().max(0.0) as u32)
.unwrap_or(0);
let lower_url: String = url.to_ascii_lowercase();
let is_svg_url: bool =
lower_url.contains(WEB_EXT_SVG) || lower_url.starts_with(WEB_DATA_SVG_PREFIX);
let missing_intrinsic: bool = raw_w == 0 || raw_h == 0;
let is_vector_svg: bool = is_svg_url || missing_intrinsic;
let (base_w, base_h): (u32, u32) = if !missing_intrinsic {
(raw_w, raw_h)
} else {
(WEB_SVG_FALLBACK_WIDTH, WEB_SVG_FALLBACK_HEIGHT)
};
let (src_w, src_h): (u32, u32) = if is_vector_svg {
let svg_scale: f64 = f64::from(web_device_pixel_ratio().clamp(1.0, WEB_SVG_RASTER_MAX_DPR));
(
(f64::from(base_w) * svg_scale).round().max(1.0) as u32,
(f64::from(base_h) * svg_scale).round().max(1.0) as u32,
)
} else {
(base_w, base_h)
};
let max_side: u32 = src_w.max(src_h);
let (out_w, out_h): (u32, u32) = if max_side > WEB_IMAGE_MAX_DIM {
let scale: f64 = f64::from(WEB_IMAGE_MAX_DIM) / f64::from(max_side);
(
(f64::from(src_w) * scale).round().max(1.0) as u32,
(f64::from(src_h) * scale).round().max(1.0) as u32,
)
} else {
(src_w, src_h)
};
let canvas_el: Element = doc.create_element(WEB_CANVAS_TAG).ok()?;
let canvas: HtmlCanvasElement = canvas_el.dyn_into::<HtmlCanvasElement>().ok()?;
canvas.set_width(out_w);
canvas.set_height(out_h);
let ctx_obj: Object = canvas.get_context(WEB_CONTEXT_2D).ok()??;
let ctx2d: CanvasRenderingContext2d = ctx_obj.dyn_into::<CanvasRenderingContext2d>().ok()?;
let _: Result<bool, JsValue> = Reflect::set(
ctx2d.as_ref(),
&JsValue::from_str(WEB_PROP_IMAGE_SMOOTHING_QUALITY),
&JsValue::from_str(WEB_IMG_SMOOTHING_HIGH),
);
ctx2d.clear_rect(0.0, 0.0, f64::from(out_w), f64::from(out_h));
let draw_val: JsValue =
Reflect::get(ctx2d.as_ref(), &JsValue::from_str(WEB_METHOD_DRAW_IMAGE)).ok()?;
let draw_fn: Function = draw_val.dyn_into::<Function>().ok()?;
let args: Array = Array::of5(
img.as_ref(),
&JsValue::from_f64(0.0),
&JsValue::from_f64(0.0),
&JsValue::from_f64(f64::from(out_w)),
&JsValue::from_f64(f64::from(out_h)),
);
let _: JsValue = draw_fn.apply(ctx2d.as_ref(), &args).ok()?;
let img_data: ImageData = ctx2d
.get_image_data(0.0, 0.0, f64::from(out_w), f64::from(out_h))
.ok()?;
let pixels: Vec<u8> = img_data.data().0;
Some(ImageBuffer::new(out_w, out_h, pixels))
}
pub(crate) fn web_load_network_image(url: &str) {
let Some(doc) = window().and_then(|width_val: Window| width_val.document()) else {
complete_network_image_load(url, None);
return;
};
let Ok(img) = doc.create_element(WEB_TAG_IMG) else {
complete_network_image_load(url, None);
return;
};
let lower: String = url.to_ascii_lowercase();
if lower.starts_with(WEB_SCHEME_HTTP) || lower.starts_with(WEB_SCHEME_HTTPS) {
let _: Result<bool, JsValue> = Reflect::set(
img.as_ref(),
&JsValue::from_str(WEB_PROP_CROSS_ORIGIN),
&JsValue::from_str(WEB_CORS_ANONYMOUS),
);
}
let url_load: String = url.to_string();
let img_load: Element = img.clone();
let doc_load: Document = doc.clone();
let on_load: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
let decoded: Option<ImageBuffer> =
web_rasterize_loaded_img(&doc_load, &img_load, &url_load);
complete_network_image_load(&url_load, decoded);
}) as Box<dyn FnMut(Event)>);
let url_err: String = url.to_string();
let on_err: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
complete_network_image_load(&url_err, None);
}) as Box<dyn FnMut(Event)>);
drop(img.add_event_listener_with_callback(WEB_EVENT_LOAD, on_load.as_ref().unchecked_ref()));
drop(img.add_event_listener_with_callback(WEB_EVENT_ERROR, on_err.as_ref().unchecked_ref()));
on_load.forget();
on_err.forget();
let _: Result<bool, JsValue> = Reflect::set(
img.as_ref(),
&JsValue::from_str(WEB_PROP_SRC),
&JsValue::from_str(url),
);
}