Creare grafica come se fossimo nel 1993
Sintesi redazionale: URL dell'articolo: https://staniks.github.io/articles/catlantean-3d-blog-1/ URL dei commenti: https://news.ycombinator.com/item?id=48459294 Punti: 589 # Commenti: 99. Fonte originale: https://staniks.github.io/articles/catlantean-3d-blog-1/
<p>Personal website and blog.</p><p>Catlantean 3D is a side-project I've been slowly building in my spare time for over a year, and I intend to release it on Steam next year.</p><p>My goal was to build a complete, shippable first-person shooter using techniques that were common in the early 90s, while allowing myself the luxury of using a modern compiler and a platform abstraction layer.</p><p>What this actually means is, the constraints I have foolishly imposed upon myself are as follows:</p><p>If this sounds unreasonable to you, that is because it is.</p><p>But I'm doing it anyway, and today I'm gonna talk about something that is typically overlooked in development blogs, and that is asset creation.</p><p>**Note:** Everything displayed here is work-in-progress, and heavily subject to change.</p><p>Mode 13h on VGA hardware was the famous 320x200 256-color graphics mode that defined a generation of PC games. From a programmer's perspective it was wonderfully simple: you'd have a linear frame buffer where each pixel was represented by a single byte indexing into a palette of 256 colors.</p><p>If you wanted to draw a pixel, you wrote a byte at a specific address, and that was it, there were no shaders or VRAM, or anything like that.</p><p>One byte per pixel, and that byte is an index into a palette which contains actual RGB values that would be rendered to screen. This imposes some interesting limitations; when making assets for modern games, you can throw millions of colors at an image, but when your limitation is that every pixel on screen can only be one of 256 colors, asset creation becomes a very different problem because every color choice has to be careful and deliberate.</p><p>Games like Doom and Duke Nukem are good examples of this done right. There is a certain crispiness and clarity to these graphics that arises *because* of these technical limitations, not in spite of them. Restriction forces deliberate choices, and deliberate choices tend to look good.</p><p>Catlantean 3D is an attempt to reproduce that feeling, but with one caveat - I'm actually going for something closer to VGA Mode-X, which is 320x240. The reason for this is, if you display 320x200 on a 4:3 display, you end up with non-square pixels! While this would be most authentic, I've chosen not to deal with this out of preference rather than objective reason.</p><p>So how does one create graphics that work within these limits?</p><p>Everything begins with 768 bytes, carefully picked through many iterations of trial and error.</p><p>The main reasoning for picking these exact colors was the following:</p><p>The palette did not spring into life all at once; it involved a lot of back-and-forth during asset creation, testing, and re-iterating in general.</p><p>Below are some examples of sprites and textures from the actual game:</p><p>Catlantean 3D is a traditional raycaster. The map consists of tiles which are all identical in size; some are walls, others are just voids with a floor and ceiling. In order to render the map, the renderer uses the DDA algorithm for each column of screen, traversing the tilemap and determining where it hits the map geometry, and based on this, a wall column is rendered on screen with the appropriate texture, sampled from appropriate coordinates. Floors and ceilings are rendered after as horizontal scanlines, filling in the rest of the screen.</p><p>Raycasting has been done to death by other blogs and websites, so I'm not going to cover all of it, but I do want to cover what I think is its most overlooked aspect: lighting.</p><p>If we were to render the game world using just the palette, without any special effects, we would end up with something that looked rather flat and unimpressive:</p><p>But what we wanted was the following. Notice how the light diminishes the further away geometry is from player, and how one side of the map tiles is just slightly darker than the other. This gives an impression of depth.</p><p>With a modern hardware-accelerated renderer, this would be trivially done in a shader - based on how far the vertex is, we would multiply its color vector by a floating point factor and get a diminished color vector as a result.</p><p>But how do we achieve something like this with a palette renderer? It has no concept of color, just indices into palette. So if we wanted to find a darker shade of a certain color, we would need to loop through the palette and find the color that meets our criteria of "darker". This is just too much because we can't loop through the entire palette for *every* pixel we render onto the screen, it would be too slow.</p><p>What we could do instead was some preprocessing, to allow a fast color lookup based on distance at runtime.</p><p>If we were to lay out our palette into a single row like this...</p><p>We then choose the number of shade levels (32 in my case) meaning each color needs 31 darker variants, all sourced *from the palette*. We know each color's RGB values, so from this, and the shade index we can determine the closest target color of that shade:</p><p>```<br>// First shade index (0) is original color.<br>float darkening_factor = (32 - shade_index) / 32.0f;<br>target_darker_color.r = current_color.r * darkening_factor;<br>target_darker_color.g = current_color.g * darkening_factor;<br>target_darker_color.b = current_color.b * darkening_factor;<br>```</p><p>But that color might not exist in the palette. So we need to loop through the palette and find the closest color to it.</p><p>Definition of "close" actually changed for me during development - at first, I just took euclidean distance as a measure, but the problem with that was that almost everything had a tendency to gravitate towards the greys, simply due to the mathematics. Some older games actually did use Euclidean distance, but to me this didn't look very good. I can't explain why exactly, but a lot of darker shades appeared somewhat cold and lifeless. So instead, I converted my colors to Oklab color space, and leveraged its perceptual distance formula, which is closer to how humans perceive color differences. I also apply a small shift towards warmer hues the darker the color is (a common concept in pixel art called "hue shifting"). This is typically not necessary, but it does make the game look just a bit better.</p><p>How do I define "better" in this case? I have no idea, it just looks right. Frustrating, isn't it? It's hard to rationalize something subjective.</p><p>Back to our algorithm...</p><p>Essentially, for each color, we create a column that represents the shades of that color. What we end up with is a 2D matrix of palette indices called the colormap. Note that the colormap gradients are imperfect, because we're still restricted to colors from the palette:</p><p>So now, determining a darker shade of color `N`</p><p>based on distance becomes trivial.</p><p>Given colormap row index (i.e. shade level) based on distance:</p><p>```<br>colormap_row = 32 * fragment_distance / view_distance<br>```</p><p>We pick N-th entry in row belonging to that shade - that is the palette index of the darkened color `N`</p><p>.</p><p>And voila, O(1).</p><p>Also, instead of calculating the colormap row index for every pixel, the cost is further reduced by performing calculation:</p><p>So we're doing colormap row index calculation 320 times for walls, at most 240 times for floors, and once per visible sprite (raycasting gives free occlusion culling). That is cheap, and the payoff is great.</p><p>Doom and many other titles used similar approaches.</p><p>Textures and sprites in Catlantean 3D fall into three categories:</p><p>I am working a full-time job and have a decently active life, so my time to work on the game is limited. Thus, I wanted to minimize the time I spend reiterating when making complex sprites that involve animations. I rarely get something right on the first attempt, so naturally, reiteration is expected, and it is hard to reiterate when you need to make changes to many frames of an animation.</p><p>The more efficient approach was to create sprites in Blender as 3D models, rig and animate them there, and then render them to a series of textures with special Python scripts that leverage Blender's Python API. Reiteration then involved making changes in the model, and the rendering scripts did the rest, which was a lot of time saved.</p><p>The main hurdle was that rendered sprites came out very blurry and washed out.</p><p>One might think that the obvious answer to this was to render the sprite in high resolution, and then downscale with filtering, but I've had mixed success with this; details would often be suppressed by filtering, and edge clarity would be lost. What I found to be the most effective and reusable was to leverage Blender's compositing functionality to get the right amount of contrast and clarity:</p><p>Once the image was ready, it would be sent through a special Python script which performed palette quantization, creating a 1-byte-per-pixel image used by the engine. For every pixel in the source image, the script finds the closest color in our palette (perceptually closest - Oklab), and uses the index of that color for that pixel. The index array, along with the dimensions, is then packed into the very simple TEX format that is used by the game.</p><p>A similar workflow was used for enemy sprites. Note: some of these nodes are either redundant, or plain useless, simply because I had used them at some point, and then changed my mind. I like leaving them in just in case I need them again.</p><p>Enemy sprites are rendered in a special way. Sprite can have multiple animations, and each animation must have frames for each of the 8 directions sprite can face. So, for every animation (walk, fire, die, etc.), the Python script that uses Blender's API rotates the sprite, renders all frames of an animation, rotates the sprite again, and so on. Sprites are saved with a special convention that denotes sprite name, action name, direction and frame index:</p><p>Nice thing about this approach is that I don't need to keep rendered sprites in the repository - they're actually .gitignored. Whenever I switch locations and use another computer, I simply run the compilation script which renders every model and produces the sprites. It is reasonably fast and runs in ~10 seconds for about 15 models on RTX 3070.</p><p>Earlier in development, I created this vaguely cat-shaped head with the texture of my cat Vilko, to use as a status bar face. After all, why would I draw something like this by hand, if Blender could render it in such a vivid likeness of life?</p><p>The obvious answer is that it looked lazy and low effort, which it was. It didn't do a very good job at conveying emotion and it didn't have soul. When I was collecting feedback on the vibes, this was usually the first thing people pointed out.</p><p>Some things just need to be drawn by hand. I'm no artist, but I'm quite confident that the hand-drawn variant with animations looks far better, and I could never quite reproduce the same result if I animated this thing in Blender. Due to the dimensions of the sprite, every pixel needs to be deliberate, so there's no room for leaving this work for the Blender renderer.</p><p>I applied the same logic to most of the pickups, which were previously pre-rendered, but at a scale where Blender's compositor can't reliably produce good results. After human touch, their clarity and readability has much improved.</p><p>You might think, why simply not increase sprite resolution? The game rasterizer will take care of the scaling, right?</p><p>Well, it would work, but the result would look terrible because pixel scale is no longer consistent. At any given row or column on screen, you subconsciously expect the pixels to remain the same size as you move towards or away from them. If pixel scale varied from one sprite to the other, that's no longer true, and it just looks off. This is probably one of biggest reasons why many asset flippers or low-effort indie games look bad; they slap together assets with different scales that don't work together at all.</p><p>_(testo troncato)_</p>
