File: test.cpp

package info (click to toggle)
mrpt 1%3A2.5.8%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 87,448 kB
  • sloc: cpp: 551,662; ansic: 38,702; xml: 3,914; python: 2,547; sh: 404; makefile: 237
file content (382 lines) | stat: -rw-r--r-- 9,633 bytes parent folder | download
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/* +------------------------------------------------------------------------+
   |                     Mobile Robot Programming Toolkit (MRPT)            |
   |                          https://www.mrpt.org/                         |
   |                                                                        |
   | Copyright (c) 2005-2023, Individual contributors, see AUTHORS file     |
   | See: https://www.mrpt.org/Authors - All rights reserved.               |
   | Released under BSD License. See: https://www.mrpt.org/License          |
   +------------------------------------------------------------------------+ */

#include <mrpt/containers/yaml.h>
#include <mrpt/core/lock_helper.h>
#include <mrpt/opengl/CAxis.h>
#include <mrpt/opengl/CFBORender.h>
#include <mrpt/opengl/CMesh.h>
#include <mrpt/opengl/COpenGLScene.h>
#include <mrpt/opengl/CPointCloud.h>
#include <mrpt/opengl/CSphere.h>
#include <mrpt/random.h>
#include <mrpt/system/CTimeLogger.h>
#include <mrpt/system/filesystem.h>
#include <mrpt/system/thread_name.h>

//#define USE_NANOGUI_WINDOW

#ifdef USE_NANOGUI_WINDOW
#include <mrpt/gui/CDisplayWindowGUI.h>
#else
#include <mrpt/gui/CDisplayWindow.h>
using my_window_t = mrpt::gui::CDisplayWindow;
#endif

#include <iostream>
#include <list>
#include <mutex>
#include <thread>

static const int RENDER_WIDTH = 600, RENDER_HEIGHT = 480;

auto& rng = mrpt::random::getRandomGenerator();
std::mutex rngMtx;

// sample scene:
static mrpt::opengl::COpenGLScene::Ptr generate_example_scene()
{
	auto s = mrpt::opengl::COpenGLScene::Create();

	{
		auto obj = mrpt::opengl::CAxis::Create(-5, -5, -5, 5, 5, 5);
		s->insert(obj);
	}
	{
		auto obj = mrpt::opengl::CSphere::Create(1.0f);
		obj->setColor_u8(0xff, 0x00, 0x00);
		obj->setLocation({1.0, 1.0, 1.0});
		s->insert(obj);
	}
	{
		auto obj = mrpt::opengl::CSphere::Create(0.25f);
		obj->setColor_u8(0x00, 0x00, 0xff);
		obj->setLocation({-1.0, -1.0, 0.25});
		obj->enableDrawSolid3D(false);
		s->insert(obj);
	}
	{
		auto obj = mrpt::opengl::CPointCloud::Create();

		auto lck = mrpt::lockHelper(rngMtx);
		for (int i = 0; i < 200; i++)
		{
			obj->insertPoint(
				rng.drawUniform(-3.0, 0.0), rng.drawUniform(-3.0, 0.0),
				rng.drawUniform(-3.0, 0.0));
		}
		obj->setPointSize(3.0f);
		s->insert(obj);
	}
	{
		using namespace std::string_literals;

		const std::string texture_file = mrpt::system::getShareMRPTDir() +
			"datasets/sample-texture-terrain.jpg"s;

		auto obj = mrpt::opengl::CMesh::Create();

		mrpt::img::CImage im;

		const int W = 128, H = 128;
		mrpt::math::CMatrixDynamic<float> Z(H, W);
		for (int r = 0; r < H; r++)
			for (int c = 0; c < W; c++)
				Z(r, c) = sin(0.05 * (c + r) - 0.5) * cos(0.9 - 0.03 * r);

		if (im.loadFromFile(texture_file))
		{
			obj->setZ(Z);
			obj->assignImageAndZ(im, Z);
			obj->setLocation(-5, 0, 0);
			obj->cullFaces(mrpt::opengl::TCullFace::BACK);
		}
		s->insert(obj);
	}

	return s;
}

mrpt::opengl::COpenGLScene::Ptr commonScene;
mrpt::system::CTimeLogger profiler;

struct RenderResult
{
	RenderResult() = default;

	std::string threadName;
	mrpt::img::CImage img;
	std::string labelText;
};

std::list<RenderResult> renderOutputs;
std::mutex renderOutputs_mtx;

static void renderer_thread_impl(
	const std::string name, const int period_ms, const int numImgs)
{
	using namespace std::string_literals;

	mrpt::system::thread_name(name);  // for debuggers

	mrpt::opengl::CFBORender::Parameters fboParams;
	fboParams.width = RENDER_WIDTH;
	fboParams.height = RENDER_HEIGHT;
	// fboParams.contextMajorVersion = 3;
	// fboParams.contextMinorVersion = 3;
	// fboParams.deviceIndexToUse = 0;
#ifdef _DEBUG
	fboParams.contextDebug = true;
#endif

	mrpt::opengl::CFBORender render(fboParams);
	mrpt::img::CImage frame(RENDER_WIDTH, RENDER_HEIGHT, mrpt::img::CH_RGB);

	// here you can put your preferred camera rendering position
	{
		auto& camera = render.getCamera(*commonScene);
		camera.setOrthogonal(false);

		auto lck = mrpt::lockHelper(rngMtx);
		camera.setZoomDistance(rng.drawUniform(15.0, 40.0));
		camera.setElevationDegrees(rng.drawUniform(20.0, 70.0));
		camera.setAzimuthDegrees(rng.drawUniform(-60.0, 60.0));

#if 0
		mrpt::containers::yaml d = mrpt::containers::yaml::Map();
		camera.toYAMLMap(d);
		std::cout << "Thread: " << name << "\nCamera:\n"
				  << d << "\n"
				  << std::endl;
#endif
	}

	const auto nameProfiler = name + "_render"s;

	for (int i = 0; i < numImgs; i++)
	{
		// render the scene
		if (i > 0) profiler.enter(nameProfiler);

		render.render_RGB(*commonScene, frame);

		if (i > 0) profiler.leave(nameProfiler);

		RenderResult res;
		res.img = frame.makeDeepCopy();
		res.labelText = mrpt::format("Img #%i", i);
		res.threadName = name;

		{
			auto lck = mrpt::lockHelper(renderOutputs_mtx);
			renderOutputs.emplace_back(std::move(res));
		}
		std::this_thread::sleep_for(std::chrono::milliseconds(period_ms));
	}
	std::cout << "\nRendering thread '" << name << "' ends." << std::endl;
}

static void renderer_thread(
	const std::string name, const int period_ms, const int numImgs)
{
	try
	{
		renderer_thread_impl(name, period_ms, numImgs);
	}
	catch (const std::exception& e)
	{
		std::cerr << "Thread '" << name << "' exception: " << e.what()
				  << std::endl;
	}
}

#ifndef USE_NANOGUI_WINDOW
// wxWidgets frontend:
static void viz_thread()
{
	const double MAX_TIME = 10.0;
	const double t0 = mrpt::Clock::nowDouble();

	std::map<std::string, my_window_t::Ptr> wins;

	double t = 0;

	while ((t = mrpt::Clock::nowDouble() - t0) < MAX_TIME)
	{
		std::list<RenderResult> done;
		{
			auto lck = mrpt::lockHelper(renderOutputs_mtx);
			std::swap(done, renderOutputs);
		}

		for (auto& r : done)
		{
			auto& win = wins[r.threadName];
			if (!win)
			{
				// first time:
				win = my_window_t::Create(
					r.threadName, r.img.getWidth(), r.img.getHeight());
			}

			// update image:
			r.img.textOut(5, 5, r.labelText, mrpt::img::TColor::white());
			win->showImage(r.img);
		}

		std::this_thread::sleep_for(std::chrono::milliseconds(1));

		std::cout << "Showing images from working threads... " << t << "/"
				  << MAX_TIME << "  \r";
	};

	std::cout << "\nVisualization thread ends." << std::endl;
}
#elif MRPT_HAS_NANOGUI
// nanogui frontend
static void viz_thread()
{
	try
	{
		mrpt::system::thread_name("viz");  // for debuggers

		nanogui::init();

		auto win = mrpt::gui::CDisplayWindowGUI::Create("main", 800, 600);

		win->performLayout();
		win->drawAll();
		win->setVisible(true);

#if 1
		win->background_scene_mtx.lock();
		win->background_scene = commonScene;
		win->background_scene_mtx.unlock();
#endif

		struct SubWindowData
		{
			SubWindowData() = default;

			nanogui::Window* win = nullptr;
			mrpt::gui::MRPT2NanoguiGLCanvas* glControl = nullptr;
			nanogui::Label* label = nullptr;
		};

		std::map<std::string, SubWindowData> subWindows;

		win->addLoopCallback([&]() {
			std::list<RenderResult> done;
			{
				auto lck = mrpt::lockHelper(renderOutputs_mtx);
				std::swap(done, renderOutputs);
			}
			if (done.empty()) return;

			for (auto& r : done)
			{
				auto& sw = subWindows[r.threadName];
				if (!sw.win)
				{
					// Add subwindow:
					sw.win = new nanogui::Window(win.get(), r.threadName);
					sw.win->setLayout(new nanogui::GroupLayout());

					sw.label = sw.win->add<nanogui::Label>("label");

					sw.glControl =
						sw.win->add<mrpt::gui::MRPT2NanoguiGLCanvas>();
					sw.win->setPosition(
						{5 + 100 * (subWindows.size() - 1), 10});
					sw.win->setFixedWidth(350);
					{
						auto scene = mrpt::opengl::COpenGLScene::Create();
						auto lck = mrpt::lockHelper(sw.glControl->scene_mtx);
						sw.glControl->scene = std::move(scene);
					}
					win->performLayout();
				}

				{
					auto lck = mrpt::lockHelper(sw.glControl->scene_mtx);
					sw.glControl->scene->getViewport()->setImageView(
						std::move(r.img));
				}
				sw.label->setCaption(r.labelText);
			}
		});

		nanogui::mainloop();
		nanogui::shutdown();

		std::cout << "\nVisualization thread ends." << std::endl;
	}
	catch (const std::exception& e)
	{
		std::cerr << "[viz_thread] Error:\n" << e.what() << std::endl;
	}
}
#endif

// ------------------------------------------------------
//				TestMultithreadRendering
// ------------------------------------------------------
static int TestOffscreenRender()
{
	commonScene = generate_example_scene();

	std::vector<std::thread> allThreads;

#ifdef USE_NANOGUI_WINDOW
	{
		// ==================================================================
		//                         ** CRITICAL **
		// Create dummy FBO Renderer to init GL as required by FBOs *before*
		// nanogui initializes it. Otherwise, GL context errors will be
		// raised by FBOs later on.
		// ==================================================================
		mrpt::opengl::CFBORender render(10, 10);
	}
#endif

	allThreads.emplace_back(&viz_thread);
	std::this_thread::sleep_for(std::chrono::milliseconds(1000));

	allThreads.emplace_back(
		&renderer_thread, "one", 5 /*period*/, 600 /*nImgs*/);

	allThreads.emplace_back(
		&renderer_thread, "two", 6 /*period*/, 700 /*nImgs*/);

	for (auto& t : allThreads)
		if (t.joinable()) t.join();

	return 0;
}

// ------------------------------------------------------
//						MAIN
// ------------------------------------------------------
int main(int argc, char* argv[])
{
	try
	{
#if MRPT_HAS_NANOGUI
		return TestOffscreenRender();
#else
		std::cerr << "This example requires MRPT built with NANOGUI.\n";
		return 1;
#endif
	}
	catch (const std::exception& e)
	{
		std::cerr << "MRPT error: " << mrpt::exception_to_str(e) << std::endl;
		return -1;
	}
}