MeshLib C++ Docs
Loading...
Searching...
No Matches
MRViewport.h
Go to the documentation of this file.
1#pragma once
2
3#include "MRViewportGL.h"
4#include "MRFitData.h"
6#include <MRMesh/MRVector3.h>
7#include <MRMesh/MRPlane3.h>
10#include <MRMesh/MRQuaternion.h>
11#include <MRMesh/MRMatrix4.h>
12#include <MRMesh/MRColor.h>
13#include <MRMesh/MRBox.h>
14#include "MRImGui.h"
15#include <memory>
16#include <functional>
17#include <unordered_map>
18#include <optional>
19#include <span>
20
21namespace MR
22{
23
24inline ImVec2 position( const ViewportRectangle& rect )
25{
26 return { rect.min.x, rect.min.y };
27}
28
29inline ImVec2 size( const ViewportRectangle& rect )
30{
31 return { width( rect ), height( rect ) };
32}
33
34// Conversion to Vector4 type, where:
35// x, y: min.x and min.y
36// z, w: width and height
37template<typename T>
38inline Vector4<T> toVec4( const ViewportRectangle& rect )
39{
40 return Vector4<T>{T( rect.min.x ), T( rect.min.y ), T( MR::width( rect ) ), T( MR::height( rect ) )};
41}
42
43// Viewport is a rectangular area, in which the objects of interest are going to be rendered.
44// An application can have a number of viewports each with its own ID.
46{
47public:
49
52 MRVIEWER_API static Viewport& get( ViewportId viewportId = {} );
53
54 MRVIEWER_API Viewport();
55 MRVIEWER_API ~Viewport();
56
57private: //hide copying from the user to avoid silly mistakes (copies are necessary only inside this project)
58 Viewport( const Viewport & ) = default;
59 Viewport & operator = ( const Viewport & ) = default;
60public:
61 [[nodiscard]] Viewport clone() const { return Viewport( *this ); }
62 Viewport( Viewport && ) noexcept = default;
63 Viewport & operator = ( Viewport && ) noexcept = default;
64
65 // Initialization
66 MRVIEWER_API void init();
67
68 // positive pixelXoffset -> offset from the left border
69 // negative pixelXoffset -> offset from the right border
70 // positive pixelYoffset -> offset from the top border
71 // negative pixelYoffset -> offset from the bottom border
72 // axisPixSize -> length of each axes arrows in pixels
73 // For example: default values -> right bottom corner with 100 offsets for the base point and 80 pixels each axis length
74 MRVIEWER_API void setAxesPos( const int pixelXoffset = -100, const int pixelYoffset = -100 );
75 MRVIEWER_API void setAxesSize( const int axisPixSize = 80 );
76
78 MRVIEWER_API const Vector2f& getAxesPosition() const;
79 MRVIEWER_API float getAxesSize() const;
80
82 [[deprecated("Use (draw/getBaseRenderParams/getModelRenderParams)OrthoFixedPos functions instead of using this value")]]
83 const Matrix4f& getAxesProjectionMatrix() const { return axesProjMat_; }
84
85 // Shutdown
86 MRVIEWER_API void shut();
87
88 // ------------------- Drawing functions
89
90 // Clear the frame buffers
91 MRVIEWER_API void clearFramebuffers();
92
94 MRVIEWER_API void recursiveDraw( const Object& obj,
95 DepthFunction depthFunc = DepthFunction::Default, const AffineXf3f& rootXf = {}, RenderModelPassMask renderType = RenderModelPassMask::All,
96 const TransparencyMode& transparentMode = {}, int* numDraws = nullptr ) const;
97
100 MRVIEWER_API bool draw( const VisualObject& obj,
101 DepthFunction depthFunc = DepthFunction::Default, RenderModelPassMask pass = RenderModelPassMask::All, const TransparencyMode& transparentMode = {} ) const;
102
105 MRVIEWER_API bool draw( const VisualObject& obj, const AffineXf3f& xf,
106 DepthFunction depthFunc = DepthFunction::Default, RenderModelPassMask pass = RenderModelPassMask::All, const TransparencyMode& transparentMode = {} ) const;
107
110 MRVIEWER_API bool draw( const VisualObject& obj, const AffineXf3f& xf, const Matrix4f & projM,
111 DepthFunction depthFunc = DepthFunction::Default, RenderModelPassMask pass = RenderModelPassMask::All, const TransparencyMode& transparentMode = {} ) const;
112
115 MRVIEWER_API bool drawOrthoFixedPos( const VisualObject& obj, const AffineXf3f& xf,
116 DepthFunction depthFunc = DepthFunction::Default, RenderModelPassMask pass = RenderModelPassMask::All, const TransparencyMode& transparentMode = {} ) const;
117
120 {
121 float width{1.0f};
122 bool depthTest{ true };
123 };
124
126 MRVIEWER_API void drawLines( const std::vector<LineSegm3f>& lines, const std::vector<SegmEndColors>& colors, const LinePointImmediateRenderParams & params );
127 void drawLines( const std::vector<LineSegm3f>& lines, const std::vector<SegmEndColors>& colors, float width = 1, bool depthTest = true )
128 { drawLines( lines, colors, { getBaseRenderParams(), width, depthTest } ); }
129
131 MRVIEWER_API void drawPoints( const std::vector<Vector3f>& points, const std::vector<Vector4f>& colors, const LinePointImmediateRenderParams & params );
132 void drawPoints( const std::vector<Vector3f>& points, const std::vector<Vector4f>& colors, float width = 1, bool depthTest = true )
133 { drawPoints( points, colors, { getBaseRenderParams(), width, depthTest } ); }
134
136 {
137 Vector4f a, b, c;
138 };
139
141 MRVIEWER_API void drawTris( const std::vector<Triangle3f>& tris, const std::vector<TriCornerColors>& colors, const ModelRenderParams& params, bool depthTest = true );
142 MRVIEWER_API void drawTris( const std::vector<Triangle3f>& tris, const std::vector<TriCornerColors>& colors, const Matrix4f& modelM = {}, bool depthTest = true );
143
145 [[nodiscard]] BaseRenderParams getBaseRenderParams() const { return getBaseRenderParams( projM_ ); }
146
148 [[nodiscard]] BaseRenderParams getBaseRenderParams( const Matrix4f & projM ) const
149 { return { viewM_, projM, id, toVec4<int>( viewportRect_ ) }; }
150
153 { return { axesViewMat_, axesProjMat_, id, toVec4<int>( viewportRect_ ) }; }
154
157 const Matrix4f & modelM,
158 Matrix4f * normM,
161 const TransparencyMode& transparentMode = {}
162 ) const
163 { return getModelRenderParams( modelM, getBaseRenderParams(projM_), normM, depthFunc, pass, transparentMode ); }
164
167 const Matrix4f & modelM,
168 Matrix4f * normM,
171 const TransparencyMode& transparentMode = {}
172 ) const
173 { return getModelRenderParams( modelM, getBaseRenderParamsOrthoFixedPos(), normM, depthFunc, pass, transparentMode ); }
174
176 [[nodiscard]] MRVIEWER_API ModelRenderParams getModelRenderParams( const Matrix4f & modelM, const BaseRenderParams& baseParams,
177 Matrix4f * normM,
180 const TransparencyMode& transparentMode = {}
181 ) const;
182
183 // Predicate to additionally filter objects that should be treated as pickable.
184 using PickRenderObjectPredicate = std::function<bool ( const VisualObject*, ViewportMask )>;
185 // Point picking parameters.
187 {
188 // If specified, this is the target screen point. Otherwise use the mouse pos in viewport coordinates.
189 std::optional<Vector2f> point;
190
191 // Predicate to additionally filter objects that should be treated as pickable.
193
194 // Radius (in pixels) of a picking area.
195 // <0 defaults to `getViewerInstance().glPickRadius`.
196 int pickRadius = -1;
197 // Usually, from several objects that fall into the peak, the closest one along the ray is selected. However,
198 // if exactPickFirst = true, then the object in which the pick exactly fell (for example, a point in point cloud)
199 // will be returned as the result, even if there are others within the radius, including closer objects.
200 bool exactPickFirst = true;
201
202 // if not nullptr it can override render params for picker
204
205 // This will always return `{}`. We need the functions because `= {}`
206 // can't be used directly inside default arguments in the same class.
207 // You don't have to use this function.
209 {
210 return {};
211 }
212 };
213 // This function allows to pick point in scene by GL with given parameters.
214 // This overload uses all objects in the scene (possibly filtered by a predicate).
216 // This overload uses objects from the list (possibly filtered by a predicate).
217 MRVIEWER_API ObjAndPick pickRenderObject( std::span<VisualObject* const> objects, const PickRenderObjectParams& params = PickRenderObjectParams::defaults() ) const;
218 // This overload uses const objects from the list (possibly filtered by a predicate). Sadly need a different name to avoid over resolution issues.
219 MRVIEWER_API ConstObjAndPick pickRenderObjectConst( std::span<const VisualObject* const> objects, const PickRenderObjectParams& params = PickRenderObjectParams::defaults() ) const;
220
221 // This function allows to pick point in scene by GL
222 // use default pick radius
223 // comfortable usage:
224 // auto [obj,pick] = pick_render_object();
225 // pick all visible and pickable objects
226 // picks objects from current mouse pose by default
227 // [[deprecated("Use `pickRenderObject()`")]] // Should eventually deprecate this?
228 MRVIEWER_API ObjAndPick pick_render_object() const;
229 [[deprecated("Use `pickRenderObject()`")]]
230 MRVIEWER_API ObjAndPick pick_render_object( uint16_t pickRadius ) const;
231 // This function allows to pick point in scene by GL
232 // use default pick radius
233 // comfortable usage:
234 // auto [obj,pick] = pick_render_object( objects );
235 // pick objects from input
236 [[deprecated("Use `pickRenderObject( objects } )`")]] // NOTE! If your list is hardcoded, use `.objects = std::array{ a, b, c }`.
237 MRVIEWER_API ObjAndPick pick_render_object( const std::vector<VisualObject*>& objects ) const;
238 // This function allows to pick point in scene by GL with a given peak radius.
239 // usually, from several objects that fall into the peak, the closest one along the ray is selected.However
240 // if exactPickFirst = true, then the object in which the pick exactly fell( for example, a point in point cloud )
241 // will be returned as the result, even if there are others within the radius, including closer objects.
242 [[deprecated("Use `pickRenderObject( ... )`")]]
243 MRVIEWER_API ObjAndPick pick_render_object( const std::vector<VisualObject*>& objects, uint16_t pickRadius, bool exactPickFirst = true ) const;
244 // This function allows to pick point in scene by GL with default pick radius, but with specified exactPickFirst parameter (see description upper).
245 [[deprecated("Use `pickRenderObject( { .exactPickFirst = ... } )`")]]
246 MRVIEWER_API ObjAndPick pick_render_object( bool exactPickFirst ) const;
247 // This function allows to pick point in scene by GL
248 // comfortable usage:
249 // auto [obj,pick] = pick_render_object( objects );
250 // pick all visible and pickable objects
251 // picks objects from custom viewport point
252 [[deprecated("Use `pickRenderObject( { .point = ... } )`")]]
253 MRVIEWER_API ObjAndPick pick_render_object( const Vector2f& viewportPoint ) const;
254 // This function allows to pick point in scene by GL
255 // comfortable usage:
256 // auto [obj,pick] = pick_render_object( objects );
257 // picks objects from custom viewport point
258 [[deprecated("Use `multiPickObjects( objects, { .point = ... } )`")]]
259 MRVIEWER_API ObjAndPick pick_render_object( const std::vector<VisualObject*>& objects, const Vector2f& viewportPoint ) const;
260
261 // This function allows to pick several custom viewport space points by GL
262 // returns vector of pairs [obj,pick]
263 // To hardcode the list of `objects`, use `{{ a, b, c }}`.
264 MRVIEWER_API std::vector<ObjAndPick> multiPickObjects( std::span<VisualObject* const> objects, const std::vector<Vector2f>& viewportPoints, const BaseRenderParams* overrideRenderParams = nullptr ) const;
265
266 // This function finds all visible objects in given rect (max excluded) in viewport space,
267 // maxRenderResolutionSide - this parameter limits render resolution to improve performance
268 // if it is too small, little objects can be lost
269 // viewport space: X [0,viewport_width], Y [0,viewport_height] - (0,0) is upper left of viewport
270 MRVIEWER_API std::vector<std::shared_ptr<VisualObject>> findObjectsInRect( const Box2i& rect,
271 int maxRenderResolutionSide = 512 ) const;
272
273 // This functions finds all visible faces in given includePixBs in viewport space,
274 // maxRenderResolutionSide - this parameter limits render resolution to improve performance
275 // if it is too small, little faces can be lost
276 // viewport space: X [0,viewport_width], Y [0,viewport_height] - (0,0) is upper left of viewport
277 MRVIEWER_API std::unordered_map<std::shared_ptr<ObjectMesh>, FaceBitSet> findVisibleFaces( const BitSet& includePixBs,
278 int maxRenderResolutionSide = 512 ) const;
279
281 [[nodiscard]] MRVIEWER_API FaceBitSet findCameraLookingFaces( const Mesh& mesh, const AffineXf3f& meshToWorld ) const;
282
283
284 // This function allows to pick point in scene by GL
285 // comfortable usage:
286 // const auto [obj,pick] = pick_render_object();
287 // pick all visible and pickable objects
288 // picks objects from current mouse pose by default
289 [[deprecated("Use `pickRenderObject()`.")]]
291 // This function allows to pick point in scene by GL
292 // comfortable usage:
293 // const auto [obj,pick] = pick_render_object( objects );
294 // pick objects from input
295 [[deprecated("Use `pickRenderObject( objects )`.")]]
296 MRVIEWER_API ConstObjAndPick const_pick_render_object( const std::vector<const VisualObject*>& objects ) const;
297 // This function allows to pick several custom viewport space points by GL
298 // returns vector of pairs [obj,pick]
299 MRVIEWER_API std::vector<ConstObjAndPick> constMultiPickObjects( const std::vector<const VisualObject*>& objects, const std::vector<Vector2f>& viewportPoints ) const;
300
301 // multiplies view-matrix on given transformation from the _right_;
302 // so if you at the same time multiplies model transformation from the _left_ on xf.inverse()
303 // and call transformView( xf ), then the user will see exactly the same picture
304 MRVIEWER_API void transformView( const AffineXf3f & xf );
305
306 bool getRedrawFlag() const { return needRedraw_; }
307 void resetRedrawFlag() { needRedraw_ = false; }
308
309 // Unique identifier
311
313 {
314 Color backgroundColor = Color( Vector3f{0.3f, 0.3f, 0.5f} );
315 Vector3f lightPosition{0.0f, 0.3f, 0.0f};// x y z - position, w - factor
316
319 float cameraZoom{1.0f};
320 float cameraViewAngle{45.0f};
321 float cameraDnear{1.0f};
322 float cameraDfar{100.0f};
323
324 bool depthTest{true};
325 bool orthographic{true};
326
328 {
329 Auto, // uses current scene size
330 Fixed // uses global basis object internal size (one can change it with globalBasisAxes->setXf( AffineXf3f::linear( Matrix3f::scale( size ) ) ) )
331 } globalBasisScaleMode{ GlobalBasisScaleMode::Auto };
332
333 // Caches the two-norm between the min/max point of the bounding box
334 float objectScale{1.0f};
335
337
338 std::string label;
339
340 Plane3f clippingPlane{Vector3f::plusX(), 0.0f};
341
343 {
344 Static, // scene is always rotated around its center or another manually set point
345 DynamicStatic, // scene is rotated around picked point on object, or around center, if miss pick
346 Dynamic // scene is rotated around picked point on object, or around last rotation pivot, if miss pick
348
349 // in Static RotationMode, this world space point is used as rotation pivot
350 // if it is not set, scene box center is used instead
351 std::optional<Vector3f> staticRotationPivot;
352
353 // if it is true, while rotation is enabled camera can be moved along forward axis
354 // in order to keep constant distance to scene center
355 bool compensateRotation{ true };
356
357 // this flag allows viewport to be selected by user
358 bool selectable{true};
359
360 bool operator==( const Viewport::Parameters& other ) const = default;
361 };
362
363 // Starts or stop rotation
364 MRVIEWER_API void setRotation( bool state );
365
366 // Note, Y is up for this box.
367 MRVIEWER_API const ViewportRectangle& getViewportRect() const;
368
369 // Finds length between near pixels on zNear plane. Only good in the orthographic projection.
370 MRVIEWER_API float getPixelSize() const;
371
372 // Finds the pixel scale at a specific world point. This works in both perspective and orthographic projection.
373 // The UI scale is NOT baked into this. You have to multiply by the scale manually if you need that.
374 MRVIEWER_API float getPixelSizeAtPoint( const Vector3f& worldPoint ) const;
375
376 // Sets position and size of viewport:
377 // rect is given as OpenGL coordinates: (0,0) is lower left corner
378 MRVIEWER_API void setViewportRect( const ViewportRectangle& rect );
379
380private:
381 // Save the OpenGL transformation matrices used for the previous rendering pass
382 Matrix4f viewM_;
383 Matrix4f projM_;
384
385public:
387 [[nodiscard]] MRVIEWER_API AffineXf3f getUnscaledViewXf() const;
388
390 [[nodiscard]] AffineXf3f getViewXf() const { return AffineXf3f( viewM_ ); }
391
393 [[nodiscard]] Vector3f getUpDirection() const { return Vector3f( viewM_.y.x, viewM_.y.y, viewM_.y.z ).normalized(); } // assume that viewM is orthogonal and inverse=transpose
394
396 [[nodiscard]] Vector3f getRightDirection() const { return Vector3f( viewM_.x.x, viewM_.x.y, viewM_.x.z ).normalized(); } // assume that viewM is orthogonal and inverse=transpose
397
399 [[nodiscard]] Vector3f getBackwardDirection() const { return Vector3f( viewM_.z.x, viewM_.z.y, viewM_.z.z ).normalized(); } // assume that viewM is orthogonal and inverse=transpose
400
401 // returns the line from Dnear to Dfar planes for the current pixel
402 // viewport space: X [0,viewport_width], Y [0,viewport_height] - (0,0) is upper left of viewport
403 // Z [0.f,1.f] - 0.f is Dnear, 1.f is Dfar
404 MRVIEWER_API Line3f unprojectPixelRay( const Vector2f& viewportPoint ) const;
405
406 // convert point(s) to camera space by applying view matrix
407 MRVIEWER_API Vector3f worldToCameraSpace( const Vector3f& p ) const;
408 MRVIEWER_API std::vector<Vector3f> worldToCameraSpace( const std::vector<Vector3f>& p ) const;
409
410 // projects point(s) to clip space. (rather, to normalized device coordinates, as it includes perspective division)
411 // clip space: XYZ [-1.f, 1.f], X axis from left(-1.f) to right(1.f), Y axis from bottom(-1.f) to top(1.f),
412 // Z axis from Dnear(-1.f) to Dfar(1.f)
413 MRVIEWER_API Vector3f projectToClipSpace( const Vector3f& worldPoint ) const;
414 MRVIEWER_API std::vector<Vector3f> projectToClipSpace( const std::vector<Vector3f>& worldPoints ) const;
415 MRVIEWER_API Vector3f unprojectFromClipSpace( const Vector3f& clipPoint ) const;
416 MRVIEWER_API std::vector<Vector3f> unprojectFromClipSpace( const std::vector<Vector3f>& clipPoints ) const;
417
418 // project point and convert coordinates to viewport space
419 // viewport space: X [0,viewport_width], Y [0,viewport_height] - (0,0) is upper left of viewport
420 // Z [0.f,1.f] - 0.f is Dnear, 1.f is Dfar
421 MRVIEWER_API Vector3f projectToViewportSpace( const Vector3f& worldPoint ) const;
422 MRVIEWER_API std::vector<Vector3f> projectToViewportSpace( const std::vector<Vector3f>& worldPoints ) const;
423 // unproject coordinates from viewport space
424 // viewport space: X [0,viewport_width], Y [0,viewport_height] - (0,0) is upper left of viewport
425 // Z [0.f,1.f] - 0.f is Dnear, 1.f is Dfar
426 MRVIEWER_API Vector3f unprojectFromViewportSpace( const Vector3f& viewportPoint ) const;
427 MRVIEWER_API std::vector<Vector3f> unprojectFromViewportSpace( const std::vector<Vector3f>& viewportPoints ) const;
428
429 // conversations between clip space and viewport space
430 // clip space: XYZ [-1.f, 1.f], X axis from left(-1.f) to right(1.f), Y axis from bottom(-1.f) to top(1.f),
431 // Z axis from Dnear(-1.f) to Dfar(1.f)
432 // viewport space: X [0,viewport_width], Y [0,viewport_height] - (0,0) is upper left of viewport
433 // Z [0.f,1.f] - 0.f is Dnear, 1.f is Dfar
434 MRVIEWER_API Vector3f clipSpaceToViewportSpace( const Vector3f& p ) const;
435 MRVIEWER_API std::vector<Vector3f> clipSpaceToViewportSpace( const std::vector<Vector3f>& p ) const;
436 MRVIEWER_API Vector3f viewportSpaceToClipSpace( const Vector3f& p ) const;
437 MRVIEWER_API std::vector<Vector3f> viewportSpaceToClipSpace( const std::vector<Vector3f>& p ) const;
438
439 // updates view and projection matrices due to camera parameters (called each frame)
440 void setupView();
441 // draws viewport primitives:
442 // lines: if depth test is on
443 // points: if depth test is on
444 // rotation center
445 // global basis
446 void preDraw();
447 // draws viewport primitives:
448 // lines: if depth test is off
449 // points: if depth test is off
450 // viewport border
451 // overlay basis
452 void postDraw() const;
453
454 // fit camera to the scene box (note: scene box does not include ancillary objects)
455 // fill = 1.0 parameter means that scene will be approximately 0.5 of screen
456 // snapView - to snap camera angle to closest canonical quaternion
457 MRVIEWER_API void fitData( float fill = 1.0f, bool snapView = true );
458
459 // set scene box by given one and fit camera to it
460 // fill = 1.0 parameter means that box diagonal will be approximately 0.5 of the viewport
461 // snapView - to snap camera angle to closest canonical quaternion
462 MRVIEWER_API void fitBox( const Box3f& newSceneBox, float fill = 1.0f, bool snapView = true );
463
468
469 // fit view and proj matrices to match the screen size with given box
470 MRVIEWER_API void preciseFitBoxToScreenBorder( const FitBoxParams& params );
471 // fit view and proj matrices to match the screen size with given objects
472 MRVIEWER_API void preciseFitDataToScreenBorder( const FitDataParams& params = {} );
473
474 // returns viewport width/height ratio
475 MRVIEWER_API float getRatio() const;
476
477 // returns true if all models are fully projected inside the viewport rectangle
478 MRVIEWER_API bool allModelsInsideViewportRectangle() const;
479
480 MRVIEWER_API const Box3f& getSceneBox() const;
481
482 const Parameters& getParameters() const { return params_; }
483
484 // returns camera world location for the current view
485 MRVIEWER_API Vector3f getCameraPoint() const;
486 // sets camera world location for the current view
487 MRVIEWER_API void setCameraPoint( const Vector3f& cameraWorldPos );
488
489 MRVIEWER_API void setCameraTrackballAngle( const Quaternionf& rot );
490
491 MRVIEWER_API void setCameraTranslation( const Vector3f& translation );
492
493 MRVIEWER_API void setCameraViewAngle( float newViewAngle );
494
495 MRVIEWER_API void setCameraZoom( float zoom );
496
497 MRVIEWER_API void setOrthographic( bool orthographic );
498
499 MRVIEWER_API void setBackgroundColor( const Color& color );
500
501 MRVIEWER_API void setClippingPlane( const Plane3f& plane );
502
503 MRVIEWER_API void setLabel( std::string s );
504
505 void setSelectable( bool on ) { params_.selectable = on; }
506
507 MRVIEWER_API void showAxes( bool on );
508 MRVIEWER_API void showClippingPlane( bool on );
509 MRVIEWER_API void showRotationCenter( bool on );
510 MRVIEWER_API void showGlobalBasis( bool on );
512
513 MRVIEWER_API void setParameters( const Viewport::Parameters& params );
514
515 // Set camera look direction and up direction (they should be perpendicular)
516 // this function changes camera position and do not change camera spot (0,0,0) by default
517 // to change camera position use setCameraTranslation after this function
518 MRVIEWER_API void cameraLookAlong( const Vector3f& dir, const Vector3f& up );
519
520 // Rotates camera around axis +direction applied to axis point
521 // note: this can make camera clip objects (as far as distance to scene center is not fixed)
522 MRVIEWER_API void cameraRotateAround( const Line3f& axis, float angle );
523
525 Vector3f getRotationPivot() const { return rotationPivot_; }
526
531 MRVIEWER_API void resetStaticRotationPivot( const std::optional<Vector3f>& pivot = std::nullopt );
532private:
535 void setRotationPivot_( const Vector3f& point ) { rotationPivot_ = point; }
536 // initializes view matrix based on camera position
537 void setupViewMatrix_();
538 // returns world space to camera space transformation
539 AffineXf3f getViewXf_() const;
540
541 // initializes proj matrix based on camera angle and viewport rectangle size
542 void setupProjMatrix_();
543 // initializes view and proj matrix for static view objects (like corner axes)
544 void setupAxesViewProjMatrix_();
545
546 // use this matrix to convert world 3d point to clip point
547 // clip space: XYZ [-1.f, 1.f], X axis from left(-1.f) to right(1.f), X axis from bottom(-1.f) to top(1.f),
548 // Z axis from Dnear(-1.f) to Dfar(1.f)
549 Matrix4f getFullViewportMatrix() const { return projM_ * viewM_; }
550 Matrix4f getFullViewportInversedMatrix() const;
551
552 ViewportRectangle viewportRect_;
553
554 ViewportGL viewportGL_;
555
556 bool previewLinesDepthTest_ = false;
557 bool previewPointsDepthTest_ = false;
558
559 void draw_border() const;
560 void draw_rotation_center() const;
561 void draw_clipping_plane() const;
562 void drawGlobalBasis() const;
563
564 // init basis axis in the corner
565 void initBaseAxes();
566 // Drawing basis axes and view controller cube in the corner
567 void drawAxesAndViewController() const;
568
569 // This matrix should be used for a static objects
570 // For example, basis axes in the corner
571 Matrix4f axesViewMat_;
572 Matrix4f axesProjMat_;
573 Vector2f basisAxesPos_;
574 float basisAxesSize_;
575
576 // basis axis params
577 int pixelXoffset_{ -100 };
578 int pixelYoffset_{ -128 };
579 int axisPixSize_{ 70 };
580
581 void updateSceneBox_();
582 void rotateView_();
583
584 enum class Space
585 {
586 World, // (x, y, z) in world space
587 CameraOrthographic, // (x, y, z) in camera space
588 CameraPerspective // (x/z, y/z, z), where (x, y, z) in camera space
589 };
590
595 Box3f calcBox_( const std::vector<std::shared_ptr<VisualObject>>& objs, Space space, bool selectedPrimitives = false ) const;
596
604 std::pair<float, bool> getZoomFOVtoScreen_( std::function<Box3f()> getBoxFn, Vector3f* cameraShift = nullptr ) const;
605 // fit view and proj matrices to match the screen size with boxes returned by getBoxFn
606 // getBoxFn( true ) - always camera space (respecting projection)
607 // getBoxFn( false ) - if orthographic - camera space, otherwise - world space
608 // getBoxFn/globalBasis - if true then getBoxFn should return box of global basis object (separately, not to interfere with actual scene size)
609 void preciseFitToScreenBorder_( std::function<Box3f( bool zoomFOV, bool globalBasis )> getBoxFn, const BaseFitParams& params );
610
611 bool rotation_{ false };
612 Vector3f rotationPivot_;
613 Vector3f static_point_;
614 Vector2f static_viewport_point;
615 float distToSceneCenter_;
616
617 bool needRedraw_{false};
618
619 // world bounding box of scene objects visible in this viewport
620 Box3f sceneBox_;
621
622 Parameters params_;
623};
624
625} //namespace MR
Definition MRMesh/MRBitSet.h:24
named object in the data model
Definition MRObject.h:62
Definition MRViewportId.h:16
stores mask of viewport unique identifiers
Definition MRViewportId.h:42
Definition MRViewport.h:46
MRVIEWER_API Vector3f projectToClipSpace(const Vector3f &worldPoint) const
MRVIEWER_API bool draw(const VisualObject &obj, const AffineXf3f &xf, const Matrix4f &projM, DepthFunction depthFunc=DepthFunction::Default, RenderModelPassMask pass=RenderModelPassMask::All, const TransparencyMode &transparentMode={}) const
MRVIEWER_API void showRotationCenter(bool on)
MRVIEWER_API ConstObjAndPick const_pick_render_object() const
MRVIEWER_API Vector3f projectToViewportSpace(const Vector3f &worldPoint) const
MRVIEWER_API void setCameraViewAngle(float newViewAngle)
MRVIEWER_API void setCameraZoom(float zoom)
MRVIEWER_API ObjAndPick pick_render_object(const std::vector< VisualObject * > &objects, uint16_t pickRadius, bool exactPickFirst=true) const
MRVIEWER_API void shut()
MR::BaseFitParams BaseFitParams
Definition MRViewport.h:465
MRVIEWER_API float getAxesSize() const
MRVIEWER_API ObjAndPick pick_render_object(const std::vector< VisualObject * > &objects, const Vector2f &viewportPoint) const
Vector3f getRightDirection() const
returns unit vector in world space corresponding to right-direction in camera space
Definition MRViewport.h:396
MRVIEWER_API ~Viewport()
MRVIEWER_API std::vector< Vector3f > unprojectFromViewportSpace(const std::vector< Vector3f > &viewportPoints) const
MRVIEWER_API bool drawOrthoFixedPos(const VisualObject &obj, const AffineXf3f &xf, DepthFunction depthFunc=DepthFunction::Default, RenderModelPassMask pass=RenderModelPassMask::All, const TransparencyMode &transparentMode={}) const
MRVIEWER_API void cameraLookAlong(const Vector3f &dir, const Vector3f &up)
MRVIEWER_API Vector3f unprojectFromClipSpace(const Vector3f &clipPoint) const
MRVIEWER_API ObjAndPick pick_render_object(uint16_t pickRadius) const
MRVIEWER_API ConstObjAndPick pickRenderObjectConst(std::span< const VisualObject *const > objects, const PickRenderObjectParams &params=PickRenderObjectParams::defaults()) const
MRVIEWER_API void showGlobalBasis(bool on)
std::function< bool(const VisualObject *, ViewportMask)> PickRenderObjectPredicate
Definition MRViewport.h:184
MRVIEWER_API void cameraRotateAround(const Line3f &axis, float angle)
Vector3f getRotationPivot() const
returns current rotation pivot in world space, which should appear static on a screen during rotation...
Definition MRViewport.h:525
MRVIEWER_API void setCameraTranslation(const Vector3f &translation)
MRVIEWER_API ObjAndPick pickRenderObject(const PickRenderObjectParams &params=PickRenderObjectParams::defaults()) const
bool getRedrawFlag() const
Definition MRViewport.h:306
BaseRenderParams getBaseRenderParams(const Matrix4f &projM) const
Prepares base rendering parameters for this viewport with custom projection matrix.
Definition MRViewport.h:148
MRVIEWER_API float getRatio() const
void setSelectable(bool on)
Definition MRViewport.h:505
MRVIEWER_API float getPixelSize() const
MRVIEWER_API ConstObjAndPick const_pick_render_object(const std::vector< const VisualObject * > &objects) const
MRVIEWER_API Vector3f unprojectFromViewportSpace(const Vector3f &viewportPoint) const
MRVIEWER_API const Vector2f & getAxesPosition() const
returns position of basis axes in viewport space
void drawLines(const std::vector< LineSegm3f > &lines, const std::vector< SegmEndColors > &colors, float width=1, bool depthTest=true)
Definition MRViewport.h:127
MRVIEWER_API void init()
MRVIEWER_API float getPixelSizeAtPoint(const Vector3f &worldPoint) const
void resetRedrawFlag()
Definition MRViewport.h:307
MRVIEWER_API void preciseFitDataToScreenBorder(const FitDataParams &params={})
MRVIEWER_API Vector3f viewportSpaceToClipSpace(const Vector3f &p) const
MR::ViewportRectangle ViewportRectangle
Definition MRViewport.h:48
MRVIEWER_API ModelRenderParams getModelRenderParams(const Matrix4f &modelM, const BaseRenderParams &baseParams, Matrix4f *normM, DepthFunction depthFunc=DepthFunction::Default, RenderModelPassMask pass=RenderModelPassMask::All, const TransparencyMode &transparentMode={}) const
Prepares rendering parameters to draw a model with given transformation in this viewport with custom ...
MRVIEWER_API void setRotation(bool state)
MRVIEWER_API void setParameters(const Viewport::Parameters &params)
MRVIEWER_API std::vector< Vector3f > clipSpaceToViewportSpace(const std::vector< Vector3f > &p) const
MRVIEWER_API void setOrthographic(bool orthographic)
MRVIEWER_API bool draw(const VisualObject &obj, DepthFunction depthFunc=DepthFunction::Default, RenderModelPassMask pass=RenderModelPassMask::All, const TransparencyMode &transparentMode={}) const
ModelRenderParams getModelRenderParamsOrthoFixedPos(const Matrix4f &modelM, Matrix4f *normM, DepthFunction depthFunc=DepthFunction::Default, RenderModelPassMask pass=RenderModelPassMask::All, const TransparencyMode &transparentMode={}) const
Prepares rendering parameters to draw a model with orthographic proj matrix and rotation component of...
Definition MRViewport.h:166
ModelRenderParams getModelRenderParams(const Matrix4f &modelM, Matrix4f *normM, DepthFunction depthFunc=DepthFunction::Default, RenderModelPassMask pass=RenderModelPassMask::All, const TransparencyMode &transparentMode={}) const
Prepares rendering parameters to draw a model with given transformation in this viewport.
Definition MRViewport.h:156
AffineXf3f getViewXf() const
converts directly from the view matrix
Definition MRViewport.h:390
void preDraw()
MRVIEWER_API void showClippingPlane(bool on)
MRVIEWER_API const ViewportRectangle & getViewportRect() const
MRVIEWER_API void fitBox(const Box3f &newSceneBox, float fill=1.0f, bool snapView=true)
MRVIEWER_API void showAxes(bool on)
BaseRenderParams getBaseRenderParamsOrthoFixedPos() const
Prepares base rendering parameters for this viewport with orthographic proj matrix and rotation compo...
Definition MRViewport.h:152
MRVIEWER_API std::vector< Vector3f > worldToCameraSpace(const std::vector< Vector3f > &p) const
MRVIEWER_API Vector3f getCameraPoint() const
MRVIEWER_API void drawTris(const std::vector< Triangle3f > &tris, const std::vector< TriCornerColors > &colors, const Matrix4f &modelM={}, bool depthTest=true)
MRVIEWER_API void drawTris(const std::vector< Triangle3f > &tris, const std::vector< TriCornerColors > &colors, const ModelRenderParams &params, bool depthTest=true)
Draw triangles immediately (flat shaded)
MRVIEWER_API void resetStaticRotationPivot(const std::optional< Vector3f > &pivot=std::nullopt)
MRVIEWER_API void setCameraTrackballAngle(const Quaternionf &rot)
MRVIEWER_API ObjAndPick pick_render_object(const std::vector< VisualObject * > &objects) const
MRVIEWER_API bool draw(const VisualObject &obj, const AffineXf3f &xf, DepthFunction depthFunc=DepthFunction::Default, RenderModelPassMask pass=RenderModelPassMask::All, const TransparencyMode &transparentMode={}) const
Vector3f getBackwardDirection() const
returns unit vector in world space corresponding to direction toward camera in camera space
Definition MRViewport.h:399
MRVIEWER_API Line3f unprojectPixelRay(const Vector2f &viewportPoint) const
MRVIEWER_API std::vector< Vector3f > unprojectFromClipSpace(const std::vector< Vector3f > &clipPoints) const
Viewport clone() const
Definition MRViewport.h:61
MRVIEWER_API void setLabel(std::string s)
MRVIEWER_API std::unordered_map< std::shared_ptr< ObjectMesh >, FaceBitSet > findVisibleFaces(const BitSet &includePixBs, int maxRenderResolutionSide=512) const
const Parameters & getParameters() const
Definition MRViewport.h:482
MRVIEWER_API std::vector< Vector3f > viewportSpaceToClipSpace(const std::vector< Vector3f > &p) const
MRVIEWER_API FaceBitSet findCameraLookingFaces(const Mesh &mesh, const AffineXf3f &meshToWorld) const
finds all triangles of a mesh that having normals oriented toward the camera in this viewport
MRVIEWER_API std::vector< Vector3f > projectToViewportSpace(const std::vector< Vector3f > &worldPoints) const
MRVIEWER_API void fitData(float fill=1.0f, bool snapView=true)
MRVIEWER_API void setAxesSize(const int axisPixSize=80)
MRVIEWER_API void recursiveDraw(const Object &obj, DepthFunction depthFunc=DepthFunction::Default, const AffineXf3f &rootXf={}, RenderModelPassMask renderType=RenderModelPassMask::All, const TransparencyMode &transparentMode={}, int *numDraws=nullptr) const
Immediate draw of given object tree.
MRVIEWER_API void drawPoints(const std::vector< Vector3f > &points, const std::vector< Vector4f > &colors, const LinePointImmediateRenderParams &params)
Draw points immediately.
MRVIEWER_API const Box3f & getSceneBox() const
static MRVIEWER_API Viewport & get(ViewportId viewportId={})
void setupView()
MRVIEWER_API ObjAndPick pickRenderObject(std::span< VisualObject *const > objects, const PickRenderObjectParams &params=PickRenderObjectParams::defaults()) const
MRVIEWER_API void setViewportRect(const ViewportRectangle &rect)
Viewport(Viewport &&) noexcept=default
MRVIEWER_API std::vector< ObjAndPick > multiPickObjects(std::span< VisualObject *const > objects, const std::vector< Vector2f > &viewportPoints, const BaseRenderParams *overrideRenderParams=nullptr) const
MRVIEWER_API void transformView(const AffineXf3f &xf)
MRVIEWER_API Vector3f worldToCameraSpace(const Vector3f &p) const
MRVIEWER_API ObjAndPick pick_render_object(bool exactPickFirst) const
MRVIEWER_API std::vector< ConstObjAndPick > constMultiPickObjects(const std::vector< const VisualObject * > &objects, const std::vector< Vector2f > &viewportPoints) const
MRVIEWER_API AffineXf3f getUnscaledViewXf() const
returns orthonormal matrix with translation
const Matrix4f & getAxesProjectionMatrix() const
returns projection matrix that is used for basis axes and view controller rendering
Definition MRViewport.h:83
MRVIEWER_API void setClippingPlane(const Plane3f &plane)
MRVIEWER_API void preciseFitBoxToScreenBorder(const FitBoxParams &params)
MRVIEWER_API bool allModelsInsideViewportRectangle() const
void postDraw() const
BaseRenderParams getBaseRenderParams() const
Prepares base rendering parameters for this viewport.
Definition MRViewport.h:145
MRVIEWER_API void drawLines(const std::vector< LineSegm3f > &lines, const std::vector< SegmEndColors > &colors, const LinePointImmediateRenderParams &params)
Draw lines immediately.
void drawPoints(const std::vector< Vector3f > &points, const std::vector< Vector4f > &colors, float width=1, bool depthTest=true)
Definition MRViewport.h:132
MRVIEWER_API Viewport()
MRVIEWER_API void setBackgroundColor(const Color &color)
MRVIEWER_API std::vector< std::shared_ptr< VisualObject > > findObjectsInRect(const Box2i &rect, int maxRenderResolutionSide=512) const
MRVIEWER_API void setAxesPos(const int pixelXoffset=-100, const int pixelYoffset=-100)
MRVIEWER_API void clearFramebuffers()
MRVIEWER_API ObjAndPick pick_render_object(const Vector2f &viewportPoint) const
MRVIEWER_API void setCameraPoint(const Vector3f &cameraWorldPos)
MRVIEWER_API Vector3f clipSpaceToViewportSpace(const Vector3f &p) const
ViewportId id
Definition MRViewport.h:310
MRVIEWER_API std::vector< Vector3f > projectToClipSpace(const std::vector< Vector3f > &worldPoints) const
MRVIEWER_API void rotationCenterMode(Parameters::RotationCenterMode mode)
Vector3f getUpDirection() const
returns unit vector in world space corresponding to up-direction in camera space
Definition MRViewport.h:393
MRVIEWER_API ObjAndPick pick_render_object() const
Visual Object.
Definition MRVisualObject.h:119
auto width(const Box< V > &box)
returns size along x axis
Definition MRMesh/MRBox.h:354
auto height(const Box< V > &box)
returns size along y axis
Definition MRMesh/MRBox.h:361
Definition MRCameraOrientationPlugin.h:8
FitMode
Definition MRFitData.h:11
ImVec2 size(const ViewportRectangle &rect)
Definition MRViewport.h:29
std::pair< std::shared_ptr< MR::VisualObject >, MR::PointOnObject > ObjAndPick
Definition MRViewerFwd.h:86
RenderModelPassMask
Various passes of the 3D rendering.
Definition MRRenderModelParameters.h:37
std::pair< std::shared_ptr< const MR::VisualObject >, MR::PointOnObject > ConstObjAndPick
Definition MRViewerFwd.h:87
Vector4< T > toVec4(const ViewportRectangle &rect)
Definition MRViewport.h:38
DepthFunction
Definition MRIRenderObject.h:18
Box2f ViewportRectangle
Viewport size.
Definition MRViewerFwd.h:14
Definition MRFitData.h:20
Common rendering parameters for meshes and UI.
Definition MRIRenderObject.h:33
Definition MRMesh/MRColor.h:9
Definition MRFitData.h:42
Definition MRFitData.h:29
Definition MRMesh/MRMesh.h:23
Mesh rendering parameters for primary rendering (as opposed to the picker).
Definition MRIRenderObject.h:51
struct to determine transparent rendering mode
Definition MRRenderModelParameters.h:10
Definition MRVector4.h:23
Rendering parameters for immediate drawing of lines and points.
Definition MRViewport.h:120
bool depthTest
Definition MRViewport.h:122
float width
Definition MRViewport.h:121
Definition MRViewport.h:313
RotationCenterMode
Definition MRViewport.h:343
float cameraViewAngle
Definition MRViewport.h:320
Vector3f cameraTranslation
Definition MRViewport.h:318
Color backgroundColor
Definition MRViewport.h:314
bool orthographic
Definition MRViewport.h:325
float cameraDfar
Definition MRViewport.h:322
Color borderColor
Definition MRViewport.h:336
bool depthTest
Definition MRViewport.h:324
Plane3f clippingPlane
Definition MRViewport.h:340
std::string label
Definition MRViewport.h:338
float cameraZoom
Definition MRViewport.h:319
Quaternionf cameraTrackballAngle
Definition MRViewport.h:317
Vector3f lightPosition
Definition MRViewport.h:315
enum MR::Viewport::Parameters::GlobalBasisScaleMode Auto
bool selectable
Definition MRViewport.h:358
GlobalBasisScaleMode
Definition MRViewport.h:328
enum MR::Viewport::Parameters::RotationCenterMode Dynamic
std::optional< Vector3f > staticRotationPivot
Definition MRViewport.h:351
bool operator==(const Viewport::Parameters &other) const =default
float cameraDnear
Definition MRViewport.h:321
bool compensateRotation
Definition MRViewport.h:355
float objectScale
Definition MRViewport.h:334
Definition MRViewport.h:187
int pickRadius
Definition MRViewport.h:196
PickRenderObjectPredicate predicate
Definition MRViewport.h:192
bool exactPickFirst
Definition MRViewport.h:200
static PickRenderObjectParams defaults()
Definition MRViewport.h:208
const BaseRenderParams * baseRenderParams
Definition MRViewport.h:203
std::optional< Vector2f > point
Definition MRViewport.h:189
Definition MRViewport.h:136
Vector4f c
Definition MRViewport.h:137
Vector4f b
Definition MRViewport.h:137
Vector4f a
Definition MRViewport.h:137