KiCad PCB EDA Suite
Loading...
Searching...
No Matches
eda_3d_canvas.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2015-2016 Mario Luzeiro <[email protected]>
5 * Copyright (C) 1992-2023 KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, you may find one here:
19 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
20 * or you may search the http://www.gnu.org website for the version 2 license,
21 * or you may write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 */
24
25#include <gal/opengl/kiglew.h> // Must be included first
26#include <gal/opengl/gl_utils.h>
27#include <wx/tokenzr.h>
28
29#include "../common_ogl/ogl_utils.h"
30#include "eda_3d_canvas.h"
31#include <eda_3d_viewer_frame.h>
34#include <3d_viewer_id.h>
35#include <advanced_config.h>
36#include <board.h>
37#include <reporter.h>
39#include <core/profile.h> // To use GetRunningMicroSecs or another profiling utility
40#include <bitmaps.h>
41#include <macros.h>
42#include <pgm_base.h>
45
47
48
56const wxChar* EDA_3D_CANVAS::m_logTrace = wxT( "KI_TRACE_EDA_3D_CANVAS" );
57
58
59// A custom event, used to call DoRePaint during an idle time
60wxDEFINE_EVENT( wxEVT_REFRESH_CUSTOM_COMMAND, wxEvent );
61
62
63BEGIN_EVENT_TABLE( EDA_3D_CANVAS, HIDPI_GL_3D_CANVAS )
64 EVT_PAINT( EDA_3D_CANVAS::OnPaint )
65
66 // mouse events
67 EVT_LEFT_DOWN( EDA_3D_CANVAS::OnLeftDown )
68 EVT_LEFT_UP( EDA_3D_CANVAS::OnLeftUp )
69 EVT_MIDDLE_UP( EDA_3D_CANVAS::OnMiddleUp )
70 EVT_MIDDLE_DOWN( EDA_3D_CANVAS::OnMiddleDown)
71 EVT_MOUSEWHEEL( EDA_3D_CANVAS::OnMouseWheel )
72 EVT_MOTION( EDA_3D_CANVAS::OnMouseMove )
73 EVT_MAGNIFY( EDA_3D_CANVAS::OnMagnify )
74
75 // other events
76 EVT_ERASE_BACKGROUND( EDA_3D_CANVAS::OnEraseBackground )
77 EVT_CUSTOM(wxEVT_REFRESH_CUSTOM_COMMAND, ID_CUSTOM_EVENT_1, EDA_3D_CANVAS::OnRefreshRequest )
78
80 EVT_SIZE( EDA_3D_CANVAS::OnResize )
81END_EVENT_TABLE()
82
83
84EDA_3D_CANVAS::EDA_3D_CANVAS( wxWindow* aParent, const int* aAttribList,
85 BOARD_ADAPTER& aBoardAdapter, CAMERA& aCamera,
86 S3D_CACHE* a3DCachePointer ) :
87 HIDPI_GL_3D_CANVAS( EDA_DRAW_PANEL_GAL::GetVcSettings(), aCamera, aParent, wxID_ANY,
88 aAttribList, wxDefaultPosition,
89 wxDefaultSize, wxFULL_REPAINT_ON_RESIZE ),
90 m_eventDispatcher( nullptr ),
91 m_parentStatusBar( nullptr ),
92 m_parentInfoBar( nullptr ),
93 m_glRC( nullptr ),
94 m_is_opengl_initialized( false ),
95 m_is_opengl_version_supported( true ),
96 m_editing_timeout_timer( this, wxID_HIGHEST + 1 ),
97 m_redraw_trigger_timer( this, wxID_HIGHEST + 2 ),
98 m_render_pivot( false ),
99 m_camera_moving_speed( 1.0f ),
100 m_strtime_camera_movement( 0 ),
101 m_animation_enabled( true ),
102 m_moving_speed_multiplier( 3 ),
103 m_boardAdapter( aBoardAdapter ),
104 m_3d_render( nullptr ),
105 m_opengl_supports_raytracing( true ),
106 m_render_raytracing_was_requested( false ),
107 m_accelerator3DShapes( nullptr ),
108 m_currentRollOverItem( nullptr )
109{
110 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::EDA_3D_CANVAS" ) );
111
112 m_editing_timeout_timer.SetOwner( this );
113 Connect( m_editing_timeout_timer.GetId(), wxEVT_TIMER,
114 wxTimerEventHandler( EDA_3D_CANVAS::OnTimerTimeout_Editing ), nullptr, this );
115
116 m_redraw_trigger_timer.SetOwner( this );
117 Connect( m_redraw_trigger_timer.GetId(), wxEVT_TIMER,
118 wxTimerEventHandler( EDA_3D_CANVAS::OnTimerTimeout_Redraw ), nullptr, this );
119
120 m_is_currently_painting.clear();
121
122 m_3d_render_raytracing = new RENDER_3D_RAYTRACE( this, m_boardAdapter, m_camera );
123 m_3d_render_opengl = new RENDER_3D_OPENGL( this, m_boardAdapter, m_camera );
124
125 wxASSERT( m_3d_render_raytracing != nullptr );
126 wxASSERT( m_3d_render_opengl != nullptr );
127
128 auto busy_indicator_factory =
129 []()
130 {
131 return std::make_unique<WX_BUSY_INDICATOR>();
132 };
133
134 m_3d_render_raytracing->SetBusyIndicatorFactory( busy_indicator_factory );
135 m_3d_render_opengl->SetBusyIndicatorFactory( busy_indicator_factory );
136
137 // We always start with the opengl engine (raytracing is avoided due to very
138 // long calculation time)
139 m_3d_render = m_3d_render_opengl;
140
141 m_boardAdapter.ReloadColorSettings();
142
143 wxASSERT( a3DCachePointer != nullptr );
144 m_boardAdapter.Set3dCacheManager( a3DCachePointer );
145
146 const wxEventType events[] =
147 {
148 // Binding both EVT_CHAR and EVT_CHAR_HOOK ensures that all key events,
149 // especially special key like arrow keys, are handled by the GAL event dispatcher,
150 // and not sent to GUI without filtering, because they have a default action (scroll)
151 // that must not be called.
152 wxEVT_LEFT_UP, wxEVT_LEFT_DOWN, wxEVT_LEFT_DCLICK,
153 wxEVT_RIGHT_UP, wxEVT_RIGHT_DOWN, wxEVT_RIGHT_DCLICK,
154 wxEVT_MIDDLE_UP, wxEVT_MIDDLE_DOWN, wxEVT_MIDDLE_DCLICK,
155 wxEVT_MOTION, wxEVT_MOUSEWHEEL, wxEVT_CHAR, wxEVT_CHAR_HOOK,
156 wxEVT_MAGNIFY,
157 wxEVT_MENU_OPEN, wxEVT_MENU_CLOSE, wxEVT_MENU_HIGHLIGHT
158 };
159
160 for( wxEventType eventType : events )
161 Connect( eventType, wxEventHandler( EDA_3D_CANVAS::OnEvent ), nullptr, m_eventDispatcher );
162}
163
164
166{
167 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::~EDA_3D_CANVAS" ) );
168
170 m_accelerator3DShapes = nullptr;
171
173}
174
175
177{
178 if( m_glRC )
179 {
181
183 m_3d_render_raytracing = nullptr;
184
185 delete m_3d_render_opengl;
186 m_3d_render_opengl = nullptr;
187
188 // This is just a copy of a pointer, can safely be set to NULL.
189 m_3d_render = nullptr;
190
193 m_glRC = nullptr;
194 }
195}
196
197
198void EDA_3D_CANVAS::OnCloseWindow( wxCloseEvent& event )
199{
201
202 event.Skip();
203}
204
205
206void EDA_3D_CANVAS::OnResize( wxSizeEvent& event )
207{
209}
210
211
213{
214 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::initializeOpenGL" ) );
215
216 const GLenum err = glewInit();
217
218 if( GLEW_OK != err )
219 {
220 const wxString msgError = (const char*) glewGetErrorString( err );
221
222 wxLogMessage( msgError );
223
224 return false;
225 }
226 else
227 {
228 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::initializeOpenGL Using GLEW version %s" ),
229 From_UTF8( (char*) glewGetString( GLEW_VERSION ) ) );
230 }
231
232 wxString version = From_UTF8( (char *) glGetString( GL_VERSION ) );
233
234 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::%s OpenGL version string %s." ),
235 __WXFUNCTION__, version );
236
237 // Extract OpenGL version from string. This method is used because prior to OpenGL 2,
238 // getting the OpenGL major and minor version as integers didn't exist.
239 wxString tmp;
240
241 wxStringTokenizer tokenizer( version );
242
243 if( tokenizer.HasMoreTokens() )
244 {
245 long major = 0;
246 long minor = 0;
247
248 tmp = tokenizer.GetNextToken();
249
250 tokenizer.SetString( tmp, wxString( wxT( "." ) ) );
251
252 if( tokenizer.HasMoreTokens() )
253 tokenizer.GetNextToken().ToLong( &major );
254
255 if( tokenizer.HasMoreTokens() )
256 tokenizer.GetNextToken().ToLong( &minor );
257
258 if( major < 2 || ( ( major == 2 ) && ( minor < 1 ) ) )
259 {
260 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::%s OpenGL ray tracing not supported." ),
261 __WXFUNCTION__ );
262
263 if( GetParent() )
264 {
265 wxCommandEvent evt( wxEVT_MENU, ID_DISABLE_RAY_TRACING );
266 GetParent()->ProcessWindowEvent( evt );
267 }
268
270 }
271
272 if( ( major == 1 ) && ( minor < 5 ) )
273 {
274 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::%s OpenGL not supported." ),
275 __WXFUNCTION__ );
276
278 }
279 }
280
283
284 return true;
285}
286
287
288void EDA_3D_CANVAS::GetScreenshot( wxImage& aDstImage )
289{
290 OglGetScreenshot( aDstImage );
291}
292
293
294void EDA_3D_CANVAS::ReloadRequest( BOARD* aBoard , S3D_CACHE* aCachePointer )
295{
296 if( aCachePointer != nullptr )
297 m_boardAdapter.Set3dCacheManager( aCachePointer );
298
299 if( aBoard != nullptr )
300 m_boardAdapter.SetBoard( aBoard );
301
303
304 if( m_3d_render )
306}
307
308
310{
312
313 if( m_3d_render )
315
317
319}
320
321
323{
325 {
326 wxString msg;
327
328 msg.Printf( wxT( "dx %3.2f" ), m_camera.GetCameraPos().x );
329 m_parentStatusBar->SetStatusText( msg, static_cast<int>( EDA_3D_VIEWER_STATUSBAR::X_POS ) );
330
331 msg.Printf( wxT( "dy %3.2f" ), m_camera.GetCameraPos().y );
332 m_parentStatusBar->SetStatusText( msg, static_cast<int>( EDA_3D_VIEWER_STATUSBAR::Y_POS ) );
333
334 msg.Printf( wxT( "zoom %3.2f" ), 1 / m_camera.GetZoom() );
335 m_parentStatusBar->SetStatusText( msg, static_cast<int>( EDA_3D_VIEWER_STATUSBAR::ZOOM_LEVEL ) );
336 }
337}
338
339
340void EDA_3D_CANVAS::OnPaint( wxPaintEvent& aEvent )
341{
342 // Please have a look at: https://lists.launchpad.net/kicad-developers/msg25149.html
343 DoRePaint();
344}
345
346
348{
349 if( m_is_currently_painting.test_and_set() )
350 return;
351
352 // SwapBuffer requires the window to be shown before calling
353 if( !IsShownOnScreen() )
354 {
355 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::DoRePaint !IsShown" ) );
357 return;
358 }
359
360 // Because the board to draw is handled by the parent viewer frame,
361 // ensure this parent is still alive. When it is closed before the viewer
362 // frame, a paint event can be generated after the parent is closed,
363 // therefore with invalid board.
364 // This is dependent of the platform.
365 // Especially on OSX, but also on Windows, it frequently happens
366 if( !GetParent()->GetParent()->IsShownOnScreen() )
367 return; // The parent board editor frame is no more alive
368
369 wxString err_messages;
370
371 // !TODO: implement error reporter
372 INFOBAR_REPORTER warningReporter( m_parentInfoBar );
373 STATUSBAR_REPORTER activityReporter( m_parentStatusBar, EDA_3D_VIEWER_STATUSBAR::ACTIVITY );
374
375 unsigned strtime = GetRunningMicroSecs();
376
377 // "Makes the OpenGL state that is represented by the OpenGL rendering
378 // context context current, i.e. it will be used by all subsequent OpenGL calls.
379 // This function may only be called when the window is shown on screen"
380
381 // Explicitly create a new rendering context instance for this canvas.
382 if( m_glRC == nullptr )
384
385 // CreateCtx could and does fail per sentry crash events, lets be graceful
386 if( m_glRC == nullptr )
387 {
388 warningReporter.Report( _( "OpenGL context creation error" ), RPT_SEVERITY_ERROR );
389 warningReporter.Finalize();
391 return;
392 }
393
395
396 // Set the OpenGL viewport according to the client size of this canvas.
397 // This is done here rather than in a wxSizeEvent handler because our
398 // OpenGL rendering context (and thus viewport setting) is used with
399 // multiple canvases: If we updated the viewport in the wxSizeEvent
400 // handler, changing the size of one canvas causes a viewport setting that
401 // is wrong when next another canvas is repainted.
402 wxSize clientSize = GetNativePixelSize();
403
404 const bool windows_size_changed = m_camera.SetCurWindowSize( clientSize );
405
406 // Initialize openGL if need
408 {
409 if( !initializeOpenGL() )
410 {
413
414 return;
415 }
416
418 {
419 warningReporter.Report( _( "Your OpenGL version is not supported. Minimum required "
420 "is 1.5." ), RPT_SEVERITY_ERROR );
421
422 warningReporter.Finalize();
423 }
424 }
425
427 {
428 glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
429 glClear( GL_COLOR_BUFFER_BIT );
430
431 SwapBuffers();
432
435
436 return;
437 }
438
439 // Don't attend to ray trace if OpenGL doesn't support it.
441 {
444 m_boardAdapter.m_Cfg->m_Render.engine = RENDER_ENGINE::OPENGL;
445 }
446
447 // Check if a raytacing was requested and need to switch to raytracing mode
448 if( m_boardAdapter.m_Cfg->m_Render.engine == RENDER_ENGINE::OPENGL )
449 {
450 const bool was_camera_changed = m_camera.ParametersChanged();
451
452 // It reverts back to OpenGL mode if it was requested a raytracing
453 // render of the current scene. AND the mouse / camera is moving
454 if( ( m_mouse_is_moving || m_camera_is_moving || was_camera_changed
455 || windows_size_changed )
457 {
460 }
461 }
462
463 float curtime_delta_s = 0.0f;
464
466 {
467 const unsigned curtime_delta = GetRunningMicroSecs() - m_strtime_camera_movement;
468 curtime_delta_s = (curtime_delta / 1e6) * m_camera_moving_speed;
469 m_camera.Interpolate( curtime_delta_s );
470
471 if( curtime_delta_s > 1.0f )
472 {
473 m_render_pivot = false;
474 m_camera_is_moving = false;
475 m_mouse_was_moved = true;
476
479 }
480 else
481 {
483 }
484 }
485
486 // It will return true if the render request a new redraw
487 bool requested_redraw = false;
488
489 if( m_3d_render )
490 {
491 try
492 {
493 m_3d_render->SetCurWindowSize( clientSize );
494
495 bool reloadRaytracingForCalculations = false;
496
497 if( m_boardAdapter.m_Cfg->m_Render.engine == RENDER_ENGINE::OPENGL
499 {
500 reloadRaytracingForCalculations = true;
501 }
502
504 &activityReporter, &warningReporter );
505
506 // Raytracer renderer is responsible for some features also used by the OpenGL
507 // renderer.
508 // FIXME: Presumably because raytracing renderer reload is called only after current
509 // renderer redraw, the old zoom value stays for a single frame. This is ugly, but only
510 // cosmetic, so I'm not fixing that for now: I don't know how to do this without
511 // reloading twice (maybe it's not too bad of an idea?) or doing a complicated
512 // refactor.
513 if( reloadRaytracingForCalculations )
514 m_3d_render_raytracing->Reload( nullptr, nullptr, true );
515 }
516 catch( std::runtime_error& )
517 {
523 return;
524 }
525 }
526
527 if( m_render_pivot )
528 {
529 const float scale = glm::min( m_camera.GetZoom(), 1.0f );
530 render_pivot( curtime_delta_s, scale );
531 }
532
533 // This will only be enabled by the 3d mouse plugin, so we can leave
534 // it as a simple if statement
536 {
537 const float scale = glm::min( m_camera.GetZoom(), 1.0f );
539 }
540
541 // "Swaps the double-buffer of this window, making the back-buffer the
542 // front-buffer and vice versa, so that the output of the previous OpenGL
543 // commands is displayed on the window."
544 SwapBuffers();
545
547
549 {
550 // Calculation time in milliseconds
551 const double calculation_time = (double)( GetRunningMicroSecs() - strtime) / 1e3;
552
553 activityReporter.Report( wxString::Format( _( "Last render time %.0f ms" ),
554 calculation_time ) );
555 }
556
557 // This will reset the flag of camera parameters changed
559
560 warningReporter.Finalize();
561
562 if( !err_messages.IsEmpty() )
563 wxLogMessage( err_messages );
564
565 if( ( !m_camera_is_moving ) && requested_redraw )
566 {
567 m_mouse_was_moved = false;
568 Request_refresh( false );
569 }
570
572}
573
574
576{
577 m_eventDispatcher = aEventDispatcher;
578}
579
580
581void EDA_3D_CANVAS::OnEvent( wxEvent& aEvent )
582{
583 if( !m_eventDispatcher )
584 aEvent.Skip();
585 else
587
588 Refresh();
589}
590
591
592void EDA_3D_CANVAS::OnEraseBackground( wxEraseEvent& event )
593{
594 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::OnEraseBackground" ) );
595 // Do nothing, to avoid flashing.
596}
597
598
599void EDA_3D_CANVAS::OnMouseWheel( wxMouseEvent& event )
600{
601 wxLogTrace( m_logTrace, wxT( "EDA_3D_CANVAS::OnMouseWheel" ) );
602
604
606 {
610 }
611}
612
613
614void EDA_3D_CANVAS::OnMagnify( wxMouseEvent& event )
615{
616 SetFocus();
617
619 return;
620
621 //m_is_moving_mouse = true;
623
624 float magnification = ( event.GetMagnification() + 1.0f );
625
626 m_camera.Zoom( magnification );
627
630}
631
632
633void EDA_3D_CANVAS::OnMouseMove( wxMouseEvent& event )
634{
636 return; // Prevents using invalid m_3d_render_raytracing data
637
639 return;
640
641 OnMouseMoveCamera( event );
642
644 {
647 // *Do not* reactivate the timer here during the mouse move command:
648 // OnMiddleUp() will do it at the end of mouse drag/move command
649 }
650
651 if( !event.Dragging() && m_boardAdapter.m_Cfg->m_Render.engine == RENDER_ENGINE::OPENGL )
652 {
653 STATUSBAR_REPORTER reporter( m_parentStatusBar, EDA_3D_VIEWER_STATUSBAR::HOVERED_ITEM );
655 BOARD_ITEM* rollOverItem = m_3d_render_raytracing->IntersectBoardItem( mouseRay );
656
657 auto printNetInfo =
658 []( BOARD_CONNECTED_ITEM* aItem )
659 {
660 return wxString::Format( _( "Net %s\tNet class %s" ),
661 aItem->GetNet()->GetNetname(),
662 aItem->GetNet()->GetNetClass()->GetName() );
663 };
664
665 if( rollOverItem )
666 {
667 wxString msg;
668
669 if( rollOverItem != m_currentRollOverItem )
670 {
672 m_currentRollOverItem = rollOverItem;
673
675 }
676
677 switch( rollOverItem->Type() )
678 {
679 case PCB_PAD_T:
680 {
681 PAD* pad = static_cast<PAD*>( rollOverItem );
682
683 if( !pad->GetNumber().IsEmpty() )
684 msg += wxString::Format( _( "Pad %s\t" ), pad->GetNumber() );
685
686 if( pad->IsOnCopperLayer() )
687 msg += printNetInfo( pad );
688
689 break;
690 }
691
692 case PCB_FOOTPRINT_T:
693 {
694 FOOTPRINT* footprint = static_cast<FOOTPRINT*>( rollOverItem );
695 msg += footprint->GetReference();
696 break;
697 }
698
699 case PCB_TRACE_T:
700 case PCB_VIA_T:
701 case PCB_ARC_T:
702 {
703 PCB_TRACK* track = static_cast<PCB_TRACK*>( rollOverItem );
704 msg += printNetInfo( track );
705 break;
706 }
707
708 case PCB_ZONE_T:
709 {
710 ZONE* zone = static_cast<ZONE*>( rollOverItem );
711
712 if( !zone->GetZoneName().IsEmpty() )
713 {
714 if( zone->GetIsRuleArea() )
715 msg += wxString::Format( _( "Rule area %s\t" ), zone->GetZoneName() );
716 else
717 msg += wxString::Format( _( "Zone %s\t" ), zone->GetZoneName() );
718 }
719
720 if( zone->IsOnCopperLayer() )
721 msg += printNetInfo( zone );
722
723 break;
724 }
725
726 default:
727 break;
728 }
729
730 reporter.Report( msg );
731 }
732 else
733 {
735 && m_boardAdapter.m_Cfg->m_Render.engine == RENDER_ENGINE::OPENGL )
736 {
739
740 reporter.Report( wxEmptyString );
741 }
742
743 m_currentRollOverItem = nullptr;
744 }
745 }
746}
747
748
749void EDA_3D_CANVAS::OnLeftDown( wxMouseEvent& event )
750{
751 SetFocus();
753
754 if( !event.Dragging() && ( m_3d_render_raytracing != nullptr ) )
755 {
757
758 BOARD_ITEM *intersectedBoardItem = m_3d_render_raytracing->IntersectBoardItem( mouseRay );
759
760 // !TODO: send a selection item to pcbnew, eg: via kiway?
761 }
762}
763
764
765void EDA_3D_CANVAS::OnLeftUp( wxMouseEvent& event )
766{
768 return;
769
771 {
772 m_mouse_is_moving = false;
774 }
775}
776
777
778void EDA_3D_CANVAS::OnMiddleDown( wxMouseEvent& event )
779{
780 SetFocus();
782}
783
784
785void EDA_3D_CANVAS::OnMiddleUp( wxMouseEvent& event )
786{
788 return;
789
791 {
792 m_mouse_is_moving = false;
794 }
795 else
796 {
798 }
799}
800
801
802void EDA_3D_CANVAS::OnTimerTimeout_Editing( wxTimerEvent& aEvent )
803{
804 if( aEvent.GetId() != m_editing_timeout_timer.GetId() )
805 {
806 aEvent.Skip();
807 return;
808 }
809
810 m_mouse_is_moving = false;
811 m_mouse_was_moved = false;
812
814}
815
816
818{
820}
821
822
824{
825 if( m_3d_render )
827}
828
829
830void EDA_3D_CANVAS::OnTimerTimeout_Redraw( wxTimerEvent& aEvent )
831{
832 if( aEvent.GetId() != m_redraw_trigger_timer.GetId() )
833 {
834 aEvent.Skip();
835 return;
836 }
837
838 Request_refresh( true );
839}
840
841
842void EDA_3D_CANVAS::OnRefreshRequest( wxEvent& aEvent )
843{
844 DoRePaint();
845}
846
847
848void EDA_3D_CANVAS::Request_refresh( bool aRedrawImmediately )
849{
850 if( aRedrawImmediately )
851 {
852 // Just calling Refresh() does not work always
853 // Using an event to call DoRepaint ensure the repaint code will be executed,
854 // and PostEvent will take priority to other events like mouse movements, keys, etc.
855 // and is executed during the next idle time
856 wxCommandEvent redrawEvent( wxEVT_REFRESH_CUSTOM_COMMAND, ID_CUSTOM_EVENT_1 );
857 wxPostEvent( this, redrawEvent );
858 }
859 else
860 {
861 // Schedule a timed redraw
862 m_redraw_trigger_timer.Start( 10 , wxTIMER_ONE_SHOT );
863 }
864}
865
866
867void EDA_3D_CANVAS::request_start_moving_camera( float aMovingSpeed, bool aRenderPivot )
868{
869 wxASSERT( aMovingSpeed > FLT_EPSILON );
870
871 // Fast forward the animation if the animation is disabled
873 {
874 m_camera.Interpolate( 1.0f );
877 return;
878 }
879
880 // Map speed multiplier option to actual multiplier value
881 // [1,2,3,4,5] -> [0.25, 0.5, 1, 2, 4]
882 aMovingSpeed *= ( 1 << m_moving_speed_multiplier ) / 8.0f;
883
884 m_render_pivot = aRenderPivot;
885 m_camera_moving_speed = aMovingSpeed;
886
888
891
892 m_camera_is_moving = true;
893
895}
896
897
899{
901
902 float hit_t;
903
904 // Test it with the board bounding box
905 if( m_boardAdapter.GetBBox().Intersect( mouseRay, &hit_t ) )
906 {
907 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::BEZIER );
909 m_camera.SetLookAtPos_T1( mouseRay.at( hit_t ) );
911
913 }
914}
915
916
918{
920 return false;
921
922 const float delta_move = m_delta_move_step_factor * m_camera.GetZoom();
923 const float arrow_moving_time_speed = 8.0f;
924 bool handled = false;
925
926 switch( aRequestedView )
927 {
928 case VIEW3D_TYPE::VIEW3D_PIVOT_CENTER:
930 return true;
931
932 case VIEW3D_TYPE::VIEW3D_PAN_LEFT:
933 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::LINEAR );
935 m_camera.Pan_T1( SFVEC3F( -delta_move, 0.0f, 0.0f ) );
936 request_start_moving_camera( arrow_moving_time_speed, false );
937 return true;
938
939 case VIEW3D_TYPE::VIEW3D_PAN_RIGHT:
940 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::LINEAR );
942 m_camera.Pan_T1( SFVEC3F( +delta_move, 0.0f, 0.0f ) );
943 request_start_moving_camera( arrow_moving_time_speed, false );
944 return true;
945
946 case VIEW3D_TYPE::VIEW3D_PAN_UP:
947 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::LINEAR );
949 m_camera.Pan_T1( SFVEC3F( 0.0f, +delta_move, 0.0f ) );
950 request_start_moving_camera( arrow_moving_time_speed, false );
951 return true;
952
953 case VIEW3D_TYPE::VIEW3D_PAN_DOWN:
954 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::LINEAR );
956 m_camera.Pan_T1( SFVEC3F( 0.0f, -delta_move, 0.0f ) );
957 request_start_moving_camera( arrow_moving_time_speed, false );
958 return true;
959
960 case VIEW3D_TYPE::VIEW3D_FIT_SCREEN:
961 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::BEZIER );
964 request_start_moving_camera( glm::min( glm::max( m_camera.GetZoom(), 1 / 1.26f ), 1.26f ) );
965 return true;
966
967 case VIEW3D_TYPE::VIEW3D_ZOOM_IN:
968 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::BEZIER );
970
971 if( m_camera.Zoom_T1( 1.26f ) ) // 3 steps per doubling
973
974 return true;
975
976 case VIEW3D_TYPE::VIEW3D_ZOOM_OUT:
977 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::BEZIER );
979
980 if( m_camera.Zoom_T1( 1/1.26f ) ) // 3 steps per halving
982
983 return true;
984
985 case VIEW3D_TYPE::VIEW3D_RIGHT:
986 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::BEZIER );
989 m_camera.RotateZ_T1( glm::radians( -90.0f ) );
990 m_camera.RotateX_T1( glm::radians( -90.0f ) );
992 return true;
993
994 case VIEW3D_TYPE::VIEW3D_LEFT:
995 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::BEZIER );
998 m_camera.RotateZ_T1( glm::radians( 90.0f ) );
999 m_camera.RotateX_T1( glm::radians( -90.0f ) );
1001 return true;
1002
1003 case VIEW3D_TYPE::VIEW3D_FRONT:
1004 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::BEZIER );
1007 m_camera.RotateX_T1( glm::radians( -90.0f ) );
1009 return true;
1010
1011 case VIEW3D_TYPE::VIEW3D_BACK:
1012 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::BEZIER );
1015 m_camera.RotateX_T1( glm::radians( -90.0f ) );
1016
1017 // The rotation angle should be 180.
1018 // We use 179.999 (180 - epsilon) to avoid a full 360 deg rotation when
1019 // using 180 deg if the previous rotated position was already 180 deg
1020 m_camera.RotateZ_T1( glm::radians( 179.999f ) );
1022 return true;
1023
1024 case VIEW3D_TYPE::VIEW3D_TOP:
1025 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::BEZIER );
1028 request_start_moving_camera( glm::min( glm::max( m_camera.GetZoom(), 0.5f ), 1.125f ) );
1029 return true;
1030
1031 case VIEW3D_TYPE::VIEW3D_BOTTOM:
1032 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::BEZIER );
1035 m_camera.RotateY_T1( glm::radians( 179.999f ) ); // Rotation = 180 - epsilon
1036 request_start_moving_camera( glm::min( glm::max( m_camera.GetZoom(), 0.5f ), 1.125f ) );
1037 return true;
1038
1039 case VIEW3D_TYPE::VIEW3D_FLIP:
1040 m_camera.SetInterpolateMode( CAMERA_INTERPOLATION::BEZIER );
1042 m_camera.RotateY_T1( glm::radians( 179.999f ) );
1044 return true;
1045
1046 default:
1047 return false;
1048 }
1049
1050 m_mouse_was_moved = true;
1051
1053
1054 DisplayStatus();
1056
1057 return handled;
1058}
1059
1060
1062{
1063 SETTINGS_MANAGER& mgr = Pgm().GetSettingsManager();
1065
1066 switch( cfg->m_Render.engine )
1067 {
1068 case RENDER_ENGINE::OPENGL: m_3d_render = m_3d_render_opengl; break;
1069 case RENDER_ENGINE::RAYTRACING: m_3d_render = m_3d_render_raytracing; break;
1070 default: m_3d_render = nullptr; break;
1071 }
1072
1073 if( m_3d_render )
1075
1076 m_mouse_was_moved = false;
1077
1079}
1080
1081
1083{
1084 SFVEC3F rayOrigin;
1085 SFVEC3F rayDir;
1086
1087 // Generate a ray origin and direction based on current mouser position and camera
1088 m_camera.MakeRayAtCurrentMousePosition( rayOrigin, rayDir );
1089
1090 RAY mouseRay;
1091 mouseRay.Init( rayOrigin, rayDir );
1092
1093 return mouseRay;
1094}
VIEW3D_TYPE
Definition: 3d_enums.h:78
@ ID_CUSTOM_EVENT_1
Definition: 3d_viewer_id.h:53
@ ID_DISABLE_RAY_TRACING
Definition: 3d_viewer_id.h:51
Helper class to handle information needed to display 3D board.
Definition: board_adapter.h:71
const BBOX_3D & GetBBox() const noexcept
Get the board outling bounding box.
void ReloadColorSettings() noexcept
void SetBoard(BOARD *aBoard) noexcept
Set current board to be rendered.
EDA_3D_VIEWER_SETTINGS * m_Cfg
bool m_MousewheelPanning
void Set3dCacheManager(S3D_CACHE *aCacheMgr) noexcept
Update the cache manager pointer.
Definition: board_adapter.h:82
A base class derived from BOARD_ITEM for items that can be connected and have a net,...
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition: board_item.h:77
Information pertinent to a Pcbnew printed circuit board.
Definition: board.h:276
A class used to derive camera objects from.
Definition: camera.h:102
bool Zoom(float aFactor)
Definition: camera.cpp:538
void RotateY_T1(float aAngleInRadians)
Definition: camera.cpp:618
bool Zoom_T1(float aFactor)
Definition: camera.cpp:569
virtual void Reset_T1()
Definition: camera.cpp:102
virtual void Pan_T1(const SFVEC3F &aDeltaOffsetInc)=0
virtual void Interpolate(float t)
It will update the matrix to interpolate between T0 and T1 values.
Definition: camera.cpp:644
bool SetCurWindowSize(const wxSize &aSize)
Update the windows size of the camera.
Definition: camera.cpp:511
void SetInterpolateMode(CAMERA_INTERPOLATION aInterpolateMode)
Definition: camera.h:255
float GetZoom() const
Definition: camera.h:219
void ResetXYpos_T1()
Definition: camera.cpp:443
virtual void SetT0_and_T1_current_T()
This will set T0 and T1 with the current values.
Definition: camera.cpp:630
void MakeRayAtCurrentMousePosition(SFVEC3F &aOutOrigin, SFVEC3F &aOutDirection) const
Make a ray based on the latest mouse position.
Definition: camera.cpp:402
void RotateX_T1(float aAngleInRadians)
Definition: camera.cpp:612
void SetLookAtPos_T1(const SFVEC3F &aLookAtPos)
Definition: camera.h:160
const SFVEC3F & GetCameraPos() const
Definition: camera.h:167
void RotateZ_T1(float aAngleInRadians)
Definition: camera.cpp:624
bool ParametersChanged()
Definition: camera.cpp:662
Implement a canvas based on a wxGLCanvas.
Definition: eda_3d_canvas.h:49
RENDER_3D_OPENGL * m_3d_render_opengl
TOOL_DISPATCHER * m_eventDispatcher
void OnEvent(wxEvent &aEvent)
Used to forward events to the canvas from popups, etc.
unsigned m_strtime_camera_movement
void OnMagnify(wxMouseEvent &event)
RENDER_3D_RAYTRACE * m_3d_render_raytracing
void restart_editingTimeOut_Timer()
Reset the editing timer.
BOARD_ITEM * m_currentRollOverItem
RENDER_3D_BASE * m_3d_render
bool m_is_opengl_initialized
void OnResize(wxSizeEvent &event)
bool m_render3dmousePivot
void OnMouseWheel(wxMouseEvent &event)
WX_INFOBAR * m_parentInfoBar
wxTimer m_editing_timeout_timer
void OnLeftDown(wxMouseEvent &event)
wxGLContext * m_glRC
bool initializeOpenGL()
ACCELERATOR_3D * m_accelerator3DShapes
void OnTimerTimeout_Redraw(wxTimerEvent &event)
wxStatusBar * m_parentStatusBar
void DoRePaint()
The actual function to repaint the canvas.
int m_moving_speed_multiplier
bool m_is_opengl_version_supported
wxTimer m_redraw_trigger_timer
BOARD_ADAPTER & m_boardAdapter
void DisplayStatus()
Update the status bar with the position information.
void render3dmousePivot(float aScale)
Render the 3dmouse pivot cursor.
void OnPaint(wxPaintEvent &aEvent)
Called by a wxPaintEvent event.
void RenderRaytracingRequest()
Request to render the current view in Raytracing mode.
void SetEventDispatcher(TOOL_DISPATCHER *aEventDispatcher)
Set a dispatcher that processes events and forwards them to tools.
bool m_render_raytracing_was_requested
float m_camera_moving_speed
bool m_animation_enabled
void OnLeftUp(wxMouseEvent &event)
void ReloadRequest(BOARD *aBoard=nullptr, S3D_CACHE *aCachePointer=nullptr)
RAY getRayAtCurrentMousePosition()
void OnCloseWindow(wxCloseEvent &event)
bool SetView3D(VIEW3D_TYPE aRequestedView)
Select a specific 3D view or operation.
void OnMiddleDown(wxMouseEvent &event)
void GetScreenshot(wxImage &aDstImage)
Request a screenshot and output it to the aDstImage.
void OnMiddleUp(wxMouseEvent &event)
void render_pivot(float t, float aScale)
Render the pivot cursor.
void request_start_moving_camera(float aMovingSpeed=2.0f, bool aRenderPivot=true)
Start a camera movement.
void RenderEngineChanged()
Notify that the render engine was changed.
std::atomic_flag m_is_currently_painting
void OnRefreshRequest(wxEvent &aEvent)
void OnEraseBackground(wxEraseEvent &event)
void releaseOpenGL()
Free created targets and openGL context.
void Request_refresh(bool aRedrawImmediately=true)
Schedule a refresh update of the canvas.
bool m_opengl_supports_raytracing
void OnMouseMove(wxMouseEvent &event)
void move_pivot_based_on_cur_mouse_position()
This function hits a ray to the board and start a movement.
void OnTimerTimeout_Editing(wxTimerEvent &event)
void stop_editingTimeOut_Timer()
Stop the editing time so it will not timeout.
KICAD_T Type() const
Returns the type of object.
Definition: eda_item.h:97
const wxString & GetReference() const
Definition: footprint.h:556
void UnlockCtx(wxGLContext *aContext)
Allow other canvases to bind an OpenGL context.
void DestroyCtx(wxGLContext *aContext)
Destroy a managed OpenGL context.
void LockCtx(wxGLContext *aContext, wxGLCanvas *aCanvas)
Set a context as current and prevents other canvases from switching it.
static GL_CONTEXT_MANAGER & Get()
Return the GL_CONTEXT_MANAGER instance (singleton).
wxGLContext * CreateCtx(wxGLCanvas *aCanvas, const wxGLContext *aOther=nullptr)
Create a managed OpenGL context.
static int SetSwapInterval(int aVal)
Attempts to set the OpenGL swap interval.
Definition: gl_utils.h:49
Provides basic 3D controls ( zoom, rotate, translate, ... )
static const float m_delta_move_step_factor
void OnMouseWheelCamera(wxMouseEvent &event, bool aPan)
void OnMouseMoveCamera(wxMouseEvent &event)
virtual wxSize GetNativePixelSize() const
A wrapper for reporting to a WX_INFOBAR UI element.
Definition: reporter.h:338
void Finalize()
Update the infobar with the reported text.
Definition: reporter.cpp:253
REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED) override
Report a string with a given severity.
Definition: reporter.cpp:237
Definition: pad.h:58
virtual bool Redraw(bool aIsMoving, REPORTER *aStatusReporter=nullptr, REPORTER *aWarningReporter=nullptr)=0
Redraw the view.
virtual int GetWaitForEditingTimeOut()=0
Give the interface the time (in ms) that it should wait for editing or movements before (this works f...
void ReloadRequest()
virtual void SetCurWindowSize(const wxSize &aSize)=0
Before each render, the canvas will tell the render what is the size of its windows,...
bool IsReloadRequestPending() const
Query if there is a pending reload request.
Object to render the board using openGL.
void SetCurrentRollOverItem(BOARD_ITEM *aRollOverItem)
BOARD_ITEM * IntersectBoardItem(const RAY &aRay)
void Reload(REPORTER *aStatusReporter, REPORTER *aWarningReporter, bool aOnlyLoadCopperAndShapes)
Cache for storing the 3D shapes.
Definition: 3d_cache.h:53
T * GetAppSettings()
Returns a handle to the a given settings by type If the settings have already been loaded,...
A wrapper for reporting to a specific text location in a statusbar.
Definition: reporter.h:309
REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED) override
Report a string with a given severity.
Definition: reporter.cpp:214
virtual void DispatchWxEvent(wxEvent &aEvent)
Process wxEvents (mostly UI events), translate them to TOOL_EVENTs, and make tools handle those.
Handle a list of polygons defining a copper zone.
Definition: zone.h:72
bool GetIsRuleArea() const
Accessors to parameters used in Rule Area zones:
Definition: zone.h:710
const wxString & GetZoneName() const
Definition: zone.h:131
bool IsOnCopperLayer() const override
Definition: zone.cpp:266
#define _(s)
wxDEFINE_EVENT(wxEVT_REFRESH_CUSTOM_COMMAND, wxEvent)
Declaration of the eda_3d_viewer class.
static const wxChar * m_logTrace
Trace mask used to enable or disable the trace output of this class.
This file contains miscellaneous commonly used macros and functions.
void OglGetScreenshot(wxImage &aDstImage)
Get the pixel data of current OpenGL image.
Definition: ogl_utils.cpp:37
void Refresh()
Update the board display after modifying it by a python script (note: it is automatically called by a...
see class PGM_BASE
unsigned GetRunningMicroSecs()
An alternate way to calculate an elapsed time (in microsecondes) to class PROF_COUNTER.
@ RPT_SEVERITY_ERROR
KIWAY Kiway & Pgm(), KFCTL_STANDALONE
The global Program "get" accessor.
Definition: single_top.cpp:119
const int scale
wxString From_UTF8(const char *cstring)
bool Intersect(const RAY &aRay, float *t) const
Definition: bbox_3d_ray.cpp:46
Definition: ray.h:63
void Init(const SFVEC3F &o, const SFVEC3F &d)
Definition: ray.cpp:35
SFVEC3F at(float t) const
Definition: ray.h:84
@ PCB_VIA_T
class PCB_VIA, a via (like a track segment on a copper layer)
Definition: typeinfo.h:95
@ PCB_ZONE_T
class ZONE, a copper pour area
Definition: typeinfo.h:105
@ PCB_FOOTPRINT_T
class FOOTPRINT, a footprint
Definition: typeinfo.h:86
@ PCB_PAD_T
class PAD, a pad in a footprint
Definition: typeinfo.h:87
@ PCB_ARC_T
class PCB_ARC, an arc track segment on a copper layer
Definition: typeinfo.h:96
@ PCB_TRACE_T
class PCB_TRACK, a track segment (segment on a copper layer)
Definition: typeinfo.h:94
glm::vec3 SFVEC3F
Definition: xv3d_types.h:44