Создание HDR скайбоксов

From Valve Developer Community
< Ru
Jump to navigation Jump to search
English (en)Русский (ru)Translate (Translate)
Вернуться к: Skybox Basics
Info content.png
This page needs to be translated.
This page either contains information that is only partially or incorrectly translated, or there isn't a translation yet.
If this page cannot be translated for some reason, or is left untranslated for an extended period of time after this notice is posted, the page should be requested to be deleted.
Also, please make sure the article complies with the alternate languages guide.(en)
Edit Tabs
Выгода HDR-Skybox (слева) в том, что они позволяют использовать более широкий диапазон яркости.

В отличие от большинства текстур в игре, Skybox представляет собой коллекцию больших и ярких объектов. Это делает HDR(en) более актуальным.

VTF(en) текстуры используются HDR-Skybox для хранения цветов либо в слегка сжатых 16-битных значениях с плавающей точкой(en) (RGBA16161616f), либо в сильно сжатых 8-битных целых(en) (BGRA8888). В любом случае, они будут созданы VTEX(en) из несжатых 32-битных с плавающей точкой Portable Float Map (.pfm) файлов.

Tip.pngСовет: Несжатые HDR VTF могут быть декомпилированы в PFM с помощью vtf2tga(en). Не обращайте внимания на название программы.
Сжатие VTF HDR файлы могут быть разжаты в exr с помощью no_vtf.

The following page describes the creation of HDR skyboxes manually, with creating the txt files the VTEX can read and splitting faces by hand.
However, a new automated way has been created, where the only manual labor consists of creating/porting LDR skyboxes in blender.
A Python script will then split all the faces, create materials, and spit out a fully finished HDR skybox with LDR fallbacks.
If you would like to learn a quicker and less manual way of creating LDR and HDR skyboxes, refer to this Video guide.

Создание отдельных текстур кубической карты из панорамы

Вы можете создать HDR скайбокс с помощью этого аддона. Просто создайте сферу с количеством сегментов равным 64 и выполните шаги третьего абзаца. Далее идут инструкции как сделать это без этого аддона в ручную.


Для того, чтобы создать HDR скайбокс, нужно иметь отдельные файлы .exr или .hdr для каждой стороны скайбокса, которые будут преобразован в .pfm, а затем уже в .vtf.

Чтобы из панорамы сделать отдельные текстуры, нужно каждую из них отрендерить с текстуры шара. Для этого удобнее всего использовать blender.

Имя Поворот (x y z)
ft 90 0 90
lf 90 0 0
bk 90 0 -90
up 180 0 180
rt 90 0 -180
dn 0 0 -180
  1. Создайте новую сцену и удалите все объекты.
  2. Создайте шар и установите количество сегментов с 32, на 64.
  3. Создайте камеру в центре сцены. В её настройках измените тип на перспективный, установите фокусное расстояние 64мм и конец на 100000, подгонку сенсора на горизонтальное и там же ширину на 128. Скопируйте эту камеру ещё 5 раз. В итоге у вас должно получиться 6 одинаковых камер, находящихся в центре сцены. Каждая из камер будет рендерить за свою текстуру определённой грани скайбокса.
  4. Для каждой из камер задайте поворот из таблицы. При рендере каждой текстуры их нужно будет назвать особым именем, так что рекомендуется переименовать камеры, чтобы не запутаться.


Теперь нужно подготовить рендер для каждой камеры.

  1. На временной шкале сделайте начальный кадр №1, а конечный кадр №7.
  2. Перетащите курсор воспроизведения на первый кадр.
  3. Выберете камеру и нажмите ctrl+b с курсором мыши на временной шкале.
  4. Перетащите курсор воспроизведения на второй кадр.
  5. Выберете другую камеру и нажмите ctrl+b с курсором мыши на временной шкале.

Сделайте так со всеми камерами.


Отлично! Теперь нужно подготовить панораму.

  1. Перейдите в окно shading и создайте новый материал и нанесите его на сферу.
  2. Удалите все ноды кроме вывода материала.
  3. Добавьте нод "Излучение" ("Emission") и подключите вывод этого нода к "Поверхности" вывода материала. Этот нод отвечает за яркость скайбокса.
  4. Добавьте нод "Изображение-текстура" и подключите вывод цвета к вводу цвета нода "Излучение".
  5. Загрузите .exr или .hdr панораму в ноде "Изображение-текстура".


Теперь пришло время рендерить текстуры. Убедитесь что в выводе у вас стоит формат файла "Open EXR" с параметром RGB, а в поле "Постобработка" убрана галочка с поля "Видеоредактор" ("Sequencer").

Теперь можно перетаскивать курсор воспроизведения на кадр с камерой и рендерить каждую грань скайбокса с помощью кнопки F12. Каждый файл .exr нужно назвать по следующему шаблону:

  • <имя_неба>_hdr<сторона>.exr

Например для камеры ft и названием скайбокса skyday01 будет соответствовать файл skyday01_hdrft.exr.

По итогу у вас должно быть 6 файлов разных сторон кубмапа:

  • <имя_неба>_hdrft.exr
  • <имя_неба>_hdrlf.exr
  • <имя_неба>_hdrbk.exr
  • <имя_неба>_hdrup.exr
  • <имя_неба>_hdrrt.exr
  • <имя_неба>_hdrdn.exr

Создание PFM

Создание правильных PFM с помощью Photoshop

Creating HDR PFMs is very easy, but the way of doing this is not stated anywhere:

  1. Obtain a common format HDR file, like .hdr or .exr (the most popular one). It could have any bit-depth you like: both 16 and 32 bit should work fine.
  2. Import it to Photoshop (Adobe sRGB 1998 or Rec.709 should work fine) and make sure that the Photoshop file is set to 32/16 bit-depth (Image --> Mode --> 32 Bits/Channel OR 16 Bits/Channel).
  3. Go to File --> Save As...* or Press Ctrl+⇧ Shift+S (or Alt+Ctrl+S).
  4. From the dropdown of available formats choose "Portable Bit Map", change the .pbm in the file name to .pfm and click "Save" . You now have a proper .pfm file for further use with VTEX.
Warning.pngПредупреждение: There's a thing called "Endianess" or "Byte order", for VTEX to properly convert your 16/32 bit HDR files it has to be set to little endian, not big endian. (This doesn't seem to apply to 8 bit non-hdr files, like .png, .jpg, .tga and so on).
Tip.pngСовет: To set the endianness when converting using ImageMagick, use the -endian LSB parameter.
Use this command for converting endianness: magick -endian LSB -read "C:\Program Files (x86)\Steam\steamapps\common\Half-Life 2\hl2\materialsrc\skybox\sky_day02_04_hdrup.pfm" -trim "C:\Program Files (x86)\Steam\steamapps\common\Half-Life 2\hl2\materialsrc\skybox\sky_day02_04_hdrup_LSB.pfm". -read is the input file, -trim is the output file.
Note.pngПримечание: * - On newer version of Adobe Photoshop (since 2021), you need to click "Save a Copy..." instead. However you can change the "Save As..." behavior back to previous version of Photoshop by going to Preferences > File Handling > check "Enable legacy "Save As"".
Tip.pngСовет:
Половина всего изображения
Поскольку нижнюю половину Skybox практически не видно, разумно отрезать "ненужную" часть. Для этого скомпилируйте стороны VTF с особой командой:
clamps 1
clampt 1

И добавьте её в материалы:

$basetexturetransform "center 0 0 scale 1 2 rotate 0 translate 0 0"

Поподробнее об использовании команд можно прочитать ниже, в подпункте Создание материалов.

Additionally, an unseen bottom skybox face can be made a single color and a small resolution, such as 4x4.

Небо с различной экспозицией

Перед созданием HDR-Skybox Вы должны запомнить, что небо выглядит в разных экспозициях:

Фотографии неба с различной экспозицией.

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

Создание основной текстуры неба

Первое, что Вы должны сделать - создать базовый куб Skybox, таким же образом, как и для LDR текстуры неба. Смотрите Небосвод (двумерный)(en)

Расположите подготовленные изображения в один большой файл, как показано ниже. Этот шаг необходим только, если используете инструмент splitskybox(en). Если это не так, то можете обрабатывать каждую текстуру отдельно.

Рекомендованное расположение Skybox (стороны помечены)

Сохраните это изображение в формате .TGA. Если появится окно с запросом, то отключите RLE-сжатие и поместите оригинал в нижний левый угол.

Tip.pngСовет: If you have a panoramic HDRI sky images (or if you want to backport Source 2 sky textures to Source 1), you can use HDRI to Cubemap to turn them into skybox cube, then use Photoshop to rearrange them like the image above.

Добавление HDR-данных

Теперь мы будем рисовать солнце на нашем Skybox, которое будет себя вести так же, как на фотографиях выше. Для этого есть хороший инструмент - HDR Shop

Note.pngПримечание: При открытии вашего TGA-Файла в HDR Shop Вы увидите диалоговое окно с ползунком. Поэкспериментируйте с ним, но лучше оставить все как есть.

Hdrshop curvedialog.png

The skybox after the response curve has been adjusted in HDR Shop. Click to enlarge.

HDR Shop работает так: берет файлы из редакторов изображений(en) для разнообразных экспозиций, чтобы затем их объединить в 32-битный формат с плавающей точкой. Вы можете регулировать изменения с помощью клавиш + и - на клавиатуре, или из меню View -> Exposure (Вид -> Экспозиция). Значение отображается в правом нижнем углу экрана, +0.00 stops indicates the base exposure level that was imported into HDR Shop. Adjust the exposure level so it reads -3.00 stops. По достижении необходимой экспозиции, выберите File -> Edit in image editor (Файл -> Изменить в редакторе изображений). Вы сможете редактировать изображение. HDR Shop откроет его в стандартном редакторе изображений для BMP-файлов, но можно использовать любой инструмент, который сохранит в правильном 24-битном формате HDRShopTEMP.bmp. Now paint the sun into this file.

When finished save the image and return to HDR Shop.

After clicking OK in this dialog, the current exposure level will be updated with the image that was just painted with the image-editing program.

Hdrshop OKdialog.png

Hdrshop saveas.png

Try adjusting the exposure up and down in HDR Shop with the + and - keys and you'll see that the sun is now integrated into the other exposures. Continue editing the different exposures until the desired result is achieved. It will be a good idea to spend some time emulating the blown-out effects around the sun and the highlights on the clouds as seen in the photographic reference.

Когда закончите, нажмите OK в диалоговом окне HDR Shop и выберите File -> Save as…, выберите формат Portable Floatmap (.PFM). Назовите и сохраните этот PFM-Файл в ту же директорию ресурсов materialsrc как и исходное изображение 2D Skybox (например, steamapps\common\Day of Defeat Source\dod\materialsrc\skybox).

Note.pngПримечание: After saving, if you open this .pfm in Photoshop or any image editor, you will noticed that the image is vertically flipped, this is normal. As soon you compile those .pfm files in VTEX, VTEX would flip the image back to where it was and compile it into a .vtf file.
Note.pngПримечание: Более подробный урок находится на сайте HDR Shop.

sdk_sky_exampleup

sdk_sky_exampleup

Используем для этого файл sourcesdk_content\dod\materialsrc\skybox\sdk_sky_exampleup.tga. Откройте его и установите экспозицию на шаг -3, затем отредактируйте изображение. Начнем рисовать солнце.

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

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

Деление Skybox

If you created your skyboxes in a single file as in the above image, you will need to use splitskybox.exe to split it into six. Just drag the PFM onto it.

Note.pngПримечание: splitskybox(en) Ep1 does not currently function. However, the OB version will work with either version of the engine.
Note.pngПримечание: In Left 4 Dead 2 Left 4 Dead 2, Splitskybox is not a required step. And in fact will not work without lots of retyping of suffixes of multiple files. Left 4 Dead 2's iteration of VTEX(en) is able to take your "T" image array (both tga into LDR and pfm into HDR) and process it directly into the proper <name_bk>vtf format. In order to do this, create your "T" array as above. Recommended simply for the sake of sanity to get proper orientation for the top (and bottom if needed) images in your custom skybox. Create your txt file as normal and drag it onto Left 4 Dead 2's Vtex. Create materials and use in game as normal. A caveat here is, although the vtf files are compiled properly for LDR, if you are opting out of an HDR skybox and plan to use a LDR skybox only, the supplied LDR material template in the Skybox (2D)(en) tutorial does not work. You will get the checkerboard pattern. If you are trying to import an HDR skybox (meaning, if you rendered out a set of skybox textures in your external software, and then used HDRShop to create the hdr data) of a night sky, you will experience extreme banding in the darker areas which resemble dx compression. This banding is actually a result of the way HDRShop handles color information and can be observed directly in HDRShop if you adjust down the exposure and inspect your image.

Создание материалов

At this stage you should have six files:

  • <имя_неба>_hdrft.pfm
  • <имя_неба>_hdrlf.pfm
  • <имя_неба>_hdrbk.pfm
  • <имя_неба>_hdrrt.pfm
  • <имя_неба>_hdrup.pfm
  • <имя_неба>_hdrdn.pfm

Make sure they are under your_mod\materialsrc\skybox\. You now need to create six corresponding TXT files (e.g. <имя_неба>_hdrft.txt) alongside them, in order to compile to VTF. Each must contain:

pfm 1 // tells vtex to load a a .pfm file instead of a .tga file
pfmscale 1 // brightness multiplier
nonice 1 // prevent seams appearing at low texture detail
skybox 1 // alternative to nonice, if NICE filtering is desired
nocompress 1 // optional; removing halves file size, but causes color banding under close inspection

Drag these text files onto VTEX and it will compile them (unfortunately VTFEdit(en) doesn't import PFMs, nor properly handle other formats when HDR). The VTFs will appear in the corresponding materials subfolder (e.g., your_mod\materials\skybox\).

Note.pngПримечание: When compile those .pfm files in VTEX, VTEX would flip the image vertically and compile it into a .vtf file. If you are using HDR Shop (which would first flip the image vertically after saving), you don't need to reflip the image, as VTEX would do that automatically. However, if you skip HDR Shop and using a panoramic image converted from HDRI to Cubemap format, you will need to flip each image vertically first using Photoshop (or any image editors) before compiling with VTEX.

Now you just need to create six VMTs named <имя_неба>_hdr<сторона>.vmt. These should read:

Sky
{
	// if you compiled with nocompress:
	$hdrbasetexture		"skybox/sdk_sky_example_hdrft"

	// if you didn't:
	$hdrcompressedtexture	"skybox/sdk_sky_example_hdrft"

	// LDR fallback
	$basetexture		"skybox/sdk_sky_exampleft"
}
Icon-Bug.pngБаг:If an $hdrbasetexture or an $hdrcompressedtexture is not specified, the skybox will appear as missing texture with HDR enabled. If you don't have an HDR version of the skybox you can use the LDR version as a $hdrbasetexture.

Creating LDR Fallbacks

Tip.pngСовет: (Во всех играх начиная с Left 4 Dead 2) LDR fallbacks aren't necessary for games that are normally HDR-only.

You must also create standard dynamic range VTFs (LDR fallbacks) for users who do not play in HDR. Compile with these settings:

nonice 1
dxt5 1 // or nocompress
Уточнить: Why is DXT5 necessary? Skyboxes aren't translucent, so shouldn't DXT1 be sufficient? The LDR skyboxes in Half-Life: Source are BGR888, with no alpha channel. The "hint DXT5" flag may be sufficient, if that even does anything.

These are ordinary textures, so you can use VTFEdit(en) if you prefer. There is no need to create new materials for LDR users; they will load the _hdr ones.

Дополнительные замечания о создании

Icon-Important.pngВажно: To avoid seams appearing at the edges of skies, open the resulting VTFs in VTFEdit VTFEdit, then add the Clamp S + Clamp T flags and/or the "no mipmaps" flag. For compressed LDR skyboxes, use the "hint DXT5" flag.
Tip.pngСовет: If an LDR fallback is present, the HDR skybox is compressed, and mipmaps are disabled, then open the compressed HDR skybox in VTFEdit, export as TGA, and reimport the exported images back into VTFEdit with mipmaps disabled. This will remove mipmaps from the file, saving a significant amount of space.
Note.pngПримечание: This does not work properly for uncompressed HDR, as VTFLib doesn't properly handle import and export of HDR formats. Additionally, mipmaps should be left in the LDR fallback, so that the skybox materials display correctly in Hammer's texture browser.

Использование

In Hammer Hammer 4.x, go to Main Menu > Map > Map Properties > Skybox Texture Name and type the name of your skybox, relative to materials\skybox\ and without any of the face suffixes. (e.g., mysky_hdr if the VMTs are materials\skybox\mysky_hdrXX.vmt.)

If there is an underscore before the face names, then these must be included as well (ex: mysky_hdr_ if the VMTs are materials\skybox\mysky_hdr_XX.vmt.)

Note.pngПримечание: Skybox selection is based on the VMT names, not the VTF names. Multiple faces of the same skybox can share a VTF, provided they have separate VMTs, and multiple skyboxes can use the same VTFs.
Icon-Bug.pngБаг:Skyboxes may fail to load if placed in a subfolder of materials\skybox\; use a prefix if organization is necessary.


Смотреть также

Внешние ссылки

  • [1] - Аддон для blender для удобного создания hdr скайбокса
  • HDRI to Skybox - Converts panoramic HDRI images to source engine ready skybox textures.
  • HDRI to Cubemap - converts panoramic HDRI images to skybox cubes.

Тематический указатель