Vector graphics on GPU
gasiulis.name
gasiulis.name
When I originally checked, Slug works in a similar way but doesn't do tiling, so it has to process more edges per scanline than Pathfinder or piet-gpu. Slug has gone through a lot of versions since then though and I wouldn't be surprised if they added tiling later.
Tiling doesn't work too well under domain transforms--3d environments, dynamic zoom, etc. That's why I am betting on high-quality space partitioning. Slug space partitioning is not amazing; I believe it still processes O(n) curves per fragment in a horizontal band.
I just implemented basically the same tiling mechanism, it works OK for me, I can already do about 1000 line segments, covering ~10000 tiles (multiply counting tiles that are touched by different polygons) in about 1ms on CPU and GPU each. Meaning the work is already quite well divided for my test cases. This is end to end without any caching. For static scenes doing world space partitioning is an idea that I considered, but for now I'm trying to optimize more in order to see what the limits of this basic approach are.
No worries, I think they know :)
And yeah, I considered doing fancier partitioning, but really toward the end (before work stopped due to layoffs) I was pushing on shipping, which meant deprioritizing fancy partitioning in favor of implementing all the bells and whistles of SVG. I certainly believe that you could get better results with more sophisticated acceleration structures, especially in cases like texturing 3D meshes with vector textures.
What did you end up moving on to after pathfinder?
> Much better approach for vector graphics is analytic anti-aliasing. And it turns out, it is not just almost as fast as a rasterizer with no anti-aliasing, but also has much better quality than what can be practically achieved with supersampling.
> Go over all segments in shape and compute area and cover values continuously adding them to alpha value.
This is approach is called "coverage to alpha". The author will be surprised to learn about the problem of coverage to alpha conflation artifacts. E.g. if you draw two shapes of exactly the same geometry over each other, but with different colors. The correct result includes only the color of the last shape, but with "coverage to alpha" you will get a bit of color bleeding around the edges (the conflation artifacts). I think Guzba also gives other examples in this thread.
Also, they did not mention the other hard problems like stroke offsetting, nested clipping and group opacity etc.
Here, IMO a good blog post about the hard problems of getting alpha blending and coverage right: https://ciechanow.ski/alpha-compositing/
What I've done in the past is representing the shape as a https://en.wikipedia.org/wiki/Signed_distance_function to allow each pixel to figure out if it is inside or outside the shape. This avoids the need to figure out the winding.
Anti-aliasing is implemented as a linear interpolation for values near zero. This also allows you to control the "thickness" of the shape boundary. The edge become mores blurry if you increase the lerp length.
Shader toy demo https://www.shadertoy.com/view/sldyRj
That problem has been solved by multi-channel signed distance fields https://github.com/Chlumsky/msdfgen
I would like to know why you think the described approach is silly? It doesn't involve a final rasterization but merely a prefiltering of segments.
Added shader toy link in my OP
SDF of a cubic bezier involves solving a quintic, so it's not analytic. There are approximations, of course, but for an outline, using an sdf is just silly. (For a stroke, you don't really have much choice--though it's common to approximate strokes using outlines.) I'll add that sdf aa is not as good as analytic aa.
(Fun fact: Firefox uses the same 2D Newton's method trick that Loop-Blinn does for antialiasing of elliptical border radii in WebRender—I implemented it a few years back.) :)
I implemented them (implicit formulation of rational cubic bezier curves) in my renderer (see one of my other replies in this thread). Here is an extract of the relevant code in a shader toy: https://www.shadertoy.com/view/WlcBRn
Even in Jim Blinn's book "Notation, Notation, Notation" he leaves some of the crucial equations as an exercise to the reader. I remember spending 2 or 3 weeks reading and trying to understand everything he wrote to derive these equations he hinted at myself.
Of course you can implement smooth circles directly in a shader the way you describe, but note that there are Vector outline shapes that are not circles...
Check out the outlines you can do using SVG - paths composed of straight line segments as well as cubic bezier curves and various arcs. Also color gradients, stroking...
If you have highly detailed characters like Chinese or emojis, you need larger resolution to faithfully represent every detail. The problem is that SDFs are sampled uniformly over the pixel grid. If the character is locally complex, a high resolution is required to display it, but if the character has simple flat regions, memory is wasted. One way to get around excessive memory requirements is to store the characters in their default vector forms and only render the subset of required characters on demand, but then you might as well render them at the required pixel resolution and do away with the additional complexity of SDF rendering.
SDFs are still useful though if you have to render graphics at many different resolutions, for example on signs in computer games, as seen in the original Valve paper https://steamcdn-a.akamaihd.net/apps/valve/2007/SIGGRAPH2007...
https://github.com/audulus/vger
and a rust version:
https://github.com/audulus/vger-rs
(which powers my rust GUI library: https://github.com/audulus/rui)
Here's the approach for rendering path fills. From the readme:
> The bezier path fill case is somewhat original. To avoid having to solve quadratic equations (which has numerical issues), the fragment function uses a sort-of reverse Loop-Blinn. To determine if a point is inside or outside, vger tests against the lines formed between the endpoints of each bezier curve, flipping inside/outside for each intersection with a +x ray from the point. Then vger tests the point against the area between the bezier segment and the line, flipping inside/outside again if inside. This avoids the pre-computation of Loop-Blinn, and the AA issues of Kokojima.
It works pretty well, and doesn't require as much preprocessing as the code in the article. Also doesn't require any GPU compute (though I do use GPU compute for some things). I think ultimately the approach in the article (essentially Piet-metal, aka tessellating and binning into tiles) will deliver better performance, and support more primitives, but at greater implementation complexity. I've tried the Piet-metal approach myself and it's tricky! I like the simpler Shadertoy/SDF inspired approach :)
> Despite vector graphics being used in every computer with a screen connected to it, rendering of vector shapes and text is still mostly a task for the CPU.
Do modern vector libraries really not use the GPU? One of the very first things I did when learning Vulkan was to use a fragment shader to draw a circle inside a square polygon. I always assumed that we've been using the GPU for pretty much any sort of vector rasterization, whether it was bezier curves or font rendering.
The specification has images that highlights some of the challenges.
There's way more to this than drawing circles and rectangles, and these hard cases are why much of path / vector graphics filling still ends up being better on CPU where you can accumulate, sort, etc which takes a lot of the work away. CPU does basically per-Y whereas this is GPU per-pixel so perhaps they're almost equal if the GPU has the square of a CPU power. Obv this isn't quite right but gives you an idea.
Video discussing path filling on CPU (super sampling and trapezoid): https://youtu.be/Did21OYIrGI?t=318 We don't talk about the complex cases but this at least may help explain the simple stuff on CPU for those curious.
Detecting when a path is antagonistic to most GPU approaches takes time, as does preparing the data however it needs to be prepared on the CPU before being uploaded to the GPU. If you can just fill the whole thing on CPU in that time, you wasted your time even thinking about the GPU.
If you can identify a simple case quickly, it's probably totally a good idea to get the path done on the GPU unless you need to bring the pixels back to the CPU, maybe for writing to disk. The upload and then download can be way slower than just, again, filling on CPU.
If you're filling on GPU and then using on GPU (maybe as a web renderer or something), GPU is probably a big win. Except, this may not actually matter. If there is no need to re-render the path after the first time, it would be dumb to keep re-rendering on the GPU each frame / screen paint. Instead you'd want to put it into a texture. Well.... if you're only rendering once and putting into a texture, this whole conversation is maybe pointless? Then what is simple is probably the best idea. Anyway lots to 2d graphics that goes underappreciated!
The reason for this is that the single 2D application that people most want to speed up is font rendering. And font rendering is also the place where the edge cases are really common.
Rendering everything else (geometric shapes) is trivial by comparison.
Text rendering is really complicated. There is a reason why we have so few text shaping engines.
2d vector graphics include things like "bones" and "tweening", which are CPU algorithms. (Much like how bone processing in 3d world is also CPU-side processing).
---------
Consider the creation of a Beizer curve, in 2d or 3d. Do you expect this to be a CPU algorithm, or GPU algorithm? Answer: clearly a CPU algorithm.
GPU algorithms generally are triangle-only, or close to it (ex: quads) as far as geometry. Sure, there are geometry shaders, but I don't think its common practice to take a Beizer Curve definition and write a Tesselator-shader for it and output (in parallel) a set of verticies. (And if someone is doing that, I'm interested in heading / learning more about it. It seems like a parallelizable algorithm to me but the devil is always in the details...).
There is a well-known paper that describes an approach how to draw bezier curves by "drawing" a single triangle. Checkout Loop-Blinn from 2005.
It can even do cubic rational bezier curves, resolution independently. And to my knowledge it is the only renderer capable of that so far.
You will need to try different nightly browsers (I think Chrome works ATM), because the WebGPU API changes and breaks all the time. Also don't forget to enable WebGPU, you can check that here: https://wgpu.rs/examples-gpu/
The WASM port is highly experimental: It currently does not use interval handlers. So for animations to run you need to constantly move the mouse to provide frame triggering events. In WebGPU MSAA is limited to 4 samples ATM, so anti aliasing will look kind of bad in browsers. And the keyboard mapping is not configured, so typing in text fields produces gibberish.
2 years ago I had a similar experience with WASM/WebGL, I tried to make use of emscripten in a sane way but it was painful to get things like event handling, file I/O and quality graphics to work. Results weren't great. When using specific libraries and coding the app in the right way from the start, porting GPU applications to the Web is allegedly easier.
If you could provide a fool-proof description how to build and set the project up in a few minutes, I would very much be willing to try your project out, it still sounds great. Or provide a few screenshots/videos just to get the idea across how it looks.
Still, my point stands that this is relatively uncommon even in the realm of 3d programmers. Unity / Unreal engine doesn't seem to do GPU-side Beizer curve processing, even if the algorithm was researched by Microsoft from 2005.
I would also like to know where Loop-Blinn is used in practice? I once did an implementation of quadratic Beziers using it, but I'm not up to doing the cubic version, it's very complex.
Its a blackbox. But Microsoft is very clear that its "hardware accelerated", whatever that means (IE: I think it means they got GPU-shaders handling a lot of details).
GDI / etc. etc. are legacy. You were supposed to start migrating towards Direct2D and DirectWrite decades ago. Cleartype itself moved to DirectWrite (though it still has GDI renderer for legacy purposes).
https://docs.microsoft.com/en-us/windows/win32/directwrite/i...
> 2d vector graphics include things like "bones" and "tweening", which are CPU algorithms. (Much like how bone processing in 3d world is also CPU-side processing).
Changing the position of bones does seem like something you would do on a CPU (or at least setting the indices of bone positions in a pre-loaded animation), but as far as I'm aware, 99% of the work for this sort of thing is done in a vertex shader as it's just matrix math to change vertex positions.
> Consider the creation of a Beizer curve, in 2d or 3d. Do you expect this to be a CPU algorithm, or GPU algorithm? Answer: clearly a CPU algorithm.
Why is it clearly a CPU algorithm? If you throw the bezier data into a uniform buffer, you can use a compute shader that writes to an image to just check if each pixel falls into the bounds of the curve. You don't need to use the graphics pipeline at all if you're not using vertices. Or even just throw a quad on the screen and jump straight to the fragment shader like I did with my circle vector.
isn't this just a tessellation basically? GPU-based tessellation is very common, mostly for meshes but can be used for line-like figure too.
I do something a bit like slug, but I'm sure slower, since slug is very optimized. (https://github.com/audulus/vger)
His latest paper is about how to handle stroking of cubic splines: https://arxiv.org/abs/2007.00308
He gives it as a talk, but you have to sign up with NVIDIA: https://developer.nvidia.com/siggraph/2020/video/sig03-vid
I actually implemented that (but using complex numbers instead of angles) in my renderer.
Also, typical GPU triangle antialiasing like MSAAx16 only gives you 16 sample levels, which is far from the quality we want out of fonts and 2D shapes. We don't have textures inside the triangles in 2D like we do in 3D, so the quality of the silhouette matters far more.
That said, this is what Direct2D does for everything except text.
At the time I looked at an nvidia rendering extension, which was described in this 2012 paper:
https://developer.nvidia.com/gpu-accelerated-path-rendering
In addition to the paper, the linked page has links to a number of youtube demos. That was 10 years ago, so I have no idea if that is still a good way to do it or if it has been superseded.
I played with it a bit, wrote a python wrapper for it, borked a fedora install trying to get real gpu support, fun times all around. Seems nobody cares about an accelerated vector graphics library.
Mesa removed support in 2015:
https://docs.mesa3d.org/relnotes/10.6.0.html
> Removed OpenVG support.
Same with the FF Rust renderer (sorry don't remember the name).
Has anyone done any image comparisons between CPU vs GPU rendering. I would be worried about potential quality and rendering issues of a GPU rendered image vs a CPU rendered reference image.
My concern was about precision of math operations on the GPU and potential differences between GPU vendors (or even different models of GPUs from the same vendor).
Thread groups are generally rectangular IME--nv is 8x4, others 8x8. So it doesn't make sense to distinguish X from Y in this respect. But yes, you do want a strategy for dealing with 'branch mispredictions'. Buffering works, and is applicable to the cpu too.
Especially when you consider what tile based renderers do for determining whether a triangle fully covers a tile (allowing rejection of any other draw onto that tile) it seems like GPUs could have built in support for 'inside a path or outside a path.' Even just approximating with triangles as a pre-pass seems faster than the row based method in the post.
Are arbitrary paths just too complex for this kind of optimization?
From my understanding there is no closed form solution to arbitrary paths defined in that way. So the only way to figure out what the shape looks like, and to figure out if a point is inside or outside, you would need to run all the commands that form the path.
> Because we evaluate wavelet coefficients through line integrals in 2D, we are able to derive analytic solutions for polygons that have Bézier curve boundaries of any order, and we provide solutions for quadratic and cubic curves.
But the row-based method in the post is not what they describe doing on the GPU version of the algorithm. The row-based method is their initial CPU-style version.
The GPU version handles each pixel in isolation, checking it against the relevant shape(s).
At least, if I understand things correctly (:
As far as I can tell, the approach described here is probably similar to what a built-in "draw path" command would do. Checking if something is inside a triangle is just extremely easy (no concavity, for instance) and common, and more complex operations are left up to shader developers — why burn that special-case stuff into silicon?
I could certainly be wrong though.
I'll be up front: you can't give me that article as input and expect usable code as an output.