Как открыть lighting в unity

Lighting Window

The Lighting Window (menu: Window > Lighting) is the main control point for Unity’s Global Illumination (GI) features. Although GI in Unity gives good results with default settings, the window’s properties allow you to adjust many aspects of the GI process to customise your scene or optimise for quality, speed and storage space as you need. This window also contains lighting-related settings that were available under the Render Settings in Unity versions prior to 5.0. These include ambient light, halos, cookies and fog.

Обзор

The controls of the Lighting window are divided among three tabs:

The Object tab lets you choose subsets of the objects in your scene and change settings for them. This is very useful for selecting which objects should participate in the GI computations and also for applying settings consistently to groups of objects.

The Scene tab has settings that apply to the scene overall rather than individual objects. These settings control lighting effects and also optimisation options.

The Lightmaps tab shows the lightmap asset files generated by the GI process.

The tabs are described in full detail below.

Regardless of which tab is selected, the window also has an Auto checkbox near the bottom. If enabled, this allows the lightmap data to be updated while you edit the scene (although you should note that the update usually take a few seconds rather than happening instantaneously). If Auto is disabled then the Build button to the right of the checkbox becomes active; use the button to trigger lightmap updates as you need them. The Build button also has a dropdown menu with an option to clear the baked data from the scene (without clearing the GI Cache).

Below the Auto checkbox is a small panel showing lightmap statistics.

Object Tab

The Object tab lets you select groups of objects and apply settings to them.

At the top of the tab is a set of Scene Filter buttons that let you limit the hierarchy view to specific types of objects: Lights, Renderers, Terrains. Selecting All will show the hierarchy view as normal.

Как открыть lighting в unity

If you select any of the other buttons then the hierarchy view will be limited to showing just those object types. This is essentially just a quick way to access the standard hierarchy view filter for the most common cases.

Как открыть lighting в unity

Note that the filter does not affect which object is currently selected, so it is possible to have, say, a terrain object selected even when the hierarchy is filtered to show only lights.

The relevance of the filter buttons is that each of the three object types has its own set of properties, each described in detail below.

Lights

For a light object, the Object tab essentially shows the same information as the light component’s standard inspector panel. The properties that specifically affect GI are Baking and Bounce Intensity.

Baking allows you to choose if the light should be baked if Baked GI is selected. Mixed will also bake it, but it will still be present at runtime to give direct lighting to non-static objects. Realtime works both for Precomputed Realtime GI and when not using global illumination.

Bounce Intensity allows you to vary the intensity of indirect light (ie, light that is bounced from one object to another. The value is a multiple of the default brightness calculated by the GI system; if you set Bounce Intensity to a value greater than one then bounced light will be made brighter, while a value less than one will make it dimmer. This is useful, for example, when a dark surface in shadow (such as the interior of a cave) needs to be rendered brighter in order to make detail visible. Or alternatively, if you want to use Precomputed Realtime GI in general, but want to limit a single light to give direct light only, you can set its Bounce Intensity to 0.

Renderers

For Renderers, the following properties are available:

Как открыть lighting в unity

Свойство:Функция:
Lightmap StaticThis indicates to Unity that the object’s location is fixed and so it should participate in the GI. If an object is not marked as Lightmap Static then it can still be lit using Light Probes.
Scale in LightmapThis value affects the number of pixels in the lightmap texture that are used for this object. With the default value of 1.0, the number of lightmap pixels used for the object is only dependent on its surface area (ie, same number of pixels per unit area for all objects). A value greater than 1.0 increases the number of pixels (ie, the lightmap resolution) used for this object while a value less than 1.0 decreases it. You can use this property to optimise lightmaps so that important and detailed areas are more accurately lit. For example, an isolated building with flat, dark walls might look fine with a low lightmap scale (less than 1.0) while a collection of colourful motorcycles displayed close together might warrant a high scale value.
Preserve UVsUnity can recalculate the UV coordinates used for the realtime lightmap texture so as to improve its storage and performance characteristics. Please note that the recalculation process will sometimes make misjudgements about discontinuities in the original UV mapping. For example, an intentionally sharp edge may be misinterpreted as a continuous surface, resulting in artifacts where the seam should be. If Preserve UVs is enabled then the lightmapping UVs from the object will be translated to the lightmap to retain the effect intended by the artist. If Preserve UVs is switched off then Unity will calculate the realtime lightmap UVs based on the baked UVs so as to join adjacent “charts” and compact the lightmap as much as possible. This calculation is based on the two settings below (max distance and max angle). The realtime charts are packed with a half pixel border around them. This ensures that we get no leaking when rendering from them.
Auto UV Max DistanceEnlighten automatically generates simplified UVs by merging UV charts. Charts will only be simplified if the worldspace distance between the charts is smaller than this value.
Auto UV Max AngleEnlighten automatically generates simplified UVs by merging UV charts. Charts will only be merged if the angle between the charts is smaller than this value.
Important GIThis tells Unity that light reflected or emitted from the object is likely to affect other objects in a noticeable way. This ensures that subtle illumination effects created by this object are not optimised away.
Advanced ParametersAllows you to choose or create a set of Lightmap Parameters for the current object selection.

Terrains

For Terrains, the properties are a subset of those available for renderers.

Как открыть lighting в unity

Свойство:Функция:
Lightmap StaticThis indicates to Unity that the object’s location is fixed and so it should participate in the GI. If an object is not marked as Lightmap Static then it can still be lit using Light Probes.
Scale in LightmapThis value affects the number of pixels in the lightmap texture that are used for this object. With the default value of 1.0, the number of lightmap pixels used for the object is only dependent on its surface area (ie, same number of pixels per unit area for all objects). A value greater than 1.0 increases the number of pixels (ie, the lightmap resolution) used for this object while a value less than 1.0 decreases it. You can use this property to optimise lightmaps so that important and detailed areas are more accurately lit.
Advanced ParametersAllows you to choose or create a set of Lightmap Parameters for the current object selection. The default parameter set for Terrains is the Very Low Resolution built-in set.

Scene Tab

The Scene tab contains settings that apply to the scene overall as opposed to individual objects. Note that Precomputed Realtime GI and Baked GI features can be enabled or disabled by clicking the checkboxes next to their names in the Scene tab.

The Build button will start the lighting build process. The button can expand into a dropdown where you can clear the baked data. This isn’t the same as clearing the GICache.

Lightmaps Tab

The final tab provides an easy way to set and locate the lightmap asset file used for the scene.

Как открыть lighting в unity

If you click the filename in the Lightmap Snapshot box, the Project view will show you the asset file. If you click the small pip next to the box, an object selection window will appear to let you select a different lightmap. If you rename the folder where the current lightmap asset is located and then set the Lightmap Snapshot property to None, a new file will be created the next time you build the lightmap. Using multiple files like this is a good way to test out GI settings and compare different sets of parameters.

The image below the Lightmap Snapshot box shows a preview of the lightmap. This is only available when Baked lights are used; the preview will be blank for Realtime lights.

Источник

Lightmapping Quickstart (Введение в карты освещения)

Это введение в карты освещения в Unity. Для получения подробностей смотрите in-depth description of lightmapping in Unity.

Unity располагает встроенным инструментом для создания карт освещения: это Beast от Illuminate Labs. Он полностью интегрирован в Unity. Это значит, что Beast запекает карты освещения для вашей сцены, основываясь на том, как ваша сцена настроена в Unity, какие содержит меши, материалы, текстуры и источники света. Это также значит, что карты освещения теперь являются неотъемлемой частью рендеринга — после их создания вам не придётся ничего больше делать, они автоматически применятся к объектам.

Как открыть lighting в unity

Подготовка сцены к запеканию карт освещения

Выбор ____Window__ – Lightmapping__ из меню откроет окно Lightmapping:

Scene View и Game View будут обновлены — теперь ваша сцена оснащена картами освещения!

Настройка запекания карт освещения

Окончательный вид вашей сцены зависит во многом от настройки освещения и настроек запекания карт освещения. Рассмотрим для примера некоторые основные настройки, которые помогут улучшить качество освещения.

This is a basic scene with a couple of cubes and one point light in the centre. The light is casting hard shadows and the effect is quite dull and artificial.

Как открыть lighting в unity

Как открыть lighting в unity

В Unity Pro можно сделать ещё один шаг вперёд, активировав Global Illumination (глобальное освещение) и добавив Sky Light (свет от небесного свода). Во вкладке Bake задайте параметру Bounces значение 1, а параметру Sky Light Intensity — значение 0.5. В результате получится намного болеее мягкое освещение с эффектами смешивания — намного красивее, и это всего лишь три куба и один источник света!

Как открыть lighting в unity

Подробности о картах освещения

Для получения подробностей о различных настройках, связанных с картами освещения, смотрите in-depth description of lightmapping in Unity.

Источник

The Lighting window

The Lighting window (menu: Window > Rendering The process of drawing graphics to the screen (or to a render texture). By default, the main camera in Unity renders its view to the screen. More info
See in Glossary > Lighting) is the main control point for Unity’s lighting features. You can use the Lighting window to adjust settings related to the lighting in your Scene, and to optimise your precomputed lighting data for quality, bake time, and storage space.

Related APIs

Lighting window layout

The Lighting window contains the following elements:

The Scene tab

The Scene A Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary tab displays information about the Lighting Settings Asset that is assigned to the active Scene. If no Lighting Settings Asset is assigned to the active Scene, it displays information about the default LightingSettings object.

The Scene tab is divided into two sections:

Lighting Settings Asset controls

Use the controls in this section to assign a Lighting Settings Asset to the active Scene, or to create a new Lighting Settings Asset.

Property:Function:
Lighting SettingsThe Lighting Settings Asset assigned to the active Scene.
New Lighting SettingsClick this button to generate a new Lighting Settings Asset in your Project, and automatically assign the new Lighting Settings Asset to the active Scene.

Lighting Settings

Use this section to view and edit the properties of the Lighting Settings Asset or LightingSettings object assigned to the current Scene. See Lighting Settings Asset.

Workflow settings

This section contains settings that help you debug your Scene.

The Environment tab

The Environment tab contains settings related to environmental lighting effects for the current Scene. The contents depend on the render pipeline that your Project uses.

Built-in Render Pipeline and Universal Render Pipeline

In the Built-in Render Pipeline and URP, the Environment tab is divided into two sections:

Environment

The Environment section contains lighting-related settings and controls that apply to the environmental lighting in the current scene, such as the Skybox, diffuse lighting and reflections.

Property:Function:
Skybox MaterialA Skybox is a Material that appears behind everything else in the Scene to simulate the sky or other distant background. Use this property to choose the Skybox you want to use for the Scene. The default value is the built-in Default Skybox.
Sun SourceWhen the Skybox Material is a Procedural Skybox, use this setting to specify a GameObject with a directional Light component to indicate the direction of the sun (or whatever large, distant light source is illuminating your Scene). If this is set to None, the brightest directional light in the Scene is assumed to represent the sun. Lights whose Render Mode property is set to Not Important do not affect the Skybox. The default value is None.

For more information about the Render Mode setting, see the Additional settings section of Lights.

Realtime Shadow ColorDefine the color that Unity uses to render real-time shadows in Subtractive Lighting Mode.

Other Settings

High Definition Render Pipeline

In HDRP, the Environment tab allows you to specify which sky to use for environment lighting. For more information on environment lighting in HDRP, see Environment Lighting in the HDRP documentation.

Property:Function:
ProfileA Volume Profile for the sky. This Volume Profile must include at least one Sky Volume override.
Static Lighting SkyThe sky to use for the Global Illumination simulation. The drop-down only contains sky types that the Profile includes. For example, if the Profile includes a Gradient Sky Volume override, you can select Gradient Sky from this drop-down.

You can only edit this setting if you assign a Volume Profile to the Profile field.

The Realtime Lightmaps tab

The Realtime Lightmaps A pre-rendered texture that contains the effects of light sources on static objects in the scene. Lightmaps are overlaid on top of scene geometry to create the effect of lighting. More info
See in Glossary tab shows a list of all lightmaps generated by the Enlighten A lighting system by Geomerics used in Unity for lightmapping and for Realtime Global Illumination. More info
See in Glossary Realtime Global Illumination A group of techniques that model both direct and indirect lighting to provide realistic lighting results. Unity has two global illumination systems that combine direct and indirect lighting.: Baked Global Illumination, and Realtime Global Illumination.
See in Glossary system in the current Scene. If Realtime Global Illumination is not enabled in your Project, this tab will be empty.

The Realtime Global Illumination system is supported in the Built-in Render Pipeline, but not in URP or HDRP. Therefore, this tab is visible only in the Built-in Render Pipeline.

The Baked Lightmaps tab

This tab shows a list of all lightmaps generated by lightmapper A tool in Unity that bakes lightmaps according to the arrangement of lights and geometry in your scene. More info
See in Glossary for the current Scene, along with the Lighting Data Asset. If Baked Global Illumination is not enabled in your Project, this tab will be empty.

Control area

Controls for precomputing lighting data are at the bottom of the Lighting window.

Property:Function:
Auto GenerateIf Auto Generate is enabled, Unity precomputes lighting data automatically when you make changes to the Scene.

This data includes lightmaps for the Baked Global Illumination system, lightmaps for the Realtime Global Illumination system, Light Probes, and Reflection Probes.

Unity usually begins the bake a few seconds after you make a change to the Scene. If Auto Generate is disabled, you must manually invoke a bake yourself, using the Generate Lighting button in the Lighting window, or the Lightmapping.Bake or Lightmapping.BakeAsync APIs.

Note that when you precompute lighting data using Auto Generate, the precomputed lighting data is not stored as Assets in your Project. It is instead stored in memory, and serialized as part of the Scene.

This property is stored in a Lighting Settings Asset. It is visible in the Lighting window only if the Scene tab is selected, and the active Scene has a Lighting Settings Asset assigned to it.

Generate LightingClick the Generate Lighting button to precompute lighting data for all open Scenes. This data includes lightmaps for the Baked Global Illumination system, lightmaps for the Realtime Global Illumination system, Light Probes, and Reflection Probes.

Click the foldout arrow on the right hand side of the Generate Lighting and then click Bake Reflection Probes to bake only the Reflection Probes for all open Scenes.

Источник

Работа с освещением в Unity — теория и практика

Как открыть lighting в unity

В течение последних пары лет мне приходилось много работать с “лайтмаппингом” как по работе, так и на своём собственном инди-проекте. Когда у вашей команды мало производственных ресурсов и вы не можете выделить много времени на создание уникальной графики для игровых локаций, освещение становится одним из ключевых факторов, помогающих оживить и разнообразить картинку.

Теория освещения

Отражённый свет

Давайте определимся с терминологией. Освещение в компьютерной графике делится, условно говоря, на две категории:

Global Illumination (GI) представляет из себя наиболее “честный” способ симуляции отражённого света. Из источника света вылетают фотоны — частички, несущие информацию о цвете и яркости света. Ударяясь о какую-либо поверхность, они освещают её, но теряют часть энергии, вследствие чего их цвет и яркость изменяются. Затем фотоны отскакивают и ударяются о следующую поверхность, повторно теряя часть энергии. Так происходит несколько раз в зависимости от настроек рендерера.

Final Gather (FG) раскидывает по сцене точки, — final gather points, — из которых в разные стороны вылетают лучи. После столкновения с какой-либо поверхностью, лучи возвращают в родительскую точку информацию о цвете и его яркости. Представьте себе такую картину: вечер, солнце почти зашло за горизонт; становится темно, но небольшая часть комнаты ещё залита оранжевым закатным светом. Находящаяся на полу final gather point отправляет в разные стороны несколько лучей, некоторые из них дотягиваются до освещённой части комнаты и с этой информацией возвращаются в исходную точку, тем самым слегка освещая пол «отражённым» оранжевым светом. Это не такой “честный” способ, как GI, но он производит хороший результат, и им часто пользуются, чтобы заполнять сцены красивым мягким освещением.

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

Как открыть lighting в unity

Ambient Occlusion

Кроме отражённого света, нам интересен так называемый Ambient Occlusion (AO). Это эффект затенения в углах, трещинах, узких проёмах. Представьте, что луч света залетает в угол комнаты, он несколько раз отражается от обеих стен, постепенно затухая. Чем дальше в угол, тем меньше света туда доходит.

Как правило, Ambient Occlusion используется, чтобы художественно подчеркнуть эффект затенения, — в реальности лучи света не теряют энергию столь быстро, чтобы в углах комнаты сгущалась такая же тьма, как показывают нам в играх. Если вы рендерите физически корректное освещение, ваш движок сам высчитывает скорость потери энергии лучом света, и вам не нужно отдельно рендерить карту (текстуру) Ambient Occlusion. Но вы можете это сделать, если потребуется для реализации художественного замысла.

Как открыть lighting в unity

Как открыть lighting в unity

Текстурные атласы

Следующим термином, который вам следует следует знать, является текстурный атлас. Грубо говоря, это одна большая текстура, в которой содержатся несколько маленьких текстурок. Чаще всего текстурные атласы создаются для экономии вычислительных ресурсов. Приведу крайне упрощённый пример, — спецы, спрячьте факелы и вилы! Пусть у вас в игре есть таверна, в которой 20 деревянных предметов (столы, стулья, ложки. ), у каждого своя текстура. В итоге CPU будет 20 раз обращаться к GPU, требуя отрендерить каждый объект по отдельности. Если мы назначим всем деревянным объектам один материал, обращающийся к одному текстурному атласу, в который зашиты все 20 текстур, то GPU сможет отрендерить 20 объектов за один вызов (он же — draw call, в конце статьи предоставлю интересные ссылки по этой теме).

В случае с “лайтмаппингом”, для каждого объекта создаётся дополнительная маленькая текстурка, в которой “запекается” информация об освещении. Затем много-много маленьких текстурок разных объектов размещаются в крупных текстурных атласах. Как и в случае с деревянной мебелью, мы также получаем прирост производительности.

Работа с Unity

Общая информация

Но вернёмся к “лайтмаппингу” в самом Unity. Прежде всего запаситесь терпением и, по возможности, мощным компьютером. Процесс рендера имеет свойство полностью занимать процессор и оперативную память, поэтому я включаю его перед тем, как ухожу на работу или иду спать. Таким образом, я возвращаюсь к компьютеру как раз в тот момент, когда рендер уже завершён.
Забегая вперёд, предупрежу, что Unity кэширует промежуточные результаты вычислений освещения. Если вы увидите, что на системном диске у вас пропало 10 гигабайт места — это оно. Чтобы настроить кэш надо зайти в: Edit — Preferences — GI Cache. Здесь вы можете указать, куда он сохраняется и его максимальный размер. Можно убрать компрессию, “весить” будет больше, но работать пошустрее. Тут же вы можете почистить кэш, но имейте ввиду, что если у вас открыта сцена с готовым “лайтмапом”, то он тоже будет удалён, будьте внимательны.

В Unity доступно 5 типов источников света:

Параметры источников света

Хочу обратить внимание на насколько ключевых настроек источников света (доступные настройки различаются в зависимости от типа источника света):

Как открыть lighting в unity

Настройка освещения сцены

Окно настроек освещения сцены вызывается через Window — Lighting, и состоит из трёх вкладок: Object, Scene, Lightmaps. Для запуска рендера освещения используется кнопка Build в самом низу окна. Там же есть галочка Auto, которая автоматически запускает рендер каждый раз, когда вы вносите изменения в сцену; используйте её, если у вас мощный компьютер. Ещё ниже находится информация о количестве и размере “лайтмапов”, появится по завершению процесса “лайтмаппинга”.

Раздел — Object

В Object отображаются настройки конкретного объекта. Если вы выделите элемент окружения на вашей сцене, то здесь увидите ряд настроек и параметров. При условии, что объект является статичным, будет стоять галочка на чекбоксе Lightmap Static. Чаще всего вы будете использовать здесь поле Scale in Lightmap. Как я говорил ранее, для каждого объекта освещение “запекается” в отдельную маленькую текстурку, которая потом размещается в крупном “лайтмап”-атласе. Параметром Scale in Lightmap вы можете регулировать, сколько места будет занимать эта текстурка. Разумеется, чем меньше места ей выделяется, тем хуже будет качество “запечённого” в неё освещения. По умолчанию здесь стоит “1”, но если вы знаете, что объект будет редко попадать в поле зрения или он расположен далеко на фоне, вы можете смело уменьшить этот параметр вплоть до 0.1 или даже меньше.

Раздел — Scene

В Scene расположены ключевые настройки рендера освещения. Я рассказываю основы работы со светом, а также делюсь опытом “лайтмаппинга” конкретно под мобильные платформы, поэтому умышленно пропускаю такие вещи, как realtime GI или использование HDR-текстуры в качестве источника света.

В Ambient Source вы настраиваете заполняющий источник света Ambient Light, который я уже упоминал. Вам предлагается выбрать между небом-текстурой, небом из единственного цвета, а также созданным на основе цветового градиента небом. Я предпочитаю выбирать Gradient. Он позволяет настроить три цвета — купол неба, экватор и землю, что создаст для вашей сцены достаточно сложный и интересный заполняющий свет. Ambient Intensity указывает яркость этого света. В зависимости от художественного замысла, вы можете иметь даже очень светлую сцену, освещённую посредством одного Ambient Light.

Во вкладке Baked GI находятся основные настройки качества освещения, как прямого, так и отражённого, включая и GI, и FG.
Прежде чем углубимся в эти настройки, хочу дать один совет. Всегда имейте ввиду, что размещая на сцене источники света, настраивая тени и Ambient Light, после рендера “лайтмапа” вы получите совершенно иную картинку, только отдалённо напоминающую то, что вы делали. Поэтому я рекомендую работать итерациями: вы выставляете минимальное качество освещения, чтобы рендер происходил быстро, смотрите на результат рендера, после чего вносите правки и запускаете повторный рендер. Когда вы более-менее довольны результатом, можно повысить качество рендера и включить Final Gather. Это займёт длительное время, поэтому есть смысл включать такой рендер перед тем, как вы отходите от компьютера на сравнительно долгий отрезок времени.

Настройки во вкладке Baked GI оперируют такой единицей, как texel. Если говорить упрощённо, тексель — это пиксель, но не на экране, а в текстурном пространстве трёхмерной модели. Но не забивайте голову, — трудно сказать, как Unity оперирует текселями и как они зависят от масштаба объектов, поэтому просто-напросто двигайтесь эксперементальным путём. Например, для своей мобильной RPG я делаю финальный рандер с Baked Resolution выставленным в 25.

Тексель (сокращение от англ. Texture element) — минимальная единица текстуры трёхмерного объекта. Пиксель текстуры.
Проще всего объяснить значение термина «тексель» на примере трёхмерных игр. Если подойти вплотную к стене в какой-нибудь старой 3D-игре — (Wolfenstein или Duke Nukem), то можно наблюдать, как текстура стены распадается на однотонные квадраты, которые увеличиваются при приближении и собираются обратно в осмысленный рисунок при отдалении. Эти квадраты и называются текселями, и чем крупнее исходный рисунок текстуры, тем меньше становятся тексели. Для идеального отображения текстуры количество текселей должно совпадать с количеством пикселей на мониторе, но практически все движки разрешают зрителю приблизиться к стене ближе чем того разрешает детальность.

Ниже я расскажу про каждый параметр отдельно, но перед этим вам нужно знать ещё кое-что. Если вы запустите в Unity рендер освещения, то справа снизу будет написано, чем именно движок занят в текущий момент. В самом конце процесса рендера там будет написано Compositing.

Дело в том, что “лайтмап” генерируется послойно. Во время рендера создаются несколько отдельных текстур. Мне неизвестно, какие именно карты делает Unity, но среди них есть либо все, либо часть из списка: Diffuse (прямой свет), GI (Global Illumination), FG (Final Gather), AO (Ambient Occlusion) и другие. После этого движок берёт эти карты и сливает друг с другом. Например, в основе может лежать слой Diffuse, над ним кладётся слой FG в режиме смешивания Lighten (прямо как в Photoshop’е), а повыше кладётся слой AO в режиме Multiply… В итоге эти слои сливаются в одну картинку и на выходе получается финальный “лайтмап”.

Вкладка — Baked GI

Вкладка — General GI

Давайте пройдёмся по интересующим нас настройкам во вкладке General GI:

Вкладка — Fog

И, наконец, туман! Fog, то бишь. К рендеру освещения он не имеет никакого отношения, может включаться и выключаться в любое время. Тут всё предельно просто, поэтому берите и экспериментируйте. Скажу лишь, что туман является крайне мощным художественным средством. Вы можете радикально изменять атмосферу сцены посредством тумана, благодаря ему солнечная сцена станет ярче, мрачная — мрачнее.

Кроме того, туман может использоваться как инструмент повышения производительности. Например, вы хотите вдалеке выключить у всех объектов текстуры и скрыть их за туманом. В более старых версиях World of Warcraft, если вы играли, вы не могли не заметить, какой густой там был туман.

Раздел — Lightmaps

Третьим разделом является Lightmaps, где будут расположены отрендеренные “лайтмапы”. Причем если атласов много, в верхней части вкладки вы не сможете увидеть все атласы, скролл в том окошке неактивен. Поэтому смотрим в нижнее и прокручиваем колесиком мышки.

Здесь нам важно увидеть насколько заполнен последний, самый нижний “лайтмап”-атлас. Если он почти пуст, то либо увеличиваем качество “лайтмапа”, чтобы заполнить весь атлас, либо уменьшаем, чтобы атлас оказался пустым и был удален. На картинке ниже изображены два хорошо заполненных атласа, а один — постольку-поскольку.

“Лайтмапы” хранятся в файлах EXR с глубиной в 32 бита.

Как открыть lighting в unity

Light Probes

Ещё я обещал рассказать про Light Probes. Они представляют из себя небольшие сферы, вбирающие в себя информацию об освещении окружающего пространства. Когда таких сфер много, они создают своебразную карту освещённости вашего уровня или локации. Затем они используются для освещения динамических объектов, в которые не “запекается” свет.

Чтобы лучше понять их смысл, дам пример. На вашей сцене находится один Point Light, у которого стоят настройки Baked, то есть он используется для “запечения” света. Вы не делаете его Real-time, потому что это дорого в плане производительности, причём многие мобильные устройства вообще не поддерживают такой источник света. Далее вы “лайтмапите” сцену и видите, что ваш Point Light освещает окружение. Но если вы возьмёте монстра и поставите рядом с источником света, он останется тёмным, потому что принадлежит к классу динамических объектов, а ваш Point Light влияет только на статические.

Теперь вы расставляете вокруг источника света сетку из Light Probes, снова запекаете освещение. И теперь ваш монстр может ходить вокруг Point Light’а и освещаться им! Это крайне эффективный и недорогой способ имитации освещения. Чтобы добавить “пробы” на сцену, заходите в Game Object — Light — Light Probe Group. На сцене появится кубик из четырёх сфер. Для выбора отдельных сфер, используйте ctrl + click. В Inspector появятся несколько кнопок, позволяющие добавлять или удалять сферы. Вы также можете использовать комбинацию ctrl + D для дублирования сфер.

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

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

Как открыть lighting в unity

Заключение

Напоследок хочу дать совет по созданию моделей окружения под “лайтмаппинг”. Создавая контент для игры, я знал, с какой стороны будет смотреть игровая камера, поэтому ради сомнительной оптимизации удалял задние стенки некоторых объектов. В то время у меня был опыт рендера “лайтмапов”, но только в Maya, а не в Unity. Выяснилось, что при рендере освещения в Unity возле объектов, имеющих дыры, то есть удалённые полигоны, появляются жесткие, хорошо заметные артефакты. Имейте ввиду.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *