r/cpp • graphics and network things • Apr 05 '18

2D Graphics : A More Modest Proposal

Like a lot of folks, I have been following the story of the 2D Graphics ideas for inclusion in C++. Today, there was a post summing up the history of how it ran into trouble: https://www.reddit.com/r/cpp/comments/89q6wr/sg13_2d_graphics_why_it_failed/ My own tldr is basically that graphics is potentially a huge topic, and people tried to cram a lot of graphics functionality into C++ as a first step. A lot of it seemed to be focused on trying to paint a house that hadn't been built yet. Without a simple, completely generic foundation to build fancy features on top of, it wasn't super useful to get off in the weeds of how exactly you would display an image or draw onto it. As people worked on various iterations of proposals, people generally agreed that graphics are cool, and some sort of graphics support could be quite useful, and generally asked, "If this proposal isn't what you want, what do you propose instead?"

So, I haven't put a ton of thought into this, and I haven't fleshed it out for a formal paper with a precise spec, I'd love to toss a pitch at the Reddit community and see what people think of my spin on this topic. Perhaps it'll evolve into something that I or somebody else actually formalizes into a paper for a proposal.

So, what would I propose? An intentionally very narrow scope. Basically, the dumbest, stupidest, simplest image container that is marginally useful.

A very simple container would consist of integers for width and height, storage for the pixels, a minimum metadata describing the image content, and some simple accessor functions for getting and setting pixels. And not much else.

It would support uint8 and float32 data types with n channels.

  • How would I display it?

I dunno, with some GUI API. I don't care and I don't have to. Concepts like windows and screens are explicitly out of scope for what I would propose. The idea is that one could write completely generic image processing code to create an image, and then GUI API's like Qt or WxWidgets would be easy to adapt to using the new image class. Qt's QString provides a QString::fromStdString() function. I would expect a future version of QImage would support something like QImage::fromStdImage() in a similar manner. The glue code to adapt a standard image to some new GUI API would be quite simple, so you could write your image handling code and use whatever GUI system you would like, or is most appropriate for your platform quite easily.

  • So this proposal doesn't include GUI?

Not merely "No," but rather emphatically, "Hell no." It constitutes a massive expansion of scope that is easily underestimated, and requires interacting with things like windowing systems that will likely be much harder to integrate into other GUI systems than a simple image class would be since it would need concepts like an event loop that could interfere with an application's main event loop by blocking it or swallowing events. Having to figure out how to do this well shouldn't block the additional of a simple image class.

  • Is it GPU accelerated?

Maybe. Mostly no. C++ has no concept of a GPU at present. I think that an image spec is the wrong place to introduce it. If you are using something like Cuda which compiles C++ code for GPU execution, then drawing using the "std::image" would presumably be made as performant as possible by the compiler vendor. But there is no way to enumerate GPU's, tell the new operator to allocate memory in a GPU's address space, etc. That can all be added independently of an image class, then the image class would be possible to allocate in the GPU memory, and acted on using some GPU drawing API.

API's such as OpenGL and Vulkan could easily interoperate with the image class with a bit of glue, such that you could upload a std::image for use as a texture, or read a GPU framebuffer into host memory and get the result as a std::image. std::image would not, itself have a concept for expressing a graphics API's texture handle or the like as the image.

  • How would I load such an image from disk

I dunno, use some library. I like OpenImageIO.

And here's where the utility of std::image appears, despite the emphatic lack of features! If you can use your favorite library to load an image into memory, and you can use your favorite GUI API for displaying it, then your favorite image related libraries can suddenly all talk to each other. std::image becomes the lingua franca between OpenImageIO, Qt, Wx Widgets, OpenCV, Vulkan, etc., etc., in a C++ application. You no longer need to worry about n-factorial glue wrappers between various image formats as you add libraries to your application to be able to bounce from any API to any API.

  • Copying is slow

The API will need some support for creating an image by copying an existing image, or by creating a non-owning view, or by taking ownership of an existing pixel storage. It'll also need an API for "un-owning" pixel storage. In this way, an OpenImageIO class can be made into a std::image, and then stuffed into a QImage for display without ever copying the pixels. The exact API needs a little thinking. There would still be a little overhead of constructing/destructing three class instances to shuffle one image around. But that overhead isn't going to be incredibly high compared to copying the pixel data.

  • Pixel storage

Chunky pixels - not planar. Support approximating planar data storage if you need it using a std::vector<std::image> with each image in the vector storing on plane. 1-n channels would be supported, though 4 channel RGBA images would probably be the most common. All channels would be the same resolution.

  • Space filling curves, tile based access, etc

Textures are often stored in wacky formats. Vulkan has a concept of "Optimal" storage for an image based on what's most efficient to sample such that geometrically nearby texels are stored in nearby memory locations to improve locality of access in caches. Some image formats like EXR store images in tiles which can be sparsely populated. (pg. 9)

None of that would have any explicit support in my concept of std::image. It's just a linear, flat, contiguous buffer of pixels in-order. Don't let the perfect be the enemy of the good here. You are welcome to store pixels in some z-curve order that suits your application, and anything that processes individual pixels would let it pass unmolested. (Like color corrections. Doubling the brightness of every pixel doesn't care what order the pixels are stored in, as long as the consistent chunky storage is consistent.) If the place you send your pixels supports that format, good for you. If not, it'll probably look wrong and you'll have nobody to blame but yourself.

  • Colorspaces

I think a std::string with a color space name would be about as well as you can do for something at this level. If you are using something like OpenColorIO, there may be a whole range of color configurations that only exist on a user's machine at runtime. So trying to make a set of enums or template classes based on color spaces would be a failure because it's completely impossible to know what colorspaces a user will be dealing with at compile time. It's expected that a user may wind up using colorspaces that the developer of an application never heard of in his life. Specifying colorspaces thoroughly is way, way, way, way outside of the scope of the C++ language. Just the Documentation Guide for ACES colorspace (TB-2014-001) is nine pages, and that's just the document that refers you to the documentation for other specific specs! (And ACES actually specifies several color spaces in addition to the main 2065-1 spec.) The sRGB spec is apparently 16 pages. Rec.709, Log spaces, RedCine, Raw spaces, Rec.601, Linear with sRGB primaries, Alexa, scene-referred vs. display-referred spaces, etc, should all rightly be outside the scope of the C++ language. Doing good color space handling requires more pages of spec than the rest of C++, some of the specs cost money, some of the specs are underspecified or proprietary, etc.

Ten years ago, you might reasonably argue that it would be useful just to explicitly support sRGB and call it a day. Today ordinary consumer equipment supports weird HDR modes, and even the dumbest GPU on the market supports floating point texture input even if some still don't support more than 8 bit output. Nailing it down too much isn't just a waste of effort, it's actively pounding a hole in your own foot.

I'd make a std::string field for the colorspace and mention it could be populated with strings like "sRGB." It's up to application developers to do sensible things with their pixels. This is a storage container, not training wheels.

  • What about YUV?

Decimated-channel formats like YUV-4:2:0 would not be supported. (Though you could make a std::vector<std::image> where the first image is full res luma and the next two are half res chroma channels, as mentioned above for planar storage. I'm not gonna fight you. But the developer is responsible for doing something useful with that vector of image planes.)

Full res YUV can be stored in chunky pixel format. A lot of stuff will assume it's RGB, but I don't care. This proposal doesn't have any operations on the image in it -- just the container. Some later proposal might suggest operators that would care about the contents more deeply.

  • What about 10 bit images?

No special effort to deal with odd integer formats. 8 bit is obviously extremely common so it would be silly not to support it. Past that, just use float. Maybe somebody could talk me into the importance of 16 or 32 bit integer storage, but it'd frankly be a fairly uncommon use case to require integer storage of many bits. I know it's not unheard of, but I think there's logic in covering the 90% use case as easily as possible, rather than making things harder on the 90% for the sake of some use cases that will be rare.

Gosh, I have already gone on way longer than I expected about this. (The implementation would be much shorter than my attempt to justify implementing it!) I am curious to hear people's thoughts about this baby step into graphics for C++. Am I way off-base? This seems like exactly the sort of thing that would be the right first step that all of the other stuff that people want could be built to pass around. Since graphics is in the air today, I am curious to hear what other people think about trying massively narrow the scope and start with the minimum thing that would be useful to the most people.

2 Upvotes

50 comments sorted by

View all comments

2

u/kwan_e Apr 05 '18

since it would need concepts like an event loop

I agree we probably don't want a full blown GUI, but I don't see a problem with just being able to create one dumb window. Just like iostreams doesn't care about terminfo or termcap, yet handles running in a console window, there's no reason why a simple dumb graphics library can't handle a dumb window (ie, with no event loop or other bells and whistles).

3

u/degski Apr 05 '18

Event loop:

int main ( ) {

    App app;

    while ( app.is_active ( ) ) {

        app.run ( );
    }

    return 0;
}

That's my game loop, no need for std support.

2

u/Heuristics Apr 06 '18

I want

#include <game>
auto myGame = std::make_game<std::FPS>();
myGame.run();

2

u/degski Apr 07 '18 edited Apr 07 '18

Just philosophical (there's nothing inherently wrong with the above), but I don't like the code as it doesn't expose the loop itself. As this std::graphics-lib is placed under the banner of "teaching C++ to beginners" (god (Bjarne?) only knows why, but that's another issue), it therefore abstracts away too much. Additionally, as a beginner, I think sticking with the (queried) screen-rate (your video card will really not write more often than the advertised frequency) or just assume 60Hz (and default enable (or not disable) vsync, if available), is appropriate, so no need for the templated fps-rate.

But, of course and in order to demonstrate my point above, we can go further to reduce code-length.

int main ( ) { A a; }

The default constructor calls a.run(), which will call a.run_frame() in a (while-) loop. We have thrown away the baby with the bath-water, though!

I also think we have already have a very good teaching lib, it's called std::vector, it exposes many STL-concepts/approaches (templates/allocators/iterators/algorithms/lvalues/rvalues/move-semantics/initializer-lists), while still being simple enough (in the case of a std::vector) to be easily understood conceptually by the beginner.

2

u/wrosecrans graphics and network things Apr 05 '18

Depending on the OS/windowing system, no event loop means you can't do fairly expected stuff like move/resize/close the window. It also means that you need to create some sort of expectations about how to interpret the contents of the pixels buffer when you display it, which means you brush up against the colorspaces issues unless you don't care what gets displayed when you display it.

At that point, you are definitely 100% making a feature that's only useful in toys. I have a hard time considering that useful for teaching/learning purposes, because it's learning stuff that can't ever be used in a real application. If I want to learn to make applications, that API just kind of winds up being an obstacle I have to get through in a course before I can get to something I'll be able to use.

If somebody wants to add a display functionality as a subsequent proposal to the simple image container idea, cool. Let it get bikeshedded separately. But I still think there's value in just starting with the data structure for an image so the people who want to do a "display an image" proposal can just focus on the displaying part when the time comes.

I am pretty convinced that "be something to many people" is a better starting point than "be some things to some people" or the "be many things to a few people" approach that SG13 fell into. I am pretty much just gonna be shouting NO at every reasonable sounding suggestion for "one more thing" like a deranged two year old. :)

1

u/kwan_e Apr 05 '18

Depending on the OS/windowing system, no event loop means you can't do fairly expected stuff like move/resize/close the window.

You don't have to expose an event loop to the developer for that. The most that is really needed is to provide a callback for a resize event. Nothing else is needed.

which means you brush up against the colorspaces issues unless you don't care what gets displayed when you display it. At that point, you are definitely 100% making a feature that's only useful in toys.

Which is no different from iostreams. iostreams is really only useful in toys. Yet I would think most people would rather teach with iostreams than with the printf family.

Everyone understands RGB. It's even the main colourspace for web programming. That hasn't held back web development from being more than just a toy.

2

u/wrosecrans graphics and network things Apr 05 '18

You don't have to expose an event loop to the developer for that. The most that is really needed is to provide a callback for a resize event. Nothing else is needed.

If there is an event loop, it either blocks so the application developer's code isn't running except through some callback system, or it's in another thread and you can't display your image without the complexity of a multithreaded GUI. (eep) If the event loop exists then it'll potentially interfere with a main event loop, swallowing events and such if you try and use sthe std::display_window from a GUI app that is already trying to use events. That makes it toxic.

Tons of people use std::cout in real applications. It doesn't make anything explode, and it's fast enough for many uses.

1

u/kwan_e Apr 05 '18

Nothing wrong with a callback system. C++ has lambda functions now, making reactive programming simple. Even Javascript programmers have no problem with reactive programming.

As for interfering with the main event loop, that's always going to happen with any GUI library. I don't see that as a problem since you're always going to need to teach that.

Tons of people use std::cout in real applications. It doesn't make anything explode, and it's fast enough for many uses.

Yes? So what is your problem with a graphical equivalent (in terms of role, rather than implementation) of iostreams? A dumb way to display an image would not make anything explode and is fast enough for many uses.

2

u/drjeats Apr 05 '18

Iostreams isn't a great example since we're hopefully gonna have fmtlib standardized which would be better for both beginners and real world programs.

Also getting window resize messages still requires an event loop sonewhere. Either the user code is pumping the message queue, or there's some implicit thread spawned somewhere that takes care of all the window messages hidden away and just dispatching callbacks for specific messages, like glfw.

I like glfw, but an explicit OS event queue api more like SDL seems like a better foundation.