Skip to content

Rely on canvas size instead of allowing size to be configured - #2416

Closed
kainino0x wants to merge 2 commits into
gpuweb:mainfrom
kainino0x:configure-separate-size
Closed

kainino0x wants to merge 2 commits into
gpuweb:mainfrom
kainino0x:configure-separate-size

Conversation

@kainino0x

@kainino0x kainino0x commented Dec 16, 2021 •

Copy link
Copy Markdown
Contributor

Notably, this means implementations may want to (at least sometimes) defer allocating underlying textures (or swap chains) until the first getCurrentTexture() call, e.g. after the canvas width changes to avoid reallocating before the canvas height is set.

Related: #2300


Preview | Diff

@kainino0x

Copy link
Copy Markdown
Contributor Author

After a bunch of internal discussion with Chromium canvas owners about our sizing/resizing semantics, this is the design we arrived on. It makes our behavior significantly closer to existing canvas APIs (WebGL/2d canvas) and makes things a bit simpler (except for the fact that we now have to invalidate the current texture on canvas resize).

@github-actions

Copy link
Copy Markdown
Contributor

Previews, as seen when this build job started (460b7a5):
WebGPU | IDL
WGSL
Explainer

@kvark kvark left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What issue is this meant to solve? Where can we see the discussion on it?

@toji

toji commented Dec 16, 2021

Copy link
Copy Markdown
Member

I missed the discussions with Chrome's canvas owners on this topic, sorry. A few questions/concerns:

  • If I recall correctly the previous move away from using width/height was based on ambiguity in the timing of when those changes were applied and the explicit width/height in configure() was used instead to make things clearer. What's changed to resolve that issue?
  • It's a little weird to have effectively two methods of changing the canvas width and height now. If the timing issues are resolved then my not just use the canvas attributes?
  • GPUExtent3D was used for the size to allow the dictionary to mirror GPUTextureDescriptor, even if it meant that the depth was ignored. Made common use cases in JavaScript easier, because you'll often be both reconfiguring the canvas and reallocating MSAA/Depth/etc textures at the same time. I'd be a little sad to lose that if we are keeping the ability to set size in configure().

@github-actions

Copy link
Copy Markdown
Contributor

Previews, as seen when this build job started (ae4866d):
WebGPU | IDL
WGSL
Explainer

@kainino0x

Copy link
Copy Markdown
Contributor Author

What issue is this meant to solve? Where can we see the discussion on it?

The discussion was about #2300 where I tried to define the natural and intrinsic sizes for WebGPU canvases since the underlying texture (the texture which was current and is now presented) could differ from the canvas size. The opinion of folks on our canvas team was that having the drawing buffer size diverge from the canvas size was undesirable - it's unlike other canvases, kind of confusing (which size is used in different places?), and not necessary (reallocation of the swap chain can be deferred until getCurrentTexture instead of being done eagerly when the configuration or canvas size changes).

  • If I recall correctly the previous move away from using width/height was based on ambiguity in the timing of when those changes were applied and the explicit width/height in configure() was used instead to make things clearer. What's changed to resolve that issue?

It's now synchronous just like you would expect with any other canvas type:
"When a canvas with a {{GPUCanvasContext}} |context| is resized (has its width or height property changed to a new, different value), the current texture gets destroyed:"

  • It's a little weird to have effectively two methods of changing the canvas width and height now. If the timing issues are resolved then my not just use the canvas attributes?

Yes, we could do this. I partially followed WebGL's drawingBufferStorage proposal (KhronosGroup/WebGL#3222) but I don't think that's necessary. I guess it's a matter of convenience. Maybe having two ways to do the same thing is unnecessarily confusing (makes them look like they should do different things).

  • GPUExtent3D was used for the size to allow the dictionary to mirror GPUTextureDescriptor, even if it meant that the depth was ignored. Made common use cases in JavaScript easier, because you'll often be both reconfiguring the canvas and reallocating MSAA/Depth/etc textures at the same time. I'd be a little sad to lose that if we are keeping the ability to set size in configure().

This was done to make it match more closely with canvas width/height but this is a fair point. I'd be happy to change it back if we keep it.

@kvark

kvark commented Dec 22, 2021

Copy link
Copy Markdown
Contributor

Agree that having 2 ways would be unfortunate.
Also not fond of the idea to do lazy swapchain creation at the first getCurrentTexture. Yes we can, but all the rest of API is made with explicit resource allocation in mind.
Besides, I think having the logic of scaling the backbuffer onto canvas is generally useful. For example, if you are on a phone/tablet, and the screen is rotated, there is typically some sort of transition happening, i.e. it's not instant. You wouldn't want the swapchain to be recreated at each step of this transition, only at the end instead.

@kainino0x

Copy link
Copy Markdown
Contributor Author

Besides, I think having the logic of scaling the backbuffer onto canvas is generally useful. For example, if you are on a phone/tablet, and the screen is rotated, there is typically some sort of transition happening, i.e. it's not instant. You wouldn't want the swapchain to be recreated at each step of this transition, only at the end instead.

We don't need this internally in our API for people to do it. You can just set the CSS width/height - that overrides the default layout size of the canvas. Many sites do this anyway to account for the devicePixelRatio so the canvas pixels map to screen pixels instead of CSS pixels.

@kvark

kvark commented Jan 11, 2022

Copy link
Copy Markdown
Contributor

We discussed this both with editors and with Mozilla (@kdashg in particular).

TL;DR: we believe the current API serves well, and this PR shouldn't be merged.

Big Argument

My understanding is the following now. Canvas in general prefers to be controlled by width and height because it's self-sufficient. I.e. users can set huge values, like 100k by 100k, and browsers are still expected to do something reasonable. They'd scale down the contents. The resulting image will be blurrier, but it's not a failure.

This is possible with WebGL, but it's not possible with WebGPU. Reason being that for WebGPU a canvas is just providing a texture to render to. WebGPU user can copy to/from this texture or render to it in a pass that also uses other attachments. These other attachments have to have the same size, and copies have to be within bounds. Typically, there is a depth texture managed by the user, which needs to be resized.

In other words, generally Canvas separates the notion of user-visible surface and what is actually rendered by the hardware. For WebGPU the only way reasonable way to separate them is to detach the surface configuration from the canvas size. This is exactly what we have today.

Smaller Arguments

Having 2 very similar ways to do the same thing (canvas attributes vs configure()) would also be unfortunate and unnecessary.

If we allow width and height to control the surface size, we'd have a bit of a trouble specifying the validation for it. There needs to be a bit of validation logic to check that surface width and height are within the limits, and a particular place for this to happen. I see configure() as the ideal place for this.

@kainino0x

Copy link
Copy Markdown
Contributor Author

Canvas in general prefers to be controlled by width and height because it's self-sufficient. I.e. users can set huge values, like 100k by 100k, and browsers are still expected to do something reasonable. They'd scale down the contents. The resulting image will be blurrier, but it's not a failure.

In other words, generally Canvas separates the notion of user-visible surface and what is actually rendered by the hardware.

I don't exactly agree. Canvas size exists to set the drawing buffer size. In 2d canvas there are no bounds on the size. In WebGL the canvas size influences the drawing buffer size but the browser has prerogative to use a different size if the requested size is too big.

This WebGPU proposal accounts for this: you can't getCurrentTexture if the canvas is too large. Since getCurrentTexture returns a new GPUTexture object, this logically directly follows from the size validation inside createTexture.

This limitation doesn't create problems for users because the only reason you need to set the canvas size is to set its drawing buffer size. For everything else, there's CSS.

kainino0x added a commit to kainino0x/gpuweb that referenced this pull request Jan 22, 2022
Previously, there was *some* validation inside configure(), but it only
covered a subset of the rules that were later covered by createTexture
inside getCurrentTexture(). This moves all of the validation to
getCurrentTexture() so it's not effectively duplicated.

Resolves an issue where configure() attempted to do device-timeline
validation but actually needed to do it on on the content timeline.

Extracted from gpuweb#2416.
kainino0x added a commit to kainino0x/gpuweb that referenced this pull request Jan 22, 2022
Previously, there was *some* validation inside configure(), but it only
covered a subset of the rules that were later covered by createTexture
inside getCurrentTexture(). This moves all of the validation to
getCurrentTexture() so it's not effectively duplicated.

Resolves an issue where configure() attempted to do device-timeline
validation but actually needed to do it on on the content timeline.

Extracted from gpuweb#2416.
kainino0x added a commit to kainino0x/gpuweb that referenced this pull request Jan 22, 2022
Previously, there was *some* validation inside configure(), but it only
covered a subset of the rules that were later covered by createTexture
inside getCurrentTexture(). This moves all of the validation to
getCurrentTexture() so it's not effectively duplicated.

Resolves an issue where configure() attempted to do device-timeline
validation but actually needed to do it on on the content timeline.

Extracted from gpuweb#2416.
@kainino0x

Copy link
Copy Markdown
Contributor Author

A point I brought up on the editors' call today which needed some expansion:

DOM APIs including Canvas are, by design, very "lazy" - for example in 2d canvas/webgl, changes like width/height have to be queued up until later to make sure drawing buffers aren't allocated redundantly. But overall, this is the nature of the web for a lot of reasons. Decisions like whether to use an overlay/underlay/etc are very dynamic and can change due to other contents on the page, what part of the page the user is scrolled to, system state including other frames/tabs, etc. This isn't to say that the browser could never early-allocate swap chains (in configure()), but that we shouldn't take it as a given or a constraint since I think often we'll still want to wait until getCurrentTexture() anyway. Performance-wise, late-allocation would only be detrimental immediately after configuration/size changes, and I think the detriment is minimal.

All that said, I think the biggest objection to WebGPU's current sizing API was basically that canvas already has two sizing states (.width/.height and CSS) and we would be introducing a third (configure()). I think that's a fair objection, and worth weighing against being able to do things earlier.

@kainino0x

Copy link
Copy Markdown
Contributor Author

#2536 extracts part of this PR if we decide we want to land it prior to figuring out the canvas width/height stuff.

@kainino0x

Copy link
Copy Markdown
Contributor Author

editors discussed and still would be happy if we completely ignored canvas width/height in our presentation model. (Would even remove the size-defaulting behavior from configure().) So really probably need a discussion with canvas spec people in the room, at least the ones at Google advocating that we shouldn't do that.

@kdashg

kdashg commented Feb 8, 2022

Copy link
Copy Markdown
Contributor

Let's touch on this in the F2F.

@kainino0x

Copy link
Copy Markdown
Contributor Author

We should probably also talk about how we deal with canvases getting too big for the device limits (discussed in #2520).

I'll see if we can get input from the Chrome canvas folks I talked to.

@annevk

annevk commented Feb 8, 2022

Copy link
Copy Markdown
Contributor

FWIW, #2416 (comment) matches my understanding. And is also how it works for 2D canvas. The "drawing buffer" is determined by width/height, and what is ultimately rendered is determined by CSS. It's not clear to me from the other comments why WebGPU needs a different model from that.

@kvark

kvark commented Feb 9, 2022

Copy link
Copy Markdown
Contributor

We talked with @annevk on matrix a bit, and they basically suggest us to remove configure/unconfigure entirely. Instead, we'd pass GPUCanvasConfiguration to the attributes parameter of HTMLCanvasElement.getContext(name, attributes). And this dictionary wouldn't have the width/height, which would be taken from the canvas itself.
I trust Anne to reflect Mozilla's position on this, although I don't think we are all in sync yet, still.

@toji

toji commented Feb 10, 2022

Copy link
Copy Markdown
Member

One other consideration if we went with a getContext()-based configuration pattern is that getPreferredFormat() is currently on the context. Since we wouldn't want developers querying a context just so they could see what the preferred format was so that they could re-configure the context with it, that would need to move elsewhere. Most logical point would be on the GPUAdapter, and probably end up looking something like:

const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();

const format = adapter.getPreferredFormat(canvas);
const context = canvas.getContext('webgpu', {
  device,
  format,
  compositingAlphaMode: 'premultiplied'
});

Not terrible, just more shuffling.

@toji

toji commented Feb 10, 2022

Copy link
Copy Markdown
Member

Sketched out the getContext() route in spec form to help facilitate this discussion: #2593

@kainino0x

kainino0x commented Feb 12, 2022 •

Copy link
Copy Markdown
Contributor Author

I spent some time investigating the WebGL issue KhronosGroup/WebGL#3360 (comment)
in service of this issue and #2520. See there for investigation into parallels with the <img> element. Here are some more thoughts.

WebGL has automatic downsizing, which results in gl.drawingBufferWidth being smaller than canvas.width.
configure() gives us an API surface to have automatic downsizing but make it opt-in: if you specify the size in configure() and it's too large, you get an error; if you don't (perhaps say "auto"), we use the canvas's size as a request, and you must check what size GPUTexture you actually got (e.g. gpucanvascontext.textureWidth). Presumably by default this would just downscale the canvas.width/.height to the device's texture size limits, but we could even (in the future) add more magical modes, like one to try to match the physical pixel size of the canvas!

Context:

The intrinsic [natural] dimensions of the canvas element when it represents embedded content [true if it has a context, AFAIU] are equal to the dimensions of the element's bitmap. [spec]

When the drawImage() method is invoked...
If the sx, sy, sw, and sh arguments are omitted, then they must default to 0, 0, the image's intrinsic width in image pixels, and the image's intrinsic height in image pixels, respectively.

Options mirroring the ones I wrote in that WebGL comment:

  1. intrinsic size = .width/.height, but
    natural dimensions = bitmap dimensions = .textureWidth/.textureHeight.
    This is like <img>. I believe this is what #2300 did.
    Problem with this: if there is any automatic sizing other than just for device limits (e.g. for OOM, or for device pixels), it can substantially affect the behavior of applications, e.g. drawImage will draw a differently sized rectangle.
  2. intrinsic size = natural dimensions = .width/.height, but
    bitmap dimensions = .textureWidth/.textureHeight.
    This would conflict with the HTML spec quote above, but otherwise is similar to option 3.
  3. intrinsic size = natural dimensions = bitmap size = .width/.height, and
    only the returned GPUTexture is .textureWidth/.textureHeight.
    That underlying data just gets scaled up to the "bitmap dimensions" when the canvas is used as a bitmap.
    I tentatively like this option for both WebGPU and WebGL.

@toji

toji commented Mar 17, 2022

Copy link
Copy Markdown
Member

@kainino0x, @austinEng, and I talked with @junov this morning to get his perspective on the canvas integration.

The overview is that Justin feels that there's a good opportunity here to "fix legacy canvas behavior", and as a result we shouldn't feel compelled to match older canvas interfaces simply for the sake of consistency. This is especially true in cases where the current canvas behavior has been observed to cause problems. For example:

  • WebGL developers have long complained about the 1:1 canvas:context association and the fact that rendering to more than one canvas at once isn't naturally supported.
  • Calling getContext() multiple times to reconfigure is strange and unexpected, breaks expectations about how that API is called even if there's nothing in the spec explicitly forbidding it. However, setting context attributes once and locking them in for the lifetime of the context is also problematic, and has been the source of a fair amount of frustration in WebGL (that you can't change antialiasing after context creation, for example.) Better to establish a new pattern, like what we have with configure() currently.
  • Relying on width/height attributes which also have style side effects to determine render target size can be problematic, and may cause difficulties with things like Flex Box, especially when developers are trying to display canvas contents with a 1:1 pixel ratio. (Kai has been working on a demonstration of the issue.) As Justin's put it: "It would be good to have values flow from ResizeObserver directly into configure() and keep CSS out of it."

(Worth noting that Justin did not express an opinion on using width/height as defaults for configure() as we currently do.)

These are solid arguments as far as we are concerned, as a result Kai and I are both going to advocate for keeping the canvas configuration behavior as-is in the spec. We may want to add some text, normative or otherwise, drawing parallels with <img> tags intrinsic width/height, because we see it as a comparable situation.

@annevk, given that you advocated for sticking closer to the behavior of other contexts in the past I'd like to get your thoughts on the arguments above?

@kainino0x

kainino0x commented Mar 17, 2022 •

Copy link
Copy Markdown
Contributor Author
  • Kai has been working on a demonstration of the issue.

Here's the test case: https://codepen.io/kainino0x/pen/popgeKx
It's not very clear what's going on, but essentially, if you try to use ResizeObserver to set the .width/.height of a canvas, then any CSS that relies on the canvas.width/.height to do layout (such as flexbox) results in a feedback loop:

  • resize canvas to match device pixel size from ResizeObserver
  • layout size changes, trigger relayout
  • canvas pixels no longer match device pixels, and ResizeObserver triggers due to resize
  • repeat

@annevk

annevk commented Mar 17, 2022

Copy link
Copy Markdown
Contributor

It would help a lot if these arguments came with some sample code to compare the "legacy way" that may or may not be able to address them and the "new way" that would fix it.

To me it's not particularly legacy as it's the only way to do 2d and bitmaprenderer and I don't see those disappearing. I trust that the webgl and webgl2 integration were not satisfactory, but it's not clear from the above if that could have been addressed by making different decisions or if there was a more fundamental flaw.

As for the above demo, could you not fix that by setting the width and height CSS properties to auto or max-content or some such? Or at least changing those first?

@kainino0x

kainino0x commented Mar 17, 2022 •

Copy link
Copy Markdown
Contributor Author

(partial response)

As for the above demo, could you not fix that by setting the width and height CSS properties to auto or max-content or some such? Or at least changing those first?

Both auto and max-content rely on the canvas.width/.height to determine the layout size. You have to use some CSS size which does not, like 100% or 50px, to avoid that.
The standard workaround (EDIT: I think) (which I've now documented in the codepen) would be to put an extra div around each canvas, have that div participate in flexbox, and set the canvas size to 100%.

However I do see that as a workaround, not something fundamentally makes sense. Going back to the comparison with the <img> element: you can set img.width/.height to fixed values that aren't tied to the underlying image file, and those participate in layout so the underlying image file's size doesn't (and relayout doesn't occur when the file loads in or src changes). The <img> element sizing semantic is exactly the one we want.

@kainino0x

Copy link
Copy Markdown
Contributor Author

It would help a lot if these arguments came with some sample code to compare the "legacy way" that may or may not be able to address them and the "new way" that would fix it.

Not sample code, but:

2d/webgl sizing: If using ResizeObserver or devicePixelRatio to match canvas.width/.height with screen pixels, must be careful to override the CSS width/height to modes which cut the layout dependence on canvas.width/.height to break the feedback loop. (Yes, people figure out how to get it right, but why not try to improve?)
Proposed sizing: Use canvas.width/.height just to set the layout size (like <img>), set underlying bitmap size separately. Can't accidentally create a feedback loop.

getContext: either the canvas has to be replaced to change any attributes, or we break strongly established expectations that getContext attributes are ignored after the first call.
configure: eliminates ambiguity, sidesteps the strange established behavior of getContext attributes.

To me it's not particularly legacy as it's the only way to do 2d and bitmaprenderer and I don't see those disappearing. I trust that the webgl and webgl2 integration were not satisfactory, but it's not clear from the above if that could have been addressed by making different decisions or if there was a more fundamental flaw.

I think this is unfair to WebGL. I personally think 2d canvas fits into the platform just as poorly as WebGL, and I think that's fair because both are quite old and predate a lot of design direction that the Web has today. Bitmaprenderer is a small API and chose to match 2d closely since 2d canvas is how you did it before bitmaprenderer existed.

And given that all three APIs are wildly different as soon as you get past the canvas setup, I don't see value in artificially trying to make canvas setup look (but not behave) extremely similar.

@toji

toji commented Mar 17, 2022 •

Copy link
Copy Markdown
Member

Regarding WebGL targeting multiple canvases, as of the advent of ImageBitmapRenderers you are able to do this:

// WebGL/Canvas2D path
const glCanvas = document.createElement('canvas');
const gl = glCanvas.getContext('webgl', { preserveDrawingBuffer: true });

const outputCanvasA = document.createElement('canvas');
const imgCtxA = outputCanvasA.getContext('bitmaprenderer');
const outputCanvasB = document.createElement('canvas');
const imgCtxB = outputCanvasB.getContext('bitmaprenderer');

async function onFrame() {
   // Clear and Draw with gl
  const imgA = await createImageBitmap(glCanvas);

  // Clear and Draw with gl
  const imgB = await createImageBitmap(glCanvas);

  imgCtxA.transferFromImageBitmap(imgA);
  imgCtxB.transferFromImageBitmap(imgB);

  requestAnimationFrame(onFrame);
}

Note the requirement for using await to get the ImageBitmaps, which can be problematic for some use cases. Also note that bitmaprenderer wasn't available till Safari 15 and still has some compatibility issues in Firefox (according to MDN), so the ability to do this at all is a recent development. Also, I think this requires the WebGL context to be created with preserveDrawingBuffer which has some associated overhead and requires copies. Another way around it, though more expensive, would be to use 2d contexts rather than bitmaprenderer and passing the glCanvas to a ctx.drawImage() call. This involves another copy, however.

In comparison, with WebGPU the pattern that we have established is the following:

// WebGPU path
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();

const outputCanvasA = document.createElement('canvas');
const gpuCtxA = outputCanvasA.getContext('webgpu');
gpuCtxA.configure({ device, format: 'bgra8unorm' });
const outputCanvasB = document.createElement('canvas');
const gpuCtxB = outputCanvasB.getContext('webgpu');
gpuCtxB.configure({ device, format: 'bgra8unorm' });

async function onFrame() {
  const textureA = gpuCtxA.getCurrentTexture(); 
  // Clear and Draw with device to textureA

  const textureB = gpuCtxB.getCurrentTexture(); 
  // Clear and Draw with device to textureB

  requestAnimationFrame(onFrame);
}

Note that the render loop no longer requires awaits or copies, since we are rendering into the textures that will be displayed on each canvas directly. This makes it more lightweight to output to multiple canvases as well as allowing developers to better control the timing of their rendering, since no async methods are required.

@toji

toji commented Mar 17, 2022

Copy link
Copy Markdown
Member

Regarding reconfiguring contexts after creation:

Imagine you are viewing a game that has a checkbox for "Enable/Disable Antialiasing". Because this is a context creation argument in WebGL, checking that box would require destroying the entire context and canvas, losing all the graphics resources you've loaded in the process. Obviously this may be a lengthy, disruptive process.

const antialiasCheckbox = document.querySelector('antialiasEnabled');

let glCanvas = document.createElement('canvas');
let gl = glCanvas.getContext('webgl', { antialias: antialiasCheckbox.checked });

loadAllGameResources();
startGame();

antialiasCheckbox.addEventListener('click', () => {
  pauseGame();
  destroyAllGameResources();

  glCanvas = document.createElement('canvas');
  gl = glCanvas.getContext('webgl', { antialias: antialiasCheckbox.checked });

  loadAllGameResources();
  resumeGame();
});

WebGPU addresses this in a slightly different way, where the decision about whether to have antialiasing or not doesn't happen at the canvas level, but there are still similar configuration options that may need to be toggled. By having a separate context configuration for the device we can do so less disruptively:

const hdrCheckbox = document.querySelector('hdrEnabled');

const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
let gpuCanvas = document.createElement('canvas');
let gpuCtx = glCanvas.getContext('webgpu');
gpuCtx.configure({
  device,
  format: hdrCheckbox .checked ? 'rgba16float' : 'bgra8unorm'
});

loadAllGameResources();
startGame();

hdrCheckbox.addEventListener('click', () => {
  gpuCtx.configure({
    device,
    format: hdrCheckbox .checked ? 'rgba16float' : 'bgra8unorm'
  });
});

@annevk

annevk commented Mar 18, 2022 •

Copy link
Copy Markdown
Contributor

The <img> element sizing semantic is exactly the one we want.

But that is how <canvas> works today, no? You can set width and height CSS properties to different values from the intrinsic values, which are given by the width and height content attributes. (width and height properties derive from the width and height attributes when not set themselves, but that's the same as with <img>.)

(Note that for <img> you don't want to manipulate the attributes to be incorrect either, aspect-ratio-wise. See discussion in WICG/intrinsicsize-attribute#16 which ultimately resulted in a number of changes to the HTML Standard, including for <canvas>.)

@annevk

annevk commented Mar 18, 2022

Copy link
Copy Markdown
Contributor

I don't think I have a big problem with configure() per se, although it would seem nicer if you could pass the arguments directly to getContext(), at least for the initial call. But I do think introducing yet another width/height dimension is wrong.

Is there a reason you need to pass device to configure() again? That seems somewhat annoying if you only want to reconfigure specific aspects of the context.

@toji

toji commented Mar 18, 2022

Copy link
Copy Markdown
Member

I think it would be reasonable to allow developers to pass a GPUCanvasConfiguration to the initial getContext() call as a convenience.

Also, given that we have unconfigure() we could treat an undefined device as a signal to leave the previously configured device in place. (We'd probably want to do the same for format for consistency if we went in that direction.) I worry that the configuration rules start to become less self-evident at that point, though.

@kainino0x

kainino0x commented Mar 19, 2022 •

Copy link
Copy Markdown
Contributor Author

But that is how <canvas> works today, no? You can set width and height CSS properties to different values from the intrinsic values, which are given by the width and height content attributes. (width and height properties derive from the width and height attributes when not set themselves, but that's the same as with <img>.)

<canvas> today (usually) has two sizes: the CSS properties, and the element attributes. (It has a third size when a WebGL canvas can't allocate at the requested size, but let's ignore that.)

<img> has three sizes: the CSS properties, the element attributes (optional), and the dimensions of the image file (if loaded). The natural dimensions (fka intrinsic dimensions) are derived here. When used as a paint source, for example, the file dimensions are used, and the element attributes are ignored. The split between natural dimensions and "dimension attributes" is somewhat described here. I can't find any reference to intrinsic size so maybe that's the wrong way to go about speccing behavior that matches <img> (as attempted in #2300).

@kainino0x

Copy link
Copy Markdown
Contributor Author

As to the rest of the configuration options - I think they're a lot less fundamental and intricate than the sizing issue, and I have no real opinions on what shape the API takes, just would like the configuration to be mutable. It seems best to come to a conclusion on the sizing question, then make everything else fit with it.

@toji

toji commented Mar 28, 2022

Copy link
Copy Markdown
Member

Friendly ping, @annevk. We were discussing this in the WebGPU editor's sync today and wanted to know if you had any thoughts on Kai's response?

@annevk

annevk commented Apr 6, 2022

Copy link
Copy Markdown
Contributor

I don't really see how <img> has three sizes. The width and height content attributes control the aspect ratio as I pointed out above, but otherwise they directly map to the CSS properties. With <canvas> the width and height attributes serve the same purpose as the actual image file does in the case of <img>, they provide the intrinsic size, not the styled size.

In the past <canvas>'s design was such that it allowed for a third size, to allow for "HD backing", but that got obsoleted in favor of web content upscaling the values of the width and height attributes and downscaling using width and height CSS properties. I don't think we want to go back on that decision and end up making it inconsistent across contexts.

@kainino0x

Copy link
Copy Markdown
Contributor Author

@annevk thanks as always for your input. Apologies for the long reply.

I don't really see how <img> has three sizes. The width and height content attributes control the aspect ratio as I pointed out above, but otherwise they directly map to the CSS properties.

Sorry, I don't quite understand. An <img> element has three pieces of independent state (all optional): the file dimensions, the element width/height, and the css width/height. Yes, the element size and css size both exist (only?) to influence the final layout size, but they're still separate states.

With <canvas> the width and height attributes serve the same purpose as the actual image file does in the case of <img>, they provide the intrinsic size, not the styled size.

I'm sure I'm missing something, but that seems like just one possible interpretation. The canvas element width/height is one piece of state that's used as input to both the intrinsic size / drawing buffer size and the final layout size. They do influence the intrinsic size, unlike in img, but I don't see why they have to be equal to the intrinsic size, just as an <img> element's width/height attributes don't have to be equal to the intrinsic dimensions (of the file).

(As an aside though, I did realize that unfortunately img and canvas seem to have slightly different default css, so they can't quite converge in behavior. https://codepen.io/kainino0x/pen/QWamGeQ)

In the past <canvas>'s design was such that it allowed for a third size, to allow for "HD backing", but that got obsoleted in favor of web content upscaling the values of the width and height attributes and downscaling using width and height CSS properties. I don't think we want to go back on that decision and end up making it inconsistent across contexts.

I definitely get the desire not to go back on that, but I believe 2d canvas is actually the only context where it's strictly true that the canvas element's width/height are equal to the intrinsic dimensions:

@annevk

annevk commented Apr 7, 2022

Copy link
Copy Markdown
Contributor

@kainino0x I will grant you that they are separate state, but in terms of influencing the final processing model the width and height content attributes only end up contributing an aspect ratio. They do not contribute a separate width/height from the CSS properties.

As for <canvas>, I'm not sure how that's one possible interpretation? That's literally how they are defined.

As for "bitmaprenderer", it doesn't seem to be defined how that actually works. If you're correct that might well invalidate some statements I've made, but it doesn't seem to be defined in sufficient detail at the moment how that actually works.

@kainino0x

kainino0x commented Apr 9, 2022 •

Copy link
Copy Markdown
Contributor Author

As for "bitmaprenderer", it doesn't seem to be defined how that actually works.

I definitely don't have a comprehensive understanding of the spec, but it seems defined to me:

https://html.spec.whatwg.org/multipage/canvas.html#the-canvas-element

The intrinsic dimensions of the canvas element when it represents embedded content are equal to the dimensions of the element's bitmap.

https://html.spec.whatwg.org/multipage/canvas.html#set-an-imagebitmaprenderingcontext's-output-bitmap

When a user agent is required to set an ImageBitmapRenderingContext's output bitmap
...
Set context's output bitmap to refer to the same underlying bitmap data as bitmap, without making a copy.

except I'm not 100% sure that the "canvas's bitmap" = the "context's output bitmap".
The 2d context also has a "context's output bitmap" but I also don't see where it's connected to "canvas's bitmap". I think it's implicit.

(EDIT: accidentally sent before I finished writing)

@kainino0x

Copy link
Copy Markdown
Contributor Author

(edited previous message to complete the thought)

@kainino0x I will grant you that they are separate state, but in terms of influencing the final processing model the width and height content attributes only end up contributing an aspect ratio. They do not contribute a separate width/height from the CSS properties.

State is really what I was talking about here, but it's fair to consider the ways the state is used. We're far into territory I'm poorly-versed in, so it's likely I have misstated something. So to try to clarify: what I want (and believe is already true) is for canvas to have the same 3 states as img, that influence layout in the same way. The differences are:

  • In img, all three states are optional. In canvas, the bitmap always has dimensions, and the width/height attributes have default values.
  • The canvas attributes sometimes also influence the bitmap dimensions/intrinsic dimensions, depending on the context type.
  • The two elements have different default CSS(?).

As for <canvas>, I'm not sure how that's one possible interpretation? That's literally how they are defined.

The spec does say "The canvas element has two attributes to control the size of the element's bitmap: width and height." I'm not sure if this is the sentence you're talking about, but my interpretation of this sentence is that the attributes influence the size of the element's bitmap (in a context-specific way), not that they equal the size of the element's bitmap. The wording is unclear, and it does seem very likely that the original author intended the "equal" interpretation. But there is a lot of language around the canvas element in the HTML spec that was clearly written with only "2d" canvases in mind, so I take the wording to be a sort of historical accident.

In any case, the "equal" interpretation still seems to conflict with "bitmaprenderer" and WebGL, while the "influence" interpretation is compatible with WebGL and not-strictly-conflicting with "bitmaprenderer".

@annevk

annevk commented Apr 19, 2022 •

Copy link
Copy Markdown
Contributor

When I play with "bitmaprenderer" I get different results from what the specification describes: https://software.hixie.ch/utilities/js/live-dom-viewer/saved/10227. According to the specification the intrinsic dimensions of the canvas would be that of the image and those would also be used for rendering (according to the Rendering section). However, the canvas element appears smaller than the image and in case of Firefox the image ends up cropped.

I filed whatwg/html#7833 to further discuss that.


As I mentioned earlier I don't think state is super meaningful here as there's a lot of redundant state. E.g., the fact that the values of the width and height attributes also have a string representation when accessed in particular ways. What matters are the intrinsic width/height/aspect-ratio and the layout width/height/aspect-ratio and how those are controlled.

One way to get where you want to be would be to say that the canvas width and height attributes also contribute to layout, but that is not how they are currently defined. (And I don't think that would be an improvement.) They only contribute to intrinsic dimensions. (Which is why "bitmaprenderer" is poorly defined.)

@kainino0x

Copy link
Copy Markdown
Contributor Author

Given Anne's strong stance on this - and ongoing discussions about whether bitmaprenderer should even work this way, I'm proposing to remove size entirely from the configure() call and rely directly on canvas.width/height.
This is almost the same as this PR, but this PR is very old. So I've revived it in a new PR, #2826.

@kainino0x kainino0x closed this May 6, 2022
@kainino0x
kainino0x deleted the configure-separate-size branch May 6, 2022 03:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants