/* * 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 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "app/Config.h" #include "app/FilamentApp.h" #include "app/MeshIO.h" #include #include #include #include using namespace math; using namespace filament; using namespace filamat; using namespace utils; static std::vector g_filenames; static std::map g_materialInstances; static std::vector g_meshes; static const Material* g_material; static Entity g_light; static Texture* g_opacityMaskMap = nullptr; static Config g_config; static struct MaskedConfig { std::string opacityMaskMap; float threshold = 0.4f; } g_maskedConfig; static void printUsage(char* name) { std::string exec_name(Path(name).getName()); std::string usage( "SAMPLE_OPACITY_MASK is an example of opacity masking\n" "Usage:\n" " SAMPLE_OPACITY_MASK [options] \n" "Options:\n" " --help, -h\n" " Prints this message\n\n" " --ibl=, -i \n" " Applies an IBL generated by cmgen's deploy option\n\n" " --split-view\n" " Splits the window into 4 views\n\n" " --scale=[number], -s [number]\n" " Applies uniform scale\n\n" " --opacity-mask=, -o \n" " Diffuse + opacity mask map (RGBA) to apply to the loaded meshes\n\n" " --threshold=[number], -t [number]\n" " Mask threshold between 0 and 1, default is 0.4\n\n" ); const std::string from("SAMPLE_OPACITY_MASK"); 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:t:o:"; 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' }, { "opacity-mask", required_argument, 0, 'o' }, { "threshold", required_argument, 0, 't' }, { 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 'o': g_maskedConfig.opacityMaskMap = arg; break; case 't': try { g_maskedConfig.threshold = std::stof(arg); } catch (std::invalid_argument& e) { // keep default } catch (std::out_of_range& e) { // keep default } break; } } return optind; } static void cleanup(Engine* engine, View* view, Scene* scene) { engine->destroy(g_opacityMaskMap); 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); } void loadOpacityMap(Engine* engine) { if (!g_maskedConfig.opacityMaskMap.empty()) { Path path(g_maskedConfig.opacityMaskMap); if (path.exists()) { int w, h, n; unsigned char* data = stbi_load(path.getAbsolutePath().c_str(), &w, &h, &n, 4); if (data != nullptr) { g_opacityMaskMap = Texture::Builder() .width(uint32_t(w)) .height(uint32_t(h)) .levels(0xff) .format(Texture::InternalFormat::SRGB8_A8) .build(*engine); Texture::PixelBufferDescriptor buffer(data, size_t(w * h * 4), Texture::Format::RGBA, Texture::Type::UBYTE, (driver::BufferDescriptor::Callback) &stbi_image_free); g_opacityMaskMap->setImage(*engine, 0, std::move(buffer)); g_opacityMaskMap->generateMipmaps(*engine); } else { std::cout << "The opacity map " << path << " could not be loaded" << std::endl; } } else { std::cout << "The opacity map " << path << " does not exist" << std::endl; } } } static void setup(Engine* engine, View* view, Scene* scene) { loadOpacityMap(engine); if (g_opacityMaskMap == nullptr) { std::cerr << "You must specify an RGBA diffuse + opacity mask" << std::endl; exit(1); } Package pkg = MaterialBuilder() .name("DefaultMaterial") .require(VertexAttribute::UV0) .parameter(MaterialBuilder::SamplerType::SAMPLER_2D, "opacityMaskMap") .set(Property::BASE_COLOR) .set(Property::METALLIC) .set(Property::ROUGHNESS) .material(R"SHADER( void material(inout MaterialInputs material) { prepareMaterial(material); material.baseColor = texture(materialParams_opacityMaskMap, getUV0()); material.roughness = 0.6; } )SHADER") .shading(Shading::LIT) .blending(BlendingMode::MASKED) .maskThreshold(g_maskedConfig.threshold) .doubleSided(true) .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); g_materialInstances["DefaultMaterial"]->setParameter("opacityMaskMap", g_opacityMaskMap, sampler); auto& rcm = engine->getRenderableManager(); auto& tcm = engine->getTransformManager(); for (auto filename : g_filenames) { MeshIO::Mesh mesh = MeshIO::loadMeshFromFile(engine, filename, g_materialInstances); if (mesh.renderable) { auto ti = tcm.getInstance(mesh.renderable); tcm.setTransform(ti, mat4f{ mat3f(g_config.scale), float3(0.0f, 0.0f, -4.0f) } * tcm.getWorldTransform(ti)); auto ri = rcm.getInstance(mesh.renderable); auto blendingMode = rcm.getMaterialInstanceAt(ri, 0)->getMaterial()->getBlendingMode(); rcm.setCastShadows(ri, blendingMode == BlendingMode::OPAQUE || blendingMode == BlendingMode::MASKED); rcm.setReceiveShadows(ri, true); scene->addEntity(mesh.renderable); g_meshes.push_back(mesh); } } g_light = EntityManager::get().create(); LightManager::Builder(LightManager::Type::DIRECTIONAL) .color(Color::toLinear({0.98f, 0.92f, 0.89f})) .intensity(110000) .direction({0.2, -0.5, -1.0}) .castShadows(true) .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 = "Opacity Mask"; FilamentApp& filamentApp = FilamentApp::get(); filamentApp.run(g_config, setup, cleanup); return 0; }