Ue4 lightning needs to be rebuilt как исправить

fiber_smart_record

Разработка

январь — 15/21

В данной статье я расскажу как избавиться от ошибки с освещением (lights need to be rebuilt).  И так мы создали уровень и сделали освещение, но по каким либо причинам мы какой либо объект передвинули и у нас появилась данная ошибка. Сейчас мы ее будем исправлять. 
Для этого нажмите на Build и выберите Lights quality, в в нем самом уже выберите Production.
Затем нам нужно применить все эти изменения. Нажимаем на Build Lightning only
Ждем перестроения освещения, мы так же заметим, что чем больше объектов у нас на уровне, тем дольше это самое перестроение у нас будет происходить.  Ничего страшного в этом нет, это нормально. 
Так мы победили эту ошибку и научились перестраивать освещение на нашем уровне. Для тех кто не чего так и не понял, попрошу удалить Unreal Engine либо посмотреть видео, которое я еще и снял. Ну может я сам пишу так что ни кто не понимает. В общем смотрим. Так же ставим лайк и оставляем комментарии. Всем спасибо. 

thumb_up+3thumb_down

Правила

question_answerДобавление комментария
+ question_answer

Epic Developer Community Forums

Loading

Почему мои тени чёрные?

По правилам освещения, чёрные тени обычно используются, если у вас нет заполняющего света.Это часто происходит по тому, что окружающая среда имеет единично направленный поток света, представленный как солнце.UE4 построен на методе ,обеспечивающем эффективное заполнение светом окружающего мира, мы называем его SkyLight.Немного про Skylight.
Без Skylight

111

С Skylight

111

Когда вы сконвертируете свою BSP геометрию в static mesh , вы увидите данный результат:

111

Не беспокойтесь, это нормально. Так как мы только что сконвертировали наш BSP в Static mesh, мы должны убедится в правильности назначенного канала для lightmap.Для того чтобы это было делать проще, lightmap автоматически генерируется когда вы конвертируете BSP.Единственное что вам осталось сделать- это выбрать нужный канал и разрешение.

  • Для того что бы это сделать — откройте новосозданный Static Mesh. Взгляните на details panel, расположенную справа в Static Mesh Settings.
  • Тут вам надо установить Lightmap Resolution. Это может быть любое значение кратное двум (к примеру, 32, 64, 128, прочее). Это будет разрешением вашей lightmap текстуры.Высокое значение разрешения lightmap даст лучший результат, но в то же время займёт больше памяти и времени просчёта.
  • Далее, установите Lightmap Coordinate Index в 1 (это наиболее используемый канал для lightmap ).Это положение вашей lightmap UV где нет наложения поверхностей
  • Если вы хотите увидеть как ваша lightmap выглядит, вы можете кликнуть по кнопке для UV в тулбаре и выбрать UV Channel 1 из выпадающего списка.

111

Что если я не хочу иметь lightmaps или моя игра в них не нуждается
Бывают моменты когда игра не нуждается в lightmaps, т.к. оптимизирована для использования лишь динамического освещения.Опция которая отключает lightmaps , расположена в world settings и проверяется пунктиком “Force No Precomputed Lighting”. Когда освещение перестроится- все ранее запечённые lightmaps будут удалены.

Есть 2 метода для отключения статического освещения:

Проектная спецификация: отключение статического освещения

  • Menu > Edit > Project Settings
  • Перейдите в Rendering Tab > Lighting Tab
  • Снимите галочку с «Allow Static Lighting»
  • Для восстановления полной функциональности данной опции вам необходимо перезапустить редактор

Спецификация уровня: отключение статического освещения

  • Откройте World Settings
  • Перейдите в Lightmass Tab .
  • Снимите галочку с «Force No Precomputed Lighting»
  • Вам будет предупреждение, нажмите ОК
  • Заново просчитайте освещение для полного обнуления ранее запечённого освещения




На данном изображении вы можете наблюдать ассет ,который был сделан в 3ds max: плоскость и трубу.

Созданный ассет в 3ds max

В редакторе всё выглядит отлично, но когда я импортирую это в ue4, часть геометрии пропадает.
Так что же происходит, ведь данное явление не является нормой?
На самом деле- это нормальное явление.Если смотреть на плоскость, то она рендерится как и положено, но вот её задняя часть, как и ближние (к камере -прим.ред.)полигоны трубы- не рендерятся.

Созданный ранее ассет импортирован в UE4

Когда вы создаёте вашу геометрию в программе для моделирования, по умолчанию стоят настройки, позволяющие видеть геометрию с двух сторон.
В UE4 невидимые полигоны не рендерятся для сохранения производительности.Это не всегда необходимо для получения дополнительных полигонов или плоскостей для рендера, так как в противном случае будут дополнительные «draw calls», которые могут вызвать уменьшение производительности.С несколькими инстансами это возможно не будет иметь значительного различия, но когда вы разрабатываете под определённую платформу или имеете лимит на «draw calls»- это преобретает значительный смысл.

Для понимания почему мы можем видеть только одну сторону нашей геометрии, мы должны открыть нашу геометрию в редакторе геометрии и включить отображение нормалей.Мы увидим зелёные линии указывающие направление полигона(имеется ввиду, что зелёная линия (нормаль) направлена перпендикулярно плоскости полигона). На изображении снизу, мы видим, что линии идут в направлении центра геометрии. Это направление которое даёт возможность увидеть геометрию.

Совет:Вы можете проверить направление нормалей в редакторе ue4 дабы увидеть, где именно у вас проблема.

Итак, у нас некоторые объекты с невидимыми сторонами, всё то нам нужно сделать, дабы это исправить:

1.(ТОЛЬКО ДЛЯ СТАТИКИ) Двухстороннее освещение

  • Включить данную опцию в details panel для выделенного ассета в Level Viewport.
  • С включённой данной опцией когда свет построится ,lightmass будут считать что освещение для геометрии запечено.Это будет давать тень, даже если мы не можем видеть её с такого ракурса.Это не работает для подвижных/днамических источников света, т.к. Unreal Engine 4 использует отложенный рендер.

Details Panel ассета в Level Viewport

Финальный результат

2. Создание двухстороннего материала

  • Откройте редактор материалов и слева в details panel выберите опцию “Two-sided”.
  • Сохраните и скомпилируйте ваш материал, чтобы увидеть результат.
  • Данный метод может быть использован с Статическим/Стационарным/Подвижным освещением.Теперь материл рендерит плоскости, которые ранее не были видны.

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

Атрибуты материала details панелька

Финальный результат

Почему это выглядит так, как будто я ничего не делал до этого или Масштабируемые настройки
Масштабируемые настройки располагаются в Settings > Engine Scalability опции на тулбаре.
Цель данного масштабирования заключается в том, что бы не шибко производительные компьютеры не умирали от ультра настроек.По умолчанию редактор занижает настройки если FPS падает слишком низко.
Опция “Shadows” непосредственно влияет на дальность прорисовки всех динамических теней.Это верно когда используется “Movable” освещение или когда освещение ещё не запекалось для статического освещения, так как те используют динамические тени до тех пор, пока освещение не будет запечено в lightmaps.

Engine Scalability Settings

Изображения снизу демонстрируют тени на дистанции при разных качествах теней указанных в настройках.

Epic

High

Medium

Low

Если у вас топовой ПеКа, но теней нет или с ними что-то не то, стоит сначала потыкать в этих настройках, прежде чем искать проблемы в других местах.Также редактор может занижать настройки если просадки фпс слишком велики.

Если вы не испытываете нужны в автоматическом подборе настроек, то вы можете выключить данную опцию, нажав на галочке внизу окошка.

Want to know more about Engine Scalability?

Почему на источниках света появился красный Х ?
Стационарные источники света ограничены 4 пересекающимися источниками. Когда добавляется ещё и 5й, появляется красный «Х», являясь индикатором того, что ИС с малым радиусом будут переведены в динамические ИС.Это может привести к проблемам производительности, так как динамические ИС потребляют больше ресурсов для запекания теней.

Пересекающиеся Стационарные источники света
Если освещение будет запечено с любым стационарным светом который имеет перекрытия, будет выдано предупреждение с описанием ИС который является источником проблемы и последующими из-за этого последствиями.
Чтобы это исправить, нужно уменьшить количество ИС до четырёх или уменьшить радиус ИС которые пересекаются.
Если же у вас 3 ИС в сцене и появляется красный «Х»,то убедитесь, что у вас на сцене нет других ИС с огромным радиусом.Часто это происходит по тому, что Directional light переключён в режим Stationary, измените этот параметр на Статический или Динамический, дабы исправить проблему.

Что ещё нужно знать про Стационарные источники освещения? 

Динамическое (Подвижное) Освещение

Некорректное качество теней


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

Пример некорректного затенения геометрии.

Только! для Directional Light : Настройки Cascaded Shadow Maps:

Cascaded Shadow Maps настройки, в Directional Light Details

Dynamic Shadow Distance Movable: Расстояние от камеры, на котором тени будут исчезать.Значение 0 отключает их.

Dynamic Shadow Distance Stationary: Расстояние от камеры, на котором тени будут исчезать.По умолчанию стоит 0 для Directional Stationary Lights.

Num Dynamic Shadow Cascades: Количество каскадов на которое будет делится фрустум.Больше каскакодов- лучше качество, но и ресурсоёмкость возрастает.
Внимание! обязательно тыкните в ссылочку ниже, ибо наверняка не все знают что такое фрустум.

Количество каскадов = 0

Количество каскадов = 1

Количество каскадов = 2

Количество каскадов = 3

Количество каскадов = 4

Cascade Distribution Exponent: Параметр регулирующий, на каком расстоянии от камеры распределение ближе (выше значение) или дальше (меньше значение) от камеры.Значение 1 означает, что переход будет пропорционален разрешению экрана.

Cascade Distribution Exponent Примеры:

Распределение = 1

Распределение = 2

Распределение = 3

Распределение = 4

Cascade Transition Exponent: Параметр регулирующий затухающий регион между каскадами. Низкое значение даст жёсткие грани, высокое- мягкие.
Cascade Transition Exponent Пример:

Эффект перехода

Cascade Transition Exponent

Жёсткая грань (низкое значение)

Смешивание граней (высокое значение)

Shadow Distance Fadeout Fraction: Параметр регулирующий на каком расстоянии тени будут затухать. Высокое значение ослабляет тени, в то время как низкое значение оставляет тени тёмными.
Shadow Distance Fadeout Fraction Пример:

Затухание = 0

Затухание = 1

Far Shadow Cascade Count: Coming in 4.8. More information to follow soon.
Far Shadow Distance: Coming in 4.8. More information to follow soon.

Регулирование Cascades для лучшего качества:


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

Это базовая сцена с одними лишь настройками по умолчанию:

Базовая сцена дефолтные настройки:

Тут у нас уже есть некоторые проблемы с точностью теней на гранях объектов.

Проблемные зоны выделены красными рамками

Демонстрация проблемы, с близкого ракурса.

Проблемные зоны, вид поближе

Сфокусируем внимание на минимизации просветов теней, в пределах разумного. По умолчанию, дистанция динамических теней установлена в 20000 юнитов.Данное значение не всегда обязательно и может быть изменено в большую или меньшую сторону.
В этой сцене настройки распределения, дистанции теней и количество каскадов просветов и их точность — на приемлемом уровне.

Базовая сцена финальный результат

Всё динамическое освещение (панель настройки освещения):


Также имеются ещё 2 настройки которые могут улучшить точность освещения.

Местонахождение этих настроек:

Те самые 2 настройки — Shadow Bias и Filter Sharpness

Shadow Bias — контролирует точность теней в сцене, но может выдать артефакты, если значение будет слишком низким.По умолчанию стоит значение 0.5 которое даёт хороший результат между точностью и эффективность.

Shadow Filter Sharpness — помогает скрыть некоторые артефакты при низких значениях и помогает создавать более резкие тени на краях.

Принимая во внимание то, что предыдущие настройки не были применены для текущих примеров, то ниже идут 2 примера с демонстрацией этих параметров ( Shadow Bias и Shadow Filter Sharpen):

Shadow Bias

Shadow Bias = 0.5 (Дефолтное значение)

Shadow Bias = 0, установлено слишком низкое значение и поэтому появляются артефакты

Решение данной проблемы- нахождение баланса между установкой не слишком низкого значения и подбором нужного значения в Cascaded Shadows

Shadow Filter Sharpen — делает края тени более резкими при высоких значениях.

Filter Sharpen = 0

Filter Sharpen = 1

Высокое значение параметра даёт резкий край тени, низкое- плавный край тени.

Почему мой подвижный источник света светится сквозь меш на дистанции?


Динамическое освещение , в частности точечные ИС,могут создавать проблемы такого рода.Unreal Engine 4 достаточно хорошо справляется с подобной оптимизацией, поэтому вам не стоит сильно об этом волноваться.Но иногда возникает подобная проблема и метод её решения не всегда очевиден.

Результат который мы хотим.Камера в близи.

Что получается в итоге.Камера в отдалении.

Что же делать?

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

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

Проход света сквозь меш

Вы можете заметить, что если вы на дистанции выберете/выделите такой меш, то освещение вернётся в нормальное состояние.Это объясняется тем, что вы сфокусировались в данный момент на данном меше.

Дабы сохранить меш пропускания света, вам нужно выделить меш, и перейти в details panel.Тут вам нужно найти во вкладке Rendering , параметр Bounds Scale.

Местонахождение Bounds Scale

По умолчанию значение установлено в 1.0 . Увеличивайте данный параметр на небольшие значение (1.1, 1.2 и тд.). Используя значение = 2 ,удваивает дистанцию которая может стать излишней. Нет необходимости использовать значение больше необходимого, так как это может повлиять на производительность и качество теней.

Вы можете увидеть/визуализировать границы вашего меша перейдя во вьюпорте > Show > Advanced > Bounds

Увидите нечто такое:

Визуализированные границы объекта.

Дополнительная заметка:

Если у вас есть вышеописанная проблема, но вы не хотите увеличивать размеры границ вашего меша из-за проблем с производительностью — попробуйте использовать Spotlight. Данный ИС пускает свет лишь в одном направлении, в отличии от point light который пускает свет по всем направлениям когда меш пропускает свет.Пусть это и возымеет некоторый положительный/требуемый эффект, но лишь методом проб и ошибок вы сможете добиться идеального решения.

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

Alternatively, you could forego a fully movable/dynamic light and use a stationary light that bakes a lightmap texture, which can also save on performance by having zero overhead during runtime for rendering shadow information.

Статическое освещение


Разрешение лайтмапы /Качество теней


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

Простенькая сцена с 3 статическими мешами.

В данной сцене 3 объекта : 2 стены и пол.Каждый объект имеет собственную тень, которая запечена в текстуру именуемую — лайтмапой (lightmap).Данная лайтмапа хранит в себе информацию о тенях/освещении, которые проецируются на эту текстуру.Она, как правило, создаётся художником в процессе создания ассета.
Что нужно знать про лайтмапы и как их эффективно создавать?

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

Теперь нам надо увеличить разрешение лайтмапы для некоторых мешей.Каждый меш имеет свою собственную лайтмапу, разрешение которой можно установить в details panel, когда наш меш выбран в mesh editor.

В данном примере рассматриваем разрешение лайпмапы пола, и только его.
Когда изменяете разрешение лайтмапы, используйте значения только кратные двум (32(по умолчанию),64,128,и т.д.) за исключением BSP представленных ниже.

Качество разрешения лайтмапы зависит от двух факторов : размер меша и размер UV шела на развёртке лайтмапы.

Разрешение = 64

Разрешение = 128

Разрешение = 256

Разрешение = 512

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

Resolution = 32

Resolution = 24

Resolution = 16

Resolution = 8

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

Что такое Overlapping UV
Когда используете статическое или стационарное освещение, необходимо использовать 2 развёртки , иначе вы получите такое сообщение:

Лог после запекания освещения

В данном случае вам надо установить 2й канал развёртки для вашей лайтмапы. В противном случае редактор будет использовать имеющуюся развёртку со всеми имеющимися ошибками.
Вы можете сделать это прямо в редакторе (картинка ниже) либо же с вашем 3d редакторе.

Оригинальные UV и результаты

Перекрывающиеся UVs

Результат в редакторе

Правильные UV и результаты

Правильные UVs

Результат в редакторе

Заметьте, что финальные UV не имеют перекрытий что даёт теням/свету правильно запечся в текстуру.

Как сгенерировать UV в редакторе

Откройте меш, лайтмапу которого ваш нужно отредактировать.
Найдите панельку похожую на эту:

Static Mesh Editor Details Panel

Данная панелька позволяет вам создать свой канал лайтмапы , но назначение разрешение лайтмапы и индекса координат происходит не здесь, а чуть ниже.
Настройки вкладки “Build Settings” на которых мы сфокусируемся:

Generate Lightmap UVs = удостоверьтесь в том, что данная галочка стоит.
Min Lightmap Resolution =Минимальный размер разрешения лайтмапы которое вы хотите.
Source Lightmap Index = Источник с которого генерируем лайтмапу
Destination Lightmap Index = Индекс развёртки которую мы хотим использовать в качестве лайтмапы.

Для большинства ассетов это достаточно хорошие настройки.Ключевой момент тут- выбор нужного индекса источника лайтмапы.Это UV который обычной используют для текстур.UV шелы в этой UV будут перепакованы, и не будут образовывать перекрытия поверхностей.Разрешение лайтмапы не влияет на качество развёртки, этот параметр влияет лишь на качество теней которые будут запекаться на эту развёртку.Если вы хотите проверить, какая у вас получилась развёртка после генерации, выберите UV channel 1 (показано на картинке):

Редактор статик мешей, выбор UV Channel

Теперь, после генерации лайтмап UV, осталось выбрать нужный id в настройках самого меша.
В редакторе меша перейдите в details panel, во вкладку “Static Mesh Settings”

В этой вкладке нужно установить разрешение лайтмапы которое нам нужно.
32 — дефолтное разрешение.для маленьких объектов оно вполне подходит, но чем больше объект, тем больше разрешение нужно указывать.
Удостоверьтесь, что значение кратно 2 (пример: 32, 64, 128, 256, и тд.)
В следующем параметре, удостоверьтесь, что индекс координат лайтмапы установлен на правильный канал.
Обычно для лайтмапы стоит значение 1.

Static Mesh Editor Details, Настройки лайтмапы

После использования данных настроек у вас есть правильное разрешение лайтмапы.

А вообще, лайтмапы лучше создавать прямо в 3d редакторе который вы используете, там вы сможете сделать идеальную развёртку для лайтмапы.Какой бы автогенерация не была, но ошибки будут всегда.
Если вы используете в своём пайплайне 3ds max или maya, посмотрите видео ниже, на них человек доступным языком объясняет как сделать отличную развёртку для лайтмапы.
Сказать автору видео «Спасибо» можете в виде like’ов и подписки на канал (там ещё много полезного видео на РУССКОМ языке (всё как вы любите)).

Как контролировать Глобальное Освещение при использовании статического освещения

Когда вы используете статическое освещение, вам необходимо забилдить освещение чтобы увидеть результаты.Лайтмасс (Lightmass) используют для генерации и компиляции текстур, которые будут хранить информацию об освещении и тенях запечённую в лайтмапы.

По умолчанию, значение лайтмасс = 3 световых отскока, дабы получить GI (глобальная иллюминация/освещение) используя статическое освещение.Если необходимо изменить данное значение, то его можно найти во вкладке World Settings.

Здесь вы можете видеть множество настроек того, как освещение будет реагировать в вашей сцене.Для GI мы сфокусируемся лишь на “Num of Indirect Lighting Bounces”. Ползунок ограничен в пределах от 1 до 4.Но вы можете установить любое значение просто вписав его туда

Lightmass World Settings по умолчанию

Global Illumination пример сцены.Одинарный источник света в 250 единиц (15w примерно)

Почему тени пятнистые или как избавится от загрязнения лайтмап?
Пятна, загрязнения, ну или как вы там это называете, не суть;данная ошибка часто возникает при использовании статического освещения в ue4.Не стоит паниковать, ведь исправить это можно через настройки лайтмасс.
Первое что приходит на ум- это то, что это связанно с непрямым освещением от отскоков GI при построении лайтмасс.
Что бы показать как это наиболее эффективно исправить, будем использовать 2 комнаты в качестве примера.

Экстерьер

Интерьер

В данной сцене будет использоваться продакшн (PRODUCTION) качество освещения.В данной сцене используются ассеты из Starter Content pack .Все меши в этой сцене используют разрешение лайтмап = 256, в других случаях об этом будет написано.Пост процессы установлены в дефолтные значения , с адаптацией глаз для того, чтобы лучше видеть тёмные места комнаты.

После постройки освещения получаются такие вот результаты:

Первоначальное освещение, дефолтные настройки

Интерьер 1й комнаты ,освещается прямым светом с одним отскоком.

интерьер 2й комнаты , освещается полностью непрямым светом

Brute force может быть использовано для удаления некоторых артефактов путём увеличения разрешения лайтмапы , но это решение не всегда верно и не всегда помогает.
Как пример, во второй интерьерной комнате, разрешение лайтмапы увеличили до 1024:

Первоначальное освещение, дефолтные настройки

интерьер 2й комнаты , разрешение лайтмапы 256

интерьер 2й комнаты , разрешение лайтмапы 1024

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

World Settings находится тут :

Настройки Lightmass изменяются тут :

Indirect Lighting Quality: увеличивает значение Global Illumination для получения требуемого качества.
Indirect Lighting Smoothness: фактор сглаживания применяемого в Indirect Lighting.
Осторожно! используя значение более чем 1 в Indirect Lighting Quality сильно увеличивает время билдинга

Настройки по умолчанию

Пример настроек #1

Вы также можете настроить количество отскоков непрямого освещения для получения требуемого результа:

количество отскоков непрямого освещения = 4

количество отскоков непрямого освещения= 5

На данный момент настройки освещения установлены в достаточных значениях для сокрытия любых артефактов с текстурами. Но если нет возможности производить данные манипуляции, то можно просто поднять значение разрешение лайтмапы. Тут это значение изменили с 256 до 512 и получили такой вот результат.

Изменённые косвенные параметры с разрешением лайтмапы = 512.

Не изменённые косвенные параметры с разрешением лайтмапы = 1024.

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

Хотя этот метод и показывает методы решения проблем с «загрязнением» лайтмап без использования света, следует помнить,что добавление в нужное место небольшого источника света, пусть и с низкой интенсивность, без теней- может дать результат получше.Методы описанные выше являются лишь отправной точкой, и лишь методом проб и ошибок вы можете добиться требуемого результата.

Хочешь узнать больше про Lightmass Basics?

Хочешь узнать больше про Lightmass Global Illumination?

Что такое “Lighting needs to be rebuilt” в левом верхнем углу?
Если вы в режиме : игра в редакторе, симуляция, standalone, в левом верхнем углу видиту надпись Lighting needs to be rebuilt, это означает, что вы должны заново запечь/простроить освещение в вашей сцене.Данное явление происходит только при статическом и стационарном освещении.Динамическое освещение не требует билдить освещение.Данное сообщение появляется в случае если источник света был передвинут или модифицирован.


Сообщение об ошибке

Сравнение качества освещения


Когда вам требуется запечь освещение в необходимом качестве, вы можете выбрать качество перейдя во вкладку Build>Lighting Quality>выбрать нужное качество.
По умолчанию качество установлено в Preview.Данный уровень качества быстрее при просчёте нежели Production, но не столь аккуратное.

Превью

Среднее

Высокое

Продакшн

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

На примере этой статуи заметить разницу между качествами не так уж и легко.Но разница есть.

Качество освещения

Превью

Среднее

Высокое

Продакшн

Улучшение развёртки лайтмапы — залог качественных теней.


качество освещения статуи

Contents

  • 1 About This Guide
  • 2 General Lighting
    • 2.1 Why Are My Shadows Black?
    • 2.2 Invalid Lightmap Settings When Converting BSP to Static Mesh
    • 2.3 What if I don’t want to have lightmaps at all or my game doesn’t need them
    • 2.4 Two-Sided Lighting for Single Sided Meshes, or Why does my light come through the roof?
    • 2.5 Why does this look nothing like it did before, or Engine Scalability and you
    • 2.6 Why is there a red “X” over my light?
  • 3 Dynamic (Movable) Lighting
    • 3.1 Shadow bleed or Incorrect Shadow Quality
      • 3.1.1 Directional Light ONLY: Cascaded Shadow Maps Settings:
      • 3.1.2 Adjusting Cascades for better Quality:
      • 3.1.3 All Dynamic Lights (Light Tab Settings):
    • 3.2 Why does my Movable light shine through my mesh at far distances?
  • 4 Static Lighting
    • 4.1 Lightmap Resolution / Shadow Quality
    • 4.2 What is this “Overlapping UV error” non-sense when I build lighting?
    • 4.3 How do I generate lightmap UVs in the editor?
    • 4.4 How to control Global Illumination with Static Lighting?, or The Wonderful Thing About Bounce
    • 4.5 Why is there shadow splotches on my static mesh?, or How to clean those dirty lightmaps?
    • 4.6 What is the “Lighting needs to be rebuilt” in the Top left corner error?
    • 4.7 Lighting Quality comparison, or Production > Preview

About This Guide

Often the difference between a good game and a great game can come down to light. Even the best model rendered with poor shadow resolution and not taking advantage of the right post process settings will look poor. In the Unreal Engine, it means digging in to our robust lighting, reflection and post process settings. This Troubleshooting guide attempts to cover some of the more common problems that people come across when they first dig into the lighting and rendering systems. This guide is by no means meant to be completely comprehensive but a living document as the engine changes so too can we add and alter advice presented here. The guide is meant to be a great first step for artist trying to get the most out of the engine’s rendering system.

Common Lighting Documentation pages for reference:

Lightmass Global Illumination
Lighting Basics
Lighting the Environment
Lighting Content Examples
Lighting for Mobile Platforms
Rendering & Graphics

General Lighting

Why Are My Shadows Black?

In lighting terms, deep black shadows usually mean you have no fill light. This can often happen when doing outdoor environments where a single directional light is meant to represent the sun. UE4 has a built in method to provide a world effecting fill light, we refer to it as a Sky Light. Want to know more about Sky Lights?

  • No Skylight

  • With Skylight


Invalid Lightmap Settings When Converting BSP to Static Mesh

When you convert your BSP geometry to a static mesh, you will likely see the following result:

Static Mesh Converted from a BSP Box

Static Mesh Editor Details Panel

Don’t worry, this is normal! Since we’ve now converted our BSP to a Static mesh we need to make sure the right lightmap channel is assigned. To make things easier, when you convert the BSP it will automatically generate your lightmapping UVs for you. The only thing that is not setup is automatically is making sure the right channel and resolution are assigned.

  • To do this, open the newly created Static Mesh. Look to the details panel on the right and locate the tab Static Mesh Settings.
  • Here you’ll need to set the Lightmap Resolution. This should be any power of two increment (ie. 32, 64, 128, etc). This will be the resolution of your lightmap texture. Higher lightmap resolutions will result in better shadow quality baked into the texture, but it will also increase memory foot print and light build times.
  • Next we’ll set the Lightmap Coordinate Index to 1 (This is the lightmap UV channel in most cases). This is the location of our lightmap UV that will have no overlapping faces.
  • If you want to see what the lightmap UV looks like you can click the button for the UV in the toolbar and choose UV Channel 1 from the drop down to the right of the button.

What if I don’t want to have lightmaps at all or my game doesn’t need them

There may be times where a game doesn’t need lightmaps at all, because it’s been opted to use only Movable (Dynamic) lighting. There is an option to disable lightmaps all together by opening the world settings and checking the option for “Force No Precomputed Lighting.” When lighting is rebuilt it will remove all lightmaps that have been previously cooked.

There are two methods to disable Static Lighting:

Project Settings, Rendering Tab, Lighting Tab

Project Specific: Disable Static Lighting

  1. Menu > Edit > Project Settings
  2. Go to the Rendering Tab > Lighting Tab
  3. Uncheck the option for Allow Static Lighting
  4. To enable this option fully you will need to Restart the Editor

Level Specific: Disable Static Lighting

World Settings

1. Open World Settings

Lightmass Settings

2. Go to the Lightmass Tab
3. Uncheck Force No Precomputed Lighting

Force No Precomputed Warning

4. You will get a warning. Click OK.
5. Build Lighting to wipe lighting data already stored.


Two-Sided Lighting for Single Sided Meshes, or Why does my light come through the roof?

Created Assets in 3DS Max

So, you’ve had fun and created some awesome new assets for your game like I’ve done here.

In this image you’ll see I’ve made myself an awesome wall and a tube that when I turn on its side can be a creepy tunnel for me to walk through!

Created Assets in UE4

All seems well and good and I can see that I’ve got my awesome work and I can see both sides of my mesh in my modeling program of choice. However, when it’s imported into Unreal Engine 4 it’s messed up!

So, what gives, because this surely cannot be right?!

This is actually 100% normal. Even though the plane looks good the back face is not being rendered just like the closest faces of our tube mesh.

Wireframe of Created Assets in UE4

When you create your geometry in your modeling program by default the software has set it so that you can see both sides of your geometry.

In UE4 the the backface of a polygon is automatically culled to save on performance, because every little bit helps! It’s not always necessary to have extra polygons or render sides that may not be needed, otherwise there would be extra draw calls that could slow down your performance. with a few instances this probably wouldn’t matter much, but when you’re developing for specific platforms or have a lot going on every draw call starts to matter.

To also understand why we can only see one side we can open our mesh in the static mesh editor and tick the toolbar option for “Normals.” You will see Green lines that point in the direction the face of the polygon is directed. In the image below for our tube asset we can see that the faces where it’s invisible have the lines going towards the center of the mesh. This is the direction that the visible face can be seen.

Static Mesh Editor

Pro Tip: While in UE4 if you have any meshes that have what appears to be invisible geometry or missing faces you can check the normals here before fixing the issue in your modeling software.

Now that we have all the boring stuff out of the way we can get right to fixing our invisible faces with some checkboxes and Materials.

1. (STATIC ONLY)Light as if Two-Sided

  • Enabled this option via the details panel for the selected asset in the Level Viewport.
  • With this option selected, when lights are built lightmass will calculate that geometry into its bake. It will cast a shadow, even though we cannot see it from this angle, to bake into the lightmap texture. This will not work with a movable/dynamic light though since Unreal Engine 4 uses a deferred rendering pipeline.
  • Asset’s Details Panel in Level Viewport

  • Final Results

2. Creating a Two-Sided Material

  • Open the material editor and in the details panel on the left select the option for “Two-sided”.
  • Save and compile your material for this to take effect.
  • This method can be used with Static/Stationary/Movable lighting. Since the material is now being rendered the faces of that were not visible before are no longer being culled and can block the light. Be aware though that this now renders both sides of the mesh adding to your draw calls. As mentioned earlier this won’t necessarily affect performance in smaller scenes or setups, but if you’re targeting hardware where every bit of performance counts this can affect that.
  • Material Attributes Details Panel

  • Final Results

Why does this look nothing like it did before, or Engine Scalability and you

The Engine Scalability settings can be accessed via the Settings > Engine Scalability option in the Toolbar.

The purpose of this is to scale the engine rendering settings to fit machines that may have a more difficult time running smoothly. By default the editor will lower settings here if the FPS drops too low.

There is a option for “Shadows” that will directly affect the shadowing distance of any movable (dynamic) shadows. This is true when the list is set to “Movable” or when lighting has not been built for the static lights yet, since those are using dynamic shadows as temporary indication until your lights are built and baked into lightmaps.

The images below will demonstrate the shadow distance of each Shadow setting in the Engine Scalability tab.

  • 2 StatueShadowsEPIC.png

    Epic

  • 3 StatueShadowsHIGH.png

    High

  • 4 StatueShadowsMEDIUM.png

    Medium

  • 5 StatueShadowsLOW.png

    Low

If there are no shadows in your level this is the best place to check first. Even if your system is top of the line these settings can still be automatically set to a lower setting and stay there if the FPS drops too low. It’s a good place to always check before looking at other issues that may be a factor.

If there is a need to not have the auto-scaling on it can be disabled by unchecking the option at the bottom of the Engine Scalability settings window. Do realize that this can cause performance issues as the editor will no longer monitor when there is a need to adjust this to a lower settings to help keep performance up.

Want to know more about Engine Scalability?


Why is there a red “X” over my light?

Stationary lights are limited to a maximum of 4 shadow casting lights being overlapped. When the 5th is added there will be a red ‘X’ indicating that the light in this area of overlapping with the smallest radius will revert to a dynamic light. This can cause performance issue because dynamic lighting that casts shadows is more expensive to use then baked lighting.

If lighting is built with any stationary lights that are overlapping offenders there will be a warning detailing which light is the offender and the ramifications.

To correct this make sure that there are no more than 4 shadow casting overlapping Stationary lights in a single area. This may require the removal of a light, disabling the Cast Shadows flag or adjusting the radius so that it’s no longer overlapping.

If there are only three placed stationary lights and there is a red X over the 4th light make sure that you have no other stationary lights in your level that would be overlapping. Often times this would be the Directional light set to Stationary that is causing this issue.

Want to know more about Stationary Lights?


Dynamic (Movable) Lighting


Shadow bleed or Incorrect Shadow Quality

In this guide we’ll look at areas that will help improve the quality so that the shadows more accurately fit the meshes. This will also help in offering tips to improve dynamic lighting at a distance.

  • Dynamic Default Shadows.png

    Example of Shadow Bleed, or Incorrect Shadow Quality

Directional Light ONLY: Cascaded Shadow Maps Settings:

  • 2 settings.png

    Cascaded Shadow Maps Settings, in Directional Light Details

Dynamic Shadow Distance Movable: This is the distance from the camera that shadows will cover. A value of 0 disables this.

Dynamic Shadow Distance Stationary: This is the distance from the camera that shadows will cover. This is set to 0 by default for Directional Stationary Lights

Num Dynamic Shadow Cascades: This is the number of cascades the view frustum will be split into. More cascades will result in better shadow resolution, but will add significant rendering cost. To read more on view frustums take a look at this article: http://en.wikipedia.org/wiki/Viewing_frustum

  • Num Dynamic Shadow Cascades (In these examples Shadow Bias, covered later, has been set to 0 to more visibly see the cascades.)
  • 1Cascades0.png

    Cascade Number = 0

  • 1Cascades1.png

    Cascade Number = 1

  • 1Cascades2.png

    Cascade Number = 2

  • 1Cascades3.png

    Cascade Number = 3 (Default)

  • 1Cascades4.png

    Cascade Number = 4

Cascade Distribution Exponent: This controls whether the cascades are distributed closer (higher value) or further away (lower value) from the camera. A value of 1 means the transition will happen proportional to their resolution.

  • Cascade Distribution Exponent
  • 2Distribution1.png

    Distribution = 1

  • 2Distribution2.png

    Distribution = 2

  • 2Distribution3.png

    Distribution = 3

  • 2Distribution4.png

    Distribution = 4

Cascade Transition Exponent: This controls the proportion of the fade region between cascades. Lower values will give a hard edges between the shadow cascades whereas higher values will blend between the two.

  • Cascade Transition Exponent
  • 3TransitionGif.gif

    Transition Effect

  • Cascade Transition Exponent
  • 3TransitionHard.png

    Hard Edge (Lower Value)

  • 3TransitionBlended.png

    Blended Edge (Higher Value)

Shadow Distance Fadeout Fraction: This controls the how the shadows fade out at distances. Higher values will fade the shadow out whereas lower values will leave a darker shadow at distances.

  • Shadow Distance Fadeout Fraction
  • 4Fadeout0.png

    Fadeout = 0

  • 4Fadeout1.png

    Fadeout = 1

Far Shadow Cascade Count: Coming in 4.8. More information to follow soon.

Far Shadow Distance: Coming in 4.8. More information to follow soon.

Adjusting Cascades for better Quality:

Shadow bleed and accuracy can be finely tuned with adjusting a combination of the settings demonstrated above. This next section will attempt to adjust the values that work best to get better accuracy with the shadows while in close proximity and as the camera moves away. Finding a balance that works with any particular game will require time, effort, and lots of testing with what works and what does not.

Here is the basic scene with only default settings:

There are already a few problems that are prevalent in this scene with shadows accuracy around edges.

More clearly demonstrated here.

By focusing on the most of the effort around the Cascade Distribution Exponent the shadow bleed can be minimized, within reason of course. The default distance for Dynamic shadows is set to 20,000 units. This isn’t always necessary to which this can be set to a lower value to better utilize the cascades.

If the game level is to use indoor and outdoor scenes finding a combination that fits all or most areas will be difficult and require lots of tweaking. There is no one setting that will make everything look perfect.

In this scene by adjusting the settings for the Distribution, the Shadows Distance, and Number of Cascades the bleed and accuracy are acceptable.

All Dynamic Lights (Light Tab Settings):

Lastly, there are two other settings under the light tab in our light source that can benefit lighting accuracy as well.

These settings can be found here:

  • DynamicLightSettings.png

    Lighting Details, Shadow Bias and Filter Sharpness

Shadow Bias will control how accurate shadows are in the scene, but will generate artifacts if set to a value that is too low. The default value is 0.5 which is a good trade off between how accurate and effective it is.

Shadow Filter Sharpness can help mask some of the artifacting that occurs with lower values and this directly contributes to how sharp the edges of the shadows are as well.

Taking into account that none of the previous settings have been adjusted for these images these are some examples to demonstrate Shadow Bias and Shadow Filter Sharpen.

  • Shadow Bias
  • Dynamic AdjustedShadows.png

    Shadow Bias = 0.5 (Default)

  • Dynamic Artifacts.png

    Shadow Bias = 0, adjusted too low will result in artifacts

The key here is to find a good balance without going too low and using the setting under the tab for Cascaded Shadows.

  • Shadow Filter Sharpen, will sharpen the edge of the shadow with higher values
  • FilterSharpen1.png

    Filter Sharpen = 0

  • FilterSharpen2.png

    Filter Sharpen = 1

Most notably the higher the value for the sharpen filter the shaper your shadows. The soft edge created by the lower values will now be lost.


Why does my Movable light shine through my mesh at far distances?

Dynamic lights, especially point lights, cause this kind of issue to crop up. Unreal Engine 4 does a good job of trying to optimize things so that you don’t have to worry about it so much. The problem is sometimes it gets carried away and can cause things like this to happen that may not be obvious how to fix.

  • 1.png

    This is what we want, Close to Camera

  • 4.png

    Opps, At a Distance from Camera

So, what gives?!

To explain this we need to discuss that awesome optimizing the engine does for you. The engine uses scene depth to determine what should be visible and what shouldn’t be visible for rendering. Since we have a point light here that shoots light throughout it’s set radius when the mesh is beyond its bounds it will be occluded or no longer rendered. This causes the issue that we’re seeing with our light starting to cast in all directions.

You can see from this image that as the camera is further away the occlusion of parts of the mesh start to halo around the outer edge until the light is free to cast in all directions.

  • WallOcclusion.gif

    Mesh Light Occlusion

You may notice that if you select the mesh when far away that the light returns to normal. This is expected as you have just selected the mesh and it is now focused.

To keep the mesh from being occluded you’ll need to select the mesh and go to the details panel. Here you can search or scroll for the “Bounds Scale” (Located under the Tab for Rendering.)

The default value is set to 1.0. When increasing this scale be sure to only use incremental small numbers. Using a value of 2.0 doubles what the distance was set to which can be overkill. Try increasing by smaller incremental values. (ie. 1.1, 1.2) There is no need in pushing to have more than you need as this can impact performance and shadow quality.

You can visualize your meshes bounds by going to the viewport > Show > Advanced > Bounds

You will see something like this:

  • Bounds.png

    Object Bounds Visualized

Additional notes:

If you’re having issues with your mesh occluding, but don’t want to increase the bounds scale due to performance concerns you can try using a Spotlight. Since this only casts light in a single direction you won’t notice the light of a point light casting in all directions when the mesh is occluded. This works well for situations similar to what has been demonstrated, but testing may need to be done on your part to get things just right.

Alternatively, you could forego a fully movable/dynamic light and use a stationary light that bakes a lightmap texture, which can also save on performance by having zero overhead during runtime for rendering shadow information.


Static Lighting


Lightmap Resolution / Shadow Quality

Every project has its own unique art direction and goals, so this section is meant to present common concepts and give you a foundation to begin achieving what you want from your static lighting. By no means will the settings we present here work all the time for every project.

  • LM Resolution.PNG

    A Sample Scene with 3 Static Meshes

There are 3 objects in this scene; two walls and a floor mesh. Each object has is own shadows that are baked into a texture known as a lightmap. This lightmap stores any shadow/light information that is being cast on to it in this texture. It is normally handled by an artist in the asset creation. ‘Want to know more about lightmaps and how to create them effectively?

In other words, If I wanted to increase the resolution of the shadow cast by the wall with the doorway, I would not adjust the doorway, but instead would adjust the floor’s lightmap resolution. This is where the shadow is being cast and baked into a lightmap.

Now with that out of the way, we may need to increase lightmap resolution for some meshes and not others. Each mesh has it’s own lightmap Resolution that can be set via the details panel when the mesh is selected or via the mesh editor.

For this lightmap quality demonstration we’ll look at the floor meshes lightmap resolution only.

When adjusting LM resolution make sure it is using a power of two (32 [default in engine], 64, 128, etc) with exception of BSPs (Covered below)

A lot of the quality in this lightmap resolution will depend on two factors: Size of the mesh and the size of the UV shells in the lightmap UV.

  • Lightmap Resolutions for Static Meshes
  • LM128.PNG

    Resolution = 128

  • LM256.PNG

    Resolution = 256

  • LM512.PNG

    Resolution = 512

The key to difference to note about using lightmaps on BSPs versus Static Meshes is that it doesn’t increase, but instead decreases to get better resolution.

  • Lightmap Resolutions for BSPs
  • BSPLM32.PNG

    Resolution = 32

  • BSPLM24.PNG

    Resolution = 24

  • BSPLM16.PNG

    Resolution = 16

  • BSPLM8.PNG

    Resolution = 8

While adjusting the lightmap resolution to get better results there are trade offs here. Using a smaller mesh will allow you to get better results for the floor with a lower lightmap resolution, while using this larger mesh you will need to increase the lightmap resolution and the texture will use more resources for your games.


What is this “Overlapping UV error” non-sense when I build lighting?

When using static or stationary lighting it is imperative to use two UVs for your meshes otherwise you will get the following warning when you build lighting:

  • Overlapping UV Error.PNG

    Message Log, Lighting Results

This means that you’ll need to setup a second UV channel for your lightmap otherwise the editor will use the existing texture UV as the lightmap which can lead to these kinds of errors.

This can be fixed by adjusting the UV for the lightmap so that there are no overlapping faces.

This can be done in the editor via generating lightmaps or by using your modeling software of choice to create and edit your UVs.

  • Original UVs and Results
  • Overlapping LogoUV.PNG

    Overlapping UVs

  • Overlapping UV Results.PNG

    Results in Editor

  • Corrected UVs and Results
  • Overlapping LogoUV Adjusted.PNG

    Corrected UVs

  • Overlapping UV Results Adjusted.PNG

    Results in Editor

Take notice that the the UV in the final result has no overlapping faces which allows shadow/light information to bake correctly for the texture that will be applied to our mesh after the light build.

With the overlapping faces these will give incorrect shading due to lighting information not being baked correctly.


How do I generate lightmap UVs in the editor?

With the release of 4.5 the editor will automatically generate UVs on import or by using the mesh editor.

We will assume you’re wanting to set them up from the mesh editor.

  • Open the mesh you’d like to create a lightmap with.
  • Locate the panel on the right that looks like this:
  • GeneratedLMs.png

    Static Mesh Editor Details Panel

This panel will allow you to create your lightmap channel, but do note that this does not directly control your lightmap resolution or it’s coordinate index assignment. These will be covered a little later.

The settings here in the “Build Settings” tab that we will focus on are:

Generate Lightmap UVs = make sure this is checked.

Min Lightmap Resolution = This is the smallest size you would want your lightmap resolution to be.
Source Lightmap Index = This is the source which we will generate our lightmap UVs from.

Destination Lightmap Index = This is the location we will store this UV when it is created.

For most assets this should be a good setup. The key here is making sure that we select the proper source lightmap index. This is the UV that is typically used for the textures. The UV shells/islands in this UV will be repacked so that there are no overlapping faces, which is integral to using lightmaps.

For the lightmap resolution setting a low value to begin with is not bad because we are not obligated to using that resolution. If you decide to use a higher resolution you do not need to come back to these settings unless you know it could improve the lightmap bake. In most cases it’s not necessary.

Once you’ve hit “Apply Changes” we can verify our lightmap has been created and see if there appears to be any errors.

You can do this by going to the mesh editor toolbar and clicking the UV icon to show the UV and using the drop down to the right to select UV channel 1 to view our newly created lightmap.

It should look something like this:

  • UVChannelSelection.png

    Static Mesh Editor, UV Channel Selection

That’s not quite it though. We still need to assign the correct UV channel to be used for our Lightmap.

In the mesh editor in the details panel on the right locate the tab labeled “Static Mesh Settings”

  • In this tab we’ll need to adjust the lightmap resolution for what we’d like here.

32 is the default lightmap resolution. For smaller objects this would work well. For larger objects we would possibly need to use higher resolutions.

Make sure to adjust it by a power of 2. (ie. 32, 64, 128, 256, etc)

  • The next setting we’ll need to verify is that the Lightmap Coordinate Index is now pointing to the right channel. Make sure this is set to the channel that you set in the build settings above. Typically this should be set to 1.

After using these settings you will now have a proper lightmap resolution.

There are some caveats to this though that may require the use of a modeling program like Blender, 3Ds Max, or Maya to fully correct the issue.

The generated lightmaps will not split or cut seams in the existing UVs from UV channel 1 used for the texture. It will only repack the existing UV layout to better fit the needs of a lightmap UV.

As an example, think of a cylinder. If you wanted to lay these faces all out flat you would need to cut a line in the side of the cylinder to do so. In a modeling program this isn’t always necessary depending on how you’ve set up the texture UV to be used. If this side face was not cut to be laid out flat the generated UVs via the mesh editor will not work and will still result in overlapping UVs warning being generated after a light build.


How to control Global Illumination with Static Lighting?, or The Wonderful Thing About Bounce

When using static lighting you will need to build lighting to see the results. Lightmass is used to compile and generate textures that will store this light and shadow information for our scene by baking this information into a lightmap texture.

By default lightmass is set to use 3 light bounces to get GI with static lighting. If more is needed we will need to directly change the lightmass settings to get different results via our World Settings tab. We can affect our Global Illumination directly by changing the number of bounces that the light will cast.

To enable World Settings tab you’ll need to go to the Toolbar and select Settings > World Settings

  • World Settings

Click on the the World Settings tab next to the Detail Panel tab on the right side.

Here you’ll see a lot of settings that can affect how our light is handled with lightmass that will directly affect our scene. For GI we’re only going to focus on the second option down “Num of Indirect Lighting Bounces.” The slider is clamped to be a value between 1 and 4. You can override this by manually typing in a value though.

The default settings are shown to the right.

  • Global Illumination Sample Scene, Single Point Light at 250 (≈ 15W Light Bulb)
  • Scene Setup.PNG

    Scene Setup

  • NumBounces0.png

    0 Bounces

  • NumBounces2.png

    2 Bounces

  • NumBounces3.png

    3 Bounces

  • NumBounces4.png

    4 Bounces

  • NumBounces100.png

    100 Bounces


Why is there shadow splotches on my static mesh?, or How to clean those dirty lightmaps?

Show stains, splotches, dirtiness, or whatever name you have for it is a common issue with UE4 when using any type of static lighting. Fear not though because we can get rid of those dirty lightmaps with a little scrubbing through our lightmass settings.

First though, the reason you see something like this is related to the indirect light from our GI bounces that happen with our lightmass build.

To replicate this in a mostly effective way this simple scene will have two rooms.

  • Sample Scene
  • 1 sceneSetup.png

    Exterior

  • 2 sceneSetup.png

    Interior

This scene will be using PRODUCTION quality for our light builds. This scene is using assets from the Starter Content pack that can be added to any newly created project. All meshes in the scene will use a lightmap resolution of 256 unless otherwise noted. The post process effects are set to default with eye adaptation to make the darker room easier to see.

After building our lighting, here are the results:

  • Initial Lighting Build, default settings
  • 3 Room1 Clean.png

    1st Interior Room, lit with direct and 1st bounce lighting

  • 4 Room2 dirty.png

    2nd Interior Room, lit entirely with indirect lighting

Brute force can be used to remove some of the indirect lighting artifacts by increasing the lightmap resolution which effectively increases the size of the textures used to store the lighting and shadowing information, but that’s not always the best idea when a high quality result can be achieved using a lower resolution and adjusting the lightmass settings. When dealing with any rendering application in the engine and especially lighting just increasing a texture size, though it may appear to solve the issue is not always the most performance friendly way to handle an issue and may even result in more problems further along in your development process.

As any example this is the same 2nd Interior Room with lightmap resolution changed to be 1024:

  • Initial Lighting Build, default settings
  • 4 Room2 dirty.png

    2nd Interior Room, Lightmap Resolution 256

  • 5 lightmap1024.png

    2nd Interior Room, Lightmap Resolution 1024

In this example a lot of the artifacts have been reduced by using the higher lightmap resolution, but this also increases the texture memory footprint by a factor of 4. There is a more performance friendly solution to these Indirect Lighting Artifacts with some simple adjustments to the World Settings.

  • You can locate World Settings here:
  • Here the settings for Lightmass can be adjusted:

Indirect Lighting Quality: This will increase the Global Illumination solver counts to get a higher quality for levels that need it.

Indirect Lighting Smoothness: This is the smoothness factor to apply to Indirect Lighting.

WARNING: Using a Value greater than 1 in the Indirect Lighting Quality will GREATLY increase build times.

  • 9 results.png

    Default Settings

  • 11 results.png

    Settings Example #1

As mentioned in How to control Global Illumination with Static Lighting?, or The Wonderful Thing About Bounce, you may also want to adjust the number of indirect light bounces which will yield the following results:

  • 13 results.png

    Num Indirect Lighting Bounces = 4

  • 14 Results2.png

    Num Indirect Lighting Bounces = 5

At this point, the lighting settings have been adjusted enough that there may be room to hide any artifacts with some textures, but if that’s not the option there is the option to bump the lightmap resolution for each mesh up to a higher value. The value used here is 256 for the lightmap resolution. By changing it to be 512 we get the following result:

  • 15 FinalResult.png

    Adjust Indirect Settings with 512 Lightmap Resolution

  • 5 lightmap1024.png

    No Adjustment to Indirect Settings with 1024 Lightmap Resolution

In the beginning of this tutorial there was a comparison shown using Lightmaps of 1024 that helped get rid of the artifacts. By adjusting a few lightmass settings the artifacts have been reduced and the assets are using a lower texture resolution with better results.

While this method is fully exploring the option of not having any light in this room and looking at ways to reduce the “dirtiness” artifacts that can be caused by Indirect Lighting it must be noted that using lighting can in these areas, even a very low intensity non-shadow casting light, can get results as well. The methods listed above are a starting point and may require a little trial and error to get the results that are more appealing.

Want to know more about Lightmass Basics?

Want to know more about Lightmass Global Illumination?


What is the “Lighting needs to be rebuilt” in the Top left corner error?

If this is appearing in your top left part of your viewport window when using PIE (Play in Editor), Simulate, or Standalone game this simply means that lighting needs to be rebuilt for your scene. This will only affect Static and Stationary lighting. Dynamically lit scenes do not need to have lighting built.

This warning is caused when lighting has been invalidated by moving or modifying a light Actor. This can cause problems because the rendered lighting in the level is not accurately representing the current state of lights in the level. This error can be solved by going to the Build menu and rebuilding lighting for a map.


Lighting Quality comparison, or Production > Preview

When lighting needs to be built for a level the quality of the light build for lightmaps can be set in the toolbar by going to the options for Build > Lighting Quality > and selecting a quality level.

By default the Quality is set to Preview. This setting has the fastest computation time whereas Production will have the slowest computational time, but be much more accurate.

The Lighting Quality settings can be found here:

  • 2 BuildOptions.png

    Lighting Quality Settings

For this demonstration there will be a enclosed room to show the quality of the shadows being built: (This will be the same scene setup used for #Why is there shadow splotches on my static mesh?, or How to clean those dirty lightmaps?

  • Light Quality Settings, Architectural
  • 6 Production.png

    Production

In this example it’s easy to see the difference between the default Preview setting and Production setting. With Production almost all of the light leaking that was prevalent in the previous quality settings is gone. This is a good way to troubleshoot your lighting issues if there is light leaking. If Production doesn’t get rid of the light leaking then it’s time to have a look at how the lightmap UVs are set up or possibly the placement of the meshes in your level.

With the Statue static mesh in this scene it’s not as easily noticeable that the shadow quality has been adjusted. There is slight differences in quality, but not enough to tell with the particular object.

  • Light Quality Settings, Organic Lines
  • 7 statue preview.png

    Preview

  • 8 statue Medium.png

    Medium

  • 10 Statue Production.png

    Production

In this animated Gif the quality differences are minuscule from this perspective. This behavior is expected for more organic shapes. The human eye notices non-organic straight lines (like Architectural right angles) before curved or more organic shapes given the same color and brightness. As a note, the jaggedness of the shadows on the ground plane are the result of having a lower lightmap resolution for a larger mesh. Increasing the lightmap resolution will improve the quality of the shadow definition.


I do not remember exactly what modification I did on my computer, but when I tried to open the UE4 the following error appeared:

enter image description here

(image taken from the internet)

It is not the first time that this error occurs, but there I went to solve it again (If I remember correctly I deleted the folder with the libraries (.dll) that resolved it the first time, so I had to download it again):

But before, a poetic pause… One day Albert Einstein said: Insanity is to keep doing the same thing and expect different results.

So this time I looked for another place to try to solve this error, :

(VIDEO LINK) => https://www.youtube.com/watch?v=kA4N0x4iG54

In this video the man orders to download a compressed file that contains three folders.

(COMPRESSED FILE) => http://www.mediafire.com/file/at50mz3rkobxe4i/Erro+0xc000007b.rar

You should copy all libraries from the first folder and paste them into the sytem32 folder (if your system is 32-bit) and the system32 and SysWOW64 folders (if your system is 64-bit).

Your pasting must be of the type that replaces existing files:

enter image description here

You will need to give administrator permission for the computer to do this:

enter image description here

There will be an «error», you select the «do this for all current items» box and then click ignore:

enter image description here

Once you click Ignore you will notice that there are numerous selected files. Press the delete key and enter to delete them (again you will have to provide administrator permission):

enter image description here

NOTE => For users of a 64-bit computer, you will have to do this in both folders (system32 and SysWOW64).

In the second folder of the file that the video man made available has the directX installer. I RECOMMEND NOT TO USE, BECAUSE WITH ME IT DID NOT WORK. I even had to reinstall directX.

(OFICIAL LINK OF DIRECTX) => https://support.microsoft.com/pt-br/help/179113/how-to-install-the-latest-version-of-directx

Just install DirectX.

In the third folder of the file that the video man provided, there is another installer (all versions of Visual Studio) that also did not work for me.

(OFICIAL LINK 64-bit) => https://www.microsoft.com/pt-br/download/confirmation.aspx?id=36805

Sorry, I downloaded 32-bit too, but I can not find the link.

Just install all versions of Visual Studio from Microsoft.

That way I killed two birds with one stone.

The lighting build works and the error has been fixed.

Понравилась статья? Поделить с друзьями:
  • Как найти драйвера по цифровой подписи
  • Как найти веревку the forest
  • Как найти район на навигаторе
  • Как найти прибыльный товар для маркетплейсов
  • Как женщине найти работу в воронеже