Skip to content

Investigation: Generate mipmaps #386

Open

Description

@litherum

Generating mipmaps is something that most 3D applications want to do. As textures are often the largest asset 3D apps need to download, generating the smaller miplevels can save significant downloading time, causing the app to be able to launch earlier. We've heard that download times are a significant concern to Web game developers; there's a strong inverse correlation between how long a games takes to load and how many users actually end up playing the game.

WebGPU currently provides no facilities to generate mipmaps. It is true that a 3rd party library could do this, but taking an additional dependency and sending a library across the wire for something that most 3D authors will want to do seems like bad design. Indeed; the purpose of doing this in the browser is to decrease download sizes, and adding an additional framework dependency is contrary to that goal.

WebGL solved this by including WebGLRenderingContext.generateMipmap(). Developers clearly desire using this; a quick search of GitHub shows that it's used more than 46,000 times. Indeed, at least one developer is using this WebGL API to generate mipmaps and then passing the results into WebGPU.

WebGPU should provide built-in facilities for generating mipmaps. Of course, we shouldn't force developers to use the built-in facilities. It is true that different developers desire mipmap filtering algorithms, and they should be free to write their own mipmap generation code. However, for most authors, the presence of built-in mipmap generation facilities will be the difference between mipmaps existing in their app at all, and mipmaps not existing in their app.

Metal

It's a method on MTLBlitCommandEncoder. It is executed on the GPU, so the command needs to be submitted to the queue and is therefore ordered with relation to other GPU operations. Also, because this is inside a command encoder, all compute/graphics command encoders need to be closed before this can be issued.

The docs have a note:

The filtering used to generate the mipmaps is implementation-dependent and may vary by Metal feature set.

Direct3D 12

The core API doesn't have any support for generating mipmaps. However, the Microsoft-authored DirectX Tool Kit 12 includes support for it. Unfortunately, this Kit isn't included in the Windows SDK; Windows browsers would take a dependency on it. The docs say that it's implemented on top of a compute shader.

The GenerateMips function uses a DirectCompute shader to perform the mip-generation using bi-linear interpolation

Direct3D 12 doesn't have passes, so there are no concerns there. However, the API isn't a one-shot generation; instead, it's a ResourceUploadBatch object that has to be opened and closed.

Vulkan

Vulkan doesn't have any built-in facilities for generating mipmaps (because of course it doesn't). It looks like you can do it with (a ton of code around)vkCmdBlitImage, which means that any render passes need to be closed.

Compute shader

Even if Windows browsers didn't want to take a dependency on DirectX Tool Kit 12, we could still implement it using a compute shader. This would require that all render passes are closed.

Recommendation

In keeping with the current design of putting blit-style commands directly on the GPUCommandEncoder, we can add a generateMipmaps(texture) call there. This will allow for us to require that any render or compute passes are closed before it's called. Such a design should be compatible with each of the above approaches.

Activity

  1. kvark commented on Aug 2, 2019

    @kvark
    Contributor

    You've almost lost me at the first sentence :)

    Generating mipmaps is something that most 3D applications want to do.

    Most 3D applications that are performance-sensitive wouldn't want to generate mipmaps at run-time, except for some cases where texture content is not known in advance (procedurally generated, captured from the environment, etc).

    As textures are often the largest asset 3D apps need to download, generating the smaller miplevels can save significant downloading time, causing the app to be able to launch earlier.

    Mipmaps constitute for 1/3 of the original texture volume. Besides, an application can start perfectly fine while the mipmap levels are still being transferred. The best way for an app to start quickly is to pre-generate the mipmaps and start loading the higher (smaller) mips first, which would allow it to start much faster than waiting for the full textures. Once other mipmap levels arrive, an application can issue copyBufferToTexture instructions to put it into the texture. Obviously, this option is very different from the approach suggested in this PR.

    It is true that a 3rd party library could do this, but taking an additional dependency and sending a library across the wire for something that most 3D authors will want to do seems like bad design.

    Is having a 3rd party dependency such a big trouble in JS/WASM world? I'm surprised we'd be trying to reduce the ecosystem as opposed to relying on it to grow.

    Previously with setSubData we concluded that the users can just copy-paste a small function implementing this into their program. Is the main difference here the fact that a shader is involved? If that's the case, we may consider just providing blitImage method in our render pipelines:

    • it's fairly non-controversial, has been around since GL days
    • can be used to fill out the mip maps in a few lines of code
  2. magcius commented on Aug 2, 2019

    @magcius
    • Mipmaps need to be filtered differently depending on whether they are used as wrap or clamp (you would want to filter edge pixels differently)
    • Compressed textures cannot have mipmaps generated at runtime, unless we require shipping a runtime BCn compressor
    • For any sort of complex PBR model, you want to do special things to your mipmaps anyway (convolve normals with roughness, prefilter env maps)

    I would encourage that if the WebGPU WG would like runtime mipmap compression, that this is shipped as a library developed inside the WG and released as open-source for application authors to use.

  3. prideout commented on Aug 2, 2019

    @prideout

    Including a simple blitting function instead of a mipmap generator would be less controversial. Note that Vulkan provides vkCmdBlitImage with somewhat configurable filtering, but fixed to CLAMP_TO_EDGE wrapping behavior.

  4. magcius commented on Aug 2, 2019

    @magcius

    I agree with including a blit image command, though I wouldn't encourage using it in place of offline mipmap generation if possible.

  5. deltakosh commented on Aug 2, 2019

    @deltakosh

    You need to see the big picture here. We have thousands of users who are relying on us (babylon.js for instance but pretty sure Three has the same concern) to generate their mipmaps. Not every developer is a AAA game developer.

  6. kvark commented on Aug 2, 2019

    @kvark
    Contributor

    @deltakosh interesting that you mention this, because Three.js and Babylon.js are in a good position to implement it once and for all in their own codebase, using the most efficient methods available.

  7. deltakosh commented on Aug 2, 2019

    @deltakosh

    So far (for webGPU) we are using webgl so I'm not sure it is the most efficient method :) We will obviously use a different technique if the spec ends up with no other option.
    I do not care too much if this is a separate library but we try to reduce external dependencies as much as possible so I would prefer having it directly available in the browser

  8. kvark commented on Aug 2, 2019

    @kvark
    Contributor

    @deltakosh is your use of WebGL justified by the inability to generate mipmaps with WebGPU directly? I mean, just having a shader that samples an image, and then running it for each level is not too difficult for you as a framework author.

  9. deltakosh commented on Aug 2, 2019

    @deltakosh

    It is not, I agree and as I stated earlier we will do it if no other option is available. We are already resampling textures using shaders to make them POT so no big deal. But again it is more about the overall usability of the API.

    (also because of the fact that spec is not stabilized, we took some shortcuts for our first implementations)

    Also as mentioned by @magcius it is not just about sampling down a texture as we need to filter the edges differently

  10. sebavan commented on Aug 2, 2019

    @sebavan

    I am wondering why we try to push a lot of the functionalities to external lib and outside of the browser api scope. I am thinking the browser APIs is an amazing place to simplify the user code and prevent everybody from writing again the same kind of code.

    Making it a lib means we expect people to use it so why not directly integrating in the browser ? (Even more as it is not just a trivial task to do well).

    I am afraid that currently to get started I would need to install a lib for mipmaps, one to deal with buffers upload, maybe a compiler, and probably some other utils.

    What is the main issue of keeping some default utils in the spec ? Like uploading imageData, we could argue that we do not need it but is it not good to have convenience method like those for the devs ?

  11. magcius commented on Aug 2, 2019

    @magcius

    I would rather not have browser-implemented helper libraries, unless they're all guaranteed to be identical (and this is a very tricky thing to ensure). There isn't a one-size-fits-all solution, and there are a lot of constraints. The blit image approach won't work for filtering cubemap images, for instance.

    We're already seeing a huge delay getting the WebGPU MVP added into browsers. If we add it into the spec, it should not be added for MVP, and Babylon will have to ship mipmap generation code anyway...

    There will be third-party code involved, the question is whether it's shipped in the browser or shipped in the app (if we agree this is post-MVP, then it'll be shipped in both!). For platform consistency reasons, I would rather see it shipped in the app.

  12. KeepItOneHundred commented on Aug 2, 2019

    @KeepItOneHundred

    IMO the problem isn't so much with having built-in helpers, it's those helpers incentivizing developers to write inefficient code. If the browser can generate mipmaps on-the-fly then the path of least resistance is to use uncompressed textures and waste a ton of memory/bandwidth, as was the case with WebGL.

    If WebGPU is going to have high-level texture helpers then I'd rather see the effort put towards supporting Basis Universal as a first-class feature with transcoding provided by the browser, so the easy path is also the fast path.

  13. deltakosh commented on Aug 2, 2019

    @deltakosh

    Well if this is not done by the browser it will be done by the frameworks so this will not incentive users much to pick Basis path

  14. 46 remaining items

  15. Kangz commented on Mar 23, 2022

    @Kangz
    Contributor

    Unfortunately not, it isn't a required capability in Metal. We gathered some statistics on the availability in Chrome macOS installs and there's about 10% of systems with no support at all, and another 50% systems that would support only r32float for read-write storage.

  16. maierfelix commented on Jun 12, 2022

    @maierfelix

    While glGenerateMipmap is heavily used in WebGL, it is a legacy method and in my opinion, the implementation of it should be left to the authors of WebGPU-based libraries. glGenerateMipmap only works reliable in a very limited subset of cases, while in modern graphics, there are too many different and specialised scenarios to cover in a spec. It is a handy method to have during development, but the performance characteristics are too intransparent and the results are too unreliable, or not usable at all.

    @kvark

    Most 3D applications that are performance-sensitive wouldn't want to generate mipmaps at run-time, except for some cases where texture content is not known in advance (procedurally generated, captured from the environment, etc).

    Outside of regular textures, there are many use cases for generating/re-generating mipmaps at runtime, often to traverse hierarchical data structures or to approximate light traversal, e.g. LPV, VXCT (or generally where a volumetric representation is used to approximate a scene for e.g. lighting).

    Also as a side note, I found that up to today, manually generating mipmaps in WebGL without glGenerateMipmap is surprisingly hard. AFAIK there are still vendors who don't correctly implement the TEXTURE_BASE_LEVEL texture parameter, which is necessary to efficiently generate mipmaps at runtime without double buffering (and without glGenerateMipmap). Here is an example to test if TEXTURE_BASE_LEVEL works in your browser.

  17. devshgraphicsprogramming commented on Jun 13, 2022

    @devshgraphicsprogramming

    glGenerateMipmap only works reliable in a very limited subset of cases

    GL and GLES impose a limit that for glGenerateMipmap to work, the format must be color renderable (probably to allow for low-effort implementations using blit sequences).

    This gets tricky with RGB8 textures (which aren't too much of a problem since they don't exist in reality), RGB9E5 and so on.

    Also as a side note, I found that up to today, manually generating mipmaps in WebGL without glGenerateMipmap is surprisingly hard.

    Its currently a 3 month long project by @achalpandeyy in our framework Devsh-Graphics-Programming/Nabla#343

    Box Filter is a rather bad default, and there's a lot of things to worry about when implementing even that poor method.

  18. devshgraphicsprogramming commented on Jun 13, 2022

    @devshgraphicsprogramming

    Unfortunately not, it isn't a required capability in Metal. We gathered some statistics on the availability in Chrome macOS installs and there's about 10% of systems with no support at all, and another 50% systems that would support only r32float for read-write storage.

    you should at least support r32u, r32i, as otherwise I cannot do atomic image ops.

    Also just because it isn't a required capability, doesn't mean it shouldn't be exposed as a feature at all.

  19. greggman commented on Aug 3, 2023

    @greggman
    Member

    Late to this discussion and not sure why it popped up in my sites but ...

    1. I'm on the side of this belongs in the user code, not in WebGPU for all the reasons mentioned above.

    2. Similar to @toji's example (which I hadn't seen) I wrote a generator. it's here. The mipmap generator is a single function that generates from mip level 0 to texture.mipLevelCount. At the moment it also handles 2d-arrays. I thought about adding 3d support but I suspect the usage for 3d mips is low. Also, there's a bunch of image/canvas/video loading functions which make it trivial to load one or more into a texture and then generate mips.

  20. tsherif commented on Feb 10, 2024

    @tsherif

    Found this discussion super interesting, as I was curious why WebGPU couldn't generate mipmaps. One suggestion I have is to consolidate the arguments for excluding mipmap generation from WebGPU in one place for easy reference, if that hasn't been done already (maybe @greggman's WebGPU from WebGL article?). I suspect this question will come up a lot, and this thread is a long, convoluted way to get to an understanding of the situation.

  21. JolifantoBambla commented on Apr 25, 2024

    @JolifantoBambla

    I also ported SPD to WGSL, mainly so I can downsample my depth buffer but it can also generate mipmaps. It's on npm and here if anyone needs it :)

  22. toji commented on Apr 25, 2024

    @toji
    Member

    That's amazing, thanks for sharing!

  23. devshgraphicsprogramming commented on Apr 25, 2024

    @devshgraphicsprogramming

    I also ported SPD to WGSL, mainly so I can downsample my depth buffer but it can also generate mipmaps. It's on npm and here if anyone needs it :)

    SPD doesn't handle NPoT textures properly.

    Handling all corner cases is actually quite tricky:
    https://www.youtube.com/watch?v=Ol_sHFVXvC0

  24. greggman commented on Jul 23, 2025

    @greggman
    Member

    solution discussion thread here

  25. AshleyScirra commented on Jul 23, 2025

    @AshleyScirra

    Based on that discussion, it does look to me like it's really difficult to design a general-purpose library that is consistently high-performance across hardware and supports arbitrary sizes, formats, and filtering modes. Based on results there a particular problem seems to be that render passes are faster on some devices, and compute shaders faster on other devices.

    In my view it would be useful for WebGPU to provide at least something to help with this - perhaps the aforementioned image-to-image filtering blit would be a good step?

  26. greggman commented on Jul 23, 2025

    @greggman
    Member

    In my view it would first be useful to provide a library that is handles this. You can have that today. As you have experienced first hand, asking browser to fix perf issues can take years. Given you can implement a fast mipmap solution today, a solution today seems better far better than a solution several years from now over which you have no control

  27. devshgraphicsprogramming commented on Jul 24, 2025

    @devshgraphicsprogramming

    Based on that discussion, it does look to me like it's really difficult to design a general-purpose library that is consistently high-performance across hardware and supports arbitrary sizes, formats, and filtering modes. Based on results there a particular problem seems to be that render passes are faster on some devices, and compute shaders faster on other devices.

    In my view it would be useful for WebGPU to provide at least something to help with this - perhaps the aforementioned image-to-image filtering blit would be a good step?

    if you're filterting nPOT textures, then you can't really do much better than a naive Blit approach most people doing Vulkan-Tutorial do.

    Sure, you can improve upon it by using a shader, which gives you the ability to:

    • workaround certain image formats not being renderable (RGB9E5, block compressed formats) and therefore unable to be used as a blit destination
    • use a custom filtering kernel (tbh simple linear interpolation sucks)

    Using a compute shader just gives you the ability to preload the filtering footprint for a block of output texels into shared memory, but you still need to do 1 mip layer per workgroup, because what SPD does is really really specific to filter kernels which are 2x2 and PoT images (so high level mip texels align neatly over low level / high res texels).

    due to the above its best done as a WebGPU library and not in the WebGPU implementation, just how AMD SPD is a Vulkan library and not a magical thing sitting in the driver.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions