39,418 karma · joined Nov 27, 2008 (18y ago) · 20,037 submissions
comment 12h ago · link · parent
Despite the artifacts at regular font sizes I see with the current version of vriffle, its text rendering is dramatically superior to what mainstream UI toolkits provide, at least to my eye. Mainstream UI toolkits do not provide Knuth–Plass paragraph wrapping, any hyphenation at all, or any justification, and many of them do not even provide subpixel glyph positioning. Consequently, their text rendering quality more closely resembles that of an amateur desktop publishing flyer printed from a Macintosh SE than that of a properly typeset book. vriffle is closer to a properly typeset book, unless you set the text to be blurry or outlined or something.
The slight artifacts in its letterforms are smaller than the variability in inking you see in a book printed from hot lead. Mostly they have the effect of making DejaVu Serif look slightly more like a slab-serif font, which improves its readability at small point sizes.
Moreover, vriffle's approach provides continuously variable font sizes and font weights, which mainstream UI toolkits do not.
Finally, on my laptop, it's rendering 1080p frames in 3–5 milliseconds on one of the laptop's four cores, so at 60fps it's only using about 25% of one core, which is 6% of the CPU. This is a long way from pegging the CPU, and that's redoing the layout and rasterization from scratch on every frame, which you don't have to do if you're just rerendering to scroll. The compositing step is more like 1–2 milliseconds, but I think that's only because of a performance bug; with luck I'll be able to speed that up 4× today.
But, you might ask, what about the 4K display at 120fps we were originally talking about? That's 4 times the pixels twice as often, but that would still only be 50% of my CPU. And, as I understand it, this laptop's HDMI port isn't physically capable of more than 1080p output at 144Hz. If you were building a machine to drive a bigger display, I imagine you'd use a higher-end CPU to do it.
comment 1d ago · link · parent
But that's still slower than memcpy(), although it was 60% faster than memcpy() on the Xeon it was initially tested on. Hopefully I can fix that today!
comment 1d ago · link · parent
If you're not familiar with some of these algorithms, just know that, for the most part, they're significantly more demanding than the layout systems used by Real Applications (if a browser is a Real Application, anyway) and produce much better results.
On my 1080p display (¼ of 4K) Riffle runs in the range 120–300 frames per second on one of my four cores, at roughly 1 gigapixel per second. However, my LCD is only 60 fps.
I tried to record a video with OBS, but not only did the extra load slow Riffle down to only about 70fps, but OBS started missing most of the screen frames I was seeing when Riffle updated the screen rapidly, adding serious jank to the recording that wasn't there in real life. Worse, my attempts to compress the resulting file with ffmpeg to anything resembling a reasonable size made complete garbage out of the text. So you'll have to run it yourself if you want to see it.
On one core of the Xeon it was first tested on, it draws roughly 3.5 gigapixels per second, which is about 60% faster than memcpy and would be about 400 frames per second at 4K resolution. On my Ryzen 5 3500U laptop, it manages about 1.1 gigapixels per second, which is 55% slower than memcpy and barely over 120 frames per second. I'm hoping I can improve that today.
Although most of the algorithms I'm using produce much higher-quality output than Real Applications, I did do two things that compromise output quality slightly to get speed:
1. Compositing the dark antialiased text onto the light background is done with elementwise minimum rather than standard α-multiplication. This is an imperceptible difference visually, but roughly doubles the fill rate even without LCD subpixel compositing, which it provides for free.
2. The glyph atlas for each frame is generated from a piecewise-linear sampled approximation of the font SDF, which is generated at startup. (Initially, I was just rendering the frame directly from the SDF, but on the Xeon that was only hitting about 1 gigapixel per second.) At large font sizes this produces visible artifacts. However, it also provides continuously variable font size, weight, and outlining.
Again, I don't want to claim that rendering the UI on the CPU is better than doing it on the GPU. Doing it on the GPU is better! But doing it on the CPU is totally tolerable, very far from "pegging the CPU while scrolling [on] a 4k120hz display".
If you want to try it out, it's at https://canonical.org/~kragen/sw/riffle-packed.tar.gz.
comment 1d ago · link · parent
It looks like GCC is failing to vectorize your blend() call in the inner loop, which is one key factor that limits your fill rate. In the listing file, I see `movzbl (%rdx,%rax), %r13d; imull $65793, %r13d, %r13d` generated from blend() with `gcc -Wa,-adhlns=codedokode.lst $(pkg-config --cflags freetype2) -O2 -g -c codedokode.c`, using Debian GCC 12.2.0-14. That multiplier is 0x010101, converting grayscale to BGRA. If you want to alpha-blend your pixels, as blend() suggests, you definitely need to vectorize that. That's not rocket science. It's more or less why we got MMX back in the Pentium Pro days. You can see my code for doing it, using GCC vector extensions rather than SSE intrinsics, at https://gitlab.com/kragen/bubbleos/-/blob/master/spikes/veca....
Also, as you can easily see, your code has 2× overdraw, visiting the whole framebuffer roughly from beginning to end twice:
/* Render the whole text grid into the framebuffer. Every cell is blended
* (no early-out on zero alpha) so the cost per letter is constant. */
static void render_text(uint32_t *buf)
{
for (size_t i = 0; i < BUF_PIXELS; i++) {
buf[i] = BG_COLOR;
}
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
const int idx = text[row][col] - FIRST_CHAR;
const int x0 = col * CELL_W;
const int y0 = row * LINE_H;
for (int y = 0; y < CELL_H; y++) {
uint32_t *dst = buf + (size_t)(y0 + y) * SCREEN_W + x0;
const uint8_t *src = glyph_cache[idx][y];
for (int x = 0; x < CELL_W; x++)
dst[x] = blend(/* dst[x] */BG_COLOR, FG_COLOR, src[x]);
}
}
}
}
That means two cache misses per cache line in the framebuffer. So every pixel has to travel from the CPU cache out to SDRAM once when it's set, then a second time from SDRAM back into the cache when setting some other pixels in its cache line results in a cache miss, and then a third time back from cache to SDRAM.I think that if you want to get pixel fill rates exceeding memcpy() on the CPU, you'll need to fix those two problems. You aren't going to get memcpy()-exceeding rates with that strategy! But, if you fix them, you probably will.
> First, the data is sent to the monitor from a framebuffer. With compositors like Wayland, every window has its own buffer, and when it is damaged (updated), the compositors copies (memcpy) the damaged part from window buffer into the framebuffer using CPU or GPU. As I understand, this part cannot be skipped and the application renders window content into a window buffer so there always will be a memcpy stage to have it actually displayed.
I don't know much about Wayland, but this is definitely not true when you're rendering fullscreen on the GPU. I've heard there are ways to allocate your memory buffers such that you get zero-copy scanout in the fullscreen case (GBM_BO_USE_SCANOUT | GBM_BO_USE_LINEAR or DRM) but I haven't tried Wayland.
> Furthermore, to render the text you need to memcpy the glyphs from glyph cache into their locations. So rendering whole window of text boils down to lot of small memcpys.
Yes, certainly you need to do memcpy or similar if you're copying pixels from the glyph cache into the framebuffer. But memcpy() is only slow when it misses cache. In this example, which is fairly typical in displaying only 95 distinct glyphs (though not in having 27000 of them on the screen at once), the glyph cache is less than 30KiB. That's a quarter the size of my L1d cache! So it doesn't have to pull data in from main-memory SDRAM (or, worse, VRAM!) to fill up the framebuffer the way it does if you're reusing previously rendered lines. It can use the main-memory bus's whole bandwidth to write to the framebuffer instead of having to also read it.
> Also, you mentioned display lists but that requires extra memory compared to my approach.
Yes, tens of kilobytes. This is not significant when the framebuffer is 8–32MiB.
comment 2d ago · link · parent
Text rendering can be made arbitrarily complex, but in most cases it is not. In Russian, most Spanish, most Japanese, Ukrainian, or English, code points map 1:1 to glyphs, and figuring out where each glyph belongs on a line is a matter of running a prefix sum over their advances. AVX-512 prefix sum on 32-element vectors is about 2 nanoseconds per 32-element vector, so you need about 5 nanoseconds of layout time per line and about 200 nanoseconds for the whole screen, say 250ns to include the time to check for exceptional cases and figure out where each line belongs on the screen. This gives you a display list of some 3000 glyphs at various places on the screen.
If you rerender 2 megapixels from that display list at, say, 5 gigapixels per second on the CPU, it's going to take 400μs, which is 400,000ns. (I think the evidence I've shown above strongly suggests that this is doable on my laptop here, although it isn't a proof.)
If, instead, you copy 2 megapixels from one place to another in RAM, you can only do that at about 2.5 gigapixels per second, so reusing previously rendered lines will take more like 800μs.
That is slower than 400μs.
It is not faster than 400μs.
If you, instead, pass the display list to the GPU to texture-map from the font atlas, well, this GPU has a theoretical peak texture fill rate of 38.4 gigatexels per second, so it will take more like 52 μs. On the GPU, you can't really reuse the previously rendered lines.
Again, 800μs is slower than 52 μs. It's not faster.
The GPU doesn't really mind rendering 3000 quads instead of two or three. The difference is down in the range of [correction!] microseconds; this GPU can in theory do one triangle per clock at 1.2GHz, so each quad takes about 1.7 nanoseconds, and you can do 3000 of them in 5μs, about 10% of the total. But this is running concurrently with the fill rate, so it doesn't increase the 52μs.
The key thing to note, though, is that even the 800μs you would get by foolishly reusing previously rendered lines is still pretty small compared to the frame time, which at 60fps (what my laptop can actually run at) is 16667μs, 20 times longer. If you parcel that out among the 3000 or so glyphs on the screen, you have almost 5.6μs to do all the text layout calculations for each glyph: kerning, ligatures, shaping, whatever.
It's true that you need to manage the texture atlas, glyph cache, etc., although multichannel SDF fonts can provide reasonable antialiased results at a fairly wide range of pixel sizes, which can reduce this load quite a lot.
comment 2d ago · link · parent
Again, I don't think this is generally true, and that was the specific point I was investigating with bgraify.c. You can potentially render a complicated document from scratch, on the CPU, at speeds closer to memset() than to memcpy(), getting more than a 2× speedup.
And, on the GPU, you can do it at texture-mapping speeds, which are much faster still. (The basic plan is that you put the glyphs of your font into a texture atlas which your fragment shader texture-maps, possibly using SDF thresholding.) rxi's MicroUI https://github.com/rxi/microui is an example of a very small, simple IMGUI library whose standard backend works this way on top of OpenGL.
comment 2d ago · link · parent
I think VS Code is slow because it's a piece of shit, not because it uses an IMGUI library. I don't think it does use an IMGUI library; I think it uses src/vs/base/browser/ui which is all retained-mode.
VS Code runs in Node, which is fundamentally mostly a single-event-loop system, and in general it's very difficult for large single-event-loop systems to be reliably responsive, because literally any loop, anywhere in the system, that runs for too many iterations, will cause it to start janking. That's a problem with browser apps, too. Erlang-style actor systems have a much better chance, but they can still run into unexpected head-of-line blocking problems.
I have some experimental designs for software transactional memory systems which I hope will solve this problem...
comment 2d ago · link · parent
Yes, you can scroll by telling the GPU to use a different starting address for its framebuffer, but only if you're scrolling the whole screen. If you want to scroll the contents of a browser window but not the browser chrome, though, or one window but not another, you start needing to tell the GPU to composite things from a few different textures, or needing to copy things around in system RAM. If you push this work off on a software compositor like Wayland, you aren't saving any work; you're just changing which process does the work.
comment 2d ago · link · parent
You say I'm assuming that the render function costs nothing. I thought it was clear that I was not assuming that; what I said in the comment that you're responding to is, "The amount of per-drawable work has to be almost three orders of magnitude larger before the per-pixel work isn't the dominant factor." But you may have responded before I added that; I forget if I added it in later. Here by "drawable" I mean talking about things like letters, not widgets that have their own render functions. Widgets that have their own render functions can take more than four orders of magnitude more time than the per-pixel work before the per-widget work becomes the dominant factor.
It's true, as you say, that people are capable of using up that margin by doing things like reading from a file, because writing good code is harder than writing bad code. But that's not really a question of immediate-mode vs. retained-mode. You can write bad code with retained-mode GUI libraries, too. In fact, my experience is that it's much harder to write good code with retained-mode GUI libraries.
As for layout calculations, the layout engine I elicited from Opus 5.5 for http://canonical.org/~kragen/sw/megilloom-sandbox lays out 60,000 lines of text per second, in JavaScript, and it supports table layout. (It caches the layout calculations so that it can remain responsive up to hundreds of thousands of lines.)
Some IMGUI libraries are capable of providing a dirty flag and damage rectangles without requiring every application to duplicate the error-prone cache-invalidation logic to do that. As Raph points out in this post, they're not a panacea. But they're not as bad as you are naïvely assuming them to be.
comment 2d ago · link · parent
1. With discrete GPUs, which have their own VRAM (unlike integrated GPUs), reading the framebuffer is often much slower than reading main memory.
2. If you're copying pixels around in the framebuffer, the best you can do is memcpy speed, which spends half of the memory bus bandwidth on reading memory. But if you're computing fresh pixels to put in the framebuffer instead, you can go about twice that fast. Sometimes more than twice that fast. As a simple example, https://canonical.org/~kragen/sw/dev3/bgraify.c unpacks 1-bit-deep bitmaps with a palette of two 32-bit colors on one core at 26 gigabytes per second (on this Ryzen 5 3500U), while memcpy() on that same core can only reach about 10 gigabytes per second. (memcpy() on two cores reaches more like 18 gigabytes per second, so the naïve extrapolation is that you ought to be able to hit 36 gigabytes per second for something like a solid-color fill.)
comment 2d ago · link · parent
(If you're mostly memcpying from a font that fits in cache, you should get a higher fill rate than this.)
Using a GPU is of course much better, but not necessary to reach the level of performance you're talking about.
comment 2d ago · link · parent
If you're concerned about efficiency, GPU support is very important. But IMGUI is not the efficiency enemy you think it is; while IMGUI libraries do need to traverse the hierarchy of visible objects on every mouse movement, there are generally only a few dozen rectangles and a few thousand letters and other graphical objects visible, so the work involved in traversing them is generally very small amount compared to copying a few million pixels into the framebuffer.
As an example, I currently have a browser viewing HN and an Emacs window open, and they total about 3000 characters (1523 mostly-blank characters and 206 words in Emacs, 335 words in HN, plus chrome), a couple dozen icons, and another dozen or so roundrects. But my screen is 2 million pixels.
So the amount of per-drawable work has to be almost three orders of magnitude larger before the per-pixel work isn't the dominant factor.
IMGUI libraries do have to do a bit more work to avoid redrawing all those pixels on every mouse movement, but many popular IMGUI libraries, such as React, do in fact do that work. It's a somewhat less simple job than for retained-mode GUI libraries like Qt (or the browser DOM), but the added complexity in the IMGUI library often pays off in simpler and more reliable apps.
comment 2d ago · link · parent
comment 2d ago · link · parent
In https://canonical.org/~kragen/sw/dev3/qfitzah.s a lot of the function calls are conditionally compiled by the macro `do` (search for `.macro do`) to index into a table of function pointers pointed to by EBP, because that makes the call instructions 3 bytes instead of 5 bytes. Here I've disassembled one of the functions from the parser code from an unstripped version that has debugging symbols:
080482b7 <read_term>:
80482b7: ff 55 08 call DWORD PTR [ebp+0x8]
80482ba: 75 10 jne 80482cc <read_term+0x15>
80482bc: 50 push eax
80482bd: e8 f5 ff ff ff call 80482b7 <read_term>
80482c2: 50 push eax
80482c3: ff 55 04 call DWORD PTR [ebp+0x4]
80482c6: 59 pop ecx
80482c7: 58 pop eax
80482c8: ff 55 00 call DWORD PTR [ebp+0x0]
80482cb: c3 ret
80482cc: 31 c0 xor eax,eax
80482ce: 40 inc eax
80482cf: c3 ret
The actual source code to that subroutine looks like this: proc read_term
do read_factor
jnz 1f # if it failed, skip ahead
push %eax # save returned term
do read_term # recursive call for tail of term
push %eax
do skip_whitespace
pop %ecx
pop %eax
do cons # XXX tail call
ret
1: setnil %eax # return nil if no factor found
ret
I didn't do this to make it harder to disassemble, but it does have that drawback.For what it's worth, Claude Opus 5.5 had no trouble disassembling it and making a list of its bugs, including six I already knew about and one I didn't. It commented:
> Reverse-engineering a program this small is satisfying in a way bigger programs rarely are, because you can hold the whole thing in your head. Working out the scheme of keeping type tags in the low pointer bits from nothing but `test al,3` and `test cl,2` scattered through the code was the best part. Watching `(D x) (x x)` print 4 MB correctly, and then segfault on the next query, was a close second.
In 32-bit ARM code you have the additional problem that you have to know whether the T bit is intended to be set when the CPU is decoding a particular subroutine. The low bit of the branch destination tells you — which is fine if it's statically reachable, but you may have to guess if it's only dynamically reachable.
comment 2d ago · link · parent
CME's Henry Hub natural gas futures NGF27 https://www.cmegroup.com/markets/energy/natural-gas/natural-... are currently at 3.791 in "U.S. dollars and cents per MMBtu", which I take to mean million BTUs. Minimum price fluctuation is given as "0.001 per MMBtu = $10.00", which I guess is because the contract unit is 10,000 MMBtu.
I think the containerized gas turbines for the data centers we're talking about are simple-cycle gas turbines ("SCGT") which are typically 35–40% efficient (https://en.wikipedia.org/wiki/Simple_cycle_combustion_turbin...) using the lower heating value ("LHV") of the fuel, which is about 90% of the higher heating value ("HHV") by which it's priced on the CME. So figure that you get about 33% of those million BTUs in electricity out of the gas generator.
A million BTU is, in modern units, about 1.06 gigajoules. So, just for the fuel, you're paying about US$10.90 per gigajoule. In the folk units used for selling electrical power, that's about US$39 per megawatt hour. That doesn't count the interest and depreciation on the generators or balance-of-plant equipment. (But those costs are relatively small, which is the main reason they're using gas turbines in the first place. https://www.eia.gov/analysis/studies/powerplants/capitalcost... has a capital-cost study of such a simple-cycle gas-turbine plant, with the capital cost coming out to US$713 per peak kilowatt, of which about a third was "Mechanical – Major Equipment". If we assume a capacity factor of 80%, that's US$891/kW delivered. At an interest rate of 6% per year, assuming no depreciation, that's US$53/year/kW. At 8.77 MWh/year/kW, that's another US$6.05/MWh. Depreciation might double or triple that.)
If we compare that to USA photovoltaic PPA pricing in recent years in the https://emp.lbl.gov/pv-ppa-prices we can see that nearly all PV PPAs are cheaper than just the gas you need to fuel your gas power plant. A few are more expensive. The cheapest one this year was US$22/MWh. This includes not just the PV modules and balance of plant but the generator operator's profit as well.
So, I don't think it's correct to say that "gas is the economically-best option" in general. Generally speaking, electrical energy from gas is more expensive than solar energy, though there are exceptions. The great benefit of gas is that the upfront investment is very low (much lower than other fossil fuels, and sometimes even slightly lower than utility-scale solar), and it's portable. There's room in an urban core next to a datacenter for a container full of gas turbines. There isn't room for a solar farm there. You have to site the solar farm somewhere relatively far away and run transmission lines, which involves politics.
It doesn't have to be that way. As Rui Ma explained last year in https://xxcancel.com/ruima/status/1955372325970514161, in China:
> Energy is considered a solved problem. The Chinese government’s investment in sustainable energy — from advanced hydropower to next-generation nuclear — means that, relative to many other markets, electricity supply is secure and inexpensive. Everywhere we went, people treated energy availability as a given. This is a stark contrast to the U.S., where AI growth is increasingly tied to debates over data center power consumption and grid limitations.
comment 2d ago · link · parent
comment 2d ago · link · parent
comment 3d ago · link · parent
comment 4d ago · link · parent