Ru/Areaportal: Difference between revisions

From Valve Developer Community
< Ru
Jump to navigation Jump to search
mNo edit summary
mNo edit summary
Line 1: Line 1:
{{Language subpage}}
{{Language subpage}}
[[File:areaportal_simple_open.jpg|200px|right|thumb|caption|Открытый areaportal (зелёный контур).]][[File:areaportal_simple_closed.jpg|200px|right|thumb|caption|Закрытый areaportal.]]


[[Image:areaportal_simple_open.jpg|200px|right|thumb|caption|Открытый areaportal (зелёный контур).]][[Image:areaportal_simple_closed.jpg|200px|right|thumb|caption|Закрытый areaportal.]]
''Areaportal'' - [[brush entity|брашевая сущность]], {{Ent|func_areaportal}}, {{Ent|func_areaportalwindow}}, которую можно использовать для 'запечатывания' [[visleaves|листов]] и управления видимостью.
 
''Areaportal'' - [[brush entity|брашевая сущность]], <code>[[func_areaportal]]</code>, <code>[[func_areaportalwindow]]</code>, которую можно использовать для 'запечатывания' [[visleaves|листов]] и управления видимостью.


Areaportal'ы служат двум разным целям: отбраковке геометрии и удалению целых областей из отрисовки.
Areaportal'ы служат двум разным целям: отбраковке геометрии и удалению целых областей из отрисовки.


Areaportal'ы похожи на дверные проемы, которые либо открыты, либо закрыты. Когда Areaportal закрыт, он блокирует видимость геометрии и объектов в области за ним. Когда он открыт, геометрия вновь видна. Areaportal'ы можно динамически открывать и закрывать во время игры. Обычно, они настраиваются на открытие и закрытие набором брашей <code>[[trigger_multiple]]</code> с помощью [[Inputs and Outputs|системы входов/выходов]] или связыванием с сущностью [[Doors:ru|двери]].
Areaportal'ы похожи на дверные проемы, которые либо открыты, либо закрыты. Когда Areaportal закрыт, он блокирует видимость геометрии и объектов в области за ним. Когда он открыт, геометрия вновь видна. Areaportal'ы можно динамически открывать и закрывать во время игры. Обычно, они настраиваются на открытие и закрытие набором брашей {{Ent|trigger_multiple}} с помощью [[Inputs and Outputs|системы входов/выходов]] или связыванием с сущностью [[Doors:ru|двери]].


== Свойства ==
== Свойства ==
 
[[File:Areaportal trainstation04.jpg|200px|thumb|right|caption|trigger_multiple можно использовать для открытия и закрытия Areaportal'ов, чтобы скрывать зоны на уровне.]]
[[Image:Areaportal trainstation04.jpg|200px|thumb|right|caption|trigger_multiple можно использовать для открытия и закрытия Areaportal'ов, чтобы скрывать зоны на уровне.]]


Areaportal'ы:
Areaportal'ы:


* связаны с сущностью <code>[[func_areaportal]]</code>.
* связаны с сущностью {{Code|func_areaportal}}.
* должны состоять только из одного браша. Areaportal'ы из более чем одного браша будут выдавать ошибку компиляции [[vbsp]].
* должны состоять только из одного браша. Areaportal'ы из более чем одного браша будут выдавать ошибку компиляции [[vbsp]].
* должны использовать материал <code>tools\toolsareaportal</code>, покрывающий все стороны их браша.
* должны использовать материал <code>tools\toolsareaportal</code>, покрывающий все стороны их браша.
Line 25: Line 23:


=== areaportal_window ===
=== areaportal_window ===
 
Сущность {{Ent|func_areaportalwindow}} ведёт себя как обычный Areaportal, с добавлением затухания и закрытия в зависимости от удалённости игрока. Это позволяет избежать "резкого" открытия Areaportalа.
Сущность <code>[[func_areaportalwindow]]</code> ведёт себя как обычный Areaportal, с добавлением затухания и закрытия в зависимости от удалённости игрока. Это позволяет избежать "резкого" открытия Areaportalа.


== Конструкция ==
== Конструкция ==
 
[[File:areaportal_simple_ex1.jpg|200px|right|thumb|caption|Конструкция основного ареа-портала.]]
[[Image:areaportal_simple_ex1.jpg|200px|right|thumb|caption|Конструкция основного ареа-портала.]]


# Создайте объём из одного твёрдого [[brush|браша]], полностью запечатав пространство между двумя зонами, которыми вы желаете управлять. (Если необходимо, это могут быть несколько ареа-порталов, соприкасающихся гранями. Не создавайте ареа-портал с более, чем шестью сторонами.)
# Создайте объём из одного твёрдого [[brush|браша]], полностью запечатав пространство между двумя зонами, которыми вы желаете управлять. (Если необходимо, это могут быть несколько ареа-порталов, соприкасающихся гранями. Не создавайте ареа-портал с более, чем шестью сторонами.)
# Если ареа-портал соединяет две области, например, дверной проём, сделайте браш размером с проём и такой же толщиной, как и стены, с которыми он соприкасается. Если область представляет собой открытое пространство, то толщина может быть любой (типичные размеры сетки: 8, 16, 32 и т.д.).
# Если ареа-портал соединяет две области, например, дверной проём, сделайте браш размером с проём и такой же толщиной, как и стены, с которыми он соприкасается. Если область представляет собой открытое пространство, то толщина может быть любой (типичные размеры сетки: 8, 16, 32 и т.д.).
# Наложите материал <code>[[Tool textures#Optimisation|tools\toolsareaportal]]</code> на все грани браша.
# Наложите материал {{Ent|Tool textures#Optimisation|tools\toolsareaportal}} на все грани браша.
# [[Entity Creation|Свяжите браш]] с сущностью [[func_areaportal]] или [[func_areaportalwindow]].
# [[Entity Creation|Свяжите браш]] с сущностью {{Ent|func_areaportal}} или {{Ent|func_areaportalwindow}}.
# Установите значение ключа ''Initial State'' (изначальное состояние) так, чтобы оно не блокировало видимость, когда этого не должно быть. Если вы хотите связать портал с поименованной дверью, установите его ''Initial State'' в то же состояние, что и для двери, и внесите имя двери в строку портала ''Name of Linked Door'' (имя связываемой двери). Если дверь закрыта, изначальное состояние портала также должно быть закрытым, и наоборот.
# Установите значение ключа ''Initial State'' (изначальное состояние) так, чтобы оно не блокировало видимость, когда этого не должно быть. Если вы хотите связать портал с поименованной дверью, установите его ''Initial State'' в то же состояние, что и для двери, и внесите имя двери в строку портала ''Name of Linked Door'' (имя связываемой двери). Если дверь закрыта, изначальное состояние портала также должно быть закрытым, и наоборот.


Line 41: Line 37:


== Влияние на производительность ==
== Влияние на производительность ==
 
<div style="text-align:center;">[[File:areaportal_culling_engine1.jpg|350px|caption|Отрисовка каркаса ареа-портала в движке. Отрисовывается только та геометрия листов, которая видима через ареа-портал.]] [[File:areaportal_culling_engine2.jpg|350px|caption|Та же сцена с отключённым ареа-порталом. Отрисовывается вся геометрия листов.]]</div>
<div style="text-align:center;">[[Image:areaportal_culling_engine1.jpg|350px|caption|Отрисовка каркаса ареа-портала в движке. Отрисовывается только та геометрия листов, которая видима через ареа-портал.]] [[Image:areaportal_culling_engine2.jpg|350px|caption|Та же сцена с отключённым ареа-порталом. Отрисовывается вся геометрия листов.]]</div>


Открытые порталы (не важно, открыты они всегда, или временами) ведут себя, как шторки для видимой сквозь них геометрии. Подобно окну дома, движок отрисовывает только те [[visleaves|листы]], которые непосредственно видны через портал. То есть, область за ним 'обрезается' по размеру окна, уменьшая величину отображаемой геометрии и улучшая производительность. Вдобавок ко всему, часть модели (prop) вообще не отрисовывается, когда она видна под ''усечённым конусом'' (или видимым углом). Это делает открытые порталы весьма полезными для управления видимостью геометрии моделей.
Открытые порталы (не важно, открыты они всегда, или временами) ведут себя, как шторки для видимой сквозь них геометрии. Подобно окну дома, движок отрисовывает только те [[visleaves|листы]], которые непосредственно видны через портал. То есть, область за ним 'обрезается' по размеру окна, уменьшая величину отображаемой геометрии и улучшая производительность. Вдобавок ко всему, часть модели (prop) вообще не отрисовывается, когда она видна под ''усечённым конусом'' (или видимым углом). Это делает открытые порталы весьма полезными для управления видимостью геометрии моделей.


[[Image:areaportal_culling_top.jpg|thumb|Открытый ареа-портал сильно ограничивает видимость модели.]]
[[File:areaportal_culling_top.jpg|thumb|Открытый ареа-портал сильно ограничивает видимость модели.]]


Благодаря таким преимуществам в производительности, ареа-порталы часто используются в состоянии ''всегда открыт''. Всегда открытый портал создаётся путём установки ключа "Initial State" (изначальное состояние) сущности <code>[[func_areaportal]]</code> в значение "Open" (открыт). Открытые порталы используются на входе в другие области, содержащие большое число листов и геометрии. Например, такой портал, размещённый в конце коридора, выходящего на более широкое пространство, может дать существенный прирост производительности. Пока игрок смотрит сквозь  дверь изнутри, будут отрисовываться только те листы с геометрией, которые видны непосредственно в проём.
Благодаря таким преимуществам в производительности, ареа-порталы часто используются в состоянии ''всегда открыт''. Всегда открытый портал создаётся путём установки ключа "Initial State" (изначальное состояние) сущности {{Ent|func_areaportal}} в значение "Open" (открыт). Открытые порталы используются на входе в другие области, содержащие большое число листов и геометрии. Например, такой портал, размещённый в конце коридора, выходящего на более широкое пространство, может дать существенный прирост производительности. Пока игрок смотрит сквозь  дверь изнутри, будут отрисовываться только те листы с геометрией, которые видны непосредственно в проём.


=== Перебор ===
=== Перебор ===
Будьте осторожны, и не создавайте слишком много видимых порталов. Каждый из них съедает ресурсы, и если портал отсекает недостаточно деталей, отрисовка сцены без него ускорится!
Будьте осторожны, и не создавайте слишком много видимых порталов. Каждый из них съедает ресурсы, и если портал отсекает недостаточно деталей, отрисовка сцены без него ускорится!


Line 57: Line 51:


== Compilation ==
== Compilation ==
 
[[File:AreaPortalLeakFig.jpg|300px|right|thumb|caption|Top view of an areaportal leak (left), and a fully sealed area (right).]]
[[Image:AreaPortalLeakFig.jpg|300px|right|thumb|caption|Top view of an areaportal leak (left), and a fully sealed area (right).]]


It is vital that any areas that an areaportal is supposed to seal off don't [[leak]] into each other. Just as with regular leaks, an area of the map is only considered sealed from another if it is completely surrounded by world (non-entity) brushes (with the exception of areaportal brushes), without gaps. If there are multiple ways that areas connect, each must be filled with an areaportal.
It is vital that any areas that an areaportal is supposed to seal off don't [[leak]] into each other. Just as with regular leaks, an area of the map is only considered sealed from another if it is completely surrounded by world (non-entity) brushes (with the exception of areaportal brushes), without gaps. If there are multiple ways that areas connect, each must be filled with an areaportal.
Line 67: Line 60:


=== Spotting compile errors ===
=== Spotting compile errors ===
Areaportal compile errors are output by [[vbsp|VBSP]]. If a leak occurs, you will see this:
Areaportal compile errors are output by [[vbsp|VBSP]]. If a leak occurs, you will see this:


Line 75: Line 67:
These error messages are sometimes not as easy to spot as normal [[leak]] error messages, but when it comes to locating the leak in the map, vbsp will generate a [[Leak#Finding_leaks|pointfile]] to help you, just as for regular geometry leaks.
These error messages are sometimes not as easy to spot as normal [[leak]] error messages, but when it comes to locating the leak in the map, vbsp will generate a [[Leak#Finding_leaks|pointfile]] to help you, just as for regular geometry leaks.


{{bug|If your map has no entities in it, for example, an info_player_start, areaportals (and the rest of the map, for that matter) will create unusual leaks. To fix this, be sure to have at least one kind of entity within your map.}}
{{Bug|If your map has no entities in it, for example, an info_player_start, areaportals (and the rest of the map, for that matter) will create unusual leaks. To fix this, be sure to have at least one kind of entity within your map.}}


{{tip|The [[glview]] application can be used to display areaportals, which as draw as gray surfaces.}}
{{Tip|The [[glview]] application can be used to display areaportals, which as draw as gray surfaces.}}


=== Areaportals and water ===
=== Areaportals and water ===
[[Image:areaportal_water.jpg||thumb|200px|right|When constructing areaportals with water, two separate areaportals must be used.]]
[[File:areaportal_water.jpg||thumb|200px|right|When constructing areaportals with water, two separate areaportals must be used.]]


One other tricky aspect of using areaportals is that they are not allowed to cross water boundaries, like the water surface. To accomplish this, you will need to divide the portal into two - one areaportal above the water surface, and another areaportal below it - so that they both meet at the water plane.
One other tricky aspect of using areaportals is that they are not allowed to cross water boundaries, like the water surface. To accomplish this, you will need to divide the portal into two - one areaportal above the water surface, and another areaportal below it - so that they both meet at the water plane.


=== Merging ===
=== Merging ===
For optimization reasons, areaportals that share the same plane (are aligned) are automatically merged by the engine. If this behavior is unwanted, simply ensure the areaportal brushes are not along the same plane. This is usually as simple as shrinking or moving one of the areaportals slightly in the editor so they are no longer aligned. Even one grid unit is sufficient to avoid an automatic merge.
For optimization reasons, areaportals that share the same plane (are aligned) are automatically merged by the engine. If this behavior is unwanted, simply ensure the areaportal brushes are not along the same plane. This is usually as simple as shrinking or moving one of the areaportals slightly in the editor so they are no longer aligned. Even one grid unit is sufficient to avoid an automatic merge.


{{tip|You can see if areaportals are being merged in the engine by using the <code>r_DrawPortals 1</code> console command.}}
{{Tip|You can see if areaportals are being merged in the engine by using the <code>r_DrawPortals 1</code> console command.}}


== Looking through areas ==
== Looking through areas ==
[[File:Areaportal-areas.png|frame|right|Visibility between leaf one and two is unaffected.]]


[[Image:Areaportal-areas.png|frame|right|Visibility between leaf one and two is unaffected.]]
Areaportals only cull ''between'' the areas that they seal off. Consider the image to the right: while the contents of the building are culled away as you would expect, visibility between [[visleaf]] one and two is unaffected because they are connected to each other via the sides of the building.


Areaportals only cull ''between'' the areas that they seal off. Consider the image to the right: while the contents of the building are culled away as you would expect, visibility between [[visleaf]] one and two is unaffected because they are connected to each other via the sides of the building.
This can be fixed by creating two further areaportals on either side of the building.


This can be fixed by creating two further areaportals on either side of the building.{{clr}}
{{clr}}


== Console commands ==
== Console commands ==
Line 102: Line 94:
You can debug and test portals in-game, using some portal-specific [[console]] variables:
You can debug and test portals in-game, using some portal-specific [[console]] variables:


;r_DrawPortals 0/1
; r_DrawPortals 0/1
: Outlines any portal border surface (between two areas) in green when set to "1". Sometimes more than one portal is condensed into one. If the portal belonging to it is open, a second green box is also drawn, showing what the visibility on the other side is clipped to.
: Outlines any portal border surface (between two areas) in green when set to "1". Sometimes more than one portal is condensed into one. If the portal belonging to it is open, a second green box is also drawn, showing what the visibility on the other side is clipped to.
;mat_wireframe 0/1/2/3
;mat_wireframe 0/1/2/3
: Draws geometry in wireframe mode, making it easy to see the effects of areaportals in the level. When debugging areaportals, you should typically use mat_wireframe set to "1" or "2", as the "3" setting can hide geometry that is actually rendering.
: Draws geometry in wireframe mode, making it easy to see the effects of areaportals in the level. When debugging areaportals, you should typically use mat_wireframe set to "1" or "2", as the "3" setting can hide geometry that is actually rendering.
;r_portalscloseall 0/1
; r_portalscloseall 0/1
: Setting this to "1" forces all areaportals closed (so that they cannot be opened). Overrides <code>r_portalsopenall 1</code>. (Try this if portals don't seem to be doing anything. It can tell you whether the problem is just that the portals aren't closing properly.)
: Setting this to "1" forces all areaportals closed (so that they cannot be opened). Overrides <code>r_portalsopenall 1</code>. (Try this if portals don't seem to be doing anything. It can tell you whether the problem is just that the portals aren't closing properly.)
{{note|This command does not exist in: {{Tf2}} {{Csgo}}}}
{{Note|This command does not exist in: {{Tf2}} {{Csgo}}}}
;r_portalsopenall 0/1
; r_portalsopenall 0/1
: Setting this to "1" forces all areaportals open (so that they cannot be closed).
: Setting this to "1" forces all areaportals open (so that they cannot be closed).


{{tip|Use the <code>BindToggle</code> console command to allow a single key to be used to toggle a console variable.}}
{{Tip|Use the <code>BindToggle</code> console command to allow a single key to be used to toggle a console variable.}}


== In multiplayer ==
== In multiplayer ==
Areaportals are very useful in multiplayer games. Their creation is identical to those in single-player games, but their function and usage is slightly different. With multiple players in a game server, there is less control of when an areaportal is going to be open, and level performance needs to be optimized for ''worst case'' scenarios (i.e. when all visible portals are open). Because of this, in most cases, 'always open' areaportals are placed most often, followed by areaportals linked to doors, and then areaportals controlled by triggers. In worst case scenarios, well-crafted 'always open' areaportals will increase performance more than portals that are designed to be triggered.
Areaportals are very useful in multiplayer games. Their creation is identical to those in single-player games, but their function and usage is slightly different. With multiple players in a game server, there is less control of when an areaportal is going to be open, and level performance needs to be optimized for ''worst case'' scenarios (i.e. when all visible portals are open). Because of this, in most cases, 'always open' areaportals are placed most often, followed by areaportals linked to doors, and then areaportals controlled by triggers. In worst case scenarios, well-crafted 'always open' areaportals will increase performance more than portals that are designed to be triggered.


An [[func_areaportalwindow| areaportal window]] can also be used seal structures in multiplayer, but are less useful because they can create gameplay imbalances in competitive multiplayer games. A player inside the structure that is near the areaportal window would be able to see any players outside, but players farther away outside would not be able to see the player inside.
An [[func_areaportalwindow|areaportal window]] can also be used seal structures in multiplayer, but are less useful because they can create gameplay imbalances in competitive multiplayer games. A player inside the structure that is near the areaportal window would be able to see any players outside, but players farther away outside would not be able to see the player inside.


== Relationship to occluders ==
== Relationship to occluders ==
Areaportals are similar to [[occluder]]s in that they help control visibilty. The main differences between them are:
Areaportals are similar to [[occluder]]s in that they help control visibilty. The main differences between them are:


Line 129: Line 119:
* Occluders have controls for the size of objects they will hide, based upon screen area.
* Occluders have controls for the size of objects they will hide, based upon screen area.


{{note|Brushes in areaportal and occluder entities should not intersect (touch) each other, and will not function correctly if they do.}}
{{Note|Brushes in areaportal and occluder entities should not intersect (touch) each other, and will not function correctly if they do.}}


== See also ==
== See also ==
 
* {{Ent|func_areaportal}} / {{Code|[[CAreaPortal]]}}
* [[func_areaportal]] / <code>[[CAreaPortal]]</code>
* {{Ent|func_areaportalwindow}}
* [[func_areaportalwindow]]
* {{Code|[[CAreaPortalOneWay]]}} (C++ code for new entity)
* <code>[[CAreaPortalOneWay]]</code> (C++ code for new entity)
* [[Controlling Geometry Visibility and Compile Times]]
* [[Controlling Geometry Visibility and Compile Times]]
* [[Leak]]
* [[Leak]]
* [[Visleaf]]
* [[Visleaf]]

Revision as of 23:32, 5 April 2023

English (en)Español (es)Русский (ru)中文 (zh)Translate (Translate)
Открытый areaportal (зелёный контур).
Закрытый areaportal.

Areaportal - брашевая сущность, func_areaportal, func_areaportalwindow, которую можно использовать для 'запечатывания' листов и управления видимостью.

Areaportal'ы служат двум разным целям: отбраковке геометрии и удалению целых областей из отрисовки.

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

Свойства

trigger_multiple можно использовать для открытия и закрытия Areaportal'ов, чтобы скрывать зоны на уровне.

Areaportal'ы:

  • связаны с сущностью func_areaportal.
  • должны состоять только из одного браша. Areaportal'ы из более чем одного браша будут выдавать ошибку компиляции vbsp.
  • должны использовать материал tools\toolsareaportal, покрывающий все стороны их браша.
  • не должны содержать деформации, иначе будет выдана ошибка vbsp.
  • должны использоваться для запечатывания всех зон, с которыми соприкасаются, чтобы избежать утечек.
  • объём, а не отдельные поверхности. Хотя, Areaportal'ы могут быть любого размера, обычно они состоят из тонких брашей по размеру зон (дверных проёмов), которые они соединяют.
  • создают новый visleaf по своему объёму.
  • можно настроить на открытие или закрытие в зависимости от логики сущности или путем присоединения их к сущности двери.

areaportal_window

Сущность func_areaportalwindow ведёт себя как обычный Areaportal, с добавлением затухания и закрытия в зависимости от удалённости игрока. Это позволяет избежать "резкого" открытия Areaportalа.

Конструкция

Конструкция основного ареа-портала.
  1. Создайте объём из одного твёрдого браша, полностью запечатав пространство между двумя зонами, которыми вы желаете управлять. (Если необходимо, это могут быть несколько ареа-порталов, соприкасающихся гранями. Не создавайте ареа-портал с более, чем шестью сторонами.)
  2. Если ареа-портал соединяет две области, например, дверной проём, сделайте браш размером с проём и такой же толщиной, как и стены, с которыми он соприкасается. Если область представляет собой открытое пространство, то толщина может быть любой (типичные размеры сетки: 8, 16, 32 и т.д.).
  3. Наложите материал Tool textures#Optimisation tools\toolsareaportal на все грани браша.
  4. Свяжите браш с сущностью func_areaportal или func_areaportalwindow.
  5. Установите значение ключа Initial State (изначальное состояние) так, чтобы оно не блокировало видимость, когда этого не должно быть. Если вы хотите связать портал с поименованной дверью, установите его Initial State в то же состояние, что и для двери, и внесите имя двери в строку портала Name of Linked Door (имя связываемой двери). Если дверь закрыта, изначальное состояние портала также должно быть закрытым, и наоборот.
PlacementTip.gifСовет по размещению:Если ареа-портал связан с поименованной дверью, убедитесь, что он тоньше, чем сама модель двери, иначе её не будет видно, когда портал закрыт.

Влияние на производительность

Отрисовка каркаса ареа-портала в движке. Отрисовывается только та геометрия листов, которая видима через ареа-портал. Та же сцена с отключённым ареа-порталом. Отрисовывается вся геометрия листов.

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

Открытый ареа-портал сильно ограничивает видимость модели.

Благодаря таким преимуществам в производительности, ареа-порталы часто используются в состоянии всегда открыт. Всегда открытый портал создаётся путём установки ключа "Initial State" (изначальное состояние) сущности func_areaportal в значение "Open" (открыт). Открытые порталы используются на входе в другие области, содержащие большое число листов и геометрии. Например, такой портал, размещённый в конце коридора, выходящего на более широкое пространство, может дать существенный прирост производительности. Пока игрок смотрит сквозь дверь изнутри, будут отрисовываться только те листы с геометрией, которые видны непосредственно в проём.

Перебор

Будьте осторожны, и не создавайте слишком много видимых порталов. Каждый из них съедает ресурсы, и если портал отсекает недостаточно деталей, отрисовка сцены без него ускорится!

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

Compilation

Top view of an areaportal leak (left), and a fully sealed area (right).

It is vital that any areas that an areaportal is supposed to seal off don't leak into each other. Just as with regular leaks, an area of the map is only considered sealed from another if it is completely surrounded by world (non-entity) brushes (with the exception of areaportal brushes), without gaps. If there are multiple ways that areas connect, each must be filled with an areaportal.

It may help to imagine a fish tank filled with water with several holes in it's sides. An areaportal must fill each of those holes, or the area will leak, generating a leak error by vbsp.

Areaportals must be used to seal every entrance to the area. func_detail brushes, translucent textures, and displacements cannot seal an area, and will generate leaks that prevent the map from running. If the compiler can still find a way between the two main surfaces of any one portal, it will report a portal leak.

Spotting compile errors

Areaportal compile errors are output by VBSP. If a leak occurs, you will see this:

Brush <brush number>: areaportal brush doesn't touch two areas
done

These error messages are sometimes not as easy to spot as normal leak error messages, but when it comes to locating the leak in the map, vbsp will generate a pointfile to help you, just as for regular geometry leaks.

Icon-Bug.pngБаг:If your map has no entities in it, for example, an info_player_start, areaportals (and the rest of the map, for that matter) will create unusual leaks. To fix this, be sure to have at least one kind of entity within your map.  [нужно проверить в ?]
Tip.pngСовет:The glview application can be used to display areaportals, which as draw as gray surfaces.

Areaportals and water

When constructing areaportals with water, two separate areaportals must be used.

One other tricky aspect of using areaportals is that they are not allowed to cross water boundaries, like the water surface. To accomplish this, you will need to divide the portal into two - one areaportal above the water surface, and another areaportal below it - so that they both meet at the water plane.

Merging

For optimization reasons, areaportals that share the same plane (are aligned) are automatically merged by the engine. If this behavior is unwanted, simply ensure the areaportal brushes are not along the same plane. This is usually as simple as shrinking or moving one of the areaportals slightly in the editor so they are no longer aligned. Even one grid unit is sufficient to avoid an automatic merge.

Tip.pngСовет:You can see if areaportals are being merged in the engine by using the r_DrawPortals 1 console command.

Looking through areas

Visibility between leaf one and two is unaffected.

Areaportals only cull between the areas that they seal off. Consider the image to the right: while the contents of the building are culled away as you would expect, visibility between visleaf one and two is unaffected because they are connected to each other via the sides of the building.

This can be fixed by creating two further areaportals on either side of the building.

Console commands

You can debug and test portals in-game, using some portal-specific console variables:

r_DrawPortals 0/1
Outlines any portal border surface (between two areas) in green when set to "1". Sometimes more than one portal is condensed into one. If the portal belonging to it is open, a second green box is also drawn, showing what the visibility on the other side is clipped to.
mat_wireframe 0/1/2/3
Draws geometry in wireframe mode, making it easy to see the effects of areaportals in the level. When debugging areaportals, you should typically use mat_wireframe set to "1" or "2", as the "3" setting can hide geometry that is actually rendering.
r_portalscloseall 0/1
Setting this to "1" forces all areaportals closed (so that they cannot be opened). Overrides r_portalsopenall 1. (Try this if portals don't seem to be doing anything. It can tell you whether the problem is just that the portals aren't closing properly.)
Note.pngПримечание:This command does not exist in: Team Fortress 2 Counter-Strike: Global Offensive
r_portalsopenall 0/1
Setting this to "1" forces all areaportals open (so that they cannot be closed).
Tip.pngСовет:Use the BindToggle console command to allow a single key to be used to toggle a console variable.

In multiplayer

Areaportals are very useful in multiplayer games. Their creation is identical to those in single-player games, but their function and usage is slightly different. With multiple players in a game server, there is less control of when an areaportal is going to be open, and level performance needs to be optimized for worst case scenarios (i.e. when all visible portals are open). Because of this, in most cases, 'always open' areaportals are placed most often, followed by areaportals linked to doors, and then areaportals controlled by triggers. In worst case scenarios, well-crafted 'always open' areaportals will increase performance more than portals that are designed to be triggered.

An areaportal window can also be used seal structures in multiplayer, but are less useful because they can create gameplay imbalances in competitive multiplayer games. A player inside the structure that is near the areaportal window would be able to see any players outside, but players farther away outside would not be able to see the player inside.

Relationship to occluders

Areaportals are similar to occluders in that they help control visibilty. The main differences between them are:

  • Occluders only hide model (prop) geometry that is behind them. Areaportals hide all types of objects.
  • Areaportals must fully seal areas (allow no leaks), while occluders can be free-standing inside areas.
  • Occluders are more expensive per object than open areaportals.
  • Occluders have controls for the size of objects they will hide, based upon screen area.
Note.pngПримечание:Brushes in areaportal and occluder entities should not intersect (touch) each other, and will not function correctly if they do.

See also