forked from google/filament
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sample_normal_map.cpp
324 lines (288 loc) · 11.1 KB
/
sample_normal_map.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include <map>
#include <vector>
#include <getopt/getopt.h>
#include <utils/Path.h>
#include <filament/Engine.h>
#include <filament/LightManager.h>
#include <filament/Material.h>
#include <filament/MaterialInstance.h>
#include <filament/RenderableManager.h>
#include <filament/TransformManager.h>
#include <filament/Scene.h>
#include <filament/Texture.h>
#include <math/mat3.h>
#include <math/mat4.h>
#include <math/vec4.h>
#include "app/Config.h"
#include "app/FilamentApp.h"
#include "app/MeshIO.h"
#include <stb_image.h>
#include <utils/EntityManager.h>
#include <filamat/MaterialBuilder.h>
using namespace math;
using namespace filament;
using namespace filamat;
using namespace utils;
static std::vector<Path> g_filenames;
static std::map<std::string, MaterialInstance*> g_materialInstances;
static std::vector<MeshIO::Mesh> g_meshes;
static const Material* g_material;
static Entity g_light;
static Texture* g_normalMap = nullptr;
static Texture* g_baseColorMap = nullptr;
static Config g_config;
static struct NormalConfig {
std::string normalMap;
std::string baseColorMap;
} g_normalConfig;
static void printUsage(char* name) {
std::string exec_name(Path(name).getName());
std::string usage(
"SAMPLE_NORMAL_MAP is an example of normal mapping\n"
"Usage:\n"
" SAMPLE_NORMAL_MAP [options] <filamesh input files>\n"
"Options:\n"
" --help, -h\n"
" Prints this message\n\n"
" --ibl=<path to cmgen IBL>, -i <path>\n"
" Applies an IBL generated by cmgen's deploy option\n\n"
" --split-view, -v\n"
" Splits the window into 4 views\n\n"
" --scale=[number], -s [number]\n"
" Applies uniform scale\n\n"
" --normal-map=<path to PNG/JPG/BMP/GIF/TGA/PSD>, -n <path>\n"
" Normal map to apply to the loaded meshes\n\n"
" --basecolor-map=<path to PNG/JPG/BMP/GIF/TGA/PSD>, -c <path>\n"
" Base color map to apply to the loaded meshes\n\n"
);
const std::string from("SAMPLE_NORMAL_MAP");
for (size_t pos = usage.find(from); pos != std::string::npos; pos = usage.find(from, pos)) {
usage.replace(pos, from.length(), exec_name);
}
std::cout << usage;
}
static int handleCommandLineArgments(int argc, char* argv[], Config* config) {
static constexpr const char* OPTSTR = "hi:vs:n:a:c:";
static const struct option OPTIONS[] = {
{ "help", no_argument, 0, 'h' },
{ "ibl", required_argument, 0, 'i' },
{ "split-view", no_argument, 0, 'v' },
{ "scale", required_argument, 0, 's' },
{ "normal-map", required_argument, 0, 'n' },
{ "basecolor-map", required_argument, 0, 'c' },
{ 0, 0, 0, 0 } // termination of the option list
};
int opt;
int option_index = 0;
while ((opt = getopt_long(argc, argv, OPTSTR, OPTIONS, &option_index)) >= 0) {
std::string arg(optarg ? optarg : "");
switch (opt) {
default:
case 'h':
printUsage(argv[0]);
exit(0);
case 'i':
config->iblDirectory = arg;
break;
case 's':
try {
config->scale = std::stof(arg);
} catch (std::invalid_argument& e) {
// keep scale of 1.0
} catch (std::out_of_range& e) {
// keep scale of 1.0
}
break;
case 'v':
config->splitView = true;
break;
case 'n':
g_normalConfig.normalMap = arg;
break;
case 'c':
g_normalConfig.baseColorMap = arg;
break;
}
}
return optind;
}
static void cleanup(Engine* engine, View* view, Scene* scene) {
engine->destroy(g_normalMap);
for (auto material : g_materialInstances) {
engine->destroy(material.second);
}
engine->destroy(g_material);
EntityManager& em = EntityManager::get();
for (auto mesh : g_meshes) {
engine->destroy(mesh.vertexBuffer);
engine->destroy(mesh.indexBuffer);
engine->destroy(mesh.renderable);
em.destroy(mesh.renderable);
}
engine->destroy(g_light);
em.destroy(g_light);
}
void loadNormalMap(Engine* engine) {
if (!g_normalConfig.normalMap.empty()) {
Path path(g_normalConfig.normalMap);
if (path.exists()) {
int w, h, n;
unsigned char* data = stbi_load(path.getAbsolutePath().c_str(), &w, &h, &n, 3);
if (data != nullptr) {
g_normalMap = Texture::Builder()
.width(uint32_t(w))
.height(uint32_t(h))
.levels(0xff)
.format(driver::TextureFormat::RGB8)
.build(*engine);
Texture::PixelBufferDescriptor buffer(data, size_t(w * h * 3),
Texture::Format::RGB, Texture::Type::UBYTE,
(driver::BufferDescriptor::Callback)&stbi_image_free);
g_normalMap->setImage(*engine, 0, std::move(buffer));
g_normalMap->generateMipmaps(*engine);
} else {
std::cout << "The normal map " << path << " could not be loaded" << std::endl;
}
} else {
std::cout << "The normal map " << path << " does not exist" << std::endl;
}
}
}
void loadBaseColorMap(Engine* engine) {
if (!g_normalConfig.baseColorMap.empty()) {
Path path(g_normalConfig.baseColorMap);
if (path.exists()) {
int w, h, n;
unsigned char* data = stbi_load(path.getAbsolutePath().c_str(), &w, &h, &n, 3);
if (data != nullptr) {
g_baseColorMap = Texture::Builder()
.width(uint32_t(w))
.height(uint32_t(h))
.levels(0xff)
.format(driver::TextureFormat::SRGB8)
.build(*engine);
Texture::PixelBufferDescriptor buffer(data, size_t(w * h * 3),
Texture::Format::RGB, Texture::Type::UBYTE,
(driver::BufferDescriptor::Callback)&stbi_image_free);
g_baseColorMap->setImage(*engine, 0, std::move(buffer));
g_baseColorMap->generateMipmaps(*engine);
} else {
std::cout << "The base color map " << path << " could not be loaded" << std::endl;
}
} else {
std::cout << "The base color map " << path << " does not exist" << std::endl;
}
}
}
static void setup(Engine* engine, View* view, Scene* scene) {
loadNormalMap(engine);
loadBaseColorMap(engine);
bool hasNormalMap = g_normalMap != nullptr;
bool hasBaseColorMap = g_baseColorMap != nullptr;
std::string shader = R"SHADER(
void material(inout MaterialInputs material) {
#if defined(MATERIAL_HAS_NORMAL)
material.normal = texture(materialParams_normalMap, getUV0()).xyz * 2.0 - 1.0;
#endif
prepareMaterial(material);
)SHADER";
if (hasBaseColorMap) {
shader += R"SHADER(
material.baseColor.rgb = texture(materialParams_baseColorMap, getUV0()).rgb;
material.metallic = 1.0;
material.roughness = 0.6;
)SHADER";
} else {
shader += R"SHADER(
material.baseColor.rgb = float3(0.93, 0.51, 0.34);
material.metallic = 1.0;
material.roughness = 0.3;
)SHADER";
}
shader += "}\n";
MaterialBuilder builder = MaterialBuilder()
.name("DefaultMaterial")
.set(Property::BASE_COLOR)
.set(Property::METALLIC)
.set(Property::ROUGHNESS)
.material(shader.c_str())
.shading(Shading::LIT);
if (hasNormalMap) {
builder
.require(VertexAttribute::UV0)
.parameter(MaterialBuilder::SamplerType::SAMPLER_2D, "normalMap")
.set(Property::NORMAL);
}
if (hasBaseColorMap) {
builder
.require(VertexAttribute::UV0)
.parameter(MaterialBuilder::SamplerType::SAMPLER_2D, "baseColorMap");
}
Package pkg = builder.build();
g_material = Material::Builder().package(pkg.getData(), pkg.getSize())
.build(*engine);
g_materialInstances["DefaultMaterial"] = g_material->createInstance();
TextureSampler sampler(TextureSampler::MinFilter::LINEAR_MIPMAP_LINEAR,
TextureSampler::MagFilter::LINEAR, TextureSampler::WrapMode::REPEAT);
sampler.setAnisotropy(8.0f);
if (hasNormalMap) {
g_materialInstances["DefaultMaterial"]->setParameter("normalMap", g_normalMap, sampler);
}
if (hasBaseColorMap) {
g_materialInstances["DefaultMaterial"]->setParameter("baseColorMap", g_baseColorMap, sampler);
}
auto& tcm = engine->getTransformManager();
for (auto filename : g_filenames) {
MeshIO::Mesh mesh = MeshIO::loadMeshFromFile(engine, filename, g_materialInstances);
if (mesh.renderable) {
auto ei = tcm.getInstance(mesh.renderable);
tcm.setTransform(ei, mat4f{ mat3f(g_config.scale), float3(0.0f, 0.0f, -4.0f) } *
tcm.getWorldTransform(ei));
scene->addEntity(mesh.renderable);
g_meshes.push_back(mesh);
}
}
g_light = EntityManager::get().create();
LightManager::Builder(LightManager::Type::DIRECTIONAL)
.color(Color::toLinear<ACCURATE>({0.98f, 0.92f, 0.89f}))
.intensity(110000)
.direction({0.6, -1, -0.8})
.build(*engine, g_light);
scene->addEntity(g_light);
}
int main(int argc, char* argv[]) {
int option_index = handleCommandLineArgments(argc, argv, &g_config);
int num_args = argc - option_index;
if (num_args < 1) {
printUsage(argv[0]);
return 1;
}
for (int i = option_index; i < argc; i++) {
utils::Path filename = argv[i];
if (!filename.exists()) {
std::cerr << "file " << argv[option_index] << " not found!" << std::endl;
return 1;
}
g_filenames.push_back(filename);
}
g_config.title = "Normal Mapping";
FilamentApp& filamentApp = FilamentApp::get();
filamentApp.run(g_config, setup, cleanup);
return 0;
}