occlusion culling что это
Occlusion culling
Occlusion culling is a process which prevents Unity from performing rendering calculations for GameObjects that are completely hidden from view (occluded) by other GameObjects.
Every frame, Cameras perform culling operations that examine the Renderers in the Scene and exclude (cull) those that do not need to be drawn. By default, Cameras perform frustum culling, which excludes all Renderers that do not fall within the Camera’s view frustum. However, frustum culling does not check whether a Renderer is occluded by other GameObjects, and so Unity can still waste CPU and GPU time on rendering operations for Renderers that are not visible in the final frame. Occlusion culling stops Unity from performing these wasted operations.
Regular frustum culling renders all Renderers within the Camera’s view.
Occlusion culling removes Renderers that are are entirely obscured by nearer Renderers.
When to use occlusion culling
To determine whether occlusion culling is likely to improve the runtime performance of your Project, consider the following:
How occlusion culling works
Occlusion culling generates data about your Scene in the Unity Editor, and then uses that data at runtime to determine what a Camera can see. The process of generating data is known as baking.
When you bake occlusion culling data, Unity divides the Scene into cells and generates data that describes the geometry within cells, and the visibility between adjacent cells. Unity then merges cells where possible, to reduce the size of the generated data. To configure the baking process, you can change parameters in the Occlusion Culling window, and use Occlusion Areas in your Scene.
At runtime, Unity loads this baked data into memory, and for each Camera that has its Occlusion Culling property enabled, it performs queries against the data to determine what that Camera can see. Note that when occlusion culling is enabled, Cameras perform both frustum culling and occlusion culling.
Additional resources
Unity uses the Umbra library to perform occlusion culling. For links to articles with more information on Umbra, see the Additional resources page.
Occlusion Culling
Occlusion Culling is a feature that disables rendering of objects when they are not currently seen by the camera because they are obscured (occluded) by other objects. This does not happen automatically in 3D computer graphics since most of the time objects farthest away from the camera are drawn first and closer objects are drawn over the top of them (this is called “overdraw”). Occlusion Culling is different from Frustum Culling. Frustum Culling only disables the renderers for objects that are outside the camera’s viewing area but does not disable anything hidden from view by overdraw. Note that when you use Occlusion Culling you will still benefit from Frustum Culling.
A maze-like indoor level. This normal scene view shows all visible Game Objects.
Regular frustum culling only renders objects within the camera’s view. This is automatic and always happens.
Occlusion culling removes additional objects from within the camera rendering work if they are entirely obscured by nearer objects.
The occlusion culling process will go through the scene using a virtual camera to build a hierarchy of potentially visible sets of objects. This data is used at runtime by each camera to identify what is visible and what is not. Equipped with this information, Unity will ensure only visible objects get sent to be rendered. This reduces the number of draw calls and increases the performance of the game.
The data for occlusion culling is composed of cells. Each cell is a subdivision of the entire bounding volume of the scene. More specifically the cells form a binary tree. Occlusion Culling uses two trees, one for View Cells (Static Objects) and the other for Target Cells (Moving Objects). View Cells map to a list of indices that define the visible static objects which gives more accurate culling results for static objects.
It is important to keep this in mind when creating your objects because you need a good balance between the size of your objects and the size of the cells. Ideally, you shouldn’t have cells that are too small in comparison with your objects but equally you shouldn’t have objects that cover many cells. You can sometimes improve the culling by breaking large objects into smaller pieces. However, you can still merge small objects together to reduce draw calls and, as long as they all belong to the same cell, occlusion culling will not be affected.
You can use the ‘overdraw’ scene rendering mode to see the amount of overdraw that is occuring, and the stats information pane in the game view to see the amount of triangles, verts, and batches that are being rendered. Below is a comparison of these before and after applying occlusion culling.
Notice in the Overdraw scene view, a high density of overdraw as many rooms beyond the visible walls are rendered. These aren’t visible in the game view, but nonetheless time is being taken to render them.
With occlusion culling applied, the distant rooms are not rendered, the overdraw is much less dense, and the number of triangles and batches being rendered has dropped dramatically, without any change to how the game view looks.
Setting up Occlusion Culling
In order to use Occlusion Culling, there is some manual setup involved. First, your level geometry must be broken into sensibly sized pieces. It is also helpful to lay out your levels into small, well defined areas that are occluded from each other by large objects such as walls, buildings, etc. The idea here is that each individual mesh will be turned on or off based on the occlusion data. So if you have one object that contains all the furniture in your room then either all or none of the entire set of furniture will be culled. This doesn’t make nearly as much sense as making each piece of furniture its own mesh, so each can individually be culled based on the camera’s view point.
You need to tag all scene objects that you want to be part of the occlusion to Occluder Static in the Inspector. The fastest way to do this is to multi-select the objects you want to be included in occlusion calculations, and mark them as Occluder Static and Occludee Static.
Marking an object for Occlusion
When should you use Occludee Static? Completely transparent or translucent objects that do not occlude, as well as small objects that are unlikely to occlude other things, should be marked as Occludees, but not Occluders. This means they will be considered in occlusion by other objects, but will not be considered as occluders themselves, which will help reduce computation.
When using LOD groups, only the base level object (LOD0) may be used as an Occluder.
Occlusion Culling Window
For most operations dealing with Occlusion Culling, you should use the Occlusion Culling Window (Window->Occlusion Culling)
In the Occlusion Culling Window, you can work with occluder meshes, and Occlusion Areas.
If you are in the Object tab of the Occlusion Culling Window and have a Mesh Renderer selected in the scene, you can modify the relevant Static flags:
Occlusion Culling Window for a Mesh Renderer
If you are in the Object tab of the Occlusion Culling Window and have an Occlusion Area selected, you can work with relevant OcclusionArea properties (for more details go to the Occlusion Area section)
Occlusion Culling Window for the Occlusion Area
NOTE: By default if you don’t create any occlusion areas, occlusion culling will be applied to the whole scene.
NOTE: Whenever your camera is outside occlusion areas, occlusion culling will not be applied. It is important to set up your Occlusion Areas to cover the places where the camera can potentially be, but making the areas too large incurs a cost during baking.
The occlusion culling bake window has a “Set Default Parameters” button, which allows you to reset the bake values to Unity’s default values. These are good for many typical scenes, however you’ll often be able to get better results by adjusting the values to suit the particular contents of your scene.
Properties
At the bottom of the bake tab is are the Clear and Bake buttons. Click on the Bake Button to start generating the Occlusion Culling data. Once the data is generated, you can use the Visualization tab to preview and test the occlusion culling. If you are not satisfied with the results, click on the Clear button to remove previously calculated data, adjust the settings, and bake again.
All the objects in the scene affect the size of the bounding volume so try to keep them all within the visible bounds of the scene.
When you’re ready to generate the occlusion data, click the Bake button. Remember to choose the Memory Limit in the Bake tab. Lower values make the generation quicker and less precise, higher values are to be used for production quality closer to release.
Bear in mind that the time taken to build the occlusion data will depend on the cell levels, the data size and the quality you have chosen.
After the processing is done, you should see some colorful cubes in the View Area. The colored areas are regions that share the same occlusion data.
Click on Clear if you want to remove all the pre-calculated data for Occlusion Culling.
Occlusion Area
After creating the Occlusion Area, check the Is View Volume checkbox to occlude moving objects.
Property: | Function: |
---|---|
Size | Defines the size of the Occlusion Area. |
Center | Sets the center of the Occlusion Area. By default this is 0,0,0 and is located in the center of the box. |
Is View Volume | Defines where the camera can be. Check this in order to occlude static objects that are inside this Occlusion Area. |
Occlusion Area properties for moving objects.
After you have added the Occlusion Area, you need to see how it divides the box into cells. To see how the occlusion area will be calculated, select Edit and toggle the View button in the Occlusion Culling Preview Panel.
Testing the generated occlusion
After your occlusion is set up, you can test it by enabling the Occlusion Culling (in the Occlusion Culling Preview Panel in Visualize mode) and moving the Main Camera around in the scene view.
The Occlusion View mode in Scene View
As you move the Main Camera around (whether or not you are in Play mode), you’ll see various objects disable themselves. The thing you are looking for here is any error in the occlusion data. You’ll recognize an error if you see objects suddenly popping into view as you move around. If this happens, your options for fixing the error are either to change the resolution (if you are playing with target volumes) or to move objects around to cover up the error. To debug problems with occlusion, you can move the Main Camera to the problematic position for spot-checking.
When the processing is done, you should see some colorful cubes in the View Area. The blue cubes represent the cell divisions for Target Volumes. The white cubes represent cell divisions for View Volumes. If the parameters were set correctly you should see some objects not being rendered. This will be because they are either outside of the view frustum of the camera or else occluded from view by other objects.
After occlusion is completed, if you don’t see anything being occluded in your scene then try breaking your objects into smaller pieces so they can be completely contained inside the cells.
Русские Блоги
Unity 3D Occlusion Culling (Только для профессионалов)
Поделитесь учебником по искусственному интеллекту моего учителя! Начинается с нуля, легко понять!http://blog.csdn.net/jiangjunshow
Вы также можете перепечатать эту статью. Делитесь знаниями, приносите пользу людям и осознайте великое омоложение нашей китайской нации!
Occlusion Culling is a feature that disables rendering of objects when they are not currently seen by the camera because they are obscured by other objects. This does not happen automatically in 3D computer graphics since most of the time objects farthest away from the camera are drawn first and closer objects are drawn over the top of them (this is called «overdraw»). Occlusion Culling is different from Frustum Culling. Frustum Culling only disables the renderers for objects that are outside the camera’s viewing area but does not disable anything hidden from view by overdraw. Note that when you use Occlusion Culling you will still benefit from Frustum Culling.
Отбор окклюзии, когда объект перекрывается другими объектами и находится вне зоны видимости камеры, он не отображается. Отбор окклюзии не является автоматическим при расчете трехмерной графики. Поскольку в большинстве случаев объект, самый дальний от камеры, отображается первым, а объект, расположенный рядом с камерой, отображается и закрывает ранее отображенный объект (это называется повторным рендерингом «overdraw»). Отбор окклюзии отличается от выбора усеченного конуса. При отбраковке по пирамиде объекты не отображаются за пределами угла обзора камеры, но объекты, которые закрыты другими объектами, но все еще находятся в пределах диапазона углов обзора, не будут отбраковываться. Обратите внимание, что при использовании отсечения при окклюзии вы по-прежнему извлекаете выгоду из отбраковки усеченного конуса ( Отбор Frustum).
The scene rendered without Occlusion Culling Рендеринг сцены без выбраковки окклюзии
The same scene rendered with Occlusion Culling Рендеринг сцены с отбраковкой окклюзии
The occlusion culling process will go through the scene using a virtual camera to build a hierarchy of potentially visible sets of objects. This data is used at runtime by each camera to identify what is visible and what is not. Equipped with this information, Unity will ensure only visible objects get sent to be rendered. This reduces the number of draw calls and increases the performance of the game.
Операция отбора окклюзии создаст иерархию потенциальных состояний видимости объектов с использованием виртуальной камеры в сцене. Эти данные позволяют каждой камере определять, что можно увидеть и не увидеть в режиме реального времени. С этими данными Unity определит, что для визуализации отправляются только видимые объекты. Это уменьшит количество розыгрышей колл и увеличит эффективность игры.
The data for occlusion culling is composed of cells. Each cell is a subdivision of the entire bounding volume of the scene. More specifically the cells form a binary tree. Occlusion Culling uses two trees, one for View Cells (Static Objects) and the other for Target Cells (Moving Objects). View Cells map to a list of indices that define the visible static objects which gives more accurate culling results for static objects.
Данные для отбора окклюзии состоят из ячеек. Каждая ячейка является частью окружающего объема всей сцены. Ячейки происходят из двоичного дерева. При отбраковке окклюзии используются два дерева, одно для View Cells (статические объекты). ), Другой для целевых ячеек (движущихся объектов). Ячейки представления отображаются в список индексов, которые определяют статические визуальные объекты (точно удаленные статические объекты).
It is important to keep this in mind when creating your objects because you need a good balance between the size of your objects and the size of the cells. Ideally, you shouldn’t have cells that are too small in comparison with your objects but equally you shouldn’t have objects that cover many cells. You can sometimes improve the culling by breaking large objects into smaller pieces. However, you can still merge small objects together to reduce draw calls and, as long as they all belong to the same cell, occlusion culling will not be affected. The collection of cells and the visibility information that determines which cells are visible from any other cell is known as a PVS (Potentially Visible Set).
Это очень важно помнить при создании объекта, потому что вам нужно найти хороший баланс между размером объекта и размером ячейки. В идеале, не должно быть слишком маленьких ячеек по сравнению с объектом. Сетка, но опять же, объекты не должны покрывать много ячеек. Иногда вы можете улучшить эффект отбраковки окклюзии, разделив большие объекты на несколько частей. Однако вы все равно можете объединять небольшие объекты, чтобы уменьшить количество вызовов отрисовки (Рисование вызовов), когда все они принадлежат одной маленькой ячейке, выборка окклюзии не будет работать. Набор ячеек и визуальная информация определяют, какие ячейки являются видимыми и считаются PVS (Потенциально видимым набором).
Настройка окклюзии выбраковки
In order to use Occlusion Culling, there is some manual setup involved. First, your level geometry must be broken into sensibly sized pieces. It is also helpful to lay out your levels into small, well defined areas that are occluded from each other by large objects such as walls, buildings, etc. The idea here is that each individual mesh will be turned on or off based on the occlusion data. So if you have one object that contains all the furniture in your room then either all or none of the entire set of furniture will be culled. This doesn’t make nearly as much sense as making each piece of furniture its own mesh, so each can individually be culled based on the camera’s view point.
Чтобы использовать окклюзионную отбраковку, необходимы соответствующие ручные настройки. Во-первых, геометрия вашего уровня должна быть разделена на блоки разумного размера. Это также помогает расположить небольшие, четко определенные области на уровне, которые заблокированы другими крупными объектами (например, стенами, зданиями). Это означает, что каждая отдельная сетка определяет, следует ли выполнять рендеринг на основе данных окклюзии. Таким образом, если у вас есть предмет, который содержит всю мебель в комнате, то вся мебель будет либо полностью обработана, либо не обработана вовсе. У каждой мебели есть своя сетка, которая будет иметь разные ощущения, тогда, в зависимости от точки зрения камеры, каждый объект может быть удален индивидуально.
You need to tag all scene objects that you want to be part of the occlusion to Occlusion Static in the Inspector. The fastest way to do this is to multi-select the objects you want to be included in occlusion calculations, and mark them as Occlusion Static and Occludee Static.
Marking an object for Occlusion Отметить объекты для окклюзии
When should I use Occludee Static? Transparent objects that do not occlude, as well as small objects that are unlikely to occlude other things, should be marked as Occludees, but not Occluders. This means they will be considered in occlusion by other objects, but will not be considered as occluders themselves, which will help reduce computation.
Когда я должен использовать Occludee Static? Прозрачные объекты не могут быть заблокированы, а маленькие объекты не могут блокировать другие объекты, они должны быть помечены как Occludees, но не заблокированы. Это означает, что они будут считаться окклюзированными другими объектами, а не самими окклюдерами, что поможет уменьшить объем вычислений.
Окклюзионное окно окклюзии
For most operations dealing with Occlusion Culling, we recommend you use the Occlusion Culling Window (Window->Occlusion Culling)
Для большинства операций, связанных с отбраковкой окклюзии, мы рекомендуем использовать окно отбора окклюзии (Window-> Occlusion Culling)
In the Occlusion Culling Window, you can work with occluder meshes, and Occlusion Areas.
В окне отбора окклюзии вы можете использовать сетку окклюзии и область окклюзии.
If you are in the Object tab of the Occlusion Culling Window and have some Mesh Renderer selected in the scene, you can modify the relevant Static flags:
Если вы блокируете метку объекта в окне выбраковки, и у вас есть некоторые в сцене Mesh Renderer После выбора вы можете изменить соответствующий статический логотип:
Occlusion Culling Window for a Mesh Renderer
If you are in the Object tab of the Occlusion Culling Window and have an Occlusion Area selected, you can work with relevant OcclusionArea properties (for more details go to the Occlusion Area section)
Если вы находитесь на вкладке «Объект» окна выбора окклюзии и выбрана область окклюзии, вы можете использовать соответствующий атрибут OcclusionArea (для получения более подробной информации перейдите к главе «Область окклюзии», чтобы просмотреть ее).
Occlusion Culling Window for the Occlusion Area
Окно выбраковки окклюзии для области окклюзии
NOTE: By default if you don’t create any occlusion areas, occlusion culling will be applied to the whole scene.
Примечание. По умолчанию, если вы не создадите область окклюзии, выборка окклюзии будет применена ко всей сцене.
NOTE: Whenever your camera is outside occlusion areas, occlusion culling will not be applied. It is important to set up your Occlusion Areas to cover the places where the camera can potentially be, but making the areas too large, incurs a cost during baking.
Примечание. Всякий раз, когда камера находится за пределами зоны окклюзии, отбор окклюзии не применяется. Важно то, что область, покрываемая этой областью окклюзии, должна иметь камеру, но если область окклюзии слишком велика, это приведет к увеличению накладных расходов на выпечку.
Окклюзия выбраковка-выпекание окклюзия выбраковка-выпечка
Occlusion culling inspector bake tab.Испечь этикетку для окклюзионной панели
When you have finished tweaking these values you can click on the Bake Button to start processing the Occlusion Culling data. If you are not satisfied with the results, you can click on the Clear button to remove previously calculated data.
После того, как вы отрегулируете эти значения, вы можете нажать кнопку Bake, чтобы начать обработку данных отбора окклюзии. Если вы не удовлетворены результатом, вы можете нажать кнопку «Очистить Очистить», чтобы удалить ранее рассчитанные данные.
Окклюзия выбраковка-визуализация окклюзия выбраковка-визуализация
Occlusion culling inspector visualization tab.Вкладка визуализации панели проверки окклюзии
The near and far planes define a virtual camera that is used to calculate the occlusion data. If you have several cameras with different near or far planes, you should use the smallest near plane and the largest far plane distance of all cameras for correct inclusion of objects.
All the objects in the scene affect the size of the bounding volume so try to keep them all within the visible bounds of the scene.
Все объекты в сцене влияют на размер вложенного тома, пожалуйста, держите все свои объекты в пределах видимого диапазона сцены.
When you’re ready to generate the occlusion data, click the Bake button. Remember to choose the Memory Limit in the Bake tab. Lower values make the generation quicker and less precise, higher values are to be used for production quality closer to release.
Когда вы будете готовы сгенерировать данные окклюзии, нажмите кнопку Bake и не забудьте выбрать ограничение памяти на вкладке Bake. Чем меньше значение, тем быстрее генерация и ниже точность. Чем выше значение, тем лучше качество продукции.
Bear in mind that the time taken to build the occlusion data will depend on the cell levels, the data size and the quality you have chosen. Unity will show the status of the PVS generation at the bottom of the main window.
Пожалуйста, имейте в виду, что скорость генерации данных при заборе окклюзии зависит от заданных вами уровней ячеек, размера данных и качества. Unity отобразит статус генерации PVS в нижней части главного окна.
After the processing is done, you should see some colorful cubes in the View Area. The colored areas are regions that share the same occlusion data.
Click on Clear if you want to remove all the pre-calculated data for Occlusion Culling.
Если вы хотите удалить все предварительно рассчитанные данные (предварительно рассчитанные данные) для отбора из окклюзии, нажмите кнопку Очистить.
Окклюзионная зона
To apply occlusion culling to moving objects you have to create an Occlusion Area and then modify its size to fit the space where the moving objects will be located (of course the moving objects cannot be marked as static). You can create Occlusion Areas is by adding the Occlusion Areacomponent to an empty game object (Component->Rendering->Occlusion Area in the menus)
Если вы хотите применить отбраковку окклюзии к движущимся объектам, вы должны создать область окклюзии (область окклюзии) и изменить ее размер так, чтобы она соответствовала пространству перемещения движущегося объекта (примечание: движущиеся объекты нельзя пометить как статические). Компонент области добавляется в пустой игровой объект (меню Компонент-> Рендеринг-> Область окклюзии)
After creating the Occlusion Area, just check the Is Target Volume checkbox to occlude moving objects.
После создания области окклюзии установите флажок Is Target Volume, чтобы блокировать и исключать движущиеся объекты.
Occlusion Area properties for moving objects.Свойства области окклюзии движущихся объектов
After you have added the Occlusion Area, you need to see how it divides the box into cells. To see how the occlusion area will be calculated, SelectEdit and toggle the View button in the Occlusion Culling Preview Panel.
После добавления области окклюзии вам необходимо понять, как коробка делится на ячейки. Чтобы увидеть, как рассчитывается область окклюзии, на панели предварительного просмотра окклюзии выберите «Редактировать, Изменить» и нажмите кнопку «Вид».
Тестирование сгенерированной окклюзии
After your occlusion is set up, you can test it by enabling the Occlusion Culling (in the Occlusion Culling Preview Panel in Visualize mode) and moving the Main Camera around in the scene view.
После завершения настройки окклюзии включите отбор окклюзии (на панели предварительного просмотра окклюзии, панель предварительного просмотра окклюзии, режим визуализации) и переместите основную камеру в окне сцены для проверки.
The Occlusion View mode in Scene ViewРежим просмотра окклюзии в режиме просмотра сцены
As you move the Main Camera around (whether or not you are in Play mode), you’ll see various objects disable themselves. The thing you are looking for here is any error in the occlusion data. You’ll recognize an error if you see objects suddenly popping into view as you move around. If this happens, your options for fixing the error are either to change the resolution (if you are playing with target volumes) or to move objects around to cover up the error. To debug problems with occlusion, you can move the Main Camera to the problematic position for spot-checking.
Когда вы перемещаете основную камеру влево или вправо (в режиме воспроизведения или нет), вы видите, что различные объекты отключаются самостоятельно. Здесь вам нужно найти любые ошибки в данных окклюзии. При перемещении камеры вы можете обнаружить, что объект внезапно появляется в поле зрения. Если это произойдет, исправьте ошибку, изменив разрешение (если оно воспроизводится в режиме целевых объемов), или переместите объект влево и вправо, чтобы замаскировать ошибку. Чтобы устранить проблему окклюзии, вы можете переместить основную камеру, чтобы проверить местонахождение проблемы.
When the processing is done, you should see some colorful cubes in the View Area. The blue cubes represent the cell divisions for Target Volumes. The white cubes represent cell divisions for View Volumes. If the parameters were set correctly you should see some objects not being rendered. This will be because they are either outside of the view frustum of the camera or else occluded from view by other objects.
После вычисления вы увидите несколько кубов с разными цветами в области просмотра. Синие кубики обозначают деление единицы на целевые объемы. Белые кубы указывают деление единицы на просмотр объёмов. Если настройки параметров верны, вы увидите некоторые Объекты не отображаются, это означает, что эти объекты либо не находятся в поле зрения камеры, либо заблокированы другими объектами.
After occlusion is completed, if you don’t see anything being occluded in your scene then try breaking your objects into smaller pieces so they can be completely contained inside the cells.
Если какие-либо объекты в сцене не блокируются после завершения окклюзии, разбейте объекты на более мелкие блоки, чтобы они могли полностью содержаться в ячейке.
Окклюзионные порталы
In order to create occlusion primitive which are openable and closable at runtime, Unity uses Occlusion Portals.
Для создания в реальном времени открываемых и закрываемых окклюзий Unity использует Occlusion Portals.