1use std::{self, fmt};
6
7use servo_canvas_traits::webgl::WebGLError::*;
8use servo_canvas_traits::webgl::{TexDataType, TexFormat, WebGLVersion};
9
10use super::WebGLValidator;
11use super::types::TexImageTarget;
12use crate::dom::bindings::root::DomRoot;
13use crate::dom::webgl::webglrenderingcontext::WebGLRenderingContext;
14use crate::dom::webgl::webgltexture::{
15 ImageInfo, TexCompression, TexCompressionValidation, WebGLTexture,
16};
17
18#[derive(Debug)]
20pub(crate) enum TexImageValidationError {
21 InvalidTextureTarget(u32),
23 TextureTargetNotBound(u32),
25 InvalidCubicTextureDimensions,
27 NegativeLevel,
29 LevelTooHigh,
31 LevelTooLow,
33 DepthTooLow,
35 NegativeDimension,
37 TextureTooBig,
40 InvalidDataType,
42 InvalidTextureFormat,
44 TextureFormatMismatch,
46 InvalidTypeForFormat,
48 InvalidBorder,
50 NonPotTexture,
52 InvalidCompressionFormat,
54 InvalidOffsets,
56 MissingBaseTexture,
58 ImmutableTexture,
60}
61
62impl std::error::Error for TexImageValidationError {}
63
64impl fmt::Display for TexImageValidationError {
65 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
66 use self::TexImageValidationError::*;
67 let description = match *self {
68 InvalidTextureTarget(texture_id) => &format!("Invalid texture target ({texture_id})"),
69 TextureTargetNotBound(texture_id) => &format!("Texture was not bound {texture_id}"),
70 InvalidCubicTextureDimensions => {
71 "Invalid dimensions were given for a cubic texture target"
72 },
73 NegativeLevel => "A negative level was passed",
74 LevelTooHigh => "Level too high",
75 LevelTooLow => "Level too low",
76 DepthTooLow => "Depth too low",
77 NegativeDimension => "Negative dimensions were passed",
78 TextureTooBig => "Dimensions given are too big",
79 InvalidDataType => "Invalid data type",
80 InvalidTextureFormat => "Invalid texture format",
81 TextureFormatMismatch => "Texture format mismatch",
82 InvalidTypeForFormat => "Invalid type for the given format",
83 InvalidBorder => "Invalid border",
84 NonPotTexture => "Expected a power of two texture",
85 InvalidCompressionFormat => "Unrecognized texture compression format",
86 InvalidOffsets => "Invalid X/Y texture offset parameters",
87 MissingBaseTexture => "No base image defined for this texture target and level",
88 ImmutableTexture => "Texture storage is immutable",
89 };
90 write!(f, "TexImageValidationError({})", description)
91 }
92}
93
94pub(crate) fn bound_texture(
97 context: &WebGLRenderingContext,
98 target: TexImageTarget,
99) -> Result<DomRoot<WebGLTexture>, TexImageValidationError> {
100 context
101 .textures()
102 .active_texture_for_image_target(target)
103 .ok_or_else(|| {
104 context.webgl_error(InvalidOperation);
105 TexImageValidationError::TextureTargetNotBound(target.as_gl_constant())
106 })
107}
108
109pub(crate) fn validate_internal_format(
112 context: &WebGLRenderingContext,
113 internal_format: u32,
114) -> Result<TexFormat, TexImageValidationError> {
115 match TexFormat::from_gl_constant(internal_format) {
116 Some(format)
117 if format.required_webgl_version() <= context.webgl_version() &&
118 format.usable_as_internal() =>
119 {
120 Ok(format)
121 },
122 _ => {
123 context.webgl_error(InvalidEnum);
124 Err(TexImageValidationError::InvalidTextureFormat)
125 },
126 }
127}
128
129pub(crate) struct CommonTexImage2DValidator<'a> {
130 context: &'a WebGLRenderingContext,
131 target: u32,
132 level: i32,
133 internal_format: u32,
134 width: i32,
135 height: i32,
136 border: i32,
137 is_sub_image: bool,
139}
140
141pub(crate) struct CommonTexImage2DValidatorResult {
142 pub(crate) texture: DomRoot<WebGLTexture>,
143 pub(crate) target: TexImageTarget,
144 pub(crate) level: u32,
145 pub(crate) internal_format: TexFormat,
146 pub(crate) width: u32,
147 pub(crate) height: u32,
148 pub(crate) border: u32,
149}
150
151impl WebGLValidator for CommonTexImage2DValidator<'_> {
152 type Error = TexImageValidationError;
153 type ValidatedOutput = CommonTexImage2DValidatorResult;
154 fn validate(self) -> Result<Self::ValidatedOutput, TexImageValidationError> {
155 let target = match TexImageTarget::from_gl_constant(self.target) {
160 Some(target) if target.dimensions() == 2 => target,
161 _ => {
162 self.context.webgl_error(InvalidEnum);
163 return Err(TexImageValidationError::InvalidTextureTarget(self.target));
164 },
165 };
166
167 let limits = self.context.limits();
168
169 let max_size = if target.is_cubic() {
170 limits.max_cube_map_tex_size
171 } else {
172 limits.max_tex_size
173 };
174
175 let texture = bound_texture(self.context, target)?;
176 let internal_format = validate_internal_format(self.context, self.internal_format)?;
177
178 if !self.is_sub_image && target.is_cubic() && self.width != self.height {
181 self.context.webgl_error(InvalidValue);
182 return Err(TexImageValidationError::InvalidCubicTextureDimensions);
183 }
184
185 if self.level < 0 {
187 self.context.webgl_error(InvalidValue);
188 return Err(TexImageValidationError::NegativeLevel);
189 }
190
191 if self.width < 0 || self.height < 0 {
193 self.context.webgl_error(InvalidValue);
194 return Err(TexImageValidationError::NegativeDimension);
195 }
196
197 let width = self.width as u32;
198 let height = self.height as u32;
199 let level = self.level as u32;
200
201 if width > max_size >> level || height > max_size >> level {
205 self.context.webgl_error(InvalidValue);
206 return Err(TexImageValidationError::TextureTooBig);
207 }
208
209 if !self.is_sub_image &&
213 self.context.webgl_version() == WebGLVersion::WebGL1 &&
214 level > 0 &&
215 (!width.is_power_of_two() || !height.is_power_of_two())
216 {
217 self.context.webgl_error(InvalidValue);
218 return Err(TexImageValidationError::NonPotTexture);
219 }
220
221 if level > max_size.ilog2() {
226 self.context.webgl_error(InvalidValue);
227 return Err(TexImageValidationError::LevelTooHigh);
228 }
229
230 if self.border != 0 {
232 self.context.webgl_error(InvalidValue);
233 return Err(TexImageValidationError::InvalidBorder);
234 }
235
236 Ok(CommonTexImage2DValidatorResult {
237 texture,
238 target,
239 level,
240 internal_format,
241 width,
242 height,
243 border: self.border as u32,
244 })
245 }
246}
247
248impl<'a> CommonTexImage2DValidator<'a> {
249 pub(crate) fn new(
250 context: &'a WebGLRenderingContext,
251 target: u32,
252 level: i32,
253 internal_format: u32,
254 width: i32,
255 height: i32,
256 border: i32,
257 ) -> Self {
258 CommonTexImage2DValidator {
259 context,
260 target,
261 level,
262 internal_format,
263 width,
264 height,
265 border,
266 is_sub_image: false,
267 }
268 }
269
270 pub(crate) fn for_sub_image(mut self) -> Self {
272 self.is_sub_image = true;
273 self
274 }
275}
276
277pub(crate) struct TexImage2DValidator<'a> {
278 common_validator: CommonTexImage2DValidator<'a>,
279 format: u32,
280 data_type: u32,
281}
282
283impl<'a> TexImage2DValidator<'a> {
284 #[expect(clippy::too_many_arguments)]
286 pub(crate) fn new(
287 context: &'a WebGLRenderingContext,
288 target: u32,
289 level: i32,
290 internal_format: u32,
291 width: i32,
292 height: i32,
293 border: i32,
294 format: u32,
295 data_type: u32,
296 ) -> Self {
297 TexImage2DValidator {
298 common_validator: CommonTexImage2DValidator::new(
299 context,
300 target,
301 level,
302 internal_format,
303 width,
304 height,
305 border,
306 ),
307 format,
308 data_type,
309 }
310 }
311
312 pub(crate) fn for_sub_image(mut self) -> Self {
314 self.common_validator = self.common_validator.for_sub_image();
315 self
316 }
317}
318
319pub(crate) struct TexImage2DValidatorResult {
321 pub(crate) width: u32,
323 pub(crate) height: u32,
324 pub(crate) level: u32,
325 pub(crate) border: u32,
326 pub(crate) texture: DomRoot<WebGLTexture>,
327 pub(crate) target: TexImageTarget,
328 pub(crate) internal_format: TexFormat,
329 pub(crate) format: TexFormat,
330 pub(crate) data_type: TexDataType,
331}
332
333impl WebGLValidator for TexImage2DValidator<'_> {
336 type ValidatedOutput = TexImage2DValidatorResult;
337 type Error = TexImageValidationError;
338
339 fn validate(self) -> Result<Self::ValidatedOutput, TexImageValidationError> {
340 let context = self.common_validator.context;
341 let CommonTexImage2DValidatorResult {
342 texture,
343 target,
344 level,
345 internal_format,
346 width,
347 height,
348 border,
349 } = self.common_validator.validate()?;
350
351 let version = context.webgl_version();
354 let data_type = match TexDataType::from_webgl_constant(self.data_type, version) {
355 Some(data_type) if data_type.required_webgl_version() <= version => data_type,
356 _ => {
357 context.webgl_error(InvalidEnum);
358 return Err(TexImageValidationError::InvalidDataType);
359 },
360 };
361
362 let format = match TexFormat::from_gl_constant(self.format) {
363 Some(format) if format.required_webgl_version() <= context.webgl_version() => format,
364 _ => {
365 context.webgl_error(InvalidEnum);
366 return Err(TexImageValidationError::InvalidTextureFormat);
367 },
368 };
369
370 if format != internal_format.to_unsized() {
373 context.webgl_error(InvalidOperation);
374 return Err(TexImageValidationError::TextureFormatMismatch);
375 }
376
377 match data_type {
389 TexDataType::UnsignedShort4444 | TexDataType::UnsignedShort5551
390 if format != TexFormat::RGBA =>
391 {
392 context.webgl_error(InvalidOperation);
393 return Err(TexImageValidationError::InvalidTypeForFormat);
394 },
395 TexDataType::UnsignedShort565 if format != TexFormat::RGB => {
396 context.webgl_error(InvalidOperation);
397 return Err(TexImageValidationError::InvalidTypeForFormat);
398 },
399 _ => {},
400 }
401
402 Ok(TexImage2DValidatorResult {
403 width,
404 height,
405 level,
406 border,
407 texture,
408 target,
409 internal_format,
410 format,
411 data_type,
412 })
413 }
414}
415
416pub(crate) struct CommonCompressedTexImage2DValidator<'a> {
417 common_validator: CommonTexImage2DValidator<'a>,
418 data_len: usize,
419}
420
421impl<'a> CommonCompressedTexImage2DValidator<'a> {
422 #[expect(clippy::too_many_arguments)]
423 pub(crate) fn new(
424 context: &'a WebGLRenderingContext,
425 target: u32,
426 level: i32,
427 width: i32,
428 height: i32,
429 border: i32,
430 compression_format: u32,
431 data_len: usize,
432 ) -> Self {
433 CommonCompressedTexImage2DValidator {
434 common_validator: CommonTexImage2DValidator::new(
435 context,
436 target,
437 level,
438 compression_format,
439 width,
440 height,
441 border,
442 ),
443 data_len,
444 }
445 }
446
447 pub(crate) fn for_sub_image(mut self) -> Self {
449 self.common_validator = self.common_validator.for_sub_image();
450 self
451 }
452}
453
454pub(crate) struct CommonCompressedTexImage2DValidatorResult {
455 pub(crate) texture: DomRoot<WebGLTexture>,
456 pub(crate) target: TexImageTarget,
457 pub(crate) level: u32,
458 pub(crate) width: u32,
459 pub(crate) height: u32,
460 pub(crate) compression: TexCompression,
461}
462
463fn valid_s3tc_dimension(level: u32, side_length: u32, block_size: u32) -> bool {
464 side_length.is_multiple_of(block_size) || (level > 0 && [0, 1, 2].contains(&side_length))
465}
466
467fn valid_compressed_data_len(
468 data_len: usize,
469 width: u32,
470 height: u32,
471 compression: &TexCompression,
472) -> bool {
473 let block_width = compression.block_width as u32;
474 let block_height = compression.block_height as u32;
475
476 let required_blocks_hor = width.div_ceil(block_width);
477 let required_blocks_ver = height.div_ceil(block_height);
478 let required_blocks = required_blocks_hor * required_blocks_ver;
479
480 let required_bytes = required_blocks * compression.bytes_per_block as u32;
481 data_len == required_bytes as usize
482}
483
484fn is_subimage_blockaligned(
485 xoffset: u32,
486 yoffset: u32,
487 width: u32,
488 height: u32,
489 compression: &TexCompression,
490 tex_info: &ImageInfo,
491) -> bool {
492 let block_width = compression.block_width as u32;
493 let block_height = compression.block_height as u32;
494
495 (xoffset.is_multiple_of(block_width) && yoffset.is_multiple_of(block_height)) &&
496 (width.is_multiple_of(block_width) || xoffset + width == tex_info.width()) &&
497 (height.is_multiple_of(block_height) || yoffset + height == tex_info.height())
498}
499
500impl WebGLValidator for CommonCompressedTexImage2DValidator<'_> {
501 type Error = TexImageValidationError;
502 type ValidatedOutput = CommonCompressedTexImage2DValidatorResult;
503
504 fn validate(self) -> Result<Self::ValidatedOutput, TexImageValidationError> {
505 let context = self.common_validator.context;
506 let CommonTexImage2DValidatorResult {
507 texture,
508 target,
509 level,
510 internal_format,
511 width,
512 height,
513 border: _,
514 } = self.common_validator.validate()?;
515
516 let compression = context
519 .extension_manager()
520 .get_tex_compression_format(internal_format.as_gl_constant());
521 let compression = match compression {
522 Some(compression) => compression,
523 None => {
524 context.webgl_error(InvalidEnum);
525 return Err(TexImageValidationError::InvalidCompressionFormat);
526 },
527 };
528
529 if !valid_compressed_data_len(self.data_len, width, height, &compression) {
532 context.webgl_error(InvalidValue);
533 return Err(TexImageValidationError::TextureFormatMismatch);
534 }
535
536 Ok(CommonCompressedTexImage2DValidatorResult {
537 texture,
538 target,
539 level,
540 width,
541 height,
542 compression,
543 })
544 }
545}
546
547pub(crate) struct CompressedTexImage2DValidator<'a> {
548 compression_validator: CommonCompressedTexImage2DValidator<'a>,
549}
550
551impl<'a> CompressedTexImage2DValidator<'a> {
552 #[expect(clippy::too_many_arguments)]
553 pub(crate) fn new(
554 context: &'a WebGLRenderingContext,
555 target: u32,
556 level: i32,
557 width: i32,
558 height: i32,
559 border: i32,
560 compression_format: u32,
561 data_len: usize,
562 ) -> Self {
563 CompressedTexImage2DValidator {
564 compression_validator: CommonCompressedTexImage2DValidator::new(
565 context,
566 target,
567 level,
568 width,
569 height,
570 border,
571 compression_format,
572 data_len,
573 ),
574 }
575 }
576}
577
578impl WebGLValidator for CompressedTexImage2DValidator<'_> {
579 type Error = TexImageValidationError;
580 type ValidatedOutput = CommonCompressedTexImage2DValidatorResult;
581
582 fn validate(self) -> Result<Self::ValidatedOutput, TexImageValidationError> {
583 let context = self.compression_validator.common_validator.context;
584 let CommonCompressedTexImage2DValidatorResult {
585 texture,
586 target,
587 level,
588 width,
589 height,
590 compression,
591 } = self.compression_validator.validate()?;
592
593 let compression_valid = match compression.validation {
597 TexCompressionValidation::S3TC => {
598 let valid_width =
599 valid_s3tc_dimension(level, width, compression.block_width as u32);
600 let valid_height =
601 valid_s3tc_dimension(level, height, compression.block_height as u32);
602 valid_width && valid_height
603 },
604 TexCompressionValidation::None => true,
605 };
606 if !compression_valid {
607 context.webgl_error(InvalidOperation);
608 return Err(TexImageValidationError::TextureFormatMismatch);
609 }
610
611 Ok(CommonCompressedTexImage2DValidatorResult {
612 texture,
613 target,
614 level,
615 width,
616 height,
617 compression,
618 })
619 }
620}
621
622pub(crate) struct CompressedTexSubImage2DValidator<'a> {
623 compression_validator: CommonCompressedTexImage2DValidator<'a>,
624 xoffset: i32,
625 yoffset: i32,
626}
627
628impl<'a> CompressedTexSubImage2DValidator<'a> {
629 #[expect(clippy::too_many_arguments)]
630 pub(crate) fn new(
631 context: &'a WebGLRenderingContext,
632 target: u32,
633 level: i32,
634 xoffset: i32,
635 yoffset: i32,
636 width: i32,
637 height: i32,
638 compression_format: u32,
639 data_len: usize,
640 ) -> Self {
641 CompressedTexSubImage2DValidator {
642 compression_validator: CommonCompressedTexImage2DValidator::new(
643 context,
644 target,
645 level,
646 width,
647 height,
648 0,
649 compression_format,
650 data_len,
651 )
652 .for_sub_image(),
653 xoffset,
654 yoffset,
655 }
656 }
657}
658
659impl WebGLValidator for CompressedTexSubImage2DValidator<'_> {
660 type Error = TexImageValidationError;
661 type ValidatedOutput = CommonCompressedTexImage2DValidatorResult;
662
663 fn validate(self) -> Result<Self::ValidatedOutput, TexImageValidationError> {
664 let context = self.compression_validator.common_validator.context;
665 let CommonCompressedTexImage2DValidatorResult {
666 texture,
667 target,
668 level,
669 width,
670 height,
671 compression,
672 } = self.compression_validator.validate()?;
673
674 let Some(tex_info) = texture.image_info_for_target(&target, level) else {
677 context.webgl_error(InvalidOperation);
678 return Err(TexImageValidationError::MissingBaseTexture);
679 };
680
681 if self.xoffset < 0 ||
686 (self.xoffset as u32 + width) > tex_info.width() ||
687 self.yoffset < 0 ||
688 (self.yoffset as u32 + height) > tex_info.height()
689 {
690 context.webgl_error(InvalidValue);
691 return Err(TexImageValidationError::InvalidOffsets);
692 }
693
694 if compression.format != tex_info.internal_format() {
697 context.webgl_error(InvalidOperation);
698 return Err(TexImageValidationError::TextureFormatMismatch);
699 }
700
701 let compression_valid = match compression.validation {
705 TexCompressionValidation::S3TC => is_subimage_blockaligned(
706 self.xoffset as u32,
707 self.yoffset as u32,
708 width,
709 height,
710 &compression,
711 &tex_info,
712 ),
713 TexCompressionValidation::None => true,
714 };
715 if !compression_valid {
716 context.webgl_error(InvalidOperation);
717 return Err(TexImageValidationError::TextureFormatMismatch);
718 }
719
720 Ok(CommonCompressedTexImage2DValidatorResult {
721 texture,
722 target,
723 level,
724 width,
725 height,
726 compression,
727 })
728 }
729}
730
731pub(crate) struct TexStorageValidator<'a> {
732 context: &'a WebGLRenderingContext,
733 dimensions: u8,
734 target: u32,
735 levels: i32,
736 internal_format: u32,
737 width: i32,
738 height: i32,
739 depth: i32,
740}
741
742pub(crate) struct TexStorageValidatorResult {
743 pub(crate) texture: DomRoot<WebGLTexture>,
744 pub(crate) target: TexImageTarget,
745 pub(crate) levels: u32,
746 pub(crate) internal_format: TexFormat,
747 pub(crate) width: u32,
748 pub(crate) height: u32,
749 pub(crate) depth: u32,
750}
751
752impl<'a> TexStorageValidator<'a> {
753 #[expect(clippy::too_many_arguments)]
754 pub(crate) fn new(
755 context: &'a WebGLRenderingContext,
756 dimensions: u8,
757 target: u32,
758 levels: i32,
759 internal_format: u32,
760 width: i32,
761 height: i32,
762 depth: i32,
763 ) -> Self {
764 TexStorageValidator {
765 context,
766 dimensions,
767 target,
768 levels,
769 internal_format,
770 width,
771 height,
772 depth,
773 }
774 }
775}
776
777impl WebGLValidator for TexStorageValidator<'_> {
778 type Error = TexImageValidationError;
779 type ValidatedOutput = TexStorageValidatorResult;
780
781 fn validate(self) -> Result<Self::ValidatedOutput, TexImageValidationError> {
782 let context = self.context;
783
784 let target = match TexImageTarget::from_gl_constant(self.target) {
786 Some(
787 target @ (TexImageTarget::Texture2D |
788 TexImageTarget::CubeMap |
789 TexImageTarget::Texture3D |
790 TexImageTarget::Texture2DArray),
791 ) if target.dimensions() == self.dimensions => target,
792 _ => {
793 context.webgl_error(InvalidEnum);
794 return Err(TexImageValidationError::InvalidTextureTarget(self.target));
795 },
796 };
797
798 let texture = bound_texture(context, target)?;
799 if texture.target().is_none() {
800 context.webgl_error(InvalidOperation);
801 return Err(TexImageValidationError::TextureTargetNotBound(self.target));
802 }
803 if texture.is_immutable() {
804 context.webgl_error(InvalidOperation);
805 return Err(TexImageValidationError::ImmutableTexture);
806 }
807
808 let internal_format = validate_internal_format(context, self.internal_format)?;
809 if !internal_format.is_sized() {
810 context.webgl_error(InvalidEnum);
811 return Err(TexImageValidationError::InvalidTextureFormat);
812 }
813 if internal_format.is_compressed() &&
814 context
815 .extension_manager()
816 .get_tex_compression_format(internal_format.as_gl_constant())
817 .is_none()
818 {
819 context.webgl_error(InvalidEnum);
820 return Err(TexImageValidationError::InvalidCompressionFormat);
821 }
822 if target == TexImageTarget::Texture3D && internal_format.is_compressed() {
824 context.webgl_error(InvalidOperation);
825 return Err(TexImageValidationError::InvalidTextureFormat);
826 }
827 if target == TexImageTarget::Texture3D &&
828 matches!(
829 internal_format.to_unsized(),
830 TexFormat::DepthComponent | TexFormat::DepthStencil
831 )
832 {
833 context.webgl_error(InvalidOperation);
834 return Err(TexImageValidationError::InvalidTextureFormat);
835 }
836
837 if self.levels < 1 {
838 context.webgl_error(InvalidValue);
839 return Err(TexImageValidationError::LevelTooLow);
840 }
841 if self.width < 1 || self.height < 1 {
842 context.webgl_error(InvalidValue);
843 return Err(TexImageValidationError::NegativeDimension);
844 }
845 if self.depth < 1 {
846 context.webgl_error(InvalidValue);
847 return Err(TexImageValidationError::DepthTooLow);
848 }
849 let levels = self.levels as u32;
850 let width = self.width as u32;
851 let height = self.height as u32;
852 let depth = self.depth as u32;
853
854 if target.is_cubic() && width != height {
855 context.webgl_error(InvalidValue);
856 return Err(TexImageValidationError::InvalidCubicTextureDimensions);
857 }
858
859 let limits = context.limits();
861 let (max_size, max_depth) = match target {
862 TexImageTarget::Texture3D => (limits.max_3d_tex_size, limits.max_3d_tex_size),
863 TexImageTarget::Texture2DArray => {
864 (limits.max_tex_size, limits.max_array_texture_layers)
865 },
866 TexImageTarget::CubeMap => (limits.max_cube_map_tex_size, 1),
867 _ => (limits.max_tex_size, 1),
868 };
869 if width > max_size || height > max_size || depth > max_depth {
870 context.webgl_error(InvalidValue);
871 return Err(TexImageValidationError::TextureTooBig);
872 }
873
874 let max_extent = match target {
876 TexImageTarget::Texture3D => width.max(height).max(depth),
877 _ => width.max(height),
878 };
879 if levels > max_extent.ilog2() + 1 {
880 context.webgl_error(InvalidOperation);
881 return Err(TexImageValidationError::LevelTooHigh);
882 }
883
884 Ok(TexStorageValidatorResult {
885 texture,
886 target,
887 levels,
888 internal_format,
889 width,
890 height,
891 depth,
892 })
893 }
894}