{"id":47965,"date":"2019-09-12T06:00:46","date_gmt":"2019-09-12T10:00:46","guid":{"rendered":"https:\/\/www.shamusyoung.com\/twentysidedtale\/?p=47965"},"modified":"2019-09-12T08:56:08","modified_gmt":"2019-09-12T12:56:08","slug":"game-programming-vexations-part-3-the-dominance-of-c","status":"publish","type":"post","link":"https:\/\/www.shamusyoung.com\/twentysidedtale\/?p=47965","title":{"rendered":"Game Programming Vexations Part 3: The Dominance of C++"},"content":{"rendered":"<p>C++ is the main language of game development. This is changing slowly as indies embrace other languages, but in the AAA space C++ is still overwhelmingly dominant. C++ is descended from &#8211; and is very similar to &#8211; the language C. First created in 1972, C is just one year younger than I am. It was devised for the world of the 1970s. It was targeted at the hardware of the 1970s, and was originally intended for writing operating systems.<\/p>\n<p>This seems crazy, doesn&#8217;t it? Writing operating systems for Nixon-era mainframes is so vastly different from building AAA games in 2019 that it&#8217;s like we&#8217;re using coal-fired steam engines to go to the moon. Sure, the steam engine has been modernized a bit, but there are still conventions built into the language that don&#8217;t make a lot of sense in the world of 2019. The fact remains that somewhere underneath all those rocket engines and silver wings is a chugging steam engine.<\/p>\n<p>C++ certainly has language features not available in C. C++ has classes, inheritance, operator overloading, and a bunch of other slick ways of expressing complex solutions in code. Those are nice, but none of those things <b>uniquely<\/b> address challenges faced in games programming. We could, in an alternate universe, use a different sort of language with a different set of features.<\/p>\n<p>It&#8217;s not like this industry is incapable of evolution! Studios have changed game engines, and game engines have changed what graphics API they favor<span class='snote' title='1'>On the PC side, this boils down to DirectX vs. OpenGL, with third-party candidate Vulkan landing a few recent wins.<\/span>. Our tools are different, the target hardware is different, the operating systems are different, and the performance challenges have changed numerous times. Rendering technology has gone through at least two major revolutions. First there was the jump from software rendering to using dedicated graphics hardware, and then another jump when we added <a href=\"?p=15956\">the ability to program that graphics hardware using shaders<\/a>. Over the last 30 years we&#8217;ve changed every single thing about game development <b>except<\/b> the language!<\/p>\n<p><!--more--><\/p>\n<h3>So Why are we still using this language?<\/h3>\n<p><div class='imagefull'><img src='https:\/\/www.shamusyoung.com\/twentysidedtale\/images\/stock_steam_engine.jpg' width=100% alt='Sure, I can take this thing to the moon... as long as you build me a track between here and there.' title='Sure, I can take this thing to the moon... as long as you build me a track between here and there.'\/><\/div><div class='mouseover-alt'>Sure, I can take this thing to the moon... as long as you build me a track between here and there.<\/div><\/p>\n<p>Some people claim that we&#8217;re stuck with this language due to industry inertia. We use this language because we&#8217;ve always used this language. We use it because that&#8217;s what the programmers study, and programmers study it because that&#8217;s what everyone uses. Four years ago <a href=\"?p=26011\">I made the case that the dominance of C++ is due to the following factors<\/a>:<\/p>\n<ol>\n<li style=\"font-weight: 400;\"><b>Lots of libraries.<\/b> There are tons and tons of C++ toolkits, libraries, and code snippets floating around in the wild. Do you need a sound library? Font loading? Access to rendering hardware? Support for gaming controllers? You don\u2019t need to write that code yourself, because there\u2019s a really good chance that someone else has already solved the problem and provided the source code for free. Of course, adding their code to your project is often a lot harder than it ought to be, but spending six hours pulling out your hair playing \u201cdependency scavenger hunt\u201d is faster than writing everything from scratch, even if it is a dumb miserable way to spend an evening.<\/li>\n<li style=\"font-weight: 400;\"><b>Lots of programmers.<\/b> Since C++ is the big important language, everyone learns it. Which makes it easy to hire people to work on your project.<\/li>\n<li style=\"font-weight: 400;\"><b>Lots of help.<\/b> Yes, answers to forum questions often take the form of abusive condescension and nerd peacocking, but at least a C++ programmer can get their question answered after their tag-team humiliation. If you\u2019re using one of the more obscure languages, then you might not get any answer at all<span class='snote' title='2'>You&#8217;ll still get mocked, though. Mostly by jackasses asking, &#8220;Why didn&#8217;t you use C?&#8221;<\/span>.<\/li>\n<li style=\"font-weight: 400;\"><b>No dominant alternative.<\/b> It would be one thing if there was another language out there to play Pepsi to C++ Coke, or could be the Apple to the C++ Windows. But there\u2019s no clear contender. Java is good for some tasks, Python is good for others, but none of the challengers works as a broad general-purpose language. And that\u2019s fine. There\u2019s lot of value in specialization. But that focus helps drive the C++ feedback loop of ubiquity.<\/li>\n<\/ol>\n<p>I&#8217;m still confident that&#8217;s all true, but after four years I&#8217;d like to argue with my past self and suggest that this industry inertia can&#8217;t be the <b>full<\/b> reason for why C++ is so deeply entrenched.<\/p>\n<h3>The Lie of Simplicity<\/h3>\n<p><div class='imagefull'><img src='https:\/\/www.shamusyoung.com\/twentysidedtale\/images\/stock_forklift.jpg' width=100% alt='This image will make sense in about three paragraphs.' title='This image will make sense in about three paragraphs.'\/><\/div><div class='mouseover-alt'>This image will make sense in about three paragraphs.<\/div><\/p>\n<p>PC hardware is usually presented as a processor and a pile of memory. When a program is run, the processor makes changes to the contents of the memory, and you get some sort of output. On this site, I describe programs this way all the time. Sadly, this is a gross over-simplification. To understand why C++ is still dominant, we need to look at how the hardware is <i>really<\/i> constructed and what it&#8217;s <i>really<\/i> doing.<\/p>\n<p>What&#8217;s actually going on inside of that humming box is that you&#8217;ve got a whole bunch of processors all bundled together in a single CPU housing. We call these separate processors &#8220;cores&#8221;. Those cores don&#8217;t make changes to memory directly. Instead, blocks of memory must be copied to a smaller pool of memory called the L2 cache. From there it&#8217;s copied to an <b>even smaller<\/b> pool of memory called the L1 cache. This L1 cache is actually inside that CPU housing with the cores. This is the only memory that the cores can manipulate directly. If the processor makes some changes to memory, then the altered block is copied back out through the layers and is stored in main memory.<\/p>\n<p>Let&#8217;s say you&#8217;re a core. The L1 cache is your tiny workbench right in front of you. You can examine bits of memory on the bench. You can compare them, perform arithmetic, and you can make changes to the contents of the memory. Sometimes you need a chunk of memory that you don&#8217;t see in front of you. When this happens, then hopefully what you need is stored in the little shed just outside, which is your L2 cache. If the required item isn&#8217;t stored there, then you need to jump in your forklift and trundle all the way to the other side of the campus. You need to drive all the way to the particular warehouse that has the stuff you need. Go inside, find the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Pallet\">pallet<\/a> that holds the data you&#8217;re looking for, and drive it all the way back to your shed. Then take the items you need off the pallet and put them on your workbench so you can get back to work.<\/p>\n<p>This is just the tip of the iceberg. There&#8217;s also some parallelism that you can take advantage of if you understand the hardware. A single core can handle multiple operations at the same time, provided you structure your operations properly. If you have the variables A and B and you need to modify them independently of each other, then it&#8217;s much faster to order your code so that you change A, then B, then A again, then B again. If you simply modify A twice and followed by B twice, then you&#8217;ll miss out on some of the potential performance gains.<\/p>\n<p><i>Disclaimer: I&#8217;ve never done any real programming at this level. Above is how it&#8217;s been described to me by people with more knowledge of programming close to the metal. Even the above is a pretty big simplification of what&#8217;s going on, but we&#8217;re basically at the edge of my knowledge at this point and I hesitate to add more.\u00a0<\/i><\/p>\n<p>Of course, maybe the compiler will help you out and re-order your operations. Maybe it won&#8217;t. Do you know how to make sure it does the right thing? Do you know how to check? Do you know what kind of performance gains you&#8217;re chasing and if it&#8217;s worth your time?<\/p>\n<p>This thing where you need to drive to the warehouse is called a &#8220;cache miss&#8221;, and it can have an immense impact on performance. If you want more detail, <a href=\"http:\/\/igoro.com\/archive\/gallery-of-processor-cache-effects\/\">this article<\/a> has some great information on when you&#8217;ll run into a cache miss and should be approachable to non-coders. I&#8217;ve never been able to find any hard numbers on the overall cost of a cache miss, but developer Mike Acton<span class='snote' title='3'>Formerly of Insomniac games. Currently working at Unity.<\/span> throws around the figure of &#8220;200 processor cycles&#8221;. That&#8217;s on the PlayStation 4 hardware, but I&#8217;m willing to bet that&#8217;s in the same ballpark as the rival consoles and the PC. 200 processor cycles is crazy expensive, and means a cache miss is one of the most expensive things that can happen to your program.<\/p>\n<p>And it&#8217;s completely invisible in the code!<\/p>\n<h3>Can&#8217;t the Compiler do it for Me?<\/h3>\n<p><div class='imagefull'><img src='https:\/\/www.shamusyoung.com\/twentysidedtale\/images\/stock_programmer_sad.jpg' width=100% alt='Can the compiler optimize my code for me? And if so, can it just write the code for me? This job is hard.' title='Can the compiler optimize my code for me? And if so, can it just write the code for me? This job is hard.'\/><\/div><div class='mouseover-alt'>Can the compiler optimize my code for me? And if so, can it just write the code for me? This job is hard.<\/div><br \/>\nI&#8217;ll be honest, I don&#8217;t enjoy messing with this stuff. I like thinking about the hardware as a simplistic CPU and a magical pool of memory. Worrying about the size of the L1 cache and the fetch timing is when programming stops being fun and starts feeling like accounting. It&#8217;s hard and annoying and adds an unwelcome layer of complexity to code. I tend to think of this business with cache limits as &#8220;intrusive&#8221; and I&#8217;d rather let the compiler handle it for me. In fact, <a href=\"?p=26133\">during my Good Robot series you can see me advocating a linked list<\/a> without giving <b>any thought<\/b> to how every single entry is likely to trigger a cache miss<span class='snote' title='4'>To be fair, I was currently being distracted by something even slower.<\/span>. That&#8217;s silly, and blunders like that would get me bounced out the door of a serious AAA studios engine team<span class='snote' title='5'>Unless it was Bethesda Softworks, where they&#8217;d probably put me in charge of engine optimization for Gamebryo.<\/span>.<\/p>\n<p>I&#8217;m not the only one averse to thinking about the actual physical limitations of the hardware. If you poke around you&#8217;ll see coders being pennywise and pound foolish with processor cycles. You&#8217;ll see advice like:<\/p>\n<ul>\n<li style=\"font-weight: 400;\">If you don&#8217;t care about precision, then you could cast this float to an int before this operation because that will be faster.<\/li>\n<li style=\"font-weight: 400;\">Woah there, buddy! That arctangent operation looks mighty expensive. That square root looks pretty scary too.<\/li>\n<li style=\"font-weight: 400;\">Rather than doing this comparison 6 times in a row, you should do it once and store the result in a bool. It&#8217;ll be faster!<\/li>\n<\/ul>\n<p>In the right context, all of these might be reasonable advice. But often coders will obsess over this stuff when their real performance problems are coming from their failure to manage their memory. I am tremendously guilty in this area, and I am not an outlier by any measure.<\/p>\n<h3>Getting Back to C++<\/h3>\n<p><div class='imagefull'><img src='https:\/\/www.shamusyoung.com\/twentysidedtale\/images\/stock_coffee.jpg' width=100% alt='Pictures of code are boring, so here&apos;s a picture of raw materials before they&apos;re converted into code.' title='Pictures of code are boring, so here&apos;s a picture of raw materials before they&apos;re converted into code.'\/><\/div><div class='mouseover-alt'>Pictures of code are boring, so here&apos;s a picture of raw materials before they&apos;re converted into code.<\/div><\/p>\n<p>I think stuff like this is why C++ is so dominant. Newer languages act like they want to protect you from having to think about the hardware. <i>Don&#8217;t use pointers, they&#8217;re dangerous. Don&#8217;t worry about the layout of data in memory or how big it might be. Just trust Friend Compiler to handle it for you. Don&#8217;t worry about the cost of allocating memory or memory fragmentation.<\/i><\/p>\n<p>As someone who hates worrying about the hardware, I really appreciate this. In the overwhelming majority of use cases, the programmer should not need to waste their time obsessing over minuscule little 64 kilobyte chunks of memory like it&#8217;s 1988. Computers have tons of power these days and programmer hours are not cheap. Hiding the cache behind layers of abstraction makes economic sense.<\/p>\n<p>It&#8217;s great to be shielded from all of that terrifying complexity, unless it happens to be <b>your job<\/b> to worry about hardware. Most areas of the code don&#8217;t need to think about optimizing the levels of cache usage, but if you <b>do<\/b> need to worry about it, then you really, <b>really<\/b> need to worry about it. If I&#8217;ve got 5 space marine objects and 6 space bugs in the scene and those are the only active objects in the game, then I do things the easy way. But if I&#8217;ve got ten thousand particles, two hundred bullets, 2,048 map zones, five hundred physics objects, and a hundred enemies in the scene at the same time, then I really need to think about how the data is being processed. If I&#8217;ve got enormous objects in memory &#8211; like texture maps or large collections of polygons &#8211; then I need to think about how often that data is being manipulated, copied, changed, and compared. If I&#8217;ve got 10,000 particles flying around the scene or I&#8217;m doing physics collisions between a lot of different objects, then doing things the Right Way\u2122 in memory can make the difference between running the game gracefully and completely tanking the framerate.<\/p>\n<p>I think this is why a lot of the newer languages haven&#8217;t gained much traction in the deep end of AAA gamedev. They make life easier for the 90% of the job where you&#8217;re doing straightforward things that aren&#8217;t serious performance concerns, but they leave you helpless when you come up against that last 10% of the job where you need direct control over where and how things are placed in memory.<\/p>\n<p>A few of the upstart languages do have these features. In particular, <a href=\"https:\/\/en.wikipedia.org\/wiki\/D_(programming_language)\">D<\/a> and <a href=\"https:\/\/en.wikipedia.org\/wiki\/Rust_(programming_language)\">Rust<\/a> both seem to have a lot of supporters who claim the languages are just fine for high-end gamedev. Other people claim they don&#8217;t offer enough, or in the right way. I&#8217;m not nearly qualified to weigh in on that argument. I&#8217;ve read about both languages, but trying to learn a language by reading about it is like learning to drive by watching <i>Top Gear<\/i>. The learning is in the doing, and I haven&#8217;t done enough with these languages to offer any meaningful analysis.<\/p>\n<p>Also, Rust has been &#8220;nearly ready&#8221; for game development for years now. I don&#8217;t know what the holdup is, but I suspect the problem isn&#8217;t that Rust is just <b>too suitable<\/b> for gamedev.<\/p>\n<p>Still, the point remains that any language intended to surpass C++ in the realm of games is going to need to match or exceed C++ in its ability to optimize very small but important things.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>C++ is the main language of game development. This is changing slowly as indies embrace other languages, but in the AAA space C++ is still overwhelmingly dominant. C++ is descended from &#8211; and is very similar to &#8211; the language C. First created in 1972, C is just one year younger than I am. It [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[66],"tags":[],"class_list":["post-47965","post","type-post","status-publish","format-standard","hentry","category-programming"],"_links":{"self":[{"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/posts\/47965","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=47965"}],"version-history":[{"count":9,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/posts\/47965\/revisions"}],"predecessor-version":[{"id":48035,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/posts\/47965\/revisions\/48035"}],"wp:attachment":[{"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=47965"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=47965"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=47965"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}