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