Example: opengl_normal_maps
Normal maps and detail maps on textured surfaces: two brick walls side by side, with and without a normal map, lit by a grazing point light, on a large terrain whose single low-resolution texture gets fine grain up close from tiled detail color and normal maps (press D to cycle them).
Modules: mrpt_core, mrpt_gui, mrpt_img, mrpt_math, mrpt_system, mrpt_viz | Requires: gui
C++ example source code:
/* _ | | Mobile Robot Programming Toolkit (MRPT) _ __ ___ _ __ _ __ | |_ | '_ ` _ \| '__| '_ \| __| https://www.mrpt.org/ | | | | | | | | |_) | |_ |_| |_| |_|_| | .__/ \__| https://github.com/MRPT/mrpt/ | | |_| Copyright (c) 2005-2026, Individual contributors, see AUTHORS file See: https://www.mrpt.org/Authors - All rights reserved. SPDX-License-Identifier: BSD-3-Clause */ #include <mrpt/core/format.h> #include <mrpt/gui/CDisplayWindow3D.h> #include <mrpt/img/CImage.h> #include <mrpt/img/TColor.h> #include <mrpt/math/CMatrixDynamic.h> #include <mrpt/system/filesystem.h> #include <mrpt/viz/CMesh.h> #include <mrpt/viz/CSkyBox.h> #include <mrpt/viz/CText.h> #include <mrpt/viz/CTexturedPlane.h> #include <mrpt/viz/Viewport.h> #include <algorithm> #include <array> #include <cmath> #include <cstdint> #include <iostream> #include <string> #include <thread> #include <vector> namespace { // --------------------------------------------------------------------------- // Texture URLs. The material textures are from cgbookcase.com (CC0 1.0, // public domain), mirrored in the MVSim models repository. // --------------------------------------------------------------------------- const char* URL_ASPHALT_COLOR = "https://mrpt.github.io/mvsim-models/textures-cgbookcase/" "Asphalt01_1K_BaseColor.png"; const char* URL_ASPHALT_NORMAL = "https://mrpt.github.io/mvsim-models/textures-cgbookcase/" "Asphalt01_1K_NormalGL.png"; const char* URL_BRICK_COLOR = "https://mrpt.github.io/mvsim-models/textures-cgbookcase/" "BrickWall01_1K_BaseColor.png"; const char* URL_BRICK_NORMAL = "https://mrpt.github.io/mvsim-models/textures-cgbookcase/" "BrickWall01_1K_NormalGL.png"; // Terrain detail maps: const char* URL_DIRT_COLOR = "https://mrpt.github.io/mvsim-models/textures-cgbookcase/" "Dirt02_1K_BaseColor.png"; const char* URL_DIRT_NORMAL = "https://mrpt.github.io/mvsim-models/textures-cgbookcase/" "Dirt02_1K_NormalGL.png"; // Skybox const char* URL_SKYBOX_ZIP = "https://mrpt.github.io/mvsim-models/skyboxes/SunSet.zip"; const char* SKYBOX_DIR = "./SunSet/"; const char* SKYBOX_FILE_PATTERN = "./SunSet/SunSet%s.jpg"; // --------------------------------------------------------------------------- // Helper: downloads a file into the current directory, named as in the URL, // unless it is already there. Returns its local path. // --------------------------------------------------------------------------- std::string downloadFile(const std::string& url) { const std::string destPath = url.substr(url.find_last_of('/') + 1); if (mrpt::system::fileExists(destPath)) { return destPath; } std::cout << "Downloading: " << url << " -> " << destPath << "\n"; // Download to a temporary name, renamed only on success, so failed // downloads do not leave a broken file behind. Try wget first, then curl: const std::string tmpPath = destPath + ".part"; int ret = ::system(mrpt::format(R"(wget "%s" -O "%s")", url.c_str(), tmpPath.c_str()).c_str()); if (ret != 0) { ret = ::system(mrpt::format(R"(curl -fL "%s" -o "%s")", url.c_str(), tmpPath.c_str()).c_str()); } if (ret != 0 || !mrpt::system::renameFile(tmpPath, destPath)) { mrpt::system::deleteFile(tmpPath); THROW_EXCEPTION_FMT("Could not download file: %s", url.c_str()); } return destPath; } // --------------------------------------------------------------------------- // Download skybox ZIP and extract if needed // --------------------------------------------------------------------------- void downloadSkybox() { if (mrpt::system::directoryExists(SKYBOX_DIR)) { return; } const std::string zipFile = downloadFile(URL_SKYBOX_ZIP); if (::system(mrpt::format(R"(unzip -q "%s")", zipFile.c_str()).c_str()) != 0) { THROW_EXCEPTION("Could not unzip skybox."); } } // --------------------------------------------------------------------------- // Terrain: a large mesh with a single low-resolution texture over all of it, // as usual in simulations of large outdoor areas. Up close, it looks blurry: // detail maps (small textures tiled many times) add the missing fine grain. // --------------------------------------------------------------------------- constexpr float TERRAIN_HALF_SIZE = 60.0f; // [m] constexpr float DETAIL_TILE_SIZE = 2.0f; // [m] // Pseudo-random value in [0,1] for each integer lattice point double latticeNoise(int ix, int iy) { uint32_t h = static_cast<uint32_t>(ix) * 374761393U + static_cast<uint32_t>(iy) * 668265263U; h = (h ^ (h >> 13U)) * 1274126177U; return static_cast<double>((h ^ (h >> 16U)) & 0xffffU) / 65535.0; } // Smooth noise in [0,1], with features of about 1 unit and smaller double fractalNoise(double x, double y) { double sum = 0; double amplitude = 0.5; for (int octave = 0; octave < 4; octave++) { const double fx = std::floor(x); const double fy = std::floor(y); const int ix = static_cast<int>(fx); const int iy = static_cast<int>(fy); const double tx = (x - fx) * (x - fx) * (3 - 2 * (x - fx)); const double ty = (y - fy) * (y - fy) * (3 - 2 * (y - fy)); const double a = latticeNoise(ix, iy) + tx * (latticeNoise(ix + 1, iy) - latticeNoise(ix, iy)); const double b = latticeNoise(ix, iy + 1) + tx * (latticeNoise(ix + 1, iy + 1) - latticeNoise(ix, iy + 1)); sum += amplitude * (a + ty * (b - a)); amplitude *= 0.5; x *= 2; y *= 2; } return sum / 0.9375; } // Flat (just below the asphalt) around the walls, and hills further away double terrainHeight(double x, double y) { const double w = std::clamp((std::hypot(x, y) - 12.0) / 15.0, 0.0, 1.0); return -0.05 + w * w * 5.0 * fractalNoise(x / 20.0, y / 20.0); } // The terrain texture: a single 512x512 image (~23 cm per pixel) with grass // and dirt patches. CMesh texture rows run along +x, and columns along +y. mrpt::img::CImage terrainTexture() { constexpr int N = 512; mrpt::img::CImage im(N, N, mrpt::img::CH_RGB); for (int row = 0; row < N; row++) { for (int col = 0; col < N; col++) { const double x = (row + 0.5) / N * 2 * TERRAIN_HALF_SIZE - TERRAIN_HALF_SIZE; const double y = (col + 0.5) / N * 2 * TERRAIN_HALF_SIZE - TERRAIN_HALF_SIZE; const double dirt = std::clamp((fractalNoise(x / 9, y / 9) - 0.4) * 4.0, 0.0, 1.0); const double shade = 0.75 + 0.5 * fractalNoise(x / 1.5 + 100, y / 1.5); const double rgb[3] = { shade * (90 + dirt * (125 - 90)), shade * (110 + dirt * (105 - 110)), shade * (50 + dirt * (80 - 50))}; for (int8_t c = 0; c < 3; c++) { im.at<uint8_t>(col, row, c) = static_cast<uint8_t>(std::clamp(rgb[c], 0.0, 255.0)); } } } return im; } mrpt::viz::CMesh::Ptr makeTerrain() { constexpr int N = 121; // 1 m cells mrpt::math::CMatrixFloat Z(N, N); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { const double x = -TERRAIN_HALF_SIZE + 2.0 * TERRAIN_HALF_SIZE * i / (N - 1); const double y = -TERRAIN_HALF_SIZE + 2.0 * TERRAIN_HALF_SIZE * j / (N - 1); Z(i, j) = static_cast<float>(terrainHeight(x, y)); } } auto terrain = mrpt::viz::CMesh::Create( false, -TERRAIN_HALF_SIZE, TERRAIN_HALF_SIZE, -TERRAIN_HALF_SIZE, TERRAIN_HALF_SIZE); terrain->assignImageAndZ(terrainTexture(), Z); terrain->enableTextureLinearInterpolation(true); return terrain; } // Detail maps are usually grayscale, averaging 50% gray so they keep the // average color of the main texture. This converts a photo into one. mrpt::img::CImage toDetailMap(const mrpt::img::CImage& photo) { const int w = static_cast<int>(photo.getWidth()); const int h = static_cast<int>(photo.getHeight()); const bool isColor = photo.channels() >= 3; std::vector<double> lum(static_cast<size_t>(w) * static_cast<size_t>(h)); double mean = 0; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { const double l = isColor ? 0.299 * photo.at<uint8_t>(x, y, 0) + 0.587 * photo.at<uint8_t>(x, y, 1) + 0.114 * photo.at<uint8_t>(x, y, 2) : photo.at<uint8_t>(x, y, 0); lum[static_cast<size_t>(y * w + x)] = l; mean += l; } } mean = std::max(1.0, mean / static_cast<double>(lum.size())); mrpt::img::CImage detail(w, h, mrpt::img::CH_GRAY); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { // Value 128 for the mean, with the contrast enhanced: const double v = 128.0 + 1.5 * 128.0 * (lum[static_cast<size_t>(y * w + x)] / mean - 1.0); detail.at<uint8_t>(x, y) = static_cast<uint8_t>(std::clamp(v, 0.0, 255.0)); } } return detail; } // Detail modes cycled with the "D" key: constexpr std::array<const char*, 3> DETAIL_MODE_NAMES = { "OFF", "detail color map", "detail color + normal maps"}; void applyDetailMode( mrpt::viz::CMesh& terrain, int mode, const mrpt::img::CImage& detailMap, const mrpt::img::CImage& detailNormalMap) { terrain.clearDetailMaps(); if (mode >= 1) { // Repetitions over the texture extension (here, the whole terrain): const float reps = 2 * TERRAIN_HALF_SIZE / DETAIL_TILE_SIZE; terrain.assignDetailMap(detailMap, {reps, reps}); } if (mode >= 2) { terrain.assignDetailNormalMap(detailNormalMap); } } // --------------------------------------------------------------------------- // Main demo // --------------------------------------------------------------------------- void TestNormalMaps() { // Download textures const std::string asphaltColorFile = downloadFile(URL_ASPHALT_COLOR); const std::string asphaltNormalFile = downloadFile(URL_ASPHALT_NORMAL); const std::string brickColorFile = downloadFile(URL_BRICK_COLOR); const std::string brickNormalFile = downloadFile(URL_BRICK_NORMAL); const std::string dirtColorFile = downloadFile(URL_DIRT_COLOR); const std::string dirtNormalFile = downloadFile(URL_DIRT_NORMAL); downloadSkybox(); // ----------------------------------------------------------------------- // Create the window // ----------------------------------------------------------------------- mrpt::gui::CDisplayWindow3D win("Normal Maps Demo - MRPT", 1024, 768); mrpt::viz::Scene::Ptr& theScene = win.get3DSceneAndLock(); // ----------------------------------------------------------------------- // Skybox // ----------------------------------------------------------------------- { using mrpt::viz::CUBE_TEXTURE_FACE; auto sb = mrpt::viz::CSkyBox::Create(); const std::vector<std::pair<CUBE_TEXTURE_FACE, const char*>> faceImages = { { CUBE_TEXTURE_FACE::FRONT, "Front"}, { CUBE_TEXTURE_FACE::BACK, "Back"}, {CUBE_TEXTURE_FACE::BOTTOM, "Down"}, { CUBE_TEXTURE_FACE::TOP, "Up"}, { CUBE_TEXTURE_FACE::LEFT, "Left"}, { CUBE_TEXTURE_FACE::RIGHT, "Right"}, }; for (const auto& p : faceImages) { const std::string fil = mrpt::format(SKYBOX_FILE_PATTERN, p.second); sb->assignImage(p.first, mrpt::img::CImage::LoadFromFile(fil)); } theScene->insert(sb); } // ----------------------------------------------------------------------- // Hemispheric ambient lighting (blueish sky, brownish ground) // ----------------------------------------------------------------------- { auto& lp = theScene->getViewport("main")->lightParameters(); lp.ambientSkyColor = mrpt::img::TColorf(0.6f, 0.7f, 1.0f); lp.ambientGroundColor = mrpt::img::TColorf(0.4f, 0.35f, 0.25f); // One directional sun-like light lp.lights.clear(); mrpt::viz::TLight sunLight; sunLight.type = mrpt::viz::TLightType::Directional; sunLight.direction = {-0.8f, 0.0f, -0.4f}; sunLight.color = mrpt::img::TColorf(1.0f, 0.95f, 0.85f); sunLight.diffuse = 0.9f; sunLight.specular = 0.4f; lp.lights.push_back(sunLight); // A warm point light close to the walls to emphasize normal map detail lp.lights.push_back(mrpt::viz::TLight::PointLight( {0.0f, -7.0f, 2.5f}, // position: grazing the walls mrpt::img::TColorf(1.0f, 0.8f, 0.5f), // warm color 1.0f, // diffuse 0.8f, // specular 1.0f, // att_constant 0.07f, // att_linear 0.017f // att_quadratic )); } // ----------------------------------------------------------------------- // Ground: asphalt WITH normal map // ----------------------------------------------------------------------- { const float halfSize = 8.0f; auto ground = mrpt::viz::CTexturedPlane::Create(-halfSize, halfSize, -halfSize, halfSize); ground->enableLighting(true); ground->assignImage(mrpt::img::CImage::LoadFromFile(asphaltColorFile)); ground->assignNormalMap(mrpt::img::CImage::LoadFromFile(asphaltNormalFile)); ground->setTextureRepeat(4.0f, 4.0f); // Ground lies in XY plane at Z=0 by default — no pose change needed theScene->insert(ground); } // ----------------------------------------------------------------------- // Two brick walls side by side, in the same vertical plane (y=-8) and both // facing +Y, so they can be compared under the same grazing light: // - Left (as seen from the camera): WITHOUT normal map // - Right: WITH normal map // ----------------------------------------------------------------------- for (const bool withNormalMap : {false, true}) { const float wallW = 4.0f; // half-width in X const float wallH = 3.0f; // height auto wall = mrpt::viz::CTexturedPlane::Create(-wallW, wallW, 0.0f, wallH); wall->enableLighting(true); wall->assignImage(mrpt::img::CImage::LoadFromFile(brickColorFile)); if (withNormalMap) { wall->assignNormalMap(mrpt::img::CImage::LoadFromFile(brickNormalFile)); } wall->setTextureRepeat(4.0f, 1.5f); // Rotate 90° around X (stands vertically, facing -Y), then 180° around Z // so it faces +Y, towards the scene center mrpt::math::TPose3D pose; pose.x = withNormalMap ? -wallW : wallW; pose.y = -8.0; pose.z = 0; pose.yaw = mrpt::DEG2RAD(180.0); pose.roll = mrpt::DEG2RAD(90.0); pose.pitch = 0; wall->setPose(pose); theScene->insert(wall); } // ----------------------------------------------------------------------- // Terrain around the scene, with detail maps // ----------------------------------------------------------------------- const auto detailMap = toDetailMap(mrpt::img::CImage::LoadFromFile(dirtColorFile)); const auto detailNormalMap = mrpt::img::CImage::LoadFromFile(dirtNormalFile); auto terrain = makeTerrain(); int detailMode = 2; applyDetailMode(*terrain, detailMode, detailMap, detailNormalMap); theScene->insert(terrain); // IMPORTANT: unlock before adding 2D text messages win.unlockAccess3DScene(); // ----------------------------------------------------------------------- // 2D overlay labels // ----------------------------------------------------------------------- mrpt::viz::TFontParams fp; fp.color = mrpt::img::TColorf(1, 1, 1); fp.vfont_scale = 15; win.addTextMessage(0.02, 0.95, "Normal Maps Demo (press ESC to exit)", 0, fp); mrpt::viz::TFontParams fp2; fp2.color = mrpt::img::TColorf(1, 1, 0.5f); fp2.vfont_scale = 13; win.addTextMessage(0.02, 0.04, "Left wall: NO normal map", 1, fp2); win.addTextMessage(0.02, 0.08, "Right wall: WITH normal map", 2, fp2); const auto showDetailMode = [&]() { win.addTextMessage( 0.02, 0.12, mrpt::format( "Terrain: %s (press D to change)", DETAIL_MODE_NAMES.at(static_cast<size_t>(detailMode))), 3, fp2); }; showDetailMode(); // ----------------------------------------------------------------------- // Camera // ----------------------------------------------------------------------- win.setCameraAzimuthDeg(90.0f); win.setCameraElevationDeg(10.0f); win.setCameraZoom(11.0f); win.setCameraPointingToPoint(0.0f, -8.0f, 1.5f); win.setFOV(50.0f); win.forceRepaint(); std::cout << "\n"; std::cout << "Normal Maps Demo\n"; std::cout << " Left wall : brick texture WITHOUT normal map\n"; std::cout << " Right wall: brick texture WITH normal map\n"; std::cout << " Ground : asphalt WITH normal map\n"; std::cout << " Terrain : one low-resolution texture, plus detail maps\n"; std::cout << " Lights : directional sun + warm point light\n"; std::cout << "\nZoom in close to the terrain, and press D to cycle its detail maps.\n"; std::cout << "Press ESC to exit.\n"; // ----------------------------------------------------------------------- // Event loop // ----------------------------------------------------------------------- while (win.isOpen()) { std::this_thread::sleep_for(std::chrono::milliseconds(50)); if (win.keyHit()) { mrpt::gui::mrptKeyModifier kmods{}; int key = win.getPushedKey(&kmods); if (key == mrpt::gui::MRPTK_ESCAPE) { break; } if (key == 'd' || key == 'D') { detailMode = (detailMode + 1) % 3; win.get3DSceneAndLock(); applyDetailMode(*terrain, detailMode, detailMap, detailNormalMap); win.unlockAccess3DScene(); showDetailMode(); win.forceRepaint(); } } } } } // namespace // --------------------------------------------------------------------------- int main() { try { TestNormalMaps(); return 0; } catch (const std::exception& e) { std::cerr << "MRPT error: " << mrpt::exception_to_str(e) << "\n"; return -1; } }