This page has been translated automatically.
Основы UNIGINE
1. Введение
2. Виртуальные миры и работа с ними
3. Подготовка 3D моделей
4. Материалы
5. Камеры и освещение
6. Реализация логики приложения
7. Создание кат-сцен и запись видео
8. Подготовка проекта к релизу
9. Физика
11. ПРОЕКТ2: Шутер от первого лица
12. ПРОЕКТ3: Аркадная гонка по пересеченной местности от 3-го лица
13. ПРОЕКТ4: VR приложение с простым взаимодействием
Внимание! Эта версия документация УСТАРЕЛА, поскольку относится к более ранней версии SDK! Пожалуйста, переключитесь на самую актуальную документацию для последней версии SDK.
Внимание! Эта версия документации описывает устаревшую версию SDK, которая больше не поддерживается! Пожалуйста, обновитесь до последней версии SDK.

Основные механизмы оптимизации

Once you have assessed the scene performance status, you already have some idea of what exactly you need to pay attention to in order to improve and speed up your application.После оценки состояния производительности сцены вы уже имеете определенное представление о том, на что именно необходимо обратить внимание, чтобы усовершенствовать и ускорить работу приложения.

As a rule, one of the main ways to improve performance is to correctly select and apply optimization tools to the 3D scene geometry.Как правило, один из основных способов повысить производительность – это правильно выбрать и применить инструменты оптимизации к геометрии 3D-сцены.

Let's take a look at the main tools available in UNIGINE:Давайте рассмотрим основные инструменты, которые есть в UNIGINE:

  • Levels of Detail (LODs) — the main way to optimize your project. The idea is to show a simplified model with less detail instead of a highly detailed model when the object is far away from the camera. To do this, you need to take a detailed model and create several versions of it for different distances, each with a reduced number of polygons.Levels of Detail (LODs) — the main way to optimize your project. The idea is to show a simplified model with less detail instead of a highly detailed model when the object is far away from the camera. To do this, you need to take a detailed model and create several versions of it for different distances, each with a reduced number of polygons.

    A model with LODs can be represented as a single Mesh object with a number of surfaces, each representing a certain LOD. LOD settings allow you to specify the distance for switching between surfaces.A model with LODs can be represented as a single Mesh object with a number of surfaces, each representing a certain LOD. LOD settings allow you to specify the distance for switching between surfaces.

    LODs can be configured automatically when importing the model into UNIGINE or manually via a 3D editor and UnigineEditor.LODs can be configured automatically when importing the model into UNIGINE or manually via a 3D editor and UnigineEditor.

    10109 polygons
    LOD 0
    10109 polygons
    LOD 0
    5004 polygons
    LOD 1
    5004 polygons
    LOD 1
    2583 polygons
    LOD 2
    2583 polygons
    LOD 2
    Levels of Detail (LODs) — the main way to optimize your project. The idea is to show a simplified model with less detail instead of a highly detailed model when the object is far away from the camera. To do this, you need to take a detailed model and create several versions of it for different distances, each with a reduced number of polygons.A model with LODs can be represented as a single Mesh object with a number of surfaces, each representing a certain LOD. LOD settings allow you to specify the distance for switching between surfaces.LODs can be configured automatically when importing the model into UNIGINE or manually via a 3D editor and UnigineEditor.10109 polygons
    LOD 0
    5004 polygons
    LOD 1
    2583 polygons
    LOD 2

    Levels of Detail (LODs) — the main way to optimize your project. The idea is to show a simplified model with less detail instead of a highly detailed model when the object is far away from the camera. To do this, you need to take a detailed model and create several versions of it for different distances, each with a reduced number of polygons.Уровни детализации (LOD-ы) — это основной способ оптимизации вашего проекта. Суть в том, чтобы вместо модели с высокой детализацией показывать более простую, с меньшим количеством деталей, когда объект находится далеко от камеры. Для этого вам нужно взять детализированную модель и создать несколько ее версий для разных дистанций, каждая с уменьшенным количеством полигонов.

    A model with LODs can be represented as a single Mesh object with a number of surfaces, each representing a certain LOD. LOD settings allow you to specify the distance for switching between surfaces.Модель с LOD-ами также можно представить в виде одного объекта Mesh с несколькими поверхностями, каждая из которых – это отдельный LOD. В настройках LOD-ов для каждой такой поверхности можно указать расстояние, на котором она должна переключится на другую.

    LODs can be configured automatically when importing the model into UNIGINE or manually via a 3D editor and UnigineEditor.LOD-ы можно настроить автоматически при импорте модели в движок или вручную с помощью 3D-редактора и UnigineEditor.

    10109 polygons
    LOD 0
    10109 polygons
    LOD 0
    5004 polygons
    LOD 1
    5004 polygons
    LOD 1
    2583 polygons
    LOD 2
    2583 polygons
    LOD 2
  • Impostors — flat images used instead of real models at a far distance from the camera. This method allows rendering objects with preserving visual accuracy: each impostor has the same transformation and appearance of the original object, but its geometry has only 2 triangles. Typically, impostors are used in scenes with a large number of objects that need to be visible from a long distance.Impostors — flat images used instead of real models at a far distance from the camera. This method allows rendering objects with preserving visual accuracy: each impostor has the same transformation and appearance of the original object, but its geometry has only 2 triangles. Typically, impostors are used in scenes with a large number of objects that need to be visible from a long distance.

    UNIGINE has a handy tool for creating impostors — Impostors Creator. It is accessible via the UnigineEditor main menu (Tools -> Impostors Creator).UNIGINE has a handy tool for creating impostors — Impostors Creator. It is accessible via the UnigineEditor main menu (Tools -> Impostors Creator).

    A real object (on the left) and its impostor (on the right) in the sceneA real object (on the left) and its impostor (on the right) in the scene
    A real object (on the left) and its impostor (on the right) in the scene

    A real object (on the left) and its impostor (on the right) in the sceneA real object (on the left) and its impostor (on the right) in the scene
    Impostors — flat images used instead of real models at a far distance from the camera. This method allows rendering objects with preserving visual accuracy: each impostor has the same transformation and appearance of the original object, but its geometry has only 2 triangles. Typically, impostors are used in scenes with a large number of objects that need to be visible from a long distance.UNIGINE has a handy tool for creating impostors — Impostors Creator. It is accessible via the UnigineEditor main menu (Tools -> Impostors Creator).
    A real object (on the left) and its impostor (on the right) in the sceneA real object (on the left) and its impostor (on the right) in the scene
    A real object (on the left) and its impostor (on the right) in the scene

    Impostors — flat images used instead of real models at a far distance from the camera. This method allows rendering objects with preserving visual accuracy: each impostor has the same transformation and appearance of the original object, but its geometry has only 2 triangles. Typically, impostors are used in scenes with a large number of objects that need to be visible from a long distance.Импосторы — плоские изображения, используемые вместо реальных моделей на большом расстоянии от камеры. Такой способ позволяет отрисовывать объекты с сохранением визуальной точности: каждый импостор повторяет преобразование и внешний вид исходного объекта, но имеет при этом всего 2 треугольника геометрии. Обычно импосторы используют в сценах с большим количеством объектов, которые должны быть видны на большом расстоянии.

    UNIGINE has a handy tool for creating impostors — Impostors Creator. It is accessible via the UnigineEditor main menu (Tools -> Impostors Creator).В UNIGINE есть удобный инструмент для создания импосторов – Impostors Creator. Он доступен в главном меню UnigineEditor (Tools -> Impostors Creator).

    A real object (on the left) and its impostor (on the right) in the sceneA real object (on the left) and its impostor (on the right) in the scene
    A real object (on the left) and its impostor (on the right) in the scene

    A real object (on the left) and its impostor (on the right) in the sceneРеальный объект (слева) и его импостор (справа) в сцене
  • Switching on and off the nodes at a certain distance from the camera using World Switcher. With this tool, you can disable parts of the virtual scene that are far away from the user, thus improving performance.Включение и выключение нод, находящихся на определенном расстоянии от камеры с помощью World Switcher. С помощью этого инструмента вы можете незаметно для пользователя отключать отдельные части виртуальной сцены, которые расположены от него на достаточно большом расстоянии, тем самым улучшая производительность.
  • Occlusion Culling allows you to avoid rendering geometry occluded by other opaque geometry by cutting it off using special occluders (Occluder, Occluder Mesh) or using Hardware Occlusion Queries.Отсечение объектов по окклюзии (Occlusion Culling) позволяет не отрисовывать геометрию, загороженную другой непрозрачной геометрией, отсекая ее с помощью специальных окклюдеров (Occluder, Occluder Mesh) или используя аппаратную окклюзию (Hardware Occlusion Queries).
  • Managing a large number of identical objects using Mesh Cluster and Mesh Clutter allows you to simplify the node hierarchy by replacing many identical objects with one. Mesh Cluster allows you to arrange the meshes it stores around the scene as you see fit. Mesh Clutter scatters meshes randomly, and they cannot be edited individually. However, using Mesh Clutter is more efficient in terms of memory consumption.Управление большим количеством идентичных объектов с помощью Mesh Cluster и Mesh Clutter позволяет упростить иерархию нод, заменив множество одинаковых объектов одним. Кластер позволяет расставлять меши, которые в нем хранятся, по сцене по вашему усмотрению. Клаттер разбрасывает меши случайным образом, и их нельзя редактировать по отдельности. Однако, использование клаттера более эффективно с точки зрения потребления памяти.

However, it's not just the geometry of a 3D scene that affects performance. Inefficient use of light sources, dynamic shadows and reflections, and other effects can significantly reduce the application speed. That's why UNIGINE has a bit masking mechanism that allows you to selectively apply certain effects or enable certain properties for individual objects. Bit masks are used in the following systems:Однако, не только геометрия 3D-сцены влияет на производительность. Нерациональное использование источников света, динамических теней и отражений, а также других эффектов может значительно снизить скорость работы приложения. Поэтому в UNIGINE существует механизм битовых масок, который позволяет выборочно применять или включать определенные эффекты или свойства для отдельных объектов. Битовые маски используются в следующих системах:

  • Rendering into viewportрендеринг во вьюпорт,
  • Shadowingотображение теней,
  • Reflections renderingотрисовка отражений,
  • Collisionsколлизии,
  • Intersectionsпересечения,
  • Decalsдекали,
  • Fieldsполя,
  • Sound sourcesисточники звука,
  • Physicalsфизические явления,
  • Pathfinding (inside Navigation Areas)построение траекторий (внутри Navigation Area).

Bit mask operating principle is as follows: an effect or property has a certain set of flags — bit masks — that define the scope of this effect or property. Cameras, Objects, Collision Shapes (used to detect collisions with physical objects) and other entities contain some of these bit masks depending on the type of entity and the possibility of applying a particular effect to it.Принцип работы механизма битовых масок таков: у эффекта или свойства есть определенный набор флагов – битовых масок – которые определяют область действия этого эффекта или свойства. Камеры, объекты, Collision Shapes (используются для обнаружения столкновений с физическими объектами) и другие сущности содержат некоторые из этих битовых масок в зависимости от типа сущности и возможности применения к ней того или иного эффекта.

Masks are compared bitwise using logical conjunction, that is, the first bit of one mask is compared to the first bit of the other mask and so on. Two bit masks are considered a match if they have at least 1 matching bit, regardless of the value of the other bits.Маски сравниваются побитно с применением логической конъюнкции, то есть первый бит одной маски сравнивается с первым битом другой маски и так далее. Две битовые маски считаются совпавшим, если у них есть как минимум 1 совпадающий бит, независимо от значение остальных битов.

An effect is only applied to an object if their bit masks match.Эффект применяется к объекту, только если их битовые маски совпадают.

Working with ContentРекомендации по работе с контентом#

So, the above are the basic optimization techniques available in UNIGINE.Итак, вы познакомились с основными механизмами оптимизации, которые есть в UNIGINE.

However, the optimization process is not limited to these tools. In most cases, it starts at the stage of importing your content into the project. In addition, most objects have a set of parameters that allow you to control their impact on performance.Однако, процесс оптимизации не ограничивается применением этих инструментов. В большинстве случаев, он начинается еще на этапе импорта вашего контента в проект. Кроме того, большинство объектов имеют набор настроек, позволяющий контролировать их влияние на производительность.

We'd like to share some recommendations on working with content that will help you keep your application's performance at a high level. Ниже собраны некоторые рекомендации по работе с контентом, которые помогут вам сохранить производительность приложения на высоком уровне.

GeometryГеометрия#

We have already mentioned that geometry is the main part of a virtual scene that significantly affects performance, and UNIGINE has enough tools to optimize it. But to achieve maximum efficiency when using these tools, you should also follow these rules:Мы уже говорили о том, что геометрия – это основная часть виртуальной сцены, которая значительно влияет на производительность, а в UNIGINE существует достаточно механизмов для ее оптимизации. Но для максимально эффективного их применения, вам также следует придерживаться некоторых правил:

  • Try to create LODs as separate surfaces of one mesh. This way you will reduce the number of nodes in the hierarchy and simplify configuring the LODs visibility.Старайтесь создавать LOD-ы как отдельные поверхности одного меша. Так вы уменьшите количество нод в иерархии и упростите настройку видимости LOD-ов.
  • The number of polygons in neighboring LODs should differ by 2-3 times at least.Количество полигонов в соседних LOD-ах должно отличаться минимум в 2-3 раза.
  • The optimal number of LODs is 2 or 3. Using more levels of detail in most cases will only create an additional CPU load.Оптимальное количество LOD-ов — 2 или 3. Использование большего количества уровней детализации без необходимости только создаст дополнительную нагрузку на CPU.
  • Avoid using occluders with large objects that have multiple surfaces, as well as in scenes with flat objects, as this can lead to a performance drop instead.Избегайте использования окклюдеров с большими объектами, которые имеют несколько поверхностей, а также в сценах с плоскими объектами, так как все это может, наоборот, привести к потере производительности.
  • Export models from a 3D editor in local coordinates, so that the size of the mesh bounding box is as close as possible to the size of the mesh itself. This will provide a more accurate occlusion culling.Экспортируйте модели из 3D-редакторов в локальных координатах, чтобы размеры границ меша (его bounding box) были максимально близки к размеру самого меша. Это обеспечит более точное отсечение по окклюзии.

Terrain, Grass, Water and Cloud LayerОбъекты Terrain, Grass, Water и Cloud Layer#

As you know, besides being imported from other 3D editors, geometry can be created directly in UnigineEditor using the built-in tools. The most performance-consuming objects created in this way are Terrain, Grass, Water and Cloud Layer. They have a set of parameters (both global and local for each object) that are designed to optimize the rendering.Как вы знаете, геометрию можно не только импортировать из других 3D-редакторов, но и создавать непосредственно в UnigineEditor, используя встроенные инструменты. Самые затратные с точки зрения производительности объекты, созданные таким образом, – это Terrain, Grass, Water и Cloud Layer. У них есть набор параметров (как глобальных, так и локальных для каждого объекта), с помощью которых вы можете оптимизировать рендеринг.

TexturesТекстуры#

As a rule, in any project a 3D model has several textures assigned for various purposes, consuming quite a lot of memory. The following techniques can help you reduce their impact on performance:Как правило, в любом проекте на одну 3D модель приходится несколько текстур разного назначения, которые потребляют довольно много памяти. Уменьшить их влияние на производительность вам помогут следующие приемы:

  • Try to use smaller textures wherever possible, but always check that the visual performance hasn't degraded.Старайтесь использовать текстуры меньшего размера там, где это возможно, но всегда проверяйте, не ухудшилось ли визуальное представление.
  • Configure the global texture settings: set the optimal Quality and Maximum Resolution values for all textures in the project to reduce the amount of GPU memory consumption.Отрегулируйте глобальные настройки текстур: задайте оптимальные значения качества (Quality) и максимального разрешения (Maximum Resolution) для всех текстур в проекте, чтобы уменьшить объем потребления графической памяти.
  • Use asynchronous streaming of graphics resources to load textures smoothly. Try not to set a low Textures Memory Limit to avoid re-uploading them from disk.Используйте асинхронный стриминг графических ресурсов для плавной загрузки текстур. Старайтесь не устанавливать низкий лимит памяти для текстур (Textures Memory Limit), чтобы избежать их повторной загрузки с диска.
  • When importing textures, enable the Unchanged flag only for *.dds or *.texture textures, and for your custom textures (e.g. HDR) that should not be compressed.При импорте текстуры используйте флаг Unchanged только для текстур формата *.dds или *.texture, а также для ваших пользовательских текстур (например, HDR), которые не должны быть сжаты.
  • Choose the appropriate Texture Preset when importing the texture, or customize your own. This will allow you to apply the correct compression to the texture and avoid creating unused texture channels.Выбирайте подходящий текстурный пресет (Texture Preset) при импорте текстуры или настройте свой собственный. Это позволит применить к текстуре корректное сжатие, а также избежать появления неиспользуемых текстурных каналов.
  • Use texture channels to store multiple textures in a single texture.Используйте каналы текстуры, чтобы хранить несколько текстур в одной.

DecalsДекали#

Decals are usually used to add extra detail to objects in a scene. Each decal has settings that may contribute to performance optimization:Декали обычно используют для того, чтобы добавить какие-то дополнительные детали существующим объектам в сцене. Каждая декаль имеет настройки, которые вы можете использовать для снижения ее воздействия на производительность:

  • Configure the decal visibility distances (Min/Max Visibility, Min/Max Fade).Настройте дистанции видимости декалей (Min/Max Visibility, Min/Max Fade).
  • Use the Viewport bit mask to control the decals visibility.Используйте битовую маску Viewport mask для контроля видимости декалей.

Particle SystemСистема частиц#

If you use particle systems in your scene, you can reduce the frame refresh rate for their simulation to improve performance. This can be done using the Periodic Update section parameters in the Particle System settings.Если вы используете в сцене системы частиц, то для улучшения производительности можно уменьшить частоту обновления кадров для их симуляции. Сделать это можно с помощью параметров блока Periodic Update в настройках системы частиц.

Here you can also specify the distance at which the particles stop updating and freeze (the Update Distance Limit parameter), as well as the frequency of their updating when only the shadow of the particle system is visible in the frame or nothing is visible at all.Здесь же вы можете указать расстояние (параметр Update Distance Limit), на котором частицы перестают обновляться и статически замирают, а также частоту их обновления, когда в кадре видна только тень от системы частиц или она вообще не видна.

LightingОсвещение#

Lighting in a scene also requires quite a bit of resources. Each light source, depending on its type, may require up to 6 rendering passes to calculate the shadows cast by the objects it illuminates. The individual settings of each source can also affect performance.Освещение в сцене также требует довольно много ресурсов. Каждому источнику света, в зависимости от его типа, может потребоваться до 6 проходов рендеринга для просчета теней, которые отбрасывают освещаемые им объекты. Отдельные настройки каждого из источников также могут влиять на производительность.

You can apply any of these methods to optimize the rendering of light sources:Для оптимизации рендеринга источников света можно применить какие-либо из этих способов:

  • Disable shadow rendering for some illuminated surfaces and materials. For example, you can do this for the farthest LOD surface (where shadows are not important).Отключите рендеринг теней для некоторых освещенных поверхностей и материалов. Например, это можно сделать для самой дальней поверхности LOD (когда тени не имеют значения).
  • Use static lighting and shadows for immovable objects instead of dynamic lighting.Используйте статическое освещение и тени для неподвижных объектов вместо динамического.
  • Use Shadow Mask to control the rendering of shadows from lit objects.Используйте битовую маску Shadow Mask для управления отрисовкой теней от освещенных объектов.
  • Use Screen Space Shadows instead of Shadow maps at long distances, since screen-space effects depend on screen resolution rather than geometry: the higher the resolution, the more accurate the shadows.Вместо Shadow maps на больших расстояниях используйте Screen Space Shadows, поскольку последние зависят не от геометрии, а от разрешения экрана: чем выше разрешение, тем точнее тени.
  • Reduce the size of the light source.Уменьшите размер источника света.
  • Enable Interlaced rendering of light sources.Включите рендеринг источников света с чередованием (Interlaced).
  • Configure the distance at which light sources and shadows are rendered.Настройте расстояние, на котором отрисовываются источники света и тени.
  • Use as few light sources that affect transparent objects as possible.Используйте как можно меньше источников света, воздействующих на прозрачные объекты.
  • Disable rendering of light sources on water.Отключите рендеринг источников света на воде.
  • Use as few World Lights as possible.Используйте как можно меньше глобальных источников света (World Lights).
  • Reduce the number of cascades for World Lights.Уменьшите количество каскадов для глобальных источников света.
  • Use Point-shaped Omni Light sources and disable shadow rendering for surfaces illuminated by such sources. Since the UNIGINE engine uses tile-based rendering, these light sources will be grouped and rendered in the batched mode. Batch rendering settings are available in the Settings window (Lights -> Batching).Используйте источники Omni Light точечной формы (Point) и отключите рендеринг теней для поверхностей, освещенных такими источниками. Так как движок UNIGINE использует тайловый рендеринг, эти источники света будут сгруппированы и отрисованы в пакетном режиме (batched). Настройки пакетного рендеринга доступны в окне Settings (Lights -> Batching).
  • Create fake lighting: use Billboards and Volumetric objects instead of real light sources.Создавайте фейковое освещения: используйте билборды (Billboards) и волюметрики (Volumetric objects) вместо реальных источников света.

PhysicsФизика#

To optimize the modeling of physical phenomena and interactions, we recommend the following:Для оптимизации моделирования физических явлений и взаимодействий, мы рекомендуем такие методы:

  • Configure the global physics settings: adjust the distance from the camera within which the physical interaction of objects takes place, specify the optimal number of computational iterations per one frame (for example, for simple scenes, one computational iteration is enough), and select a suitable time budget within which the physical calculations take place in the current frame (if the physical interactions look like slow motion, the time budget should be increased).Отрегулируйте глобальные настройки физики: настройте расстояние от камеры, на котором происходит физическое взаимодействие объектов, укажите оптимальное количество вычислительных итераций за 1 кадр (например, для простых сцен достаточно одной вычислительной итерации), а также подберите подходящий бюджет времени, в рамках которого происходят физические расчеты в текущем кадре (если физические взаимодействия напоминают замедленную съемку, то бюджет времени стоит увеличить).
  • Use bit masks to fine-tune physical interactions between objects. For example, you can limit object collisions by using the Collision Mask.Используйте механизм битовых масок, для тонкой настройки физического взаимодействия между объектами. Например, можно ограничить столкновения объектов с помощью маски коллизий (Collision Mask).
  • Use a simplified geometry for Collision Shapes used in collision detection. For example, you can use the least detailed LOD or just a primitive.Используйте более простую геометрию для Collision Shapes, применяемых для обнаружения столкновений. Например, это может быть наименее детализированный LOD или просто геометрический примитив.
  • Try to use as few Collision Shapes for a single object as possible.Старайтесь использовать как можно меньше Collision Shapes для одного объекта.
  • Use discrete collision detection wherever possible.Используйте дискретное обнаружение столкновений там, где это возможно.
  • Enable the Freezing option for Rigid, Ragdoll, and Fracture bodies to stop physics calculations when no external force is affecting the body.Включите застывание (Freezing) для тел с типом Rigid, Ragdoll и Fracture, чтобы остановить вычисления физики, когда на тело не воздействует внешняя сила.

Adjust the amount of pieces for Fracture bodies, as too many pieces can reduce performance.Отрегулируйте количество обломков для разрушаемых тел (Fracture), поскольку слишком большое их количество может снизить производительность.

Последнее обновление: 04.04.2024
Build: ()