Streaming data from a worker thread into a live viewer with a safe producer/consumer handoff.
This tutorial grows a point cloud while the viewer is running: a background worker thread generates batches of 100 random colored points every 300 ms, and the UI thread picks them up and appends them to the displayed cloud. It demonstrates the pattern every interactive application needs when computation and rendering run at different speeds — and the golden rule that makes it safe: only the UI thread ever touches scene or graphics state.
Graphics APIs (OpenGL contexts, Vulkan command submission) and Easy3D's scene structures are not thread-safe, so the classic mistake is letting a worker thread modify a model or drawable directly. The correct design is a producer/consumer pipeline: the worker (producer) computes plain CPU data — here immutable batches of positions and colors — and publishes them through a mutex-protected slot; the UI thread (consumer) takes a batch during its animation callback and applies it to the cloud, then refreshes the renderer so the new points appear. Ownership transfer via std::shared_ptr<const PointBatch> means no data is shared mutably: once published, a batch is read-only, and the consumer owns its copy. At most one batch may wait in the slot (backpressure): if the viewer is paused or minimized, the worker blocks instead of queueing unbounded data in memory. A condition_variable coordinates the handoff, and the worker's destructor signals shutdown and joins the thread before any viewer resource is destroyed — including when the user closes the window early.
The cloud starts with 100 red points and gains 100 randomly colored points every ~300 ms (66 batches total); the point count is printed to the console. Press F2 to pause/resume consumption — while paused the worker waits instead of producing more. When all batches are consumed the animation stops automatically.
27#include <easy3d/viewer/viewer.h>
28#include <easy3d/core/point_cloud.h>
29#include <easy3d/core/random.h>
30#include <easy3d/renderer/renderer.h>
31#include <easy3d/renderer/drawable_points.h>
32#include <easy3d/util/initializer.h>
33#include "point_worker.h"
89int main(
int argc,
char **argv) {
94 Viewer viewer(EXAMPLE_TITLE);
100 for (
int i = 0; i < 100; ++i) {
101 auto v = cloud->add_vertex(
easy3d::vec3(random_float(), random_float(), random_float()));
103 colors[v] =
vec3(1.0f, 0.0f, 0.0f);
106 viewer.add_model(std::shared_ptr<PointCloud>(cloud));
109 auto drawable = cloud->renderer()->get_points_drawable(
"vertices");
111 drawable->set_point_size(10.0f);
113 drawable->set_coloring(Drawable::COLOR_PROPERTY, Drawable::VERTEX,
"v:color");
119 PointBatchWorker worker;
122 if (!worker.wait_for_batch(std::chrono::seconds(5))) {
123 std::cerr <<
"point worker did not produce its first batch" << std::endl;
129 viewer.animation_func_ = [&](
Viewer *v) {
130 const auto batch = worker.take();
133 append_point_batch(*cloud, *batch);
135 std::cout <<
"#points: " << cloud->n_vertices() << std::endl;
138 if (worker.drained())
139 v->set_animation(
false);
142 viewer.set_animation(
true);
A data structure for point clouds.
Definition point_cloud.h:46
VertexProperty< T > add_vertex_property(const std::string &name, const T t=T())
Add a vertex property of type T with name name and default value t.
Definition point_cloud.h:489
The default viewer implementation for both OpenGL and Vulkan backends.
Definition viewer.h:143
Definition collider.cpp:182
28#ifndef EASY3D_TUTORIAL_POINT_WORKER_H
29#define EASY3D_TUTORIAL_POINT_WORKER_H
30#include <easy3d/core/types.h>
31#include <easy3d/core/point_cloud.h>
32#include <easy3d/renderer/renderer.h>
34#include <condition_variable>
51using PointBatch = std::vector<ColoredPoint>;
59 for (
const auto &point : batch)
60 colors[cloud.add_vertex(point.position)] = point.color;
76class PointBatchWorker {
81 explicit PointBatchWorker(
unsigned batches = 66,
82 std::chrono::milliseconds interval = std::chrono::milliseconds(300))
83 : batches_(batches), interval_(interval) {
84 if (interval.count() < 0)
85 throw std::invalid_argument(
"negative point batch interval");
86 thread_ = std::thread([
this] {
97 PointBatchWorker(
const PointBatchWorker &) =
delete;
98 PointBatchWorker &operator=(
const PointBatchWorker &) =
delete;
103 std::shared_ptr<const PointBatch> take() {
104 std::lock_guard<std::mutex> lock(mutex_);
107 std::rethrow_exception(error_);
108 auto result = std::move(pending_);
115 bool wait_for_batch(std::chrono::milliseconds timeout) {
116 std::unique_lock<std::mutex> lock(mutex_);
117 ready_.wait_for(lock, timeout, [
this] {
118 return pending_ || finished_ || stopping_ || error_;
121 std::rethrow_exception(error_);
122 return bool(pending_);
127 bool drained()
const {
128 std::lock_guard<std::mutex> lock(mutex_);
129 return finished_ && !pending_;
136 std::lock_guard<std::mutex> lock(mutex_);
141 if (thread_.joinable())
148 void produce() noexcept {
151 std::mt19937
random(0x312);
152 std::uniform_real_distribution<float> unit(0, 1);
153 for (
unsigned i = 0; i < batches_; ++i) {
157 std::unique_lock<std::mutex> lock(mutex_);
158 ready_.wait(lock, [
this] {
159 return stopping_ || !pending_;
165 auto batch = std::make_shared<PointBatch>();
167 for (
unsigned j = 0; j < 100; ++j) {
169 const float x = unit(random), y = unit(random), z = unit(random);
170 const float r = unit(random), g = unit(random), b = unit(random);
174 std::unique_lock<std::mutex> lock(mutex_);
177 pending_ = std::move(batch);
181 if (i + 1 < batches_ && ready_.wait_for(lock, interval_, [
this] {
188 std::lock_guard<std::mutex> lock(mutex_);
189 error_ = std::current_exception();
192 std::lock_guard<std::mutex> lock(mutex_);
199 std::chrono::milliseconds interval_;
200 mutable std::mutex mutex_;
201 std::condition_variable ready_;
202 std::shared_ptr<const PointBatch> pending_;
203 std::exception_ptr error_;
204 bool stopping_ =
false, finished_ =
false;
Renderer * renderer()
Definition model.cpp:66
VertexProperty< T > vertex_property(const std::string &name, const T t=T())
Gets or adds a vertex property of type T with name name.
Definition point_cloud.h:540
void update()
Invalidates the rendering buffers of the model and thus updates the rendering (delayed in rendering).
Definition renderer.cpp:322
Vec< 3, float > vec3
A 3D point/vector of float type.
Definition types.h:44
Matrix< FT > random(int row, int col)
Generate a matrix with all its elements randomly initialized in the range [0.0, 1....
Definition matrix.h:1540