Easy3D 3.0.0
Loading...
Searching...
No Matches
Tutorial_501_AmbientOcclusion

Rendering a surface mesh with screen-space ambient occlusion (AO) to improve depth perception.

Overview

This tutorial adds ambient occlusion to the standard Easy3D Viewer. The portable pattern is to subclass Viewer, install a RenderSettings in init(), and replace those settings when the user changes an effect parameter. The entry point below simply loads a model, gives it a neutral white material, and runs the custom viewer; all of the effect logic lives in the TutorialAmbientOcclusion class (shown after this file).

The technique

Ambient occlusion approximates how much diffuse ambient light reaches each surface point. A point sitting in a crease, corner, or contact region is surrounded by nearby geometry that blocks part of the incoming hemisphere, so it receives less light and should look darker; a point on an exposed convex region receives almost full ambient light. Darkening occluded regions gives a strong cue of shape, depth, and contact — even with no explicit light source. Easy3D offers two complementary implementations.

The first one is computed in screen space (a GTAO-style pass): the scene depth is rendered first, then a post-process samples the neighborhood of each pixel in the depth buffer to estimate how much of the hemisphere is blocked, and multiplies the shaded color by the resulting per-pixel occlusion factor. The "radius ratio" parameter sets the world-space extent of that neighborhood as a fraction of the scene radius: a larger ratio yields broader, softer occlusion; a smaller ratio emphasizes fine creases. See RenderSettings::ambient_occlusion.

The second one is a per-vertex bake by hemisphere ray casting (SurfaceMeshAmbientOcclusion::bake()). It is view independent and deterministic, so the shading of a surface does not change while the camera moves, which is what figures in scientific publications need. Press 'b' to bake the current model once and display the occlusion through its vertex colors.

Easy3D API

Running it

Press 'space' to toggle ambient occlusion on/off and compare the depth cues; press 'up'/'down' to increase/decrease the occlusion radius ratio (the current value is printed to the console); press 'b' to bake the occlusion into vertex colors and compare the view-independent result.

1
27#include "viewer.h"
28#include <easy3d/core/model.h>
29#include <easy3d/renderer/drawable_triangles.h>
30#include <easy3d/renderer/renderer.h>
31#include <easy3d/util/resource.h>
32#include <easy3d/util/initializer.h>
33
95using namespace easy3d;
96
97int main(int argc, char **argv) {
98 // Bootstrap Easy3D (logging, resource directory, ...). Must come first.
99 initialize();
100
101 // The model to render. general_open.obj is an open surface whose folds and contacts
102 // make the occlusion darkening easy to see.
103 const std::string file = resource::directory() + "/data/general_open.obj";
104
105 // Create our custom viewer (a Viewer subclass that applies ambient occlusion).
106 TutorialAmbientOcclusion viewer(EXAMPLE_TITLE);
107
108 // Load the model and add it to the viewer. add_model() creates the model's renderer;
109 // the second argument (true) centers and scales the model to fit the scene.
110 auto model = viewer.add_model(file, true);
111 if (!model) {
112 std::cerr << "failed to load model. Please make sure the file exists and format is correct" << std::endl;
113 return EXIT_FAILURE;
114 }
115
116 // Give the surface a neutral white material so the only shading variation is the
117 // ambient occlusion. "faces" is the standard triangles drawable of a surface mesh.
118 auto drawable = model->renderer()->get_triangles_drawable("faces");
119 drawable->set_uniform_coloring(vec4(1.0f, 1.0f, 1.0f, 1.0f));
120
121 // Enter the interactive loop (returns when the window is closed).
122 return viewer.run();
123}
Definition collider.cpp:182

The header file of the viewer class:

1
27#ifndef EASY3D_TUTORIAL_AMBIENT_OCCLUSION_H
28#define EASY3D_TUTORIAL_AMBIENT_OCCLUSION_H
29
30#include <easy3d/viewer/viewer.h>
31
41class TutorialAmbientOcclusion : public easy3d::Viewer {
42public:
43 // Builds the viewer; the ambient-occlusion settings are installed in init().
44 explicit TutorialAmbientOcclusion(const std::string &title = "");
45
46protected:
47 // Installs the initial RenderSettings after the viewer's device is ready.
48 void init() override;
49 // Handles 'space' (toggle), 'up'/'down' (radius), and 'b' (bake); forwards other keys to Viewer.
50 bool key_press_event(int key, int modifiers) override;
51
52private:
53 bool baked_;
54};
55
56#endif // EASY3D_TUTORIAL_AMBIENT_OCCLUSION_H
The default viewer implementation for both OpenGL and Vulkan backends.
Definition viewer.h:143

The source file of the viewer class:

1
27#include "viewer.h"
28#include <algorithm>
29
30#include <easy3d/core/surface_mesh.h>
31#include <easy3d/algo/surface_mesh_ambient_occlusion.h>
32#include <easy3d/renderer/camera.h>
33#include <easy3d/renderer/render_settings.h>
34#include <easy3d/renderer/drawable_triangles.h>
35#include <easy3d/renderer/renderer.h>
36#include <easy3d/renderer/state.h>
37#include <easy3d/util/logging.h>
38
39
40using namespace easy3d;
41
42// The implementation is reproduced on the example page via \include in main.cpp, so we hide
43// it from Doxygen's separate symbol documentation to avoid documenting it twice.
44// \cond
45
46TutorialAmbientOcclusion::TutorialAmbientOcclusion(const std::string &title) : Viewer(title) {
47 // Look from a viewpoint so the effect is better perceived
48 camera()->set_view_direction(vec3(-1, -1, -1));
49 baked_ = false;
50
51 // hint_ is shown in the viewer HUD; it tells the user which keys control the effect.
52 hint_ = "Press 'space' to switch on/off ambient occlusion\n"
53 "Press 'up/down' to increase/decrease the radius\n"
54 "Press 'b' to bake ambient occlusion into vertex colors";
55}
56
57void TutorialAmbientOcclusion::init() {
58 Viewer::init();
59
60 // Effects are declarative: the viewer applies these settings to every frame,
61 // including file snapshots. Start with AO visible so the depth cues are obvious.
62 RenderSettings settings;
63 settings.ambient_occlusion.enabled = true;
64 set_render_settings(settings);
65}
66
67// Interactive control of the effect. Returning true marks the key as handled; any key we do
68// not recognize is forwarded to the base Viewer so navigation and other shortcuts still work.
69bool TutorialAmbientOcclusion::key_press_event(int key, int modifiers) {
70 if (key == KEY_SPACE) {
71 // Replace the settings to toggle the effect; the viewer redraws the next frame.
72 RenderSettings settings = render_settings();
73 settings.ambient_occlusion.enabled = !settings.ambient_occlusion.enabled;
74 set_render_settings(settings);
75 update();
76 return true;
77 } else if (key == KEY_DOWN || key == KEY_UP) {
78 // Tune the sampling radius in the settings (finer with 'down', broader with 'up').
79 RenderSettings settings = render_settings();
80 if (settings.ambient_occlusion.enabled) {
81 const float delta = key == KEY_UP ? 0.01f : -0.01f;
82 settings.ambient_occlusion.radius_ratio = std::min(0.3f, std::max(
83 0.01f, settings.ambient_occlusion.radius_ratio + delta));
84 set_render_settings(settings);
85 std::cout << "radius ratio: " << settings.ambient_occlusion.radius_ratio << std::endl;
86 update();
87 }
88 return true;
89 } else if (key == KEY_B) {
90 // Bake ambient occlusion into vertex colors. The baked term is view independent:
91 // rotating the camera does not change it, which is what figures need. The
92 // screen-space effect is switched off while the baked term is shown.
93 auto mesh = dynamic_cast<SurfaceMesh *>(current_model());
94 if (!mesh) {
95 LOG(INFO) << "the current model is not a surface mesh";
96 return true;
97 }
98 auto drawable = mesh->renderer()->get_triangles_drawable("faces");
99 RenderSettings settings = render_settings();
100 if (!baked_) {
101 if (!mesh->is_triangle_mesh()) {
102 mesh->triangulate();
103 LOG(WARNING) << "input is not a triangle mesh (triangulated for baking AO)";
104 }
105
106 auto ao = SurfaceMeshAmbientOcclusion::bake(mesh);
107 SurfaceMeshAmbientOcclusion::colorize(mesh, ao, vec3(0.8f));
108 if (drawable) {
109 drawable->set_property_coloring(State::VERTEX, "v:ao_color");
110 drawable->update();
111 }
112 baked_ = true;
113 settings.ambient_occlusion.enabled = false;
114 } else {
115 if (drawable) {
116 drawable->set_uniform_coloring(vec4(1.0f, 1.0f, 1.0f, 1.0f));
117 drawable->update();
118 }
119 baked_ = false;
120 settings.ambient_occlusion.enabled = true;
121 LOG(INFO) << "removed the baked ambient occlusion";
122 }
123 set_render_settings(settings);
124 update();
125 return true;
126 } else
127 return Viewer::key_press_event(key, modifiers);
128}
129
130// \endcond
A halfedge data structure for polygonal meshes of 2-manifold topology.
Definition surface_mesh.h:51
Declarative effect settings shared by all rendering hosts.
Definition render_settings.h:80
See also
RenderSettings, Viewer, DrawableTriangles