Occluder Nodes

В дополнение к окклюзии с помощью :ref: doc_rooms_and_portals, Godot также имеет возможность обеспечить базовую окклюзию с помощью простых геометрических узлов Occluder. Это геометрические фигуры, которые отображаются в редакторе с помощью gizmos, но невидимы во время выполнения.

Любой объект, который полностью закрыт формой (позади или в некоторых случаях внутри), будет обрезан во время выполнения. Они разработаны так, чтобы быть простыми в использовании и недорогими во время выполнения, но компромисс заключается в том, что они могут быть не такими эффективными при отбраковке, как :ref: doc_rooms_and_portals. Тем не менее, в некоторых ситуациях они все еще могут значительно повысить производительность.

Примечание

It is important to understand that geometric occluders work by testing the axis aligned bounding box (AABB) of the occludee against the occluder. The AABB must be fully occluded to be culled. The consequence of this is that smaller objects are more likely to be effectively culled than larger objects, and larger occluders tend to be much more effective than smaller ones.

Основным преимуществом окклюдер узлов является то, что они полностью динамичны. Например, если вы разместите узел окклюдер в качестве дочернего элемента космического корабля, он будет перемещаться по мере перемещения родительского объекта.

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

Сам узел окклюдер является держателем ресурса ОкклюдерСферы, который определяет функциональность. Чтобы начать, добавьте узел Окклюдер в дерево сцены.

Совет

Вы увидите желтый предупреждающий треугольник, который дает вам знать, что вы должны установить ОкклюдерСферу из инспектора, прежде чем Окклюдер заработает

OccluderShapeSphere

Сфера является одним из самых простых и быстрых окклюдеров, ее легко настроить и расположить. Недостатком является то, что сфера имеет смысл только в определенных дизайнах игровых уровней и больше подходит для ландшафта или органической геометрии фона.

После того, как вы добавили OccluderNode и выбрали добавление новой OccluderShapeSphere в инспекторе, щелкните OccluderShapeSphere в инспекторе, чтобы открыть параметры.

../../_images/occluder_shape_sphere_inspector.png

В отличие от многих узлов, OccluderShapeSphere может хранить несколько сфер в одном объекте. Это более эффективно в движке и делает ваше дерево сцен более четким. Вам не обязательно хранить все ваши сферы в одном окклюдере, так как это может усложнить управление, но вполне разумно добавить 10 или около того сфер или больше. Они очень дешевы, и часто, чем больше вы размещаете, тем лучше они соответствуют вашей геометрии.

Чтобы сохранить несколько сфер, они хранятся в виде массива. Если вы нажмете на массив в инспекторе, вы можете увеличить размер массива, чтобы добавить его.

../../_images/occluder_shape_sphere_terrain.png

Сфера появится в окне редактора в виде маленького розового сферического объекта. На каждой сфере есть две ручки. Большая средняя ручка позволяет перемещать сферу в локальном пространстве окклюдера, а маленькая ручка позволяет регулировать радиус.

Хотя вы можете изменить положение сферы с помощью преобразования Occluder Node в инспекторе, это перемещает * весь массив* сфер. Если вы хотите использовать несколько сфер в одном occluder, эту работу выполняют ручки. Чтобы разрешить позиционирование в 3D, gizmo будет перемещать 3D-положение только по двум основным осям в зависимости от точки обзора в редакторе. Вам легче освоиться с этим, попробовав, чем объяснив.

Совет

В редакторе есть еще одна удобная функция при использовании нескольких сфер. Если вы нажмете кнопку на панели инструментов Центральный узел, она пересчитает локальные положения сфер относительно среднего значения для всего узла и изменит преобразование Occluder Node. Это удобная функция, облегчающая их размещение.

Во время выполнения, сферы можно включать и выключать, изменяя видимость Occluder node , а Узел можно перемещать, масштабировать, поворачивать и т.д.

Распространенным вариантом использования окклюдирующих сфер является обеспечение окклюзии на горной / холмистой местности. Размещая сферы внутри гор, вы можете предотвратить отображение деревьев, растений, зданий и объектов за горами. При некотором творческом подходе их также можно использовать для перемещения объектов, таких как большие космические корабли, планеты и т.д.

OccluderShapePolygon

The polygon is a generalist occluder. It can be made to work well in almost all situations, and can quickly provide a degree of occlusion culling to most scenes.

As with all geometric occluders, the key to success is to make them large. They do not have to match rendered geometry, and in many cases they will work better if you extend them past rendered geometry to make them as big as possible (without blocking legitimate lines of sight). The reason why they need to be large is that in general, they will only cull objects whose AABB is completely hidden by the polygon. For large objects to be culled, you will need large occluders.

Примечание

Like all occluders, polygons can overlap, and in many cases they will work better if you overlap them (they are more likely to cull objects on boundaries).

Editing and details

Occluder polygons are edited as a list of points which define a convex polygon, on a single plane. In order to confine the polygon to a single plane, the points are defined in 2D space rather than 3D. The orientation, position and scale of the polygon is taken instead from the transform of the Occluder Node.

../../_images/occluder_shape_polygon_inspector.png

If you create an Occluder and add to it a OccluderShapePolygon resource, by default it will create 4 starting points forming a rectangle. If you move the position and rotation of the Occluder Node you will see how the rectangle follows the node. When the Occluder is selected in the editor, handles will appear for each of the points. You can actually click and drag these handles, to match your polygon to the environment of your scene.

../../_images/occluder_shape_polygon.png

You are not restricted to 4 points, you can add and remove points in the Inspector, but note that:

  • Редактор автоматически очистит ваши точки, чтобы сформировать выпуклый многоугольник. Если вы перетащите точку в положение, которое образовало бы вогнутый многоугольник, она будет проигнорирована.

  • В общем, чем меньше ребер (и, следовательно, точек), тем быстрее многоугольник будет работать во время выполнения. Многоугольник с 6 ребрами должен будет выполнить вдвое больше вычислений, чем многоугольник с 3 ребрами. В большинстве случаев 4 ребер достаточно.

../../_images/occluder_shape_polygon2.png

Holes

Real world game levels don't always have large continuous areas that should be occluded. Often walls will have a door or windows, caves will have an entrance, etc. In some cases we have to make do by placing several OccluderShapePolygons around such an opening, but Occluder polygons have one more trick up their sleeve - they can have "holes".

In the inspector you will notice that as well as a set of points for the polygon, the polygon has a set of points for a single "hole". If you add 3 or 4 to your polygon, you will see they appear in the editor as smaller handles. You can drag these around just like the polygon handles, to form a convex hole.

../../_images/occluder_shape_polygon_hole.png

The hole can be totally within the polygon (such as a window), abutting the edge (like a door) or crossing the edge of the polygon completely, to make the occluder concave. The way the hole works is that the culling follows a simple rule:

  • If the object to be culled is totally hidden by the polygon, it then looks to see whether it can be seen through the hole. If the object touches the hole, it is not culled, but if hidden by the polygon and not seen through the hole it is culled.

Примечание

Placing holes is usually far more convenient, and works faster and better at runtime, than creating lots of smaller OccluderShapePolygons.

Hole Limits

The main limitation of holes is that there can only be one per polygon. If you have a situation which requires two or more holes, you have a choice:

  • Combine the area of the two holes into one bigger hole (if they are close together).

  • Use two or more OccluderPolygons.

Совет

Remember that if you are using more than one polygon, they can overlap, and you should use this to your advantage.

How many Occluder polys are needed?

This very much depends on your scene, but generally you can start getting a good benefit from 3 or 4 well placed polygons. After that it is totally up to you how much time you want to spend. Placing occluders is a bit of an art form, and you will get better at it and learn new tricks the more you work with them.

Some ideas:

  • Build your levels to take advantage of occlusion.

This is one of the secrets of the pros. A good level design is not just about what the gameplay demands, it should also be built with occlusion in mind.

  • When in a building with multiple floors, try placing an occluder polygon between each floor, with a hole for where the staircase transitions between them. This can potentially cull out entire floors and greatly improve performance.

  • Don't be afraid to extend your occluder polygons far past the edges of visible geometry to cull more objects - for instance far into the ground or sky.

Using polygons dynamically

Like all geometric occluders, polygons are not confined to static (non-moving) geometry. You can place them on moving objects. You can even change the relative position of the points in realtime.

Some guidelines:

  • There is a slight cost to moving polygons, the points of the polygons must be transformed on the CPU each time their transform changes.

This is not something to worry excessively about, even CPUs are reasonably fast at transforming points, and generally polygons have very few points compared to rendered geometry. But it is something to consider, if you wanted to create e.g. 10,000 simultaneous spaceships all with occluder polys.

  • Changing the transform of the polygon Node (e.g. by moving the parent object) is cheaper than changing the points themselves. Use the former rather than the latter wherever possible.