1use std::cell::Cell;
8use std::cmp;
9
10use dom_struct::dom_struct;
11use js::context::JSContext;
12use script_bindings::cell::DomRefCell;
13use script_bindings::reflector::{DomObject as _, reflect_dom_object};
14use script_bindings::weakref::WeakRef;
15use servo_canvas_traits::webgl::{
16 TexDataType, TexFormat, TexParameter, TexParameterBool, TexParameterInt, WebGLCommand,
17 WebGLError, WebGLResult, WebGLTextureId, WebGLVersion, webgl_channel,
18};
19
20use crate::dom::bindings::codegen::Bindings::EXTTextureFilterAnisotropicBinding::EXTTextureFilterAnisotropicConstants;
21use crate::dom::bindings::codegen::Bindings::WebGL2RenderingContextBinding::WebGL2RenderingContextConstants as constants;
22use crate::dom::bindings::inheritance::Castable;
23use crate::dom::bindings::reflector::DomGlobal;
24use crate::dom::bindings::root::{DomRoot, MutNullableDom};
25use crate::dom::webgl::validations::types::TexImageTarget;
26use crate::dom::webgl::webglframebuffer::WebGLFramebuffer;
27use crate::dom::webgl::webglobject::WebGLObject;
28use crate::dom::webgl::webglrenderingcontext::{Operation, WebGLRenderingContext};
29use crate::dom::webglrenderingcontext::capture_webgl_backtrace;
30#[cfg(feature = "webxr")]
31use crate::dom::xrsession::XRSession;
32
33pub(crate) enum TexParameterValue {
34 Float(f32),
35 Int(i32),
36 Bool(bool),
37}
38
39#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
42#[derive(JSTraceable, MallocSizeOf)]
43enum WebGLTextureOwner {
44 WebGL,
45 #[cfg(feature = "webxr")]
46 WebXR(WeakRef<XRSession>),
47}
48
49const MAX_LEVEL_COUNT: usize = 31;
50const MAX_FACE_COUNT: usize = 6;
51
52#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
53#[derive(JSTraceable, MallocSizeOf)]
54struct DroppableWebGLTexture {
55 context: WeakRef<WebGLRenderingContext>,
56 #[no_trace]
57 id: WebGLTextureId,
58 is_deleted: Cell<bool>,
59 owner: WebGLTextureOwner,
60}
61
62impl DroppableWebGLTexture {
63 fn send_with_fallibility(&self, command: WebGLCommand, fallibility: Operation) {
64 if let Some(root) = self.context.root() {
65 let result = root.sender().send(command, capture_webgl_backtrace());
66 if matches!(fallibility, Operation::Infallible) {
67 result.expect("Operation failed");
68 }
69 }
70 }
71
72 fn delete(&self, operation_fallibility: Operation) {
73 if !self.is_deleted.get() {
74 self.is_deleted.set(true);
75
76 if let Some(context) = self.context.root() {
85 if let Some(fb) = context.get_draw_framebuffer_slot().get() {
86 let _ = fb.detach_texture(self.id);
87 }
88 if let Some(fb) = context.get_read_framebuffer_slot().get() {
89 let _ = fb.detach_texture(self.id);
90 }
91 }
92
93 #[cfg(feature = "webxr")]
95 if let WebGLTextureOwner::WebXR(_) = self.owner {
96 return;
97 }
98
99 self.send_with_fallibility(WebGLCommand::DeleteTexture(self.id), operation_fallibility);
100 }
101 }
102}
103
104impl Drop for DroppableWebGLTexture {
105 fn drop(&mut self) {
106 self.delete(Operation::Fallible);
107 }
108}
109
110#[dom_struct]
111pub(crate) struct WebGLTexture {
112 webgl_object: WebGLObject,
113 target: Cell<Option<u32>>,
115 #[ignore_malloc_size_of = "I do not know how"]
117 image_info_array: DomRefCell<[Option<ImageInfo>; MAX_LEVEL_COUNT * MAX_FACE_COUNT]>,
118 face_count: Cell<u8>,
120 base_mipmap_level: u32,
121 min_filter: Cell<u32>,
123 mag_filter: Cell<u32>,
124 attached_framebuffer: MutNullableDom<WebGLFramebuffer>,
126 immutable_levels: Cell<Option<u32>>,
128 droppable: DroppableWebGLTexture,
129}
130
131impl WebGLTexture {
132 fn new_inherited(
133 context: &WebGLRenderingContext,
134 id: WebGLTextureId,
135 #[cfg(feature = "webxr")] owner: Option<&XRSession>,
136 ) -> Self {
137 Self {
138 webgl_object: WebGLObject::new_inherited(context),
139 target: Cell::new(None),
140 immutable_levels: Cell::new(None),
141 face_count: Cell::new(0),
142 base_mipmap_level: 0,
143 min_filter: Cell::new(constants::NEAREST_MIPMAP_LINEAR),
144 mag_filter: Cell::new(constants::LINEAR),
145 image_info_array: DomRefCell::new([None; MAX_LEVEL_COUNT * MAX_FACE_COUNT]),
146 attached_framebuffer: Default::default(),
147 droppable: DroppableWebGLTexture {
148 context: WeakRef::new(context),
149 id,
150 is_deleted: Cell::new(false),
151 #[cfg(feature = "webxr")]
152 owner: owner
153 .map(|session| WebGLTextureOwner::WebXR(WeakRef::new(session)))
154 .unwrap_or(WebGLTextureOwner::WebGL),
155 #[cfg(not(feature = "webxr"))]
156 owner: WebGLTextureOwner::WebGL,
157 },
158 }
159 }
160
161 pub(crate) fn maybe_new(
162 cx: &mut JSContext,
163 context: &WebGLRenderingContext,
164 ) -> Option<DomRoot<Self>> {
165 let (sender, receiver) = webgl_channel().unwrap();
166 context.send_command(WebGLCommand::CreateTexture(sender));
167 receiver
168 .recv()
169 .unwrap()
170 .map(|id| WebGLTexture::new(cx, context, id))
171 }
172
173 pub(crate) fn new(
174 cx: &mut JSContext,
175 context: &WebGLRenderingContext,
176 id: WebGLTextureId,
177 ) -> DomRoot<Self> {
178 reflect_dom_object(
179 cx,
180 Box::new(WebGLTexture::new_inherited(
181 context,
182 id,
183 #[cfg(feature = "webxr")]
184 None,
185 )),
186 &*context.global(),
187 )
188 }
189
190 #[cfg(feature = "webxr")]
191 pub(crate) fn new_webxr(
192 cx: &mut JSContext,
193 context: &WebGLRenderingContext,
194 id: WebGLTextureId,
195 session: &XRSession,
196 ) -> DomRoot<Self> {
197 reflect_dom_object(
198 cx,
199 Box::new(WebGLTexture::new_inherited(context, id, Some(session))),
200 &*context.global(),
201 )
202 }
203}
204
205impl WebGLTexture {
206 pub(crate) fn id(&self) -> WebGLTextureId {
207 self.droppable.id
208 }
209
210 pub(crate) fn bind(&self, target: u32) -> WebGLResult<()> {
212 if self.is_invalid() {
213 return Err(WebGLError::InvalidOperation);
214 }
215
216 if let Some(previous_target) = self.target.get() {
217 if target != previous_target {
218 return Err(WebGLError::InvalidOperation);
219 }
220 } else {
221 let face_count = match target {
223 constants::TEXTURE_2D | constants::TEXTURE_2D_ARRAY | constants::TEXTURE_3D => 1,
224 constants::TEXTURE_CUBE_MAP => 6,
225 _ => return Err(WebGLError::InvalidEnum),
226 };
227 self.face_count.set(face_count);
228 self.target.set(Some(target));
229 }
230
231 self.upcast()
232 .send_command(WebGLCommand::BindTexture(target, Some(self.id())));
233
234 Ok(())
235 }
236
237 #[expect(clippy::too_many_arguments)]
238 pub(crate) fn initialize(
239 &self,
240 target: TexImageTarget,
241 width: u32,
242 height: u32,
243 depth: u32,
244 internal_format: TexFormat,
245 level: u32,
246 data_type: Option<TexDataType>,
247 ) -> WebGLResult<()> {
248 let image_info = ImageInfo {
249 width,
250 height,
251 depth,
252 internal_format,
253 data_type,
254 };
255
256 let face_index = self.face_index_for_target(&target);
257 self.set_image_infos_at_level_and_face(level, face_index, image_info);
258
259 if let Some(fb) = self.attached_framebuffer.get() {
260 fb.update_status();
261 }
262
263 self.update_size();
264
265 Ok(())
266 }
267
268 pub(crate) fn generate_mipmap(&self) -> WebGLResult<()> {
269 let target = match self.target.get() {
270 Some(target) => target,
271 None => {
272 error!("Cannot generate mipmap on texture that has no target!");
273 return Err(WebGLError::InvalidOperation);
274 },
275 };
276
277 let base_image_info = self.base_image_info().ok_or(WebGLError::InvalidOperation)?;
278
279 let is_cubic = target == constants::TEXTURE_CUBE_MAP;
280 if is_cubic && !self.is_cube_complete() {
281 return Err(WebGLError::InvalidOperation);
282 }
283
284 let Some(context) = self.upcast().context() else {
285 return Err(WebGLError::ContextLost);
286 };
287 if context.webgl_version() == WebGLVersion::WebGL1 && !base_image_info.is_power_of_two() {
289 return Err(WebGLError::InvalidOperation);
290 }
291
292 if base_image_info.is_compressed_format() {
293 return Err(WebGLError::InvalidOperation);
294 }
295
296 self.upcast()
297 .send_command(WebGLCommand::GenerateMipmap(target));
298
299 if self.base_mipmap_level + base_image_info.get_max_mimap_levels() == 0 {
300 return Err(WebGLError::InvalidOperation);
301 }
302
303 let last_level = self.base_mipmap_level + base_image_info.get_max_mimap_levels() - 1;
304 self.populate_mip_chain(self.base_mipmap_level, last_level)
305 }
306
307 pub(crate) fn delete(&self, operation_fallibility: Operation) {
308 self.droppable.delete(operation_fallibility);
309 }
310
311 pub(crate) fn is_invalid(&self) -> bool {
312 #[cfg(feature = "webxr")]
314 if let WebGLTextureOwner::WebXR(ref session) = self.droppable.owner &&
315 let Some(xr) = session.root() &&
316 xr.is_outside_raf()
317 {
318 return true;
319 }
320 self.droppable.is_deleted.get()
321 }
322
323 pub(crate) fn is_immutable(&self) -> bool {
324 self.immutable_levels.get().is_some()
325 }
326
327 pub(crate) fn target(&self) -> Option<u32> {
328 self.target.get()
329 }
330
331 pub(crate) fn maybe_get_tex_parameter(&self, param: TexParameter) -> Option<TexParameterValue> {
332 match param {
333 TexParameter::Int(TexParameterInt::TextureImmutableLevels) => Some(
334 TexParameterValue::Int(self.immutable_levels.get().unwrap_or(0) as i32),
335 ),
336 TexParameter::Bool(TexParameterBool::TextureImmutableFormat) => {
337 Some(TexParameterValue::Bool(self.is_immutable()))
338 },
339 _ => None,
340 }
341 }
342
343 pub(crate) fn tex_parameter(&self, param: u32, value: TexParameterValue) -> WebGLResult<()> {
346 let target = self.target().unwrap();
347
348 let (int_value, float_value) = match value {
349 TexParameterValue::Int(int_value) => (int_value, int_value as f32),
350 TexParameterValue::Float(float_value) => (float_value as i32, float_value),
351 TexParameterValue::Bool(_) => unreachable!("no settable tex params should be booleans"),
352 };
353
354 let Some(context) = self.upcast().context() else {
355 return Err(WebGLError::ContextLost);
356 };
357 let is_webgl2 = context.webgl_version() == WebGLVersion::WebGL2;
358
359 let update_filter = |filter: &Cell<u32>| {
360 if filter.get() == int_value as u32 {
361 return Ok(());
362 }
363 filter.set(int_value as u32);
364 context.send_command(WebGLCommand::TexParameteri(target, param, int_value));
365 Ok(())
366 };
367 if is_webgl2 {
368 match param {
369 constants::TEXTURE_BASE_LEVEL | constants::TEXTURE_MAX_LEVEL => {
370 context.send_command(WebGLCommand::TexParameteri(target, param, int_value));
371 return Ok(());
372 },
373 constants::TEXTURE_COMPARE_FUNC => match int_value as u32 {
374 constants::LEQUAL |
375 constants::GEQUAL |
376 constants::LESS |
377 constants::GREATER |
378 constants::EQUAL |
379 constants::NOTEQUAL |
380 constants::ALWAYS |
381 constants::NEVER => {
382 context.send_command(WebGLCommand::TexParameteri(target, param, int_value));
383 return Ok(());
384 },
385 _ => return Err(WebGLError::InvalidEnum),
386 },
387 constants::TEXTURE_COMPARE_MODE => match int_value as u32 {
388 constants::COMPARE_REF_TO_TEXTURE | constants::NONE => {
389 context.send_command(WebGLCommand::TexParameteri(target, param, int_value));
390 return Ok(());
391 },
392 _ => return Err(WebGLError::InvalidEnum),
393 },
394 constants::TEXTURE_MAX_LOD | constants::TEXTURE_MIN_LOD => {
395 context.send_command(WebGLCommand::TexParameterf(target, param, float_value));
396 return Ok(());
397 },
398 constants::TEXTURE_WRAP_R => match int_value as u32 {
399 constants::CLAMP_TO_EDGE | constants::MIRRORED_REPEAT | constants::REPEAT => {
400 self.upcast()
401 .send_command(WebGLCommand::TexParameteri(target, param, int_value));
402 return Ok(());
403 },
404 _ => return Err(WebGLError::InvalidEnum),
405 },
406 _ => {},
407 }
408 }
409 match param {
410 constants::TEXTURE_MIN_FILTER => match int_value as u32 {
411 constants::NEAREST |
412 constants::LINEAR |
413 constants::NEAREST_MIPMAP_NEAREST |
414 constants::LINEAR_MIPMAP_NEAREST |
415 constants::NEAREST_MIPMAP_LINEAR |
416 constants::LINEAR_MIPMAP_LINEAR => update_filter(&self.min_filter),
417 _ => Err(WebGLError::InvalidEnum),
418 },
419 constants::TEXTURE_MAG_FILTER => match int_value as u32 {
420 constants::NEAREST | constants::LINEAR => update_filter(&self.mag_filter),
421 _ => Err(WebGLError::InvalidEnum),
422 },
423 constants::TEXTURE_WRAP_S | constants::TEXTURE_WRAP_T => match int_value as u32 {
424 constants::CLAMP_TO_EDGE | constants::MIRRORED_REPEAT | constants::REPEAT => {
425 context.send_command(WebGLCommand::TexParameteri(target, param, int_value));
426 Ok(())
427 },
428 _ => Err(WebGLError::InvalidEnum),
429 },
430 EXTTextureFilterAnisotropicConstants::TEXTURE_MAX_ANISOTROPY_EXT => {
431 if float_value < 1. || !float_value.is_normal() {
433 return Err(WebGLError::InvalidValue);
434 }
435 context.send_command(WebGLCommand::TexParameterf(target, param, float_value));
436 Ok(())
437 },
438 _ => Err(WebGLError::InvalidEnum),
439 }
440 }
441
442 pub(crate) fn min_filter(&self) -> u32 {
443 self.min_filter.get()
444 }
445
446 pub(crate) fn mag_filter(&self) -> u32 {
447 self.mag_filter.get()
448 }
449
450 pub(crate) fn is_using_linear_filtering(&self) -> bool {
451 let filters = [self.min_filter.get(), self.mag_filter.get()];
452 filters.iter().any(|filter| {
453 matches!(
454 *filter,
455 constants::LINEAR |
456 constants::NEAREST_MIPMAP_LINEAR |
457 constants::LINEAR_MIPMAP_NEAREST |
458 constants::LINEAR_MIPMAP_LINEAR
459 )
460 })
461 }
462
463 pub(crate) fn populate_mip_chain(&self, first_level: u32, last_level: u32) -> WebGLResult<()> {
464 let base_image_info = self
465 .image_info_at_face(0, first_level)
466 .ok_or(WebGLError::InvalidOperation)?;
467
468 let mut ref_width = base_image_info.width;
469 let mut ref_height = base_image_info.height;
470
471 if ref_width == 0 || ref_height == 0 {
472 return Err(WebGLError::InvalidOperation);
473 }
474
475 for level in (first_level + 1)..last_level {
476 if ref_width == 1 && ref_height == 1 {
477 break;
478 }
479
480 ref_width = cmp::max(1, ref_width / 2);
481 ref_height = cmp::max(1, ref_height / 2);
482
483 let image_info = ImageInfo {
484 width: ref_width,
485 height: ref_height,
486 depth: 0,
487 internal_format: base_image_info.internal_format,
488 data_type: base_image_info.data_type,
489 };
490
491 self.set_image_infos_at_level(level, image_info);
492 }
493
494 self.update_size();
495 Ok(())
496 }
497
498 fn is_cube_complete(&self) -> bool {
499 debug_assert_eq!(self.face_count.get(), 6);
500
501 let image_info = match self.base_image_info() {
502 Some(info) => info,
503 None => return false,
504 };
505
506 let ref_width = image_info.width;
507 let ref_format = image_info.internal_format;
508
509 for face in 0..self.face_count.get() {
510 let current_image_info = match self.image_info_at_face(face, self.base_mipmap_level) {
511 Some(info) => info,
512 None => return false,
513 };
514
515 if current_image_info.internal_format != ref_format ||
517 current_image_info.width != ref_width ||
518 current_image_info.height != ref_width
519 {
520 return false;
521 }
522 }
523
524 true
525 }
526
527 fn face_index_for_target(&self, target: &TexImageTarget) -> u8 {
528 match *target {
529 TexImageTarget::CubeMapPositiveX => 0,
530 TexImageTarget::CubeMapNegativeX => 1,
531 TexImageTarget::CubeMapPositiveY => 2,
532 TexImageTarget::CubeMapNegativeY => 3,
533 TexImageTarget::CubeMapPositiveZ => 4,
534 TexImageTarget::CubeMapNegativeZ => 5,
535 _ => 0,
536 }
537 }
538
539 pub(crate) fn image_info_for_target(
540 &self,
541 target: &TexImageTarget,
542 level: u32,
543 ) -> Option<ImageInfo> {
544 let face_index = self.face_index_for_target(target);
545 self.image_info_at_face(face_index, level)
546 }
547
548 pub(crate) fn image_info_at_face(&self, face: u8, level: u32) -> Option<ImageInfo> {
549 let pos = (level * self.face_count.get() as u32) + face as u32;
550 self.image_info_array.borrow()[pos as usize]
551 }
552
553 fn set_image_infos_at_level(&self, level: u32, image_info: ImageInfo) {
554 for face in 0..self.face_count.get() {
555 self.set_image_infos_at_level_and_face(level, face, image_info);
556 }
557 }
558
559 fn set_image_infos_at_level_and_face(&self, level: u32, face: u8, image_info: ImageInfo) {
560 debug_assert!(face < self.face_count.get());
561 let pos = (level * self.face_count.get() as u32) + face as u32;
562 self.image_info_array.borrow_mut()[pos as usize] = Some(image_info);
563 }
564
565 fn update_size(&self) {
566 let size = self
567 .image_info_array
568 .borrow()
569 .iter()
570 .filter_map(|info| *info)
571 .map(|info| info.physical_size())
572 .sum();
573 self.reflector().update_memory_size(self, size);
574 }
575
576 fn base_image_info(&self) -> Option<ImageInfo> {
577 assert!((self.base_mipmap_level as usize) < MAX_LEVEL_COUNT);
578
579 self.image_info_at_face(0, self.base_mipmap_level)
580 }
581
582 pub(crate) fn attach_to_framebuffer(&self, fb: &WebGLFramebuffer) {
583 self.attached_framebuffer.set(Some(fb));
584 }
585
586 pub(crate) fn detach_from_framebuffer(&self) {
587 self.attached_framebuffer.set(None);
588 }
589
590 pub(crate) fn storage(
591 &self,
592 target: TexImageTarget,
593 levels: u32,
594 internal_format: TexFormat,
595 width: u32,
596 height: u32,
597 depth: u32,
598 ) -> WebGLResult<()> {
599 assert!(!self.is_immutable());
601 assert!(self.target().is_some());
602
603 let target_id = target.as_gl_constant();
604 let command = match target {
605 TexImageTarget::Texture2D | TexImageTarget::CubeMap => {
606 WebGLCommand::TexStorage2D(target_id, levels, internal_format, width, height)
607 },
608 TexImageTarget::Texture3D | TexImageTarget::Texture2DArray => {
609 WebGLCommand::TexStorage3D(target_id, levels, internal_format, width, height, depth)
610 },
611 _ => unreachable!(), };
613 self.upcast().send_command(command);
614
615 let mut width = width;
616 let mut height = height;
617 let mut depth = depth;
618 for level in 0..levels {
619 let image_info = ImageInfo {
620 width,
621 height,
622 depth,
623 internal_format,
624 data_type: None,
625 };
626 self.set_image_infos_at_level(level, image_info);
627
628 width = cmp::max(1, width / 2);
629 height = cmp::max(1, height / 2);
630 if target == TexImageTarget::Texture3D {
631 depth = cmp::max(1, depth / 2);
632 }
633 }
634
635 self.immutable_levels.set(Some(levels));
636
637 if let Some(fb) = self.attached_framebuffer.get() {
638 fb.update_status();
639 }
640
641 self.update_size();
642
643 Ok(())
644 }
645}
646
647#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
648pub(crate) struct ImageInfo {
649 width: u32,
650 height: u32,
651 depth: u32,
652 #[no_trace]
653 internal_format: TexFormat,
654 #[no_trace]
655 data_type: Option<TexDataType>,
656}
657
658impl ImageInfo {
659 pub(crate) fn width(&self) -> u32 {
660 self.width
661 }
662
663 pub(crate) fn height(&self) -> u32 {
664 self.height
665 }
666
667 pub(crate) fn internal_format(&self) -> TexFormat {
668 self.internal_format
669 }
670
671 pub(crate) fn data_type(&self) -> Option<TexDataType> {
672 self.data_type
673 }
674
675 fn is_power_of_two(&self) -> bool {
676 self.width.is_power_of_two() &&
677 self.height.is_power_of_two() &&
678 self.depth.is_power_of_two()
679 }
680
681 fn get_max_mimap_levels(&self) -> u32 {
682 let largest = cmp::max(cmp::max(self.width, self.height), self.depth);
683 if largest == 0 {
684 return 0;
685 }
686 (largest as f64).log2() as u32 + 1
688 }
689
690 fn is_compressed_format(&self) -> bool {
691 self.internal_format.is_compressed()
692 }
693
694 pub(crate) fn physical_size(&self) -> usize {
696 self.width as usize *
697 self.height as usize *
698 self.depth as usize *
699 self.internal_format.components() as usize
700 }
701}
702
703#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf)]
704pub(crate) enum TexCompressionValidation {
705 None,
706 S3TC,
707}
708
709#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf)]
710pub(crate) struct TexCompression {
711 #[no_trace]
712 pub(crate) format: TexFormat,
713 pub(crate) bytes_per_block: u8,
714 pub(crate) block_width: u8,
715 pub(crate) block_height: u8,
716 pub(crate) validation: TexCompressionValidation,
717}