> Данная страница является частью большой статьи [[Render Hell 2.0 – Book II. Pipeline (Ад Рендера 2.0. Книга вторая. Пайплайн)]] ##### 3.9 Patch Assembly (Сборка Патчей) Until here we only saw **single** `vertices`. Sure, they came in a specific order send by a programmer but we treated them independently and not as a group. The following sections deal with steps that are **only** done when `tessellation shaders` are being used. The first of such steps creates `patches` from the individual `vertices`. That way it is possible to [[Subdivide (Подразделить) в контексте второй книги из серии Render Hell|subdivide]] them and add geometric detail. How many `vertices` make a `patch` is defined by the programmer, the maximum is, guess what, 32 vertices. До этого момента мы видели только **отдельные** `вершины`. Конечно, они поступали в определенном порядке, отправленном программистом, но мы рассматривали их независимо, а не как группу. Следующие разделы описывают шаги, которые выполняются **только** при использовании `шейдеров тесселяции`. Первый из таких шагов создает `патчи` из отдельных `вершин`. Таким образом, становится возможным их [[Subdivide (Подразделить) в контексте второй книги из серии Render Hell|подразделение]] и добавление геометрических деталей. Количество `вершин` в `патче` определяет программист, максимум, угадайте, 32 `вершины`. In `OpenGL` is this stage called `Patch/Primitive Assembly` and in `DirectX` only `Patch Assembly` (`Primitive Assembly` comes later). More detailled information about `patch/primitive assembly` [can be found in \[a57\]](http://www.lighthouse3d.com/tutorials/glsl-core-tutorial/primitive-assembly/). На `OpenGL` этот этап называется `Сборка патчей/примитивов`, а на `DirectX` - только `Сборка патчей` (`Сборка примитивов` происходит позже). Более подробную информацию о `сборке патчей/примитивов` [можно найти в \[a57\]](http://www.lighthouse3d.com/tutorials/glsl-core-tutorial/primitive-assembly/). ![[pipeline_patch_assembly_01.mp4]] ##### 3.10 Hull Shader (Шейдер оболочки) The `Hull shader` takes all the `vertices` which belong to the just created `patch` and calculates a `tessellation factor` e.g. dependent on the distance to the camera. As the hardware can only `tessellate` three basic shapes (quad, triangle or a series of lines), the `shader` code also contains which shape is being used by the `tessellator`. As a result there is not just a single `tessellation factor`, but they are computed for each outer side and also a special “inner” side of the shape. To be able to create meaningful geometry later, the `Hull Shader` also computes the input values for the `Domain Shader`, which takes care of the positions. `Шейдер оболочки` принимает все `вершины`, которые принадлежат только что созданному `патчу`, и рассчитывает `фактор тесселяции`, например, в зависимости от расстояния до камеры. Поскольку аппаратное обеспечение может `тесселировать` только три основные формы (квадрат, треугольник или ряд линий), код `шейдера` также содержит информацию о том, какая форма используется `тесселятором`. В результате коэффициент тесселяции не просто один, а [[вычисляется]] для каждой внешней стороны, а также для специальной "внутренней" стороны фигуры. Чтобы позже создать осмысленную геометрию, `шейдер оболочки` также рассчитывает входные значения для `шейдера домена`, который занимается позициями. ![[pipeline_hull_shader_01.mp4]] ##### 3.11 Tessellation (Тесселяция) Now we know in which shape and how much we want to [[Subdivide (Подразделить) в контексте второй книги из серии Render Hell|subdivide]] the `patch` – the `Polymorph Engine` takes this information and does the actual work. Out of this arrive a lot new `vertices`. These are sent back to the `Gigathread Engine` to be distributed across the `GPU` and are handled by the ``Domain Shader``. More information about the `shader` stages can be found [here \[a55\]](http://www.highperformancegraphics.org/previous/www_2010/media/Hot3D/HPG2010_Hot3D_NVIDIA.pdf) and [here \[a79\]](http://www.hotchips.org/wp-content/uploads/hc_archives/hc22/HC22.23.110-1-Wittenbrink-Fermi-GF100.pdf). Теперь мы знаем, в какой форме и насколько мы хотим [[Subdivide (Подразделить) в контексте второй книги из серии Render Hell|подразделить]] `патч` - `Polymorph Engine` принимает эту информацию и выполняет фактическую работу. Из этого получается много новых `вершин`. Они отправляются обратно в `Gigathread Engine` для распределения по `GPU` и обрабатываются `шейдером домена`. Более подробную информацию о стадиях `шейдера` можно найти [здесь \[a55\]](http://www.highperformancegraphics.org/previous/www_2010/media/Hot3D/HPG2010_Hot3D_NVIDIA.pdf) и [здесь \[a79\]](http://www.hotchips.org/wp-content/uploads/hc_archives/hc22/HC22.23.110-1-Wittenbrink-Fermi-GF100.pdf). ![[pipeline_tesselation_01.mp4]] Here you can find Detailed articles about [Triangle Tesselation](http://prideout.net/blog/?p=48) and [Quad Tesselation](http://prideout.net/blog/?p=49). Здесь вы можете найти подробные статьи о [Треугольной тесселяции](http://prideout.net/blog/?p=48) и [Квадратной тесселяции](http://prideout.net/blog/?p=49). You might ask why not directly put the geometry detail into the model. There are two reasons for this. First, you might remember how accessing memory is slow compared to just doing calculations. So instead of having to fetch all those additional `vertices` with all their attributes (position, normal, uv…), it is better to generate them from less data (`patch` corner `vertices` + displacement logic or textures, which support [[Mipmaps (Mip-карты, мипмапы)|mipmaps]], compression…). Second, with tessellation you’re able to adjust the detail depending on the distance to the camera – so you’re very flexible. Otherwise we may compute tons of vertices, that belong to triangles that are not even visible in the end (too small or not in view). Вы можете спросить, почему бы не включить детали геометрии напрямую в модель. Для этого есть две причины. Во-первых, вы, возможно, помните, как медленно происходит доступ к памяти по сравнению с простыми вычислениями. Так что, вместо того чтобы извлекать все эти дополнительные `вершины` со всеми их атрибутами (позиция, нормаль, uv...), лучше генерировать их из меньшего количества данных (`вершины` углов `патча` + логика смещения или `текстуры`, которые поддерживают [[Mipmaps (Mip-карты, мипмапы)|мипмапы]], сжатие...). Во-вторых, с `тесселяцией` вы можете настроить детали в зависимости от расстояния до камеры - так что вы очень гибки. В противном случае мы можем вычислить тонны `вершин`, которые принадлежат треугольникам, которые в конце концов даже не видны (слишком маленькие или не видимые). ##### 3.12 Domain Shader (Шейдер домена) Now the final position for the generated `tessellation` `vertices` are calculated. If the programmer wanted to use a [[Displacement Map (Карта Смещения)|displacement map]], it is applied here. The input of the `Domain Shader` are the outputs of the `Hull Shader` (for example the `patch vertices`) as well as a `barycentric coordinate` from the `tessellator`. With the coordinate and the `patch vertices` you can compute a new position of the `vertex`, and you can then apply the displacement to it. Similar to a `vertex shader`, the `Domain Shader` computes the data passed to the next `shader` stages, which can be either the `Geometry Shader` if active, or the `Fragment Shader`. Теперь рассчитывается окончательное положение для сгенерированных `вершин` `тесселяции`. Если программист хотел использовать [[Displacement Map (Карта Смещения)|карту смещения]], она применяется здесь. Входные данные `шейдера домена` являются выходными данными `шейдера оболочки` (например, `вершины патча`), а также `барицентрическая координата` от `тесселятора`. С помощью координаты и `вершин патча` вы можете вычислить новое положение `вершины`, и затем применить к нему смещение. Подобно `вершинному шейдеру`, `Шейдер домена` вычисляет данные, передаваемые на следующие стадии `шейдера`, которыми могут быть либо `шейдер геометрии`, если он активен, либо `шейдер фрагмента`. ![[pipeline_domain_shader01.mp4]]