Debian Codegraph @

tools/cmgen/src/cmgen.cpp

raw
1 /*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "ProgressUpdater.h"
18
19 #include <ibl/Cubemap.h>
20 #include <ibl/CubemapIBL.h>
21 #include <ibl/CubemapSH.h>
22 #include <ibl/CubemapUtils.h>
23 #include <ibl/Image.h>
24 #include <ibl/utilities.h>
25
26 #ifdef IMAGEIO_SUPPORTS_BLOCK_COMPRESSION
27 #include <imageio/BlockCompression.h>
28 #endif
29
30 #include <imageio/ImageDecoder.h>
31 #include <imageio/ImageEncoder.h>
32
33 #include <image/KtxBundle.h>
34 #include <image/ColorTransform.h>
35
36 #include <utils/JobSystem.h>
37 #include <utils/Path.h>
38 #include <utils/algorithm.h>
39
40 #include <math/scalar.h>
41 #include <math/vec4.h>
42
43 #include <cmath>
44 #include <fstream>
45 #include <iomanip>
46 #include <iostream>
47 #include <sstream>
48
49 #include <string.h>
50
51 #include <getopt/getopt.h>
52
53
54 using namespace filament::math;
55 using namespace filament::ibl;
56 using namespace image;
57
58 // -----------------------------------------------------------------------------------------------
59
60 enum class ShFile {
61 SH_NONE, SH_FILE, SH_TEXT
62 };
63
64 static const size_t DFG_LUT_DEFAULT_SIZE = 128;
65 static const size_t IBL_DEFAULT_SIZE = 256;
66 static const size_t IBL_DEFAULT_MIN_LOD_SIZE = 16;
67
68 enum class OutputType {
69 FACES, KTX, EQUIRECT, OCTAHEDRON
70 };
71
72 static image::ImageEncoder::Format g_format = image::ImageEncoder::Format::PNG;
73 static OutputType g_type = OutputType::FACES;
74 static std::string g_compression;
75 static bool g_extract_faces = false;
76 static float g_extract_blur = 0.0;
77 static utils::Path g_extract_dir;
78
79 static size_t g_output_size = 0;
80 static size_t g_min_lod_size = 0;
81
82 static bool g_quiet = false;
83 static bool g_debug = false;
84
85 static size_t g_sh_compute = 0;
86 static bool g_sh_output = false;
87 static bool g_sh_shader = false;
88 static bool g_sh_irradiance = false;
89 static float g_sh_window = 0.0f; // <0 none, 0=auto, or cutoff
90 static bool g_noclamp = true;
91 static ShFile g_sh_file = ShFile::SH_NONE;
92 static utils::Path g_sh_filename;
93 static std::unique_ptr<filament::math::float3[]> g_sh_coefficients;
94
95 static bool g_is_mipmap = false;
96 static utils::Path g_is_mipmap_dir;
97 static bool g_prefilter = false;
98 static utils::Path g_prefilter_dir;
99 static bool g_dfg = false;
100 static utils::Path g_dfg_filename;
101 static bool g_dfg_multiscatter = false;
102 static bool g_dfg_cloth = false;
103
104 static bool g_ibl_irradiance = false;
105 static bool g_ibl_no_prefilter = false;
106 static utils::Path g_ibl_irradiance_dir;
107
108 static bool g_deploy = false;
109 static utils::Path g_deploy_dir;
110
111 static size_t g_num_samples = 1024;
112
113 static bool g_mirror = false;
114
115 // -----------------------------------------------------------------------------------------------
116
117 static void generateMipmaps(utils::JobSystem& js, std::vector<Cubemap>& levels,
118 std::vector<Image>& images);
119 static void sphericalHarmonics(utils::JobSystem& js, const utils::Path& iname,
120 const Cubemap& inputCubemap);
121 static void iblRoughnessPrefilter(
122 utils::JobSystem& js, const utils::Path& iname, const std::vector<Cubemap>& levels,
123 bool prefilter, const utils::Path& dir);
124 static void iblDiffuseIrradiance(utils::JobSystem& js, const utils::Path& iname,
125 const std::vector<Cubemap>& levels, const utils::Path& dir);
126 static void iblMipmapPrefilter(utils::JobSystem& js, const utils::Path& iname,
127 const std::vector<Image>& images, const std::vector<Cubemap>& levels,
128 const utils::Path& dir);
129 static void iblLutDfg(utils::JobSystem& js, const utils::Path& filename, size_t size,
130 bool multiscatter,
131 bool cloth);
132 static void extractCubemapFaces(utils::JobSystem& js, const utils::Path& iname, const Cubemap& cm,
133 const utils::Path& dir);
134 static void outputSh(std::ostream& out, const std::unique_ptr<filament::math::float3[]>& sh, size_t numBands);
135 static void UTILS_UNUSED outputSpectrum(std::ostream& out,
136 const std::unique_ptr<filament::math::float3[]>& sh, size_t numBands);
137 static void saveImage(const std::string& path, ImageEncoder::Format format, const Image& image,
138 const std::string& compression);
139 static LinearImage toLinearImage(const Image& image);
140 static void exportKtxFaces(KtxBundle& container, uint32_t miplevel, const Cubemap& cm);
141
142 // -----------------------------------------------------------------------------------------------
143
144 static void printUsage(char* name) {
145 std::string exec_name(utils::Path(name).getName());
146 std::string usage(
147 "CMGEN is a command-line tool for generating SH and mipmap levels from an env map.\n"
148 "Cubemaps and equirectangular formats are both supported, automatically detected \n"
149 "according to the aspect ratio of the source image.\n"
150 "\n"
151 "Usages:\n"
152 " CMGEN [options] <input-file>\n"
153 " CMGEN [options] <uv[N]>\n"
154 "\n"
155 "Supported input formats:\n"
156 " PNG, 8 and 16 bits\n"
157 " Radiance (.hdr)\n"
158 " Photoshop (.psd), 16 and 32 bits\n"
159 " OpenEXR (.exr)\n"
160 "\n"
161 "Options:\n"
162 " --help, -h\n"
163 " Print this message\n\n"
164 " --license\n"
165 " Print copyright and license information\n\n"
166 " --quiet, -q\n"
167 " Quiet mode. Suppress all non-error output\n\n"
168 " --type=[cubemap|equirect|octahedron|ktx], -t [cubemap|equirect|octahedron|ktx]\n"
169 " Specify output type (default: cubemap)\n\n"
170 " --format=[exr|hdr|psd|rgbm|rgb32f|png|dds|ktx], -f [exr|hdr|psd|rgbm|rgb32f|png|dds|ktx]\n"
171 " Specify output file format. ktx implies -type=ktx.\n"
172 " KTX files are always encoded with 3-channel RGB_10_11_11_REV data\n\n"
173 " --compression=COMPRESSION, -c COMPRESSION\n"
174 " Format specific compression:\n"
175 #ifdef IMAGEIO_SUPPORTS_BLOCK_COMPRESSION
176 " KTX:\n"
177 " astc_[fast|thorough]_[ldr|hdr]_WxH, where WxH is a valid block size\n"
178 " s3tc_rgba_dxt5\n"
179 " etc_FORMAT_METRIC_EFFORT\n"
180 " FORMAT is rgb8_alpha, srgb8_alpha, rgba8, or srgb8_alpha8\n"
181 " METRIC is rgba, rgbx, rec709, numeric, or normalxyz\n"
182 " EFFORT is an integer between 0 and 100\n"
183 #endif
184 " PNG: Ignored\n"
185 " PNG RGBM: Ignored\n"
186 " Radiance: Ignored\n"
187 " Photoshop: 16 (default), 32\n"
188 " OpenEXR: RAW, RLE, ZIPS, ZIP, PIZ (default)\n"
189 " DDS: 8, 16 (default), 32\n\n"
190 " --size=power-of-two, -s power-of-two\n"
191 " Size of the output cubemaps (base level), 256 by default\n"
192 " Also applies to DFG LUT\n\n"
193 " --deploy=dir, -x dir\n"
194 " Generate everything needed for deployment into <dir>\n\n"
195 " --extract=dir\n"
196 " Extract faces of the cubemap into <dir>\n\n"
197 " --extract-blur=roughness\n"
198 " Blurs the cubemap before saving the faces using the roughness blur\n\n"
199 " --clamp\n"
200 " Clamp environment before processing\n\n"
201 " --no-mirror\n"
202 " Skip mirroring of generated cubemaps (for assets with mirroring already backed in)\n\n"
203 " --ibl-samples=numSamples\n"
204 " Number of samples to use for IBL integrations (default 1024)\n\n"
205 " --ibl-ld=dir\n"
206 " Roughness pre-filter into <dir>\n\n"
207 " --sh-shader\n"
208 " Generate irradiance SH for shader code\n\n"
209 "\n"
210 "Private use only:\n"
211 " --ibl-dfg=filename.[exr|hdr|psd|png|rgbm|rgb32f|dds|h|hpp|c|cpp|inc|txt]\n"
212 " Compute the IBL DFG LUT\n\n"
213 " --ibl-dfg-multiscatter\n"
214 " If --ibl-dfg is set, computes the DFG for multi-scattering GGX\n\n"
215 " --ibl-dfg-cloth\n"
216 " If --ibl-dfg is set, adds a 3rd channel to the DFG for cloth shading\n\n"
217 " --ibl-is-mipmap=dir\n"
218 " Generate mipmap for pre-filtered importance sampling\n\n"
219 " --ibl-irradiance=dir\n"
220 " Diffuse irradiance into <dir>\n\n"
221 " --ibl-no-prefilter\n"
222 " Use importance sampling instead of prefiltered importance sampling\n\n"
223 " --ibl-min-lod-size\n"
224 " Minimum LOD size [default: 16]\n\n"
225 " --sh=bands\n"
226 " SH decomposition of input cubemap\n\n"
227 " --sh-output=filename.[exr|hdr|psd|rgbm|rgb32f|png|dds|txt]\n"
228 " SH output format. The filename extension determines the output format\n\n"
229 " --sh-irradiance, -i\n"
230 " Irradiance SH coefficients\n\n"
231 " --sh-window=cutoff|no|auto (default), -w cutoff|no|auto (default)\n"
232 " SH windowing to reduce ringing\n\n"
233 " --debug, -d\n"
234 " Generate extra data for debugging\n\n"
235 );
236 const std::string from("CMGEN");
237 for (size_t pos = usage.find(from); pos != std::string::npos; pos = usage.find(from, pos)) {
238 usage.replace(pos, from.length(), exec_name);
239 }
240 printf("%s", usage.c_str());
241 }
242
243 static void license() {
244 static const char *license[] = {
245 #include "licenses/licenses.inc"
246 nullptr
247 };
248
249 const char **p = &license[0];
250 while (*p)
251 std::cout << *p++ << std::endl;
252 }
253
254 static int handleCommandLineArgments(int argc, char* argv[]) {
255 static constexpr const char* OPTSTR = "hqidt:f:c:s:x:w:S:";
256 static const struct option OPTIONS[] = {
257 { "help", no_argument, nullptr, 'h' },
258 { "license", no_argument, nullptr, 'l' },
259 { "quiet", no_argument, nullptr, 'q' },
260 { "type", required_argument, nullptr, 't' },
261 { "format", required_argument, nullptr, 'f' },
262 { "compression", required_argument, nullptr, 'c' },
263 { "size", required_argument, nullptr, 's' },
264 { "extract", required_argument, nullptr, 'e' },
265 { "extract-blur", required_argument, nullptr, 'r' },
266 { "sh", optional_argument, nullptr, 'z' },
267 { "sh-output", required_argument, nullptr, 'o' },
268 { "sh-irradiance", no_argument, nullptr, 'i' },
269 { "sh-shader", no_argument, nullptr, 'b' },
270 { "sh-window", required_argument, nullptr, 'w' },
271 { "clamp", no_argument, nullptr, 'K' },
272 { "ibl-is-mipmap", required_argument, nullptr, 'y' },
273 { "ibl-ld", required_argument, nullptr, 'p' },
274 { "ibl-irradiance", required_argument, nullptr, 'P' },
275 { "ibl-dfg", required_argument, nullptr, 'a' },
276 { "ibl-dfg-multiscatter", no_argument, nullptr, 'u' },
277 { "ibl-dfg-cloth", no_argument, nullptr, 'C' },
278 { "ibl-no-prefilter", no_argument, nullptr, 'n' },
279 { "ibl-min-lod-size", required_argument, nullptr, 'S' },
280 { "ibl-samples", required_argument, nullptr, 'k' },
281 { "deploy", required_argument, nullptr, 'x' },
282 { "no-mirror", no_argument, nullptr, 'm' },
283 { "debug", no_argument, nullptr, 'd' },
284 { nullptr, 0, nullptr, 0 } // termination of the option list
285 };
286 int opt;
287 int option_index = 0;
288 int num_sh_bands = 3;
289 bool format_specified = false;
290 bool type_specified = false;
291 bool ktx_format_requested = false;
292 while ((opt = getopt_long(argc, argv, OPTSTR, OPTIONS, &option_index)) >= 0) {
293 std::string arg(optarg ? optarg : "");
294 switch (opt) {
295 default:
296 case 'h':
297 printUsage(argv[0]);
298 exit(0);
299 break; // NOLINT
300 case 'l':
301 license();
302 exit(0);
303 break; // NOLINT
304 case 'q':
305 g_quiet = true;
306 break;
307 case 't':
308 if (arg == "cubemap") {
309 g_type = OutputType::FACES;
310 type_specified = true;
311 }
312 if (arg == "ktx") {
313 g_type = OutputType::KTX;
314 type_specified = true;
315 }
316 if ((arg == "equirect") || (arg == "equirectangular")) {
317 g_type = OutputType::EQUIRECT;
318 type_specified = true;
319 }
320 if (arg == "octahedron") {
321 g_type = OutputType::OCTAHEDRON;
322 type_specified = true;
323 }
324 break;
325 case 'f':
326 if (arg == "png") {
327 g_format = ImageEncoder::Format::PNG;
328 format_specified = true;
329 }
330 if (arg == "hdr") {
331 g_format = ImageEncoder::Format::HDR;
332 format_specified = true;
333 }
334 if (arg == "rgbm") {
335 g_format = ImageEncoder::Format::RGBM;
336 format_specified = true;
337 }
338 if (arg == "rgb32f") {
339 g_format = ImageEncoder::Format::RGB_10_11_11_REV;
340 format_specified = true;
341 }
342 if (arg == "exr") {
343 g_format = ImageEncoder::Format::EXR;
344 format_specified = true;
345 }
346 if (arg == "psd") {
347 g_format = ImageEncoder::Format::PSD;
348 format_specified = true;
349 }
350 if (arg == "dds") {
351 g_format = ImageEncoder::Format::DDS_LINEAR;
352 format_specified = true;
353 }
354 if (arg == "ktx") {
355 ktx_format_requested = true;
356 format_specified = true;
357 }
358 break;
359 case 'c':
360 g_compression = arg;
361 break;
362 case 's':
363 g_output_size = std::stoul(arg);
364 if (!isPOT(g_output_size)) {
365 std::cerr << "output size must be a power of two" << std::endl;
366 exit(0);
367 }
368 break;
369 case 'S':
370 g_min_lod_size = std::stoul(arg);
371 if (!isPOT(g_min_lod_size)) {
372 std::cerr << "min LOD size must be a power of two" << std::endl;
373 exit(0);
374 }
375 break;
376 case 'z':
377 g_sh_compute = 1;
378 g_sh_output = true;
379 try {
380 num_sh_bands = std::stoi(arg);
381 } catch (std::invalid_argument &e) {
382 // keep default value
383 }
384 break;
385 case 'o':
386 g_sh_compute = 1;
387 g_sh_output = true;
388 g_sh_file = ShFile::SH_FILE;
389 g_sh_filename = arg;
390 if (g_sh_filename.getExtension() == "txt") {
391 g_sh_file = ShFile::SH_TEXT;
392 }
393 break;
394 case 'w':
395 if (arg == "auto") { g_sh_window = 0.0f; }
396 else if (arg == "no") { g_sh_window = -1.0f; }
397 else { g_sh_window = std::stof(arg); }
398 break;
399 case 'K':
400 g_noclamp = false;
401 break;
402 case 'i':
403 g_sh_compute = 1;
404 g_sh_irradiance = true;
405 break;
406 case 'b':
407 g_sh_compute = 1;
408 g_sh_irradiance = true;
409 g_sh_shader = true;
410 break;
411 case 'e':
412 g_extract_dir = arg;
413 g_extract_faces = true;
414 break;
415 case 'r':
416 g_extract_blur = std::stod(arg);
417 if (g_extract_blur < 0 || g_extract_blur > 1) {
418 std::cerr << "roughness (blur) parameter must be between 0.0 and 1.0" <<
419 std::endl;
420 exit(0);
421 }
422 break;
423 case 'y':
424 g_is_mipmap = true;
425 g_is_mipmap_dir = arg;
426 break;
427 case 'p':
428 g_prefilter = true;
429 g_prefilter_dir = arg;
430 break;
431 case 'P':
432 g_ibl_irradiance = true;
433 g_ibl_irradiance_dir = arg;
434 break;
435 case 'n':
436 g_ibl_no_prefilter = true;
437 break;
438 case 'a':
439 g_dfg = true;
440 g_dfg_filename = arg;
441 break;
442 case 'u':
443 g_dfg_multiscatter = true;
444 break;
445 case 'C':
446 g_dfg_cloth = true;
447 break;
448 case 'k':
449 g_num_samples = (size_t)std::stoi(arg);
450 break;
451 case 'x':
452 g_deploy = true;
453 g_deploy_dir = arg;
454 break;
455 case 'd':
456 g_debug = true;
457 break;
458 case 'm':
459 g_mirror = true;
460 break;
461 }
462 }
463
464 if (ktx_format_requested) {
465 g_type = OutputType::KTX;
466 type_specified = true;
467 }
468
469 if (g_deploy && !type_specified) {
470 g_type = OutputType::FACES;
471 }
472
473 if (g_deploy && !format_specified) {
474 g_format = ImageEncoder::Format::RGB_10_11_11_REV;
475 }
476
477 if (num_sh_bands && g_sh_compute) {
478 g_sh_compute = (size_t) num_sh_bands;
479 }
480 return optind;
481 }
482
483 int main(int argc, char* argv[]) {
484 utils::JobSystem js;
485 js.adopt();
486
487 int option_index = handleCommandLineArgments(argc, argv);
488 int num_args = argc - option_index;
489 if (!g_dfg && num_args < 1) {
490 printUsage(argv[0]);
491 return 1;
492 }
493
494 if (g_dfg) {
495 if (!g_quiet) {
496 std::cout << "Generating IBL DFG LUT..." << std::endl;
497 }
498 size_t size = g_output_size ? g_output_size : DFG_LUT_DEFAULT_SIZE;
499 iblLutDfg(js, g_dfg_filename, size, g_dfg_multiscatter, g_dfg_cloth);
500 if (num_args < 1) return 0;
501 }
502
503 std::string command(argv[option_index]);
504 utils::Path iname(command);
505
506 if (g_deploy) {
507 utils::Path sh_dir = g_deploy_dir;
508
509 // KTX files are self-contained and do not need to live in a subfolder.
510 if (g_type != OutputType::KTX) {
511 sh_dir += iname.getNameWithoutExtension();
512 }
513
514 // generate pre-scaled irradiance sh to text file
515 g_sh_compute = 3;
516 g_sh_shader = true;
517 g_sh_irradiance = true;
518 g_sh_filename = sh_dir + "sh.txt";
519 g_sh_file = ShFile::SH_TEXT;
520 g_sh_output = true;
521
522 // faces
523 g_extract_dir = g_deploy_dir;
524 g_extract_faces = true;
525
526 // prefilter
527 g_prefilter = true;
528 g_prefilter_dir = g_deploy_dir;
529 }
530
531 // Images store the actual data
532 std::vector<Image> images;
533
534 // Cubemaps are just views on Images
535 std::vector<Cubemap> levels;
536
537 if (iname.exists()) {
538 if (!g_quiet) {
539 std::cout << "Decoding image..." << std::endl;
540 }
541 std::ifstream input_stream(iname.getPath(), std::ios::binary);
542 LinearImage linputImage = ImageDecoder::decode(input_stream, iname.getPath());
543 if (!linputImage.isValid()) {
544 std::cerr << "Unable to open image: " << iname.getPath() << std::endl;
545 exit(1);
546 }
547 if (linputImage.getChannels() != 3) {
548 std::cerr << "Input image must be RGB (3 channels)! This image has "
549 << linputImage.getChannels() << " channels." << std::endl;
550 exit(1);
551 }
552
553 // Convert from LinearImage to the deprecated Image object which is used throughout cmgen.
554 const size_t width = linputImage.getWidth(), height = linputImage.getHeight();
555 Image inputImage(width, height);
556 memcpy(inputImage.getData(), linputImage.getPixelRef(), height * inputImage.getBytesPerRow());
557
558 if (!g_noclamp) {
559 CubemapUtils::clamp(inputImage);
560 }
561
562 if ((isPOT(width) && (width * 3 == height * 4)) ||
563 (isPOT(height) && (height * 3 == width * 4))) {
564 // This is cross cubemap
565 size_t dim = g_output_size ? g_output_size : IBL_DEFAULT_SIZE;
566 if (!g_quiet) {
567 std::cout << "Loading cross... " << std::endl;
568 }
569
570 Image temp;
571 Cubemap cml = CubemapUtils::create(temp, dim);
572 CubemapUtils::crossToCubemap(js, cml, inputImage);
573 images.push_back(std::move(temp));
574 levels.push_back(std::move(cml));
575 } else if (width == 2 * height) {
576 // we assume a spherical (equirectangular) image, which we will convert to a cross image
577 size_t dim = g_output_size ? g_output_size : IBL_DEFAULT_SIZE;
578 if (!g_quiet) {
579 std::cout << "Converting equirectangular image... " << std::endl;
580 }
581 Image temp;
582 Cubemap cml = CubemapUtils::create(temp, dim);
583 CubemapUtils::equirectangularToCubemap(js, cml, inputImage);
584 images.push_back(std::move(temp));
585 levels.push_back(std::move(cml));
586 } else {
587 std::cerr << "Aspect ratio not supported: " << width << "x" << height << std::endl;
588 std::cerr << "Supported aspect ratios:" << std::endl;
589 std::cerr << " 2:1, lat/long or equirectangular" << std::endl;
590 std::cerr << " 3:4, vertical cross (height must be power of two)" << std::endl;
591 std::cerr << " 4:3, horizontal cross (width must be power of two)" << std::endl;
592 exit(0);
593 }
594 } else {
595 if (!g_quiet) {
596 std::cout << iname << " does not exist; generating UV grid..." << std::endl;
597 }
598
599 size_t dim = g_output_size ? g_output_size : IBL_DEFAULT_SIZE;
600 Image temp;
601 Cubemap cml = CubemapUtils::create(temp, dim);
602
603 unsigned int p = 0;
604 std::string name = iname.getNameWithoutExtension();
605 if (sscanf(name.c_str(), "uv%u", &p) == 1) { // NOLINT
606 CubemapUtils::generateUVGrid(js, cml, p, p);
607 } else if (sscanf(name.c_str(), "u%u", &p) == 1) { // NOLINT
608 CubemapUtils::generateUVGrid(js, cml, p, 1);
609 } else if (sscanf(name.c_str(), "v%u", &p) == 1) { // NOLINT
610 CubemapUtils::generateUVGrid(js, cml, 1, p);
611 } else if (sscanf(name.c_str(), "brdf%u", &p) == 1) { // NOLINT
612 float linear_roughness = sq(p / std::log2(dim));
613 CubemapIBL::brdf(js, cml, linear_roughness);
614 } else {
615 CubemapUtils::generateUVGrid(js, cml, 1, 1);
616 }
617
618 images.push_back(std::move(temp));
619 levels.push_back(std::move(cml));
620 }
621
622 // we mirror by default -- the mirror option in fact un-mirrors.
623 g_mirror = !g_mirror;
624 if (g_mirror) {
625 if (!g_quiet) {
626 std::cout << "Mirroring..." << std::endl;
627 }
628 Image temp;
629 Cubemap cml = CubemapUtils::create(temp, levels[0].getDimensions());
630 CubemapUtils::mirrorCubemap(js, cml, levels[0]);
631 std::swap(levels[0], cml);
632 std::swap(images[0], temp);
633 } else {
634 if (!g_quiet) {
635 std::cout << "Skipped mirroring." << std::endl;
636 }
637 }
638
639 // make the cubemap seamless
640 levels[0].makeSeamless();
641
642 // Now generate all the mipmap levels
643 generateMipmaps(js, levels, images);
644
645 if (g_sh_compute) {
646 if (!g_quiet) {
647 std::cout << "Spherical harmonics..." << std::endl;
648 }
649 Cubemap const& cm(levels[0]);
650 sphericalHarmonics(js, iname, cm);
651 }
652
653 if (g_is_mipmap) {
654 if (!g_quiet) {
655 std::cout << "IBL mipmaps for prefiltered importance sampling..." << std::endl;
656 }
657 iblMipmapPrefilter(js, iname, images, levels, g_is_mipmap_dir);
658 }
659
660 if (g_prefilter) {
661 if (!g_quiet) {
662 std::cout << "IBL prefiltering..." << std::endl;
663 }
664 iblRoughnessPrefilter(js, iname, levels, !g_ibl_no_prefilter, g_prefilter_dir);
665 }
666
667 if (g_ibl_irradiance) {
668 if (!g_quiet) {
669 std::cout << "IBL diffuse irradiance..." << std::endl;
670 }
671 iblDiffuseIrradiance(js, iname, levels, g_ibl_irradiance_dir);
672 }
673
674 if (g_extract_faces) {
675 Cubemap const& cm(levels[0]);
676 if (g_extract_blur != 0) {
677 ProgressUpdater updater(1);
678 if (!g_quiet) {
679 std::cout << "Blurring..." << std::endl;
680 updater.start();
681 }
682 const float linear_roughness = g_extract_blur * g_extract_blur;
683 const size_t dim = g_output_size ? g_output_size : cm.getDimensions();
684 Image image;
685 Cubemap blurred = CubemapUtils::create(image, dim);
686 CubemapIBL::roughnessFilter(js, blurred, levels, linear_roughness, g_num_samples,
687 float3{ 1, 1, 1 }, !g_ibl_no_prefilter,
688 [](size_t index, float v, void* userdata) {
689 if (!g_quiet) {
690 ((ProgressUpdater*) userdata)->update(index, v);
691 }
692 }, &updater);
693 if (!g_quiet) {
694 updater.stop();
695 std::cout << "Extract faces..." << std::endl;
696 }
697 extractCubemapFaces(js, iname, blurred, g_extract_dir);
698 } else {
699 if (!g_quiet) {
700 std::cout << "Extract faces..." << std::endl;
701 }
702 extractCubemapFaces(js, iname, cm, g_extract_dir);
703 }
704 }
705
706 return 0;
707 }
708
709 void generateMipmaps(utils::JobSystem& js, std::vector<Cubemap>& levels,
710 std::vector<Image>& images) {
711 Image temp;
712 const Cubemap& base(levels[0]);
713 size_t dim = base.getDimensions();
714 size_t mipLevel = 0;
715 while (dim > 1) {
716 dim >>= 1u;
717 Cubemap dst = CubemapUtils::create(temp, dim);
718 const Cubemap& src(levels[mipLevel++]);
719 CubemapUtils::downsampleCubemapLevelBoxFilter(js, dst, src);
720 dst.makeSeamless();
721 images.push_back(std::move(temp));
722 levels.push_back(std::move(dst));
723 }
724 }
725
726 void sphericalHarmonics(utils::JobSystem& js, const utils::Path& iname, const Cubemap& inputCubemap) {
727 std::unique_ptr<filament::math::float3[]> sh;
728 if (g_sh_shader) {
729 sh = CubemapSH::computeSH(js, inputCubemap, 3, true);
730 } else {
731 sh = CubemapSH::computeSH(js, inputCubemap, g_sh_compute, g_sh_irradiance);
732 }
733
734 if (g_sh_window >= 0) {
735 CubemapSH::windowSH(sh, g_sh_compute, g_sh_window);
736 }
737
738 if (g_sh_shader) {
739 CubemapSH::preprocessSHForShader(sh);
740 }
741
742 if (!g_quiet && g_sh_output) {
743 outputSh(std::cout, sh, g_sh_compute);
744 }
745
746 if (g_sh_file != ShFile::SH_NONE || g_debug) {
747 Image image;
748 const size_t dim = g_output_size ? g_output_size : inputCubemap.getDimensions();
749 Cubemap cm = CubemapUtils::create(image, dim);
750
751 if (g_sh_file != ShFile::SH_NONE) {
752 utils::Path outputDir(g_sh_filename.getAbsolutePath().getParent());
753 if (!outputDir.exists()) {
754 outputDir.mkdirRecursive();
755 }
756
757 if (g_sh_shader) {
758 CubemapSH::renderPreScaledSH3Bands(js, cm, sh);
759 } else {
760 CubemapSH::renderSH(js, cm, sh, g_sh_compute);
761 }
762
763 cm.makeSeamless();
764
765 if (g_sh_file == ShFile::SH_FILE) {
766 Image image;
767 if (g_type == OutputType::EQUIRECT) {
768 size_t dim = cm.getDimensions();
769 image = Image(dim * 2, dim);
770 CubemapUtils::cubemapToEquirectangular(js, image, cm);
771 }
772
773 if (g_type == OutputType::OCTAHEDRON) {
774 size_t dim = cm.getDimensions();
775 image = Image(dim, dim);
776 CubemapUtils::cubemapToOctahedron(js, image, cm);
777 }
778
779 saveImage(g_sh_filename, ImageEncoder::chooseFormat(g_sh_filename.getName()),
780 image, g_compression);
781 }
782 if (g_sh_file == ShFile::SH_TEXT) {
783 std::ofstream outputStream(g_sh_filename, std::ios::trunc);
784 outputSh(outputStream, sh, g_sh_compute);
785 }
786 }
787
788 if (g_debug) {
789 utils::Path outputDir(g_sh_filename.getAbsolutePath().getParent());
790 if (!outputDir.exists()) {
791 outputDir.mkdirRecursive();
792 }
793
794 { // save a file with what we just calculated (radiance or irradiance)
795 std::string basename = iname.getNameWithoutExtension();
796 utils::Path filePath =
797 outputDir + (basename + "_sh" + (g_sh_irradiance ? "_i" : "_r") + ".hdr");
798 CubemapUtils::highlight(image);
799 saveImage(filePath, ImageEncoder::Format::HDR, image, "");
800 }
801
802 { // save a file with the "other one" (irradiance or radiance)
803 std::unique_ptr<filament::math::float3[]> sh
804 = CubemapSH::computeSH(js, inputCubemap, g_sh_compute, !g_sh_irradiance);
805 CubemapSH::renderSH(js, cm, sh, g_sh_compute);
806 std::string basename = iname.getNameWithoutExtension();
807 utils::Path filePath =
808 outputDir + (basename + "_sh" + (!g_sh_irradiance ? "_i" : "_r") + ".hdr");
809 CubemapUtils::highlight(image);
810 saveImage(filePath, ImageEncoder::Format::HDR, image, "");
811 }
812 }
813 }
814 // Stash the computed coefficients in case we need to use them at a later stage (e.g. KTX gen)
815 g_sh_coefficients = std::move(sh);
816 }
817
818 void outputSh(std::ostream& out,
819 const std::unique_ptr<filament::math::float3[]>& sh, size_t numBands) {
820 for (ssize_t l = 0; l < numBands; l++) {
821 for (ssize_t m = -l; m <= l; m++) {
822 size_t i = CubemapSH::getShIndex(m, (size_t) l);
823 std::string name = "L" + std::to_string(l) + std::to_string(m);
824 if (g_sh_irradiance) {
825 name.append(", irradiance");
826 }
827 if (g_sh_shader) {
828 name.append(", pre-scaled base");
829 }
830 out << "("
831 << std::fixed << std::setprecision(15) << std::setw(18) << sh[i].r << ", "
832 << std::fixed << std::setprecision(15) << std::setw(18) << sh[i].g << ", "
833 << std::fixed << std::setprecision(15) << std::setw(18) << sh[i].b
834 << "); // " << name
835 << std::endl;
836 }
837 }
838 }
839
840 void UTILS_UNUSED outputSpectrum(std::ostream& out,
841 const std::unique_ptr<filament::math::float3[]>& sh, size_t numBands) {
842 // We assume a symetrical function (i.e. m!=0 terms are zero)
843 for (ssize_t l = 0; l < numBands; l++) {
844 size_t i = CubemapSH::getShIndex(0, (size_t) l);
845 float L = dot(sh[i], float3{ 0.2126, 0.7152, 0.0722 });
846 out << std::fixed << std::setprecision(15) << std::setw(18) << sq(L) << std::endl;
847 }
848 }
849
850 void iblMipmapPrefilter(utils::JobSystem& js, const utils::Path& iname,
851 const std::vector<Image>& images, const std::vector<Cubemap>& levels,
852 const utils::Path& dir) {
853 utils::Path outputDir(dir.getAbsolutePath() + iname.getNameWithoutExtension());
854 if (!outputDir.exists()) {
855 outputDir.mkdirRecursive();
856 }
857
858 const size_t numLevels = levels.size();
859 for (size_t level=0 ; level<numLevels ; level++) {
860 Cubemap const& dst(levels[level]);
861 Image const& img(images[level]);
862 if (g_debug) {
863 ImageEncoder::Format debug_format = ImageEncoder::Format::HDR;
864 std::string ext = ImageEncoder::chooseExtension(debug_format);
865 std::string basename = iname.getNameWithoutExtension();
866 utils::Path filePath = outputDir + (basename + "_is_m" + (std::to_string(level) + ext));
867 saveImage(filePath, debug_format, img, g_compression);
868 }
869
870 std::string ext = ImageEncoder::chooseExtension(g_format);
871
872 if (g_type == OutputType::EQUIRECT) {
873 size_t dim = dst.getDimensions();
874 Image image(dim * 2, dim);
875 CubemapUtils::cubemapToEquirectangular(js, image, dst);
876 std::string filename = outputDir + ("is_m" + std::to_string(level) + ext);
877 saveImage(filename, g_format, image, g_compression);
878 continue;
879 }
880
881 if (g_type == OutputType::OCTAHEDRON) {
882 size_t dim = dst.getDimensions();
883 Image image(dim, dim);
884 CubemapUtils::cubemapToOctahedron(js, image, dst);
885 std::string filename = outputDir + ("is_m" + std::to_string(level) + ext);
886 saveImage(filename, g_format, image, g_compression);
887 continue;
888 }
889
890 for (size_t i = 0; i < 6; i++) {
891 Cubemap::Face face = (Cubemap::Face)i;
892 std::string filename = outputDir
893 + ("is_m" + std::to_string(level) + "_" + CubemapUtils::getFaceName(face) + ext);
894 saveImage(filename, g_format, dst.getImageForFace(face), g_compression);
895 }
896 }
897 }
898
899 static float lodToPerceptualRoughness(float lod) noexcept {
900 // Inverse perceptualRoughness-to-LOD mapping:
901 // The LOD-to-perceptualRoughness mapping is a quadratic fit for
902 // log2(perceptualRoughness)+iblMaxMipLevel when iblMaxMipLevel is 4.
903 // We found empirically that this mapping works very well for a 256 cubemap with 5 levels used,
904 // but also scales well for other iblMaxMipLevel values.
905 const float a = 2.0f;
906 const float b = -1.0f;
907 return (lod != 0)
908 ? saturate((std::sqrt(a * a + 4.0f * b * lod) - a) / (2.0f * b))
909 : 0.0f;
910 }
911
912 void iblRoughnessPrefilter(
913 utils::JobSystem& js, const utils::Path& iname, const std::vector<Cubemap>& levels,
914 bool prefilter, const utils::Path& dir) {
915 utils::Path outputDir = dir.getAbsolutePath();
916 if (g_type != OutputType::KTX) {
917 outputDir += iname.getNameWithoutExtension();
918 }
919 if (!outputDir.exists()) {
920 outputDir.mkdirRecursive();
921 }
922
923 // DEBUG: enable this to generate pre-filter mipmaps at full resolution
924 // (of course, they're not mimaps at this point)
925 // This is useful for debugging.
926 const bool DEBUG_FULL_RESOLUTION = false;
927
928 const size_t baseExp = utils::ctz(g_output_size ? g_output_size : IBL_DEFAULT_SIZE);
929 size_t minLod = utils::ctz(g_min_lod_size ? g_min_lod_size : IBL_DEFAULT_MIN_LOD_SIZE);
930 if (minLod >= baseExp) {
931 minLod = 0;
932 }
933
934 size_t numSamples = g_num_samples;
935 const size_t numLevels = (baseExp + 1) - minLod;
936
937 // It's convenient to create an empty KTX bundle on the stack in this scope, regardless of
938 // whether KTX is requested. It does not consume memory if empty.
939 KtxBundle container((uint32_t) numLevels, 1, true);
940 container.info() = {
941 .endianness = KtxBundle::ENDIAN_DEFAULT,
942 .glType = KtxBundle::R11F_G11F_B10F,
943 .glTypeSize = 1,
944 .glFormat = KtxBundle::RGB,
945 .glInternalFormat = KtxBundle::R11F_G11F_B10F,
946 .glBaseInternalFormat = KtxBundle::R11F_G11F_B10F,
947 .pixelWidth = 1U << baseExp,
948 .pixelHeight = 1U << baseExp,
949 .pixelDepth = 0,
950 };
951
952 for (ssize_t i = baseExp; i >= ssize_t((baseExp + 1) - numLevels) ; --i) {
953 const size_t dim = 1U << (DEBUG_FULL_RESOLUTION ? baseExp : i); // NOLINT
954 const size_t level = baseExp - i;
955 if (level >= 2) {
956 // starting at level 2, we increase the number of samples per level
957 // this helps as the filter gets wider, and since there are 4x less work
958 // per level, this doesn't slow things down a lot.
959 if (!DEBUG_FULL_RESOLUTION) { // NOLINT
960 numSamples *= 2;
961 }
962 }
963
964 const float lod = saturate(level / (numLevels - 1.0f));
965 // map the lod to a perceptualRoughness
966 const float perceptualRoughness = lodToPerceptualRoughness(lod);
967 const float roughness = perceptualRoughness * perceptualRoughness;
968 if (!g_quiet) {
969 std::cout << "Level " << level << std::setprecision(3)
970 << ", roughness = " << roughness
971 << ", roughness (perceptual) = " << perceptualRoughness
972 << std::endl;
973 }
974 Image image;
975 Cubemap dst = CubemapUtils::create(image, dim);
976
977 ProgressUpdater updater(1);
978 if (!g_quiet) {
979 updater.start();
980 }
981 CubemapIBL::roughnessFilter(js, dst, levels, roughness, numSamples,
982 float3{ 1, 1, 1 }, prefilter,
983 [](size_t index, float v, void* userdata) {
984 if (!g_quiet) {
985 ((ProgressUpdater*) userdata)->update(index, v);
986 }
987 }, &updater);
988 if (!g_quiet) {
989 updater.stop();
990 }
991
992 dst.makeSeamless();
993
994 if (g_debug) {
995 ImageEncoder::Format debug_format = ImageEncoder::Format::HDR;
996 std::string ext = ImageEncoder::chooseExtension(debug_format);
997 std::string basename = iname.getNameWithoutExtension();
998 utils::Path filePath = outputDir + (basename + "_roughness_m" + (std::to_string(level) + ext));
999 saveImage(filePath, debug_format, image, g_compression);
1000 }
1001
1002 std::string ext = ImageEncoder::chooseExtension(g_format);
1003
1004 if (g_type == OutputType::KTX) {
1005 exportKtxFaces(container, (uint32_t) level, dst);
1006 continue;
1007 }
1008
1009 if (g_type == OutputType::EQUIRECT) {
1010 Image outImage(dim * 2, dim);
1011 CubemapUtils::cubemapToEquirectangular(js, outImage, dst);
1012 std::string filename = outputDir + ("m" + std::to_string(level) + ext);
1013 saveImage(filename, g_format, outImage, g_compression);
1014 continue;
1015 }
1016
1017 if (g_type == OutputType::OCTAHEDRON) {
1018 Image outImage(dim, dim);
1019 CubemapUtils::cubemapToOctahedron(js, outImage, dst);
1020 std::string filename = outputDir + ("m" + std::to_string(level) + ext);
1021 saveImage(filename, g_format, outImage, g_compression);
1022 continue;
1023 }
1024
1025 for (size_t j = 0; j < 6; j++) {
1026 Cubemap::Face face = (Cubemap::Face) j;
1027 std::string filename = outputDir
1028 + ("m" + std::to_string(level) + "_" + CubemapUtils::getFaceName(face) + ext);
1029 saveImage(filename, g_format, dst.getImageForFace(face), g_compression);
1030 }
1031 }
1032
1033 if (g_type == OutputType::KTX) {
1034 if (g_sh_coefficients) {
1035 std::ostringstream sstr;
1036 for (ssize_t l = 0; l < g_sh_compute; l++) {
1037 for (ssize_t m = -l; m <= l; m++) {
1038 auto v = g_sh_coefficients[CubemapSH::getShIndex(m, (size_t) l)];
1039 sstr << v.r << " " << v.g << " " << v.b << "\n";
1040 }
1041 }
1042 container.setMetadata("sh", sstr.str().c_str());
1043 }
1044 std::vector<uint8_t> fileContents(container.getSerializedLength());
1045 container.serialize(fileContents.data(), (uint32_t) fileContents.size());
1046 std::string filename = dir.getNameWithoutExtension() + "_ibl.ktx";
1047 auto fullpath = outputDir + filename;
1048 std::ofstream outputStream(fullpath.c_str(), std::ios::out | std::ios::binary);
1049 outputStream.write((const char*) fileContents.data(), fileContents.size());
1050 outputStream.close();
1051 }
1052 }
1053
1054 void iblDiffuseIrradiance(utils::JobSystem& js, const utils::Path& iname,
1055 const std::vector<Cubemap>& levels, const utils::Path& dir) {
1056 utils::Path outputDir(dir.getAbsolutePath() + iname.getNameWithoutExtension());
1057 if (!outputDir.exists()) {
1058 outputDir.mkdirRecursive();
1059 }
1060
1061 const size_t baseExp = utils::ctz(g_output_size ? g_output_size : IBL_DEFAULT_SIZE);
1062 size_t numSamples = g_num_samples;
1063 const size_t dim = 1U << baseExp;
1064 Image image;
1065 Cubemap dst = CubemapUtils::create(image, dim);
1066
1067 ProgressUpdater updater(1);
1068 if (!g_quiet) {
1069 updater.start();
1070 }
1071 CubemapIBL::diffuseIrradiance(js, dst, levels, numSamples,
1072 [](size_t index, float v, void* userdata) {
1073 if (!g_quiet) {
1074 ((ProgressUpdater*) userdata)->update(index, v);
1075 }
1076 }, &updater);
1077 if (!g_quiet) {
1078 updater.stop();
1079 }
1080
1081 dst.makeSeamless();
1082
1083 std::string ext = ImageEncoder::chooseExtension(g_format);
1084
1085 if (g_type == OutputType::EQUIRECT) {
1086 size_t dim = dst.getDimensions();
1087 Image image(dim * 2, dim);
1088 CubemapUtils::cubemapToEquirectangular(js, image, dst);
1089 std::string filename = outputDir + ("irradiance" + ext);
1090 saveImage(filename, g_format, image, g_compression);
1091 }
1092
1093 if (g_type == OutputType::OCTAHEDRON) {
1094 size_t dim = dst.getDimensions();
1095 Image image(dim, dim);
1096 CubemapUtils::cubemapToOctahedron(js, image, dst);
1097 std::string filename = outputDir + ("irradiance" + ext);
1098 saveImage(filename, g_format, image, g_compression);
1099 }
1100
1101 if (g_type == OutputType::FACES) {
1102 for (size_t j = 0; j < 6; j++) {
1103 Cubemap::Face face = (Cubemap::Face)j;
1104 std::string filename =
1105 outputDir + ("i_" + std::string(CubemapUtils::getFaceName(face)) + ext);
1106 saveImage(filename, g_format, dst.getImageForFace(face), g_compression);
1107 }
1108 }
1109
1110 if (g_debug) {
1111 ImageEncoder::Format debug_format = ImageEncoder::Format::HDR;
1112 std::string basename = iname.getNameWithoutExtension();
1113 std::string fileExt = ImageEncoder::chooseExtension(debug_format);
1114 utils::Path filePath = outputDir + (basename + "_diffuse_irradiance" + fileExt);
1115 saveImage(filePath, debug_format, image, "");
1116
1117 // this generates SHs from the importance-sampled version above. This is just used
1118 // to compare the resuts and see if the later is better.
1119 Image outImage;
1120 Cubemap cm = CubemapUtils::create(outImage, dim);
1121 auto sh = CubemapSH::computeSH(js, dst, g_sh_compute, false);
1122 CubemapSH::renderSH(js, cm, sh, g_sh_compute);
1123 filePath = outputDir + (basename + "_diffuse_irradiance_sh" + fileExt);
1124 saveImage(filePath, debug_format, outImage, "");
1125 }
1126 }
1127
1128 static bool isTextFile(const utils::Path& filename) {
1129 std::string extension(filename.getExtension());
1130 return extension == "h" || extension == "hpp" ||
1131 extension == "c" || extension == "cpp" ||
1132 extension == "inc" || extension == "txt";
1133 }
1134
1135 static bool isIncludeFile(const utils::Path& filename) {
1136 std::string extension(filename.getExtension());
1137 return extension == "inc";
1138 }
1139
1140 void iblLutDfg(utils::JobSystem& js, const utils::Path& filename, size_t size, bool multiscatter,
1141 bool cloth) {
1142 Image image(size, size);
1143 CubemapIBL::DFG(js, image, multiscatter, cloth);
1144
1145 utils::Path outputDir(filename.getAbsolutePath().getParent());
1146 if (!outputDir.exists()) {
1147 outputDir.mkdirRecursive();
1148 }
1149
1150 if (isTextFile(filename)) {
1151 const bool isInclude = isIncludeFile(filename);
1152 std::ofstream outputStream(filename, std::ios::trunc);
1153
1154 outputStream << "// generated with: cmgen --ibl-dfg=" << filename.c_str() << std::endl;
1155 outputStream << "// DFG LUT stored as an RG16F texture, in GL order" << std::endl;
1156 if (!isInclude) {
1157 outputStream << "const uint16_t DFG_LUT[] = {";
1158 }
1159 for (size_t y = 0; y < size; y++) {
1160 for (size_t x = 0; x < size; x++) {
1161 if (x % 4 == 0) outputStream << std::endl << " ";
1162 const half3 d = half3(*static_cast<float3*>(image.getPixelRef(x, size - 1 - y)));
1163 const uint16_t r = *reinterpret_cast<const uint16_t*>(&d.r);
1164 const uint16_t g = *reinterpret_cast<const uint16_t*>(&d.g);
1165 const uint16_t b = *reinterpret_cast<const uint16_t*>(&d.b);
1166 outputStream << "0x" << std::setfill('0') << std::setw(4) << std::hex << r << ", ";
1167 outputStream << "0x" << std::setfill('0') << std::setw(4) << std::hex << g << ", ";
1168 if (g_dfg_cloth) {
1169 outputStream << "0x" << std::setfill('0') << std::setw(4) << std::hex << b << ", ";
1170 }
1171 }
1172 }
1173 if (!isInclude) {
1174 outputStream << std::endl << "};" << std::endl;
1175 }
1176
1177 outputStream << std::endl;
1178 outputStream.flush();
1179 outputStream.close();
1180 } else {
1181 ImageEncoder::Format format = ImageEncoder::chooseFormat(filename.getName(), true);
1182 saveImage(filename, format, image, g_compression);
1183 }
1184 }
1185
1186 void extractCubemapFaces(utils::JobSystem& js, const utils::Path& iname, const Cubemap& cm,
1187 const utils::Path& dir) {
1188 utils::Path outputDir(dir.getAbsolutePath());
1189 if (g_type != OutputType::KTX) {
1190 outputDir += iname.getNameWithoutExtension();
1191 }
1192 if (!outputDir.exists()) {
1193 outputDir.mkdirRecursive();
1194 }
1195
1196 if (g_type == OutputType::KTX) {
1197 const uint32_t dim = (const uint32_t) cm.getDimensions();
1198 KtxBundle container(1, 1, true);
1199 container.info() = {
1200 .endianness = KtxBundle::ENDIAN_DEFAULT,
1201 .glType = KtxBundle::R11F_G11F_B10F,
1202 .glTypeSize = 1,
1203 .glFormat = KtxBundle::RGB,
1204 .glInternalFormat = KtxBundle::R11F_G11F_B10F,
1205 .glBaseInternalFormat = KtxBundle::R11F_G11F_B10F,
1206 .pixelWidth = dim,
1207 .pixelHeight = dim,
1208 .pixelDepth = 0,
1209 };
1210 exportKtxFaces(container, 0, cm);
1211 std::string filename = dir.getNameWithoutExtension() + "_skybox.ktx";
1212 auto fullpath = outputDir + filename;
1213 std::vector<uint8_t> fileContents(container.getSerializedLength());
1214 container.serialize(fileContents.data(), (uint32_t) fileContents.size());
1215 std::ofstream outputStream(fullpath.c_str(), std::ios::out | std::ios::binary);
1216 outputStream.write((const char*) fileContents.data(), fileContents.size());
1217 outputStream.close();
1218 return;
1219 }
1220
1221 std::string ext = ImageEncoder::chooseExtension(g_format);
1222
1223 if (g_type == OutputType::EQUIRECT) {
1224 size_t dim = cm.getDimensions();
1225 Image image(dim * 2, dim);
1226 CubemapUtils::cubemapToEquirectangular(js, image, cm);
1227 std::string filename = outputDir + ("skybox" + ext);
1228 saveImage(filename, g_format, image, g_compression);
1229 return;
1230 }
1231
1232 if (g_type == OutputType::OCTAHEDRON) {
1233 size_t dim = cm.getDimensions();
1234 Image image(dim, dim);
1235 CubemapUtils::cubemapToOctahedron(js, image, cm);
1236 std::string filename = outputDir + ("skybox" + ext);
1237 saveImage(filename, g_format, image, g_compression);
1238 return;
1239 }
1240
1241 for (size_t i = 0; i < 6; i++) {
1242 Cubemap::Face face = (Cubemap::Face) i;
1243 std::string filename(outputDir + (CubemapUtils::getFaceName(face) + ext));
1244 saveImage(filename, g_format, cm.getImageForFace(face), g_compression);
1245 }
1246 }
1247
1248 // Converts a cmgen Image into a libimage LinearImage
1249 static LinearImage toLinearImage(const Image& image) {
1250 LinearImage linearImage((uint32_t) image.getWidth(), (uint32_t) image.getHeight(), 3);
1251
1252 // Copy row by row since the image has padding.
1253 assert(image.getBytesPerPixel() == 12);
1254 const size_t w = image.getWidth(), h = image.getHeight();
1255 for (size_t row = 0; row < h; ++row) {
1256 float* dst = linearImage.getPixelRef(0, (uint32_t) row);
1257 float const* src = static_cast<float const*>(image.getPixelRef(0, row));
1258 memcpy(dst, src, w * 12);
1259 }
1260 return linearImage;
1261 }
1262
1263 static void saveImage(const std::string& path, ImageEncoder::Format format, const Image& image,
1264 const std::string& compression) {
1265 std::ofstream outputStream(path, std::ios::binary | std::ios::trunc);
1266 if (!ImageEncoder::encode(outputStream, format, toLinearImage(image), compression, path)) {
1267 exit(1);
1268 }
1269 }
1270
1271 static void exportKtxFaces(KtxBundle& container, uint32_t miplevel, const Cubemap& cm) {
1272 auto& info = container.info();
1273
1274 #ifdef IMAGEIO_SUPPORTS_BLOCK_COMPRESSION
1275 CompressionConfig compression {};
1276 if (!g_compression.empty()) {
1277 bool valid = parseOptionString(g_compression, &compression);
1278 if (!valid) {
1279 std::cerr << "Unrecognized compression: " << g_compression << std::endl;
1280 exit(1);
1281 }
1282 // The KTX spec says the following for compressed textures: glTypeSize should 1,
1283 // glFormat should be 0, and glBaseInternalFormat should be RED, RG, RGB, or RGBA.
1284 // The glInternalFormat field is the only field that specifies the actual format.
1285 info.glTypeSize = 1;
1286 info.glFormat = 0;
1287 // FIXME: not sure this is always correct to use RGB here, does this work with HDR formats?
1288 info.glBaseInternalFormat = KtxBundle::RGB;
1289 info.glInternalFormat = KtxBundle::RGB;
1290 }
1291 #else
1292 if (!g_compression.empty()) {
1293 std::cerr << "Block compression is not supported in this build." << std::endl;
1294 exit(1);
1295 }
1296 #endif
1297
1298 const uint32_t dim = (const uint32_t) cm.getDimensions();
1299 for (uint32_t j = 0; j < 6; j++) {
1300 KtxBlobIndex blobIndex {(uint32_t) miplevel, 0, j};
1301 Cubemap::Face face;
1302 switch (j) {
1303 case 0: face = Cubemap::Face::PX; break;
1304 case 1: face = Cubemap::Face::NX; break;
1305 case 2: face = Cubemap::Face::PY; break;
1306 case 3: face = Cubemap::Face::NY; break;
1307 case 4: face = Cubemap::Face::PZ; break;
1308 case 5: face = Cubemap::Face::NZ; break;
1309 default: face = Cubemap::Face::PX; break; // make linters happy
1310 }
1311 LinearImage image = toLinearImage(cm.getImageForFace(face));
1312
1313 #ifdef IMAGEIO_SUPPORTS_BLOCK_COMPRESSION
1314 if (compression.type != CompressionConfig::INVALID) {
1315 CompressedTexture tex = compressTexture(compression, image);
1316 container.setBlob(blobIndex, tex.data.get(), tex.size);
1317 info.glInternalFormat = (uint32_t) tex.format;
1318 continue;
1319 }
1320 #endif
1321
1322 auto uintData = fromLinearToRGB_10_11_11_REV(image);
1323 container.setBlob(blobIndex, uintData.get(), dim * dim * 4);
1324 }
1325 }