createTexture method

Texture createTexture(
  1. StorageMode storageMode,
  2. int width,
  3. int height, {
  4. PixelFormat format = PixelFormat.r8g8b8a8UNormInt,
  5. dynamic sampleCount = 1,
  6. TextureType? textureType,
  7. bool enableRenderTargetUsage = true,
  8. bool enableShaderReadUsage = true,
  9. bool enableShaderWriteUsage = false,
  10. int mipLevelCount = 1,
})

Allocates a new texture in GPU-resident memory.

mipLevelCount specifies the number of mip levels to allocate for the texture. The default is 1 (no mip chain). Use Texture.fullMipCount to allocate a full chain. Must be in the range [1, Texture.fullMipCount(width, height)].

Throws an exception if the Texture creation failed.

Implementation

Texture createTexture(
  StorageMode storageMode,
  int width,
  int height, {
  PixelFormat format = PixelFormat.r8g8b8a8UNormInt,
  sampleCount = 1,

  /// The type of texture to create.
  ///
  /// If not specified, this will be inferred from the `sampleCount`.
  TextureType? textureType,
  bool enableRenderTargetUsage = true,
  bool enableShaderReadUsage = true,
  bool enableShaderWriteUsage = false,
  int mipLevelCount = 1,
}) {
  final resolvedTextureType =
      textureType ??
      ((sampleCount == 1)
          ? TextureType.texture2D
          : TextureType.texture2DMultisample);
  final int maxMipLevels = Texture.fullMipCount(width, height);
  if (mipLevelCount < 1 || mipLevelCount > maxMipLevels) {
    throw Exception(
      'mipLevelCount ($mipLevelCount) must be in the range [1, $maxMipLevels] '
      'for a ${width}x$height texture',
    );
  }
  if (format.isCompressed) {
    if (enableRenderTargetUsage ||
        enableShaderWriteUsage ||
        !enableShaderReadUsage ||
        sampleCount != 1 ||
        storageMode == StorageMode.deviceTransient) {
      throw ArgumentError(
        'Compressed pixel format $format can only be used as a sample-only '
        'texture (sampleCount=1, enableShaderReadUsage=true, no render '
        'target, no shader write, and storageMode != deviceTransient)',
      );
    }
    final int bw = format.blockWidth;
    final int bh = format.blockHeight;
    if (width % bw != 0 || height % bh != 0) {
      throw ArgumentError(
        'Compressed pixel format $format requires width and height to be a '
        'multiple of the block size (${bw}x$bh), got ${width}x$height',
      );
    }
  }
  Texture result = Texture._initialize(
    this,
    storageMode,
    format,
    width,
    height,
    sampleCount,
    resolvedTextureType,
    enableRenderTargetUsage,
    enableShaderReadUsage,
    enableShaderWriteUsage,
    mipLevelCount,
  );
  // `Texture._initialize` throws on failure, so `result` is always valid here.
  return result;
}