https://www.cybersport.ru/games/articles/kak-razvivalas-grafika-v-igrakh-ot-tochek-na-ekrane-oscillografa-do-trassirovki-luchei

How fast time flies! It would seem that not so long ago we played two-dimensional platformers on Dandy, or sat for hours at pixel games like Doom. And today we are already turning up our nose at the only “soapy” texture in AAA games at a huge level. But for the graphics to take on a modern look, it took several decades of development of computer technology and the thought of game designers. What was this path, you can find out from our material.

->

->

When graphics didn’t matter

Despite the fact that the industry took its first steps in the middle of the 20th century, historians have not come to an unequivocal opinion which computer game can be considered the first. Some have conferred this title on the program from a doctoral dissertation by Briton Alexander Douglas, written in 1952. His development, called OXO, was analogous to the game “tic-tac-toe” for the university computer EDSAC in 1952. With the help of it, the scientist described a method for studying human-computer interaction – a competition between a player and artificial intelligence. OXO did not receive mass distribution, since the program was sharpened only for the EDSAC computer, which existed in a single copy at the University of Cambridge.

Seven years later, the head of the instrumentation department Brookhaven Laboratory in the USA William Higinbotham came up with a device that was supposed to entertain visitors on an open house. Using an analog computer and an oscilloscope, he developed Tennis for Two, which was a computer simulation of table tennis. The only caveat was that the rackets were not visible, users could only observe the table, net and ball. To realize this idea, he was helped by developments in the calculation of the flight of nuclear warheads – Tennis for Two was distinguished by excellent physics. The device for the game lasted for two years, after which it was disassembled.

“‘>


Look

But even with such a small set of functions, the developers managed to release 28 games for the console. The thing is that the image was supplemented with translucent color filters that were glued to the screen. They depicted fields for hockey, football, handball, volleyball, basketball and even race tracks. It was they who gave what was happening on the display “meaning”, turning the chaotic movements of objects into sports games.

The Magnavox Odyssey sold over 350,000 units, but was not commercially successful. A few years later, Magnavox ceased production of the Odyssey and was bought by the Dutch corporation Philips.

Everything that the Magnavox Odyssey was equipped with

However, it was this console that inspired the novice game developer Allan Alcorn of Atari (by the way, the company was opened by the manufacturer Computer Space) to create the arcade machine Pong, which became a real hit. This game brought profit to the creators of arcade machines for the first time. Soon other companies followed Atari’s example – Konami, Namco, Sega, and so on.

All the first successful arcade machines used raster graphics. The image with this approach consists of many points (pixels) that are assembled into a mosaic. If we do not talk about color output (in the first machines the image was black and white), then if the pixel is turned on, a white dot appears on the screen. By activating the required pixels, the system creates a complete picture. The disadvantage of this approach is that at low resolutions (and at the dawn of the gaming industry there were no others), lines at oblique angles turned into “steps”.

Vector was an alternative to the raster principle. With it, the image is formed from the simplest geometric shapes (primitives) – circles, lines, arcs, and so on, the location of which is described in the file. Because of this, vector images were easily scaled, and therefore, with their help, it was possible to easily simulate three-dimensionality, creating models from a vector wireframe and gradually increasing or decreasing them in real time. For example, this principle was implemented in the 1980 Atari Red Baron arcade machine.

Vector graphics in the Atari Red Baron

The vector principle was very promising at the time, but in the end it lost the fight to pixels. The point is that vector screens were too complicated and expensive to maintain. And not to say that the demand for them among the players was higher than that of the raster ones, so they were less profitable economically. In addition, at the level of technology development of those years, the vector method did not allow creating complex scenes. To do this, too many primitives were needed, the performance of which was not enough. With pixels, this task was much easier to solve.

Vector machines were released until 1985, and there were also attempts to release a home vector game system – Vectrex. It was even recognized as commercially successful, but the technology still did not find mass demand and was happily forgotten in the gaming device market.

Add color to your life

Color television appeared before World War II, but games learned to work with color much later. Above, we have already talked about how the color playing field was obtained on the Magnavox Odyssey – this was facilitated by translucent filters that were attached to the screen. Similar methods were used in the first arcade machines. For example, Boot Hill had an underlay that mimics the landscape, and only cowboys controlled by players, cacti and passing carriages that served as obstacles, and a score in the corner were dynamic.

The first game to immediately display a color image was Atari’s Indy 4, which was released in 1976. This racing machine could be used by up to four people, and so that the cars could be distinguished from each other, they were painted in four different colors. At the same time, the playing field was still black and white, but the first step was taken – in subsequent games the color palette only increased. For a long time, arcade machines have become the absolute leaders in terms of the variety of colors.

As for the consoles, even there the color image appeared just in the mid-1970s. For example, the Atari 2600 console, released in late 1977, supported a palette of 128 colors using the NTSC standard, but only up to four colors could be present on one line on the screen at a time. Moreover, two of them were on the playing field and two more – on sprites. The situation was aggravated even more by the presence of only 128 bytes of RAM. To understand how far the consoles of the time lagged behind arcade machines, it is enough to compare the Pac-Man versions for the Atari 2600 and the arcade machine.

1/2
Pac-Man on the Atari 2600

The mid-1970s also saw the emergence of the first personal computers available to ordinary people. But the first games on them also did not differ in a variety of colors. The most graphically advanced PC of the time was the eight-bit Apple II, which went on sale in 1976. When switching the video controller to color mode, the resolution was reduced from 280×192 to 140×192, while only six colors were supported. As a result, when trying to color the picture, the player received a pixel something.

Choplifter – 1982 Apple II game

But at that time, PC users were happy with this – a machine useful in the household could also entertain them. In addition, PCs significantly outperformed consoles in terms of the amount of RAM, which made it possible to run more complex games. These devices have evolved gradually (as opposed to consoles, which moved in leaps and bounds), so we will focus on them later.

So, from the mid-70s to the early 80s, in addition to Apple, several other companies were engaged in the production of home PCs – Tendy, Commodore, Atari, ZX and others. Each of them had their own architecture, which they carefully concealed from competitors. But soon IBM came to this market – a company that until then was exclusively engaged in supercomputers and large servers.

By the early 1980s, IBM was an information technology giant. Entering the PC market, she used a completely different strategy – she completely opened the architecture, releasing, along with the first computer, a manual, which indicated all the nuances, right down to the layout of printed circuit boards. This allowed IBM to take over the market – many third-party companies were involved in the creation of peripherals for its computers, and closed-architecture PC makers were left out of business.

Prince of Persia in different color modes – VGA / EGA / CGA / MDA

The first IBM PC could be equipped with two video adapters – monochrome MDA and color CGA. The second supported 16 colors, but could display images in 320×120 resolution only using one of three four-color palettes. This is why most games from that era used only white, black, magenta, and blue-green colors. Three years later, IBM released the new EGA video adapter. The palette increased to 64 colors, of which 16 could be displayed on the screen at a resolution of 640×350. In addition, the EGA had four times more video memory than the CGA – 64 against 16 KB. In 1987, IBM introduced a new VGA standard with support for up to 256 colors.

The openness of the IBM-compatible architecture has led to the emergence of many manufacturers of peripherals for such PCs on the market. When in 1988 IBM wanted to introduce a new XGA standard with a resolution increased to 800×600, a new consortium of video adapter developers – VESA – was already formed. He introduced a more versatile and advanced SVGA circuit. It was fully compatible with VGA, but in addition to resolutions from 800×600, video adapters created according to this standard were capable of displaying up to 16.7 million colors. This is the palette that most modern monitors support – only expensive professional solutions can display over a billion colors.

Moving from 2D to 3D

Quake is considered the first truly “fair” 3D game. However, in fact, in the early 1980s there were already separate titles in 3D, they just did not gain popularity. This is due to the extremely low productivity of iron at that time. The fact is that any three-dimensional model consists of polygons – relatively speaking, planes built on three points. This means that any surface can be divided into a huge number of flat triangles, and the more there are, the better the picture is. Accordingly, a lot of power is required to calculate the position of these triangles in real time. And any attempts to assemble a three-dimensional virtual space in a game on hardware accessible to ordinary people at that time gave no more than five frames per second at the output.

A picture in 2D games consists of a background and sprites. Sprites are objects moving across the screen. Depending on the specific platform, sharpened for 2D graphics, they can have many restrictions, for example, in size, number of colors, and so on. Animation of objects is obtained by alternating different sprites after a certain number of frames. The background is set in advance, and objects on it move only with the camera. For example, let’s take the well-known Super Mario Bros .: mushrooms, enemies and Mario himself are sprites, and bricks, pipes, clouds, bushes and coins are the background.

1/3
An example of using sprites in a relatively new game is Days Gone. We rotate the camera, and the blood splashes are always turned to us with one side

Still, the developers came up with a few tricks to make the 2D image appear three-dimensional. Basically, these methods can be roughly divided into two:

Pseudo-3D + sprite scaling… Often these methods were used separately, but there are many cult games where they are used in conjunction, so we combined them into one group. For example, this was the case in the classic versions of Doom: the entire level was two-dimensional, that is, it was impossible to arrange one room under another, while the steps, in fact, were a projection onto a plane, and stepping on them, the character did not go up himself, but as if moving the screen. All surfaces were located at right angles – floors and ceilings were strictly horizontal, and walls and pillars were vertical.

The enemies were completely sprite, like their projectiles. When zooming in and out, the engine itself recalculated their size displayed on the screen. Thus, the user had the impression that he was playing a three-dimensional title. But it was just an illusion.

Doom is an example of a great symbiosis of pseudo-3D and sprite scaling

Parallax scrolling. There are several ways to implement this method, however, only the technical principle differs. The very essence remains the same: the background is divided into several layers, which are scrolled at different speeds when the camera moves. The method can be seen in many platformers or side-scrolling shooters.

Разница в результате при различных методах фильтрации текстур | Изображение: Tom’s Hardware

Следующим шагом развития фильтрации текстур стала трилинейная фильтрация. С ней метод билинейной фильтрации дополняется использованием мипмапов. Сейчас объясним, что это такое. Для отображения самых близких объектов разработчики используют текстуры самого высокого разрешения. Но на расстоянии в этом нет смысла — там можно использовать текстуры меньшего разрешения без потери качества, но экономя таким образом ресурсы. Поэтому в файлах игры одни и те же текстуры хранятся в нескольких разрешениях — от самого большого для ближних дистанций вплоть до 1х1 для наиболее отдалённых точек поверхности. Эти уменьшенные копии и называются мипмапами.

Метод трилинейной фильтрации дополняет билинейный: после вычисления средневзвешенного цвета четырёх текселов исходной текстуры следом аналогичный подсчёт делают с использованием нужного мипмапа. После этого берётся средневзвешенный цвет от полученных в предыдущих вычислениях, который и присваивается пикселю. Всех проблем билинейной фильтрации это не решает, однако размытие становится меньше, хоть и ценой производительности.

Окончательно эту проблему победила анизотропная фильтрация. Она использует намного более сложные алгоритмы, которые находят средневзвешенный цвет текселов не только MIP-текстур по направлению обзора, но и поперёк. Ещё одно отличие от предыдущих методов — использование до 128 текселов для поиска средневзвешенного цвета. Размытие при таком подходе получается минимальным, но сам метод требует большей производительности. Однако в наше время даже самые слабые видеокарты способны справляться с анизотропной фильтрацией, минимизируя ее влияние на частоту кадров.

Сглаживание, или Anti-Aliasing, — устранение «ступенчатости» (алиасинга) на границах текстур. Пиксели, которые формируют изображения, во всех мониторах квадратные. То есть этот эффект будет наблюдаться на всех кривых и прямых границах, угол которых отличен от 90 или 180 градусов. С увеличением разрешения алиасинг становится всё менее заметным. Однако даже на 4К-дисплеях он присутствует, не говоря уже о самых распространённых в наше время Full HD.

Самый простой по своему принципу алгоритм сглаживания — Supersample Anti-Aliasing (SSAA). Прежде чем получить искомый кадр, видеокарта рендерит изображение в большем разрешении, чем необходимо, затем уменьшает его, усредняя значения цветов пограничных пикселей. Нетрудно догадаться, что если мы хотим сгладить изображение до практически нулевого алиасинга, то нам необходима запредельная производительность — для рендера картинки в очень высоком разрешении.

Сравнение выключенного и включённого сглаживания в American Truck Simulator

Чтобы рационализировать ресурсы ПК, был разработан новый метод — Multisample Anti-Aliasing (MSAA), который рендерит уже не полный кадр в повышенном разрешении, а только те самые пограничные участки, где нужно устранить алиасинг. Есть ещё несколько алгоритмов вроде CSAA и CFAA, которые являются модификациями MSAA, но значительно более быстрыми.

Абсолютно иной принцип имеет алгоритм сглаживания TXAA, который изначально разрабатывался под видеокарты NVIDIA на архитектуре Maxwell, представленные в 2014 году. Позже аналоги TXAA стали поддерживать и графические процессоры других производителей, только там он назывался немного иначе — TAA. Суть алгоритма заключается в сопоставлении пограничных кадров и усреднении участков, нуждающихся в сглаживании. Если сравнивать с другими технологиями, то TXAA отлично показывает себя при медленном движении объектов, но плохо справляется с динамичными сценами.

Самой совершенной на текущий момент технологией сглаживания является DLSS (Deep Learning Super Sampling). Она поддерживается только на видеокартах NVIDIA, оснащённых тензорными ядрами (архитектуры Turing и Ampere). DLSS использует нейросеть, которую обучают, показывая ей «идеальные кадры» в разрешении до 16х. Впоследствии нейросеть сможет превращать кадры с низким разрешением в кадры с высоким разрешением, тем самым снижая алиасинг. Она также анализирует векторы движения, чтобы предсказывать, как ей выдать наилучшее изображение в следующем кадре. Технология постоянно совершенствуется, а нейросеть — обучается. И если поначалу эффективность DLSS вызывала вопросы, то со временем она стала показывать себя всё лучше.

Как мы уже говорили ранее, с повышением разрешения необходимость в сглаживании становится всё меньше и меньше. Текущее поколение консолей поддерживает разрешение только до 4К при достаточной частоте кадров, новейшие видеокарты для ПК также пока не рассчитаны на более высокие разрешения. На больших мониторах, особенно если сидеть близко к ним, алиасинг всё ещё заметен. Но пройдёт пара десятков лет, и стандартное разрешение увеличится до 16К, а то и больше, и мы навсегда забудем про все эти странные аббревиатуры и будем наслаждаться идеальной картинкой без TAA, SSAA или DLSS.

Lighting — чуть ли не самая главная деталь для достижения фотореалистичной графики, так как в действительности человек видит не сами предметы, а отражённый от них свет. В принципе, и пиксели на экране — это тоже светящиеся определённым цветом точки.

Свет — одна из самых сложных составляющих игровой графики. Существует множество способов реализации освещения. Самый простой для понимания — световые карты. Для какой-либо локации создаётся, грубо говоря, отдельный фильтр, который показывает, где должны быть освещённые участки, а где — тени. Этот способ работает только со статичными объектами. Их тени можно заготовить заранее и загружать по мере надобности вместе с картой освещения. Рассчитать максимально мягкие тени помогает метод Ambient Occlusion.

1/2
AO включено

Но если мы хотим получить динамические тени (например, тень героя, машины и так далее от солнца), то обычный Ambient Occlusion уже не подойдёт — ресурсов видеокарты не хватит. Чтобы выводить на экран тени в реальном времени, разработаны специальные алгоритмы.

SSAO (Screen Space Ambient Occlusion) работает по принципу Ambient Occlusion, но метод расчёта менее точный. Максимально приближенная к реальной тень получается при использовании Z-буфера — массива данных, который позволяет оценить расстояние до объектов сцены. Конечный результат хуже, чем у статических теней, полученных с помощью обычного Ambient Occlusion.

HBAO+, PCSS и HDAO — дальнейшее развитие SSAO от NVIDIA и AMD соответственно. Первый и последний метод при генерации теней используют сцену в более высоком разрешении, поэтому затенение получается намного точнее, а PCSS размывает очертания тени по мере удаления от объекта.

1/2
Максимальное качество теней в GTA 5 без PCSS

Самые большие возможности в плане создания освещения и затенения даст использование метода трассировки лучей (Ray Tracing). Массово внедрять её в свои продукты разработчики получили стали недавно — в 2018 году после релиза видеокарт NVIDIA на архитектуре Turing. Позже её поддержка появилась на видеокартах AMD RDNA 2.

Принцип трассировки лучей позволяет учитывать не только поведение света в одном направлении, но и дальнейшее его влияние на сцену — куда он отразится, с какой интенсивностью, сменится ли его цвет. Этот метод давно использовался там, где на рендер кадра можно затратить большое количество времени, вплоть до нескольких часов или даже дней, например в киноиндустрии — в сценах, созданных с помощью компьютерной графики. Но использовать рейтрейсинг в реальном времени стало можно только в 2018 году, когда видеокартам стало хватать производительности для обработки таких задач. И его повсеместное внедрение откроет перед разработчиками новые возможности.

Проще всего это объяснить на примере зеркала: если раньше изображение в нём было, по сути, отзеркаленной комнатой за невидимой текстурой, то при использовании Ray Tracing это будет честное отражение. Если же сравнивать качество затенения, то SSAO нам давал только имитацию глобального затенения около углов, то трассировка лучей позволит рассчитать всё физически корректным образом, в том числе с учётом цвета, интенсивности и так далее.

o.addEventListener('load', function () { callback(); }, false);

s.parentNode.insertBefore(o, s); } }

asyncLoad( 'https://platform.instagram.com/en_US/embeds.js', function () { window.instgrm.Embeds.process(); }, !!window.instgrm );

asyncLoad( 'https://cdn.playbuzz.com/widget/feed.js', function () {

}, !!window.PlayBuzz );

asyncLoad( 'https://static.apester.com/js/sdk/v2.0/apester-javascript-sdk.min.js', function () {

}, !!window.APESTER );

asyncLoad( 'https://wtrfall.com/widget.js', function () { if (!window.WTF || !WTF.bootstrap || !WTF.bootstrap("wtf-broadcast")) { setTimeout(arguments.callee, 50); } }, !!window.WTF );

asyncLoad( '//vk.com/js/api/openapi.js?147', function() { if (!window.$ || !window.VK || !VK.Widgets || !VK.Widgets.Post) { setTimeout(arguments.callee, 50);

return; }

$('.vk_post').each(function(i, elm) { var post = $(elm).data();

VK.Widgets.Post($(elm).attr('id'), post.userId, post.id, post.hash); }); }, !!window.VK ); })(); });