KiCad PCB EDA Suite
Loading...
Searching...
No Matches
opengl_gal.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) 2012 Torsten Hueter, torstenhtr <at> gmx.de
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 * Copyright (C) 2013-2017 CERN
7 * @author Maciej Suminski <[email protected]>
8 *
9 * Graphics Abstraction Layer (GAL) for OpenGL
10 *
11 * This program is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU General Public License
13 * as published by the Free Software Foundation; either version 2
14 * of the License, or (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 */
24
25#include <kicad_gl/kiglu.h> // Must be included first
26#include <kicad_gl/gl_utils.h>
27
28#include <advanced_config.h>
29#include <build_version.h>
31#include <gal/bitmap_texture.h>
32#include <gal/opengl/utils.h>
33#include <gal/definitions.h>
36#include <font/glyph_types.h>
37#include <math/vector2wx.h>
38#include <bitmap_base.h>
39#include <bezier_curves.h>
40#include <math/util.h> // for KiROUND
41#include <pgm_base.h>
42#include <trace_helpers.h>
43
44#include <wx/app.h>
45#include <wx/frame.h>
46#include <wx/image.h>
47
48#include <macros.h>
49#include <optional>
51#include <thread_pool.h>
52
53#include <core/profile.h>
54
55#include <functional>
56#include <limits>
57#include <memory>
58#include <list>
59#include <vector>
60using namespace std::placeholders;
61using namespace KIGFX;
62
63//#define DISABLE_BITMAP_CACHE
64
65// The current font is "Ubuntu Mono" available under Ubuntu Font Licence 1.0
66// (see ubuntu-font-licence-1.0.txt for details)
67#include "gl_resources.h"
68#include <glsl_kicad_frag.h>
69#include <glsl_kicad_vert.h>
70using namespace KIGFX::BUILTIN_FONT;
71
72static void InitTesselatorCallbacks( GLUtesselator* aTesselator );
73
74// Trace mask for XOR/difference mode debugging
75static const wxChar* const traceGalXorMode = wxT( "KICAD_GAL_XOR_MODE" );
76
77// Stencil bit allocation used by OPENGL_GAL. Each independent use of the stencil
78// buffer claims a distinct bit so they can coexist within one frame.
79namespace
80{
81constexpr GLuint STENCIL_DOTS_MARKER = 0x01; // Set at every dot position by the
82 // display-grid DOTS rendering pass.
83constexpr GLuint STENCIL_GRID_COVERAGE = 0x80; // Set inside a PCB_GRIDITEM's coverage
84 // area to cut the display grid (and
85 // lower-priority grid-items) out.
86} // namespace
87
88static wxGLAttributes getGLAttribs()
89{
90 wxGLAttributes attribs;
91
92 // Without minimum channel sizes EGL lists its smallest matching config first, which on
93 // Wayland is a dithered 16-bit one
94 attribs.RGBA().MinRGBA( 8, 8, 8, 0 ).DoubleBuffer().Depth( 8 ).EndList();
95
96 return attribs;
97}
98
99wxGLContext* OPENGL_GAL::m_glMainContext = nullptr;
103
106bool OPENGL_GAL::m_glLoaded = false;
107GL_RESET_BUDGET OPENGL_GAL::m_resetBudget( 3, std::chrono::seconds( 60 ) );
108std::set<OPENGL_GAL*> OPENGL_GAL::m_instances;
110
111GL_RESET_BUDGET::CLOCK::time_point OPENGL_GAL::m_resetDetectedAt;
112
113namespace KIGFX
114{
116{
117public:
119 m_cacheSize( 0 )
120 {}
121
123
125 void Abandon() { m_bitmaps.clear(); }
126
127 GLuint RequestBitmap( const BITMAP_BASE* aBitmap );
128
129private:
131 {
132 GLuint id;
133 int w, h;
134 size_t size;
135 long long int accessTime;
136 };
137
138 GLuint cacheBitmap( const BITMAP_BASE* aBitmap );
139
140 const size_t m_cacheMaxElements = 50;
141
142 std::map<const KIID, CACHED_BITMAP> m_bitmaps;
143 std::list<KIID> m_cacheLru;
145 std::list<GLuint> m_freedTextureIds;
146};
147
148}; // namespace KIGFX
149
150
152{
153 for( auto& bitmap : m_bitmaps )
154 glDeleteTextures( 1, &bitmap.second.id );
155}
156
157
159{
160#ifndef DISABLE_BITMAP_CACHE
161 auto it = m_bitmaps.find( aBitmap->GetImageID() );
162
163 if( it != m_bitmaps.end() )
164 {
165 // A bitmap is found in cache bitmap. Ensure the associated texture is still valid.
166 if( glIsTexture( it->second.id ) )
167 {
168 it->second.accessTime = wxGetUTCTimeMillis().GetValue();
169 return it->second.id;
170 }
171 else
172 {
173 // Delete the invalid bitmap cache and its data
174 glDeleteTextures( 1, &it->second.id );
175 m_freedTextureIds.emplace_back( it->second.id );
176
177 auto listIt = std::find( m_cacheLru.begin(), m_cacheLru.end(), it->first );
178
179 if( listIt != m_cacheLru.end() )
180 m_cacheLru.erase( listIt );
181
182 m_cacheSize -= it->second.size;
183
184 m_bitmaps.erase( it );
185 }
186
187 // the cached bitmap is not valid and deleted, it will be recreated.
188 }
189
190#endif
191 return cacheBitmap( aBitmap );
192}
193
194
196{
197 CACHED_BITMAP bmp;
198
199 const wxImage* imgPtr = aBitmap->GetOriginalImageData();
200
201 if( !imgPtr )
202 return std::numeric_limits< GLuint >::max();
203
204 GLint maxTextureSize;
205 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &maxTextureSize );
206
207 wxImage imgData = FitImageToTexture( *imgPtr, maxTextureSize );
208
209 if( !imgData.IsOk() )
210 return std::numeric_limits< GLuint >::max();
211
212 bmp.w = imgData.GetSize().x;
213 bmp.h = imgData.GetSize().y;
214
215 GLuint textureID;
216
217 if( m_freedTextureIds.empty() )
218 {
219 glGenTextures( 1, &textureID );
220 }
221 else
222 {
223 textureID = m_freedTextureIds.front();
224 m_freedTextureIds.pop_front();
225 }
226
227 glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
228
229 if( imgData.HasAlpha() || imgData.HasMask() )
230 {
231 bmp.size = static_cast<size_t>( bmp.w ) * bmp.h * 4;
232
233 const std::vector<uint8_t> rgba = ImageToRgba( imgData );
234
235 glBindTexture( GL_TEXTURE_2D, textureID );
236 glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, bmp.w, bmp.h, 0, GL_RGBA, GL_UNSIGNED_BYTE,
237 rgba.data() );
238 }
239 else
240 {
241 bmp.size = static_cast<size_t>( bmp.w ) * bmp.h * 3;
242
243 uint8_t* srcP = imgData.GetData();
244
245 glBindTexture( GL_TEXTURE_2D, textureID );
246 glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB8, bmp.w, bmp.h, 0, GL_RGB, GL_UNSIGNED_BYTE, srcP );
247 }
248
249 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
250 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
251
252 long long currentTime = wxGetUTCTimeMillis().GetValue();
253
254 bmp.id = textureID;
255 bmp.accessTime = currentTime;
256
257#ifndef DISABLE_BITMAP_CACHE
258 // A single oversized bitmap can exceed the whole cache budget, so evict until it fits or the
259 // cache is drained
260 while( ( m_cacheLru.size() + 1 > m_cacheMaxElements || m_cacheSize + bmp.size > BITMAP_CACHE_MAX_BYTES )
261 && !m_cacheLru.empty() )
262 {
263 KIID toRemove( 0 );
264 auto toRemoveLru = m_cacheLru.end();
265
266 // Remove entries accessed > 1s ago first
267 for( const auto& [kiid, cachedBmp] : m_bitmaps )
268 {
269 const int cacheTimeoutMillis = 1000L;
270
271 if( currentTime - cachedBmp.accessTime > cacheTimeoutMillis )
272 {
273 toRemove = kiid;
274 toRemoveLru = std::find( m_cacheLru.begin(), m_cacheLru.end(), toRemove );
275 break;
276 }
277 }
278
279 // Otherwise, remove the latest entry (it's less likely to be needed soon)
280 if( toRemove == niluuid )
281 {
282 toRemoveLru = m_cacheLru.end();
283 toRemoveLru--;
284
285 toRemove = *toRemoveLru;
286 }
287
288 CACHED_BITMAP& cachedBitmap = m_bitmaps[toRemove];
289
290 m_cacheSize -= cachedBitmap.size;
291 glDeleteTextures( 1, &cachedBitmap.id );
292 m_freedTextureIds.emplace_back( cachedBitmap.id );
293
294 m_bitmaps.erase( toRemove );
295 m_cacheLru.erase( toRemoveLru );
296 }
297
298 m_cacheLru.emplace_back( aBitmap->GetImageID() );
299 m_cacheSize += bmp.size;
300 m_bitmaps.emplace( aBitmap->GetImageID(), std::move( bmp ) );
301#endif
302
303 return textureID;
304}
305
306
308 wxWindow* aParent,
309 wxEvtHandler* aMouseListener, wxEvtHandler* aPaintListener,
310 const wxString& aName ) :
311 GAL( aDisplayOptions ),
312 HIDPI_GL_CANVAS( aVcSettings, aParent, getGLAttribs(), wxID_ANY, wxDefaultPosition,
313 wxDefaultSize,
314 wxEXPAND, aName ),
316 m_mouseListener( aMouseListener ),
317 m_paintListener( aPaintListener ),
318 m_currentManager( nullptr ),
319 m_cachedManager( nullptr ),
320 m_nonCachedManager( nullptr ),
321 m_overlayManager( nullptr ),
322 m_tempManager( nullptr ),
323 m_mainBuffer( 0 ),
324 m_overlayBuffer( 0 ),
325 m_tempBuffer( 0 ),
326 m_isContextLocked( false ),
327 m_isContextValid( false ),
329{
330 if( m_glMainContext == nullptr )
331 {
333
334 if( !m_glMainContext )
335 throw std::runtime_error( "Could not create the main OpenGL context" );
336
338 }
339 else
340 {
342
343 if( !m_glPrivContext )
344 throw std::runtime_error( "Could not create a private OpenGL context" );
345 }
346
347 m_shader = new SHADER();
349 m_instances.insert( this );
350
351 m_bitmapCache = std::make_unique<GL_BITMAP_CACHE>();
352
354 m_compositor->SetAntialiasingMode( m_options.antialiasing_mode );
355
356 // Initialize the flags
359 m_isInitialized = false;
360 m_isGrouping = false;
361 m_groupCounter = 0;
362
363 // Connect the native cursor handler
364 Connect( wxEVT_SET_CURSOR, wxSetCursorEventHandler( OPENGL_GAL::onSetNativeCursor ), nullptr,
365 this );
366
367 // Connecting the event handlers
368 Connect( wxEVT_PAINT, wxPaintEventHandler( OPENGL_GAL::onPaint ) );
369
370 // Mouse events are skipped to the parent
371 Connect( wxEVT_MOTION, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
372 Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
373 Connect( wxEVT_LEFT_UP, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
374 Connect( wxEVT_LEFT_DCLICK, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
375 Connect( wxEVT_MIDDLE_DOWN, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
376 Connect( wxEVT_MIDDLE_UP, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
377 Connect( wxEVT_MIDDLE_DCLICK, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
378 Connect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
379 Connect( wxEVT_RIGHT_UP, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
380 Connect( wxEVT_RIGHT_DCLICK, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
381 Connect( wxEVT_AUX1_DOWN, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
382 Connect( wxEVT_AUX1_UP, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
383 Connect( wxEVT_AUX1_DCLICK, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
384 Connect( wxEVT_AUX2_DOWN, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
385 Connect( wxEVT_AUX2_UP, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
386 Connect( wxEVT_AUX2_DCLICK, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
387 Connect( wxEVT_MOUSEWHEEL, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
388 Connect( wxEVT_MAGNIFY, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
389
390#if defined _WIN32 || defined _WIN64
391 Connect( wxEVT_ENTER_WINDOW, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
392 Connect( wxEVT_LEAVE_WINDOW, wxMouseEventHandler( OPENGL_GAL::skipMouseEvent ) );
393#endif
394
395 Bind( wxEVT_GESTURE_ZOOM, &OPENGL_GAL::skipGestureEvent, this );
396 Bind( wxEVT_GESTURE_PAN, &OPENGL_GAL::skipGestureEvent, this );
397
398 SetSize( aParent->GetClientSize() );
399#ifdef __WXMAC__
400 // wxDefaultPosition can place the GL child one pixel above and left of its parent.
401 SetPosition( wxPoint( 0, 0 ) );
402#endif
404
405 // Grid color settings are different in Cairo and OpenGL
406 SetGridColor( COLOR4D( 0.8, 0.8, 0.8, 0.1 ) );
408
409 // Tesselator initialization
410 m_tesselator = gluNewTess();
412
413 gluTessProperty( m_tesselator, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_POSITIVE );
414
416
417 // Avoid uninitialized variables:
423 ufm_fontTexture = -1;
425 m_swapInterval = 0;
426}
427
428
430{
432
433 if( gl_mgr )
434 {
435 // wxMSW destroys child windows before their C++ objects, so our own device context
436 // can already be gone and the teardown below would run against a sibling's context
437 m_isContextValid = gl_mgr->LockCtx( m_glPrivContext, this );
438
439 // A reset already destroyed our objects, and some drivers report every call as out of memory
441 m_isContextValid = false;
442
444 m_instances.erase( this );
445
446 if( !m_isContextValid )
447 {
448 // Whichever context is still current may belong to another share group, so every
449 // delete below would be aimed at an unrelated object of the same name
450 m_compositor->Abandon();
451 m_bitmapCache->Abandon();
452 m_shader->Abandon();
453
454 if( m_isInitialized )
455 {
456 m_cachedManager->Abandon();
457 m_nonCachedManager->Abandon();
458 m_overlayManager->Abandon();
459 m_tempManager->Abandon();
460 }
461 }
462 else if( m_isInitialized )
463 {
464 glFlush();
465 }
466
467 gluDeleteTess( m_tesselator );
468
469 if( m_isContextValid )
470 ClearCache();
471
472 // Groups free their vertices through the cached manager, so they must go before it does
473 m_groups.clear();
474
475 delete m_compositor;
476
477 if( m_isInitialized )
478 {
479 delete m_cachedManager;
480 delete m_nonCachedManager;
481 delete m_overlayManager;
482 delete m_tempManager;
483 }
484
485 // The program lives in the share group, so it outlives this canvas unless it is deleted
486 // while the context is still current
487 delete m_shader;
488
489 gl_mgr->UnlockCtx( m_glPrivContext );
490
491 // If it was the main context, then it will be deleted
492 // when the last OpenGL GAL instance is destroyed (a few lines below)
494 gl_mgr->DestroyCtx( m_glPrivContext );
495
496 // Are we destroying the last GAL instance?
498 {
499 if( gl_mgr->LockCtx( m_glMainContext, this ) && m_isBitmapFontLoaded )
500 glDeleteTextures( 1, &g_fontTexture );
501
502 gl_mgr->UnlockCtx( m_glMainContext );
503 gl_mgr->DestroyCtx( m_glMainContext );
504 m_glMainContext = nullptr;
505
506 // The texture dies with the context even when it could not be made current to delete it
507 g_fontTexture = 0;
508 m_isBitmapFontLoaded = false;
509 }
510 }
511}
512
513
515{
516 static std::optional<wxString> cached;
517
518 if( cached.has_value() )
519 return *cached;
520
521 wxString retVal = wxEmptyString;
522
523 wxFrame* testFrame = new wxFrame( nullptr, wxID_ANY, wxT( "" ), wxDefaultPosition,
524 wxSize( 1, 1 ), wxFRAME_TOOL_WINDOW | wxNO_BORDER );
525
526 KIGFX::OPENGL_GAL* opengl_gal = nullptr;
527
528 try
529 {
531 opengl_gal = new KIGFX::OPENGL_GAL( dummy, aOptions, testFrame );
532
533 testFrame->Raise();
534 testFrame->Show();
535
536#ifdef __WXGTK__
537 // On GTK, Show() only queues realization. The GDK drawing window
538 // needed by SetCurrent() may not exist yet. Yield to let the event
539 // loop process the realize signal before we try to lock the context.
540 wxYield();
541#endif
542
543 GAL_CONTEXT_LOCKER lock( opengl_gal );
544 opengl_gal->init();
545 }
546 catch( std::runtime_error& err )
547 {
548 //Test failed
549 retVal = wxString( err.what() );
550 }
551
552 delete opengl_gal;
553 delete testFrame;
554
555 cached = retVal;
556 return retVal;
557}
558
559
560void OPENGL_GAL::PostPaint( wxPaintEvent& aEvent )
561{
562 // posts an event to m_paint_listener to ask for redraw the canvas.
563 if( m_paintListener )
564 wxPostEvent( m_paintListener, aEvent );
565}
566
567
569{
570 GAL_CONTEXT_LOCKER lock( this );
571
572 bool refresh = false;
573
574 // Options arrive before the canvas is realized, so the context is not current yet. Only
575 // the compositor needs it; BeginDrawing reconciles the mode once we can bind
576 if( m_isContextValid && m_options.antialiasing_mode != m_compositor->GetAntialiasingMode() )
577 {
578 m_compositor->SetAntialiasingMode( m_options.antialiasing_mode );
580 refresh = true;
581 }
582
583 if( super::updatedGalDisplayOptions( aOptions ) || refresh )
584 {
585 Refresh();
586 refresh = true;
587 }
588
589 return refresh;
590}
591
592
594{
596 return std::min( std::abs( matrix.GetScale().x ), std::abs( matrix.GetScale().y ) );
597}
598
599
601{
602 double sf = GetScaleFactor();
603 return VECTOR2D( 2.0 / (double) ( m_screenSize.x * sf ), 2.0 /
604 (double) ( m_screenSize.y * sf ) );
605}
606
607
609{
610#ifdef KICAD_GAL_PROFILE
611 PROF_TIMER totalRealTime( "OPENGL_GAL::beginDrawing()", true );
612#endif /* KICAD_GAL_PROFILE */
613
614 wxASSERT_MSG( m_isContextLocked, "GAL_DRAWING_CONTEXT RAII object should have locked context. "
615 "Calling GAL::beginDrawing() directly is not allowed." );
616
617 wxASSERT_MSG( IsVisible(), "GAL::beginDrawing() must not be entered when GAL is not visible. "
618 "Other drawing routines will expect everything to be initialized "
619 "which will not be the case." );
620
621 if( !m_isInitialized )
622 init();
623
624 // Set up the view port
625 glMatrixMode( GL_PROJECTION );
626 glLoadIdentity();
627
628 // Create the screen transformation (Do the RH-LH conversion here)
629 glOrtho( 0, (GLint) m_screenSize.x, (GLsizei) m_screenSize.y, 0,
630 -m_depthRange.x, -m_depthRange.y );
631
632 // An antialiasing change that arrived without a current context never reached the compositor
633 if( m_options.antialiasing_mode != m_compositor->GetAntialiasingMode() )
634 {
635 m_compositor->SetAntialiasingMode( m_options.antialiasing_mode );
637 }
638
640 {
641 // Prepare rendering target buffers
642 m_compositor->Initialize();
643 m_mainBuffer = m_compositor->CreateBuffer();
644 try
645 {
646 m_tempBuffer = m_compositor->CreateBuffer();
647 }
648 catch( const std::runtime_error& )
649 {
650 wxLogVerbose( "Could not create a framebuffer for diff mode blending.\n" );
651 m_tempBuffer = 0;
652 }
653 try
654 {
655 m_overlayBuffer = m_compositor->CreateBuffer();
656 }
657 catch( const std::runtime_error& )
658 {
659 wxLogVerbose( "Could not create a framebuffer for overlays.\n" );
660 m_overlayBuffer = 0;
661 }
662
664 }
665
666 m_compositor->Begin();
667
668 // Disable 2D Textures
669 glDisable( GL_TEXTURE_2D );
670
671 glShadeModel( GL_FLAT );
672
673 // Enable the depth buffer
674 glEnable( GL_DEPTH_TEST );
675 glDepthFunc( GL_LESS );
676
677 // Setup blending, required for transparent objects
678 glEnable( GL_BLEND );
679 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
680
681 glMatrixMode( GL_MODELVIEW );
682
683 // Set up the world <-> screen transformation
685 GLdouble matrixData[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
686 matrixData[0] = m_worldScreenMatrix.m_data[0][0];
687 matrixData[1] = m_worldScreenMatrix.m_data[1][0];
688 matrixData[2] = m_worldScreenMatrix.m_data[2][0];
689 matrixData[4] = m_worldScreenMatrix.m_data[0][1];
690 matrixData[5] = m_worldScreenMatrix.m_data[1][1];
691 matrixData[6] = m_worldScreenMatrix.m_data[2][1];
692 matrixData[12] = m_worldScreenMatrix.m_data[0][2];
693 matrixData[13] = m_worldScreenMatrix.m_data[1][2];
694 matrixData[14] = m_worldScreenMatrix.m_data[2][2];
695 glLoadMatrixd( matrixData );
696
697 // Set defaults
700
701 // Remove all previously stored items
702 m_nonCachedManager->Clear();
703 m_overlayManager->Clear();
704 m_tempManager->Clear();
705
706 m_cachedManager->BeginDrawing();
707 m_nonCachedManager->BeginDrawing();
708 m_overlayManager->BeginDrawing();
709 m_tempManager->BeginDrawing();
710
712 {
713 // Keep bitmap font texture always bound to the second texturing unit
714 const GLint FONT_TEXTURE_UNIT = 2;
715
716 // Either load the font atlas to video memory, or simply bind it to a texture unit
718 {
719 glActiveTexture( GL_TEXTURE0 + FONT_TEXTURE_UNIT );
720 glGenTextures( 1, &g_fontTexture );
721 glBindTexture( GL_TEXTURE_2D, g_fontTexture );
722 glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB8, font_image.width, font_image.height, 0, GL_RGB,
723 GL_UNSIGNED_BYTE, font_image.pixels );
724 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
725 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
726 checkGlError( "loading bitmap font", __FILE__, __LINE__ );
727
728 glActiveTexture( GL_TEXTURE0 );
729
731 }
732 else
733 {
734 glActiveTexture( GL_TEXTURE0 + FONT_TEXTURE_UNIT );
735 glBindTexture( GL_TEXTURE_2D, g_fontTexture );
736 glActiveTexture( GL_TEXTURE0 );
737 }
738
739 m_shader->Use();
740 m_shader->SetParameter( ufm_fontTexture, (int) FONT_TEXTURE_UNIT );
741 m_shader->SetParameter( ufm_fontTextureWidth, (int) font_image.width );
742 m_shader->Deactivate();
743 checkGlError( "setting bitmap font sampler as shader parameter", __FILE__, __LINE__ );
744
746 }
747
748 m_shader->Use();
749 m_shader->SetParameter( ufm_worldPixelSize,
750 (float) ( getWorldPixelSize() / GetScaleFactor() ) );
751 const VECTOR2D& screenPixelSize = getScreenPixelSize();
752 m_shader->SetParameter( ufm_screenPixelSize, screenPixelSize );
753 double pixelSizeMultiplier = m_compositor->GetAntialiasSupersamplingFactor();
754 m_shader->SetParameter( ufm_pixelSizeMultiplier, (float) pixelSizeMultiplier );
755 VECTOR2D renderingOffset = m_compositor->GetAntialiasRenderingOffset();
756 renderingOffset.x *= screenPixelSize.x;
757 renderingOffset.y *= screenPixelSize.y;
758 m_shader->SetParameter( ufm_antialiasingOffset, renderingOffset );
760 m_shader->Deactivate();
761
762 // Something between BeginDrawing and EndDrawing seems to depend on
763 // this texture unit being active, but it does not assure it itself.
764 glActiveTexture( GL_TEXTURE0 );
765
766 // Unbind buffers - set compositor for direct drawing
768
769#ifdef KICAD_GAL_PROFILE
770 totalRealTime.Stop();
771 wxLogTrace( traceGalProfile, wxT( "OPENGL_GAL::beginDrawing(): %.1f ms" ),
772 totalRealTime.msecs() );
773#endif /* KICAD_GAL_PROFILE */
774}
775
776void OPENGL_GAL::SetMinLineWidth( float aLineWidth )
777{
778 GAL::SetMinLineWidth( aLineWidth );
779
780 if( m_shader && ufm_minLinePixelWidth != -1 )
781 {
782 m_shader->Use();
783 m_shader->SetParameter( ufm_minLinePixelWidth, aLineWidth );
784 m_shader->Deactivate();
785 }
786}
787
788
790{
791 wxASSERT_MSG( m_isContextLocked, "What happened to the context lock?" );
792
793 PROF_TIMER cntTotal( "gl-end-total" );
794 PROF_TIMER cntEndCached( "gl-end-cached" );
795 PROF_TIMER cntEndNoncached( "gl-end-noncached" );
796 PROF_TIMER cntEndOverlay( "gl-end-overlay" );
797 PROF_TIMER cntComposite( "gl-composite" );
798 PROF_TIMER cntSwap( "gl-swap" );
799
800 cntTotal.Start();
801
802 // Cached & non-cached containers are rendered to the same buffer
803 m_compositor->SetBuffer( m_mainBuffer );
804
805 cntEndNoncached.Start();
806 m_nonCachedManager->EndDrawing();
807 cntEndNoncached.Stop();
808
809 cntEndCached.Start();
810 m_cachedManager->EndDrawing();
811 cntEndCached.Stop();
812
813 cntEndOverlay.Start();
814 // Overlay container is rendered to a different buffer
815 if( m_overlayBuffer )
816 m_compositor->SetBuffer( m_overlayBuffer );
817
818 m_overlayManager->EndDrawing();
819 cntEndOverlay.Stop();
820
821 cntComposite.Start();
822
823 // Be sure that the framebuffer is not colorized (happens on specific GPU&drivers combinations)
824 glColor4d( 1.0, 1.0, 1.0, 1.0 );
825
826 // Draw the remaining contents, blit the rendering targets to the screen, swap the buffers
827 m_compositor->DrawBuffer( m_mainBuffer );
828
829 if( m_overlayBuffer )
830 m_compositor->DrawBuffer( m_overlayBuffer );
831
832 m_compositor->Present();
833 blitCursor();
834
835 cntComposite.Stop();
836
837 cntSwap.Start();
838 SwapBuffers();
839 cntSwap.Stop();
840
841 cntTotal.Stop();
842
843#ifdef KICAD_GAL_PROFILE
844 wxLogTrace( traceGalProfile, "Timing: %s %s %s %s %s %s", cntTotal.to_string(),
845 cntEndCached.to_string(), cntEndNoncached.to_string(), cntEndOverlay.to_string(),
846 cntComposite.to_string(), cntSwap.to_string() );
847#endif
848}
849
850
851bool OPENGL_GAL::GetScreenshot( wxImage& aDstImage )
852{
853 // A canvas that has never drawn has no compositor buffers to read
855 return false;
856
857 GAL_CONTEXT_LOCKER locker( this );
858
859 if( !m_isContextValid )
860 return false;
861
862 m_compositor->SetBuffer( m_mainBuffer );
863
864 GLint viewport[4];
865 glGetIntegerv( GL_VIEWPORT, viewport );
866
867 const int w = viewport[2];
868 const int h = viewport[3];
869
870 GLint readBuffer = GL_COLOR_ATTACHMENT0;
871 glGetIntegerv( GL_DRAW_BUFFER, &readBuffer );
872
873 bool ok = false;
874
875 if( w > 0 && h > 0 )
876 {
877 std::vector<unsigned char> rgba( (size_t) w * h * 4 );
878
879 glFinish();
880 glPixelStorei( GL_PACK_ALIGNMENT, 1 );
881 glReadBuffer( (GLenum) readBuffer );
882 glReadPixels( 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, rgba.data() );
883
884 // wxImage wants separate RGB and alpha buffers and takes ownership of them.
885 unsigned char* rgb = (unsigned char*) malloc( (size_t) w * h * 3 );
886 unsigned char* alpha = (unsigned char*) malloc( (size_t) w * h );
887
888 for( int i = 0; i < w * h; ++i )
889 {
890 rgb[i * 3 + 0] = rgba[i * 4 + 0];
891 rgb[i * 3 + 1] = rgba[i * 4 + 1];
892 rgb[i * 3 + 2] = rgba[i * 4 + 2];
893 alpha[i] = rgba[i * 4 + 3];
894 }
895
896 aDstImage.SetData( rgb, w, h, false );
897 aDstImage.SetAlpha( alpha, false );
898
899 aDstImage = aDstImage.Mirror( false );
900 ok = true;
901 }
902
904
905 return ok;
906}
907
908
909void OPENGL_GAL::LockContext( int aClientCookie )
910{
911 wxASSERT_MSG( !m_isContextLocked, "Context already locked." );
912 m_isContextLocked = true;
913 m_lockClientCookie = aClientCookie;
914
916
917 if( !mgr )
918 return;
919
921
922 // Entry points are process wide, so a canvas that has not drawn yet can still be polled
924 {
926 }
927
928 // A lost context accepts commands but ignores them, so treat it as unusable
930 m_isContextValid = false;
931}
932
933
941
942
944{
945 if( glGetGraphicsResetStatus )
946 return glGetGraphicsResetStatus();
947
948 if( glGetGraphicsResetStatusARB )
949 return glGetGraphicsResetStatusARB();
950
951 return GL_NO_ERROR;
952}
953
954
956{
957 // Only contexts created with the lose-on-reset strategy ever report a reset
958 GLenum status = queryResetStatus();
959
960 if( status != GL_NO_ERROR )
961 wxLogTrace( traceGalContext, wxS( "GL context %p reset, status 0x%x" ), m_glPrivContext, status );
962
963 return status != GL_NO_ERROR;
964}
965
966
968{
970 m_resetDetectedAt = GL_RESET_BUDGET::CLOCK::now();
971 m_resetSettled = false;
973
974 wxLogTrace( traceGalContext, wxS( "Orphaned GL context group, now %d, budget exhausted %d" ), m_contextGroupId,
975 m_resetBudgetExhausted ? 1 : 0 );
976
977 bool mainOwned = false;
978
979 for( OPENGL_GAL* gal : m_instances )
980 {
981 if( gal->m_glPrivContext == m_glMainContext )
982 mainOwned = true;
983 }
984
985 // A live owner destroys the old main context itself; an ownerless one would otherwise leak
986 if( !mainOwned && m_glMainContext )
988
989 // The dead group still owns these; the next canvas created starts a new group
990 m_glMainContext = nullptr;
991 g_fontTexture = 0;
992 m_isBitmapFontLoaded = false;
993
994 for( OPENGL_GAL* gal : m_instances )
995 gal->Refresh();
996}
997
998
1000{
1002
1003 if( m_resetSettled || !mgr )
1004 return true;
1005
1006 if( GL_RESET_BUDGET::CLOCK::now() - m_resetDetectedAt >= std::chrono::seconds( 2 ) )
1007 {
1008 wxLogTrace( traceGalContext, wxS( "GL reset did not report completion, rebuilding anyway" ) );
1009 m_resetSettled = true;
1010 return true;
1011 }
1012
1013 // The lost context keeps reporting the reset until the hardware has finished it
1014 if( mgr->LockCtx( m_glPrivContext, this ) && queryResetStatus() == GL_NO_ERROR )
1015 {
1016 wxLogTrace( traceGalContext, wxS( "GL reset completed" ) );
1017 m_resetSettled = true;
1018 }
1019
1020 mgr->UnlockCtx( m_glPrivContext );
1021 return m_resetSettled;
1022}
1023
1024
1025void OPENGL_GAL::UnlockContext( int aClientCookie )
1026{
1027 wxASSERT_MSG( m_isContextLocked, "Context not locked. A GAL_CONTEXT_LOCKER RAII object must "
1028 "be stacked rather than making separate lock/unlock calls." );
1029
1030 wxASSERT_MSG( m_lockClientCookie == aClientCookie,
1031 "Context was locked by a different client. "
1032 "Should not be possible with RAII objects." );
1033
1034 m_isContextLocked = false;
1035
1037
1038 if( !mgr )
1039 return;
1040
1041 mgr->UnlockCtx( m_glPrivContext );
1042}
1043
1044
1046{
1047 wxASSERT_MSG( m_isContextLocked, "GAL_UPDATE_CONTEXT RAII object should have locked context. "
1048 "Calling this from anywhere else is not allowed." );
1049
1050 wxASSERT_MSG( IsVisible(), "GAL::beginUpdate() must not be entered when GAL is not visible. "
1051 "Other update routines will expect everything to be initialized "
1052 "which will not be the case." );
1053
1054 if( !m_isInitialized )
1055 init();
1056
1057 m_cachedManager->Map();
1058}
1059
1060
1062{
1063 if( !m_isInitialized )
1064 return;
1065
1066 m_cachedManager->Unmap();
1067}
1068
1069
1070void OPENGL_GAL::DrawLine( const VECTOR2D& aStartPoint, const VECTOR2D& aEndPoint )
1071{
1073
1074 drawLineQuad( aStartPoint, aEndPoint );
1075}
1076
1077
1078void OPENGL_GAL::DrawSegment( const VECTOR2D& aStartPoint, const VECTOR2D& aEndPoint,
1079 double aWidth )
1080{
1081 drawSegment( aStartPoint, aEndPoint, aWidth );
1082}
1083
1084
1085void OPENGL_GAL::drawSegment( const VECTOR2D& aStartPoint, const VECTOR2D& aEndPoint, double aWidth,
1086 bool aReserve )
1087{
1088 VECTOR2D startEndVector = aEndPoint - aStartPoint;
1089 double lineLength = startEndVector.EuclideanNorm();
1090
1091 // Be careful about floating point rounding. As we draw segments in larger and larger
1092 // coordinates, the shader (which uses floats) will lose precision and stop drawing small
1093 // segments. In this case, we need to draw a circle for the minimal segment.
1094 // Check if the coordinate differences can be accurately represented as floats
1095 float startX = static_cast<float>( aStartPoint.x );
1096 float startY = static_cast<float>( aStartPoint.y );
1097 float endX = static_cast<float>( aEndPoint.x );
1098 float endY = static_cast<float>( aEndPoint.y );
1099
1100 if( startX == endX && startY == endY )
1101 {
1102 drawCircle( aStartPoint, aWidth / 2, aReserve );
1103 return;
1104 }
1105
1106 if( m_isFillEnabled || aWidth == 1.0 )
1107 {
1109
1110 SetLineWidth( aWidth );
1111 drawLineQuad( aStartPoint, aEndPoint, aReserve );
1112 }
1113 else
1114 {
1115 EDA_ANGLE lineAngle( startEndVector );
1116
1117 // Outlined tracks
1118 SetLineWidth( 1.0 );
1120 m_strokeColor.a );
1121
1122 Save();
1123
1124 if( aReserve )
1125 m_currentManager->Reserve( 6 + 6 + 3 + 3 ); // Two line quads and two semicircles
1126
1127 m_currentManager->Translate( aStartPoint.x, aStartPoint.y, 0.0 );
1128 m_currentManager->Rotate( lineAngle.AsRadians(), 0.0f, 0.0f, 1.0f );
1129
1130 drawLineQuad( VECTOR2D( 0.0, aWidth / 2.0 ), VECTOR2D( lineLength, aWidth / 2.0 ), false );
1131
1132 drawLineQuad( VECTOR2D( 0.0, -aWidth / 2.0 ), VECTOR2D( lineLength, -aWidth / 2.0 ),
1133 false );
1134
1135 // Draw line caps
1136 drawStrokedSemiCircle( VECTOR2D( 0.0, 0.0 ), aWidth / 2, M_PI / 2, false );
1137 drawStrokedSemiCircle( VECTOR2D( lineLength, 0.0 ), aWidth / 2, -M_PI / 2, false );
1138
1139 Restore();
1140 }
1141}
1142
1143
1144void OPENGL_GAL::DrawCircle( const VECTOR2D& aCenterPoint, double aRadius )
1145{
1146 drawCircle( aCenterPoint, aRadius );
1147}
1148
1149
1150void OPENGL_GAL::DrawHoleWall( const VECTOR2D& aCenterPoint, double aHoleRadius,
1151 double aWallWidth )
1152{
1153 if( m_isFillEnabled )
1154 {
1156
1157 m_currentManager->Shader( SHADER_HOLE_WALL, 1.0, aHoleRadius, aWallWidth );
1158 m_currentManager->Vertex( aCenterPoint.x, aCenterPoint.y, m_layerDepth );
1159
1160 m_currentManager->Shader( SHADER_HOLE_WALL, 2.0, aHoleRadius, aWallWidth );
1161 m_currentManager->Vertex( aCenterPoint.x, aCenterPoint.y, m_layerDepth );
1162
1163 m_currentManager->Shader( SHADER_HOLE_WALL, 3.0, aHoleRadius, aWallWidth );
1164 m_currentManager->Vertex( aCenterPoint.x, aCenterPoint.y, m_layerDepth );
1165 }
1166}
1167
1168
1169void OPENGL_GAL::drawCircle( const VECTOR2D& aCenterPoint, double aRadius, bool aReserve )
1170{
1171 if( m_isFillEnabled )
1172 {
1173 if( aReserve )
1174 m_currentManager->Reserve( 3 );
1175
1177
1178 /* Draw a triangle that contains the circle, then shade it leaving only the circle.
1179 * Parameters given to Shader() are indices of the triangle's vertices
1180 * (if you want to understand more, check the vertex shader source [shader.vert]).
1181 * Shader uses this coordinates to determine if fragments are inside the circle or not.
1182 * Does the calculations in the vertex shader now (pixel alignment)
1183 * v2
1184 * /\
1185 * //\\
1186 * v0 /_\/_\ v1
1187 */
1188 m_currentManager->Shader( SHADER_FILLED_CIRCLE, 1.0, aRadius );
1189 m_currentManager->Vertex( aCenterPoint.x, aCenterPoint.y, m_layerDepth );
1190
1191 m_currentManager->Shader( SHADER_FILLED_CIRCLE, 2.0, aRadius );
1192 m_currentManager->Vertex( aCenterPoint.x, aCenterPoint.y, m_layerDepth );
1193
1194 m_currentManager->Shader( SHADER_FILLED_CIRCLE, 3.0, aRadius );
1195 m_currentManager->Vertex( aCenterPoint.x, aCenterPoint.y, m_layerDepth );
1196 }
1197
1198 if( m_isStrokeEnabled )
1199 {
1200 if( aReserve )
1201 m_currentManager->Reserve( 3 );
1202
1204 m_strokeColor.a );
1205
1206 /* Draw a triangle that contains the circle, then shade it leaving only the circle.
1207 * Parameters given to Shader() are indices of the triangle's vertices
1208 * (if you want to understand more, check the vertex shader source [shader.vert]).
1209 * and the line width. Shader uses this coordinates to determine if fragments are
1210 * inside the circle or not.
1211 * v2
1212 * /\
1213 * //\\
1214 * v0 /_\/_\ v1
1215 */
1216 m_currentManager->Shader( SHADER_STROKED_CIRCLE, 1.0, aRadius, m_lineWidth );
1217 m_currentManager->Vertex( aCenterPoint.x, // v0
1218 aCenterPoint.y, m_layerDepth );
1219
1220 m_currentManager->Shader( SHADER_STROKED_CIRCLE, 2.0, aRadius, m_lineWidth );
1221 m_currentManager->Vertex( aCenterPoint.x, // v1
1222 aCenterPoint.y, m_layerDepth );
1223
1224 m_currentManager->Shader( SHADER_STROKED_CIRCLE, 3.0, aRadius, m_lineWidth );
1225 m_currentManager->Vertex( aCenterPoint.x, aCenterPoint.y, // v2
1226 m_layerDepth );
1227 }
1228}
1229
1230
1231void OPENGL_GAL::DrawArc( const VECTOR2D& aCenterPoint, double aRadius,
1232 const EDA_ANGLE& aStartAngle, const EDA_ANGLE& aAngle )
1233{
1234 if( aRadius <= 0 )
1235 return;
1236
1237 double startAngle = aStartAngle.AsRadians();
1238 double endAngle = startAngle + aAngle.AsRadians();
1239
1240 // Normalize arc angles
1241 normalize( startAngle, endAngle );
1242
1243 const double alphaIncrement = calcAngleStep( aRadius );
1244
1245 Save();
1246 m_currentManager->Translate( aCenterPoint.x, aCenterPoint.y, 0.0 );
1247
1248 if( m_isFillEnabled )
1249 {
1250 double alpha;
1252 m_currentManager->Shader( SHADER_NONE );
1253
1254 // Triangle fan
1255 for( alpha = startAngle; ( alpha + alphaIncrement ) < endAngle; )
1256 {
1257 m_currentManager->Reserve( 3 );
1258 m_currentManager->Vertex( 0.0, 0.0, m_layerDepth );
1259 m_currentManager->Vertex( cos( alpha ) * aRadius, sin( alpha ) * aRadius,
1260 m_layerDepth );
1261 alpha += alphaIncrement;
1262 m_currentManager->Vertex( cos( alpha ) * aRadius, sin( alpha ) * aRadius,
1263 m_layerDepth );
1264 }
1265
1266 // The last missing triangle
1267 const VECTOR2D endPoint( cos( endAngle ) * aRadius, sin( endAngle ) * aRadius );
1268
1269 m_currentManager->Reserve( 3 );
1270 m_currentManager->Vertex( 0.0, 0.0, m_layerDepth );
1271 m_currentManager->Vertex( cos( alpha ) * aRadius, sin( alpha ) * aRadius, m_layerDepth );
1272 m_currentManager->Vertex( endPoint.x, endPoint.y, m_layerDepth );
1273 }
1274
1275 if( m_isStrokeEnabled )
1276 {
1278 m_strokeColor.a );
1279
1280 VECTOR2D p( cos( startAngle ) * aRadius, sin( startAngle ) * aRadius );
1281 double alpha;
1282 unsigned int lineCount = 0;
1283
1284 for( alpha = startAngle + alphaIncrement; alpha <= endAngle; alpha += alphaIncrement )
1285 lineCount++;
1286
1287 if( alpha != endAngle )
1288 lineCount++;
1289
1290 reserveLineQuads( lineCount );
1291
1292 for( alpha = startAngle + alphaIncrement; alpha <= endAngle; alpha += alphaIncrement )
1293 {
1294 VECTOR2D p_next( cos( alpha ) * aRadius, sin( alpha ) * aRadius );
1295 drawLineQuad( p, p_next, false );
1296
1297 p = p_next;
1298 }
1299
1300 // Draw the last missing part
1301 if( alpha != endAngle )
1302 {
1303 VECTOR2D p_last( cos( endAngle ) * aRadius, sin( endAngle ) * aRadius );
1304 drawLineQuad( p, p_last, false );
1305 }
1306 }
1307
1308 Restore();
1309}
1310
1311
1312void OPENGL_GAL::DrawArcSegment( const VECTOR2D& aCenterPoint, double aRadius,
1313 const EDA_ANGLE& aStartAngle, const EDA_ANGLE& aAngle,
1314 double aWidth, double aMaxError )
1315{
1316 if( aRadius <= 0 )
1317 {
1318 // Arcs of zero radius are a circle of aWidth diameter
1319 if( aWidth > 0 )
1320 DrawCircle( aCenterPoint, aWidth / 2.0 );
1321
1322 return;
1323 }
1324
1325 double startAngle = aStartAngle.AsRadians();
1326 double endAngle = startAngle + aAngle.AsRadians();
1327
1328 // Swap the angles, if start angle is greater than end angle
1329 normalize( startAngle, endAngle );
1330
1331 // Calculate the seg count to approximate the arc with aMaxError or less
1332 int segCount360 = GetArcToSegmentCount( aRadius, aMaxError, FULL_CIRCLE );
1333 segCount360 = std::max( SEG_PER_CIRCLE_COUNT, segCount360 );
1334 double alphaIncrement = 2.0 * M_PI / segCount360;
1335
1336 // Refinement: Use a segment count multiple of 2, because we have a control point
1337 // on the middle of the arc, and the look is better if it is on a segment junction
1338 // because there is no approx error
1339 int seg_count = KiROUND( ( endAngle - startAngle ) / alphaIncrement );
1340
1341 if( seg_count % 2 != 0 )
1342 seg_count += 1;
1343
1344 // Our shaders have trouble rendering null line quads, so delegate this task to DrawSegment.
1345 if( seg_count == 0 )
1346 {
1347 VECTOR2D p_start( aCenterPoint.x + cos( startAngle ) * aRadius,
1348 aCenterPoint.y + sin( startAngle ) * aRadius );
1349
1350 VECTOR2D p_end( aCenterPoint.x + cos( endAngle ) * aRadius,
1351 aCenterPoint.y + sin( endAngle ) * aRadius );
1352
1353 DrawSegment( p_start, p_end, aWidth );
1354 return;
1355 }
1356
1357 // Recalculate alphaIncrement with a even integer number of segment
1358 alphaIncrement = ( endAngle - startAngle ) / seg_count;
1359
1360 Save();
1361 m_currentManager->Translate( aCenterPoint.x, aCenterPoint.y, 0.0 );
1362
1363 if( m_isStrokeEnabled )
1364 {
1366 m_strokeColor.a );
1367
1368 double width = aWidth / 2.0;
1369 VECTOR2D startPoint( cos( startAngle ) * aRadius, sin( startAngle ) * aRadius );
1370 VECTOR2D endPoint( cos( endAngle ) * aRadius, sin( endAngle ) * aRadius );
1371
1372 drawStrokedSemiCircle( startPoint, width, startAngle + M_PI );
1373 drawStrokedSemiCircle( endPoint, width, endAngle );
1374
1375 VECTOR2D pOuter( cos( startAngle ) * ( aRadius + width ),
1376 sin( startAngle ) * ( aRadius + width ) );
1377
1378 VECTOR2D pInner( cos( startAngle ) * ( aRadius - width ),
1379 sin( startAngle ) * ( aRadius - width ) );
1380
1381 double alpha;
1382
1383 for( alpha = startAngle + alphaIncrement; alpha <= endAngle; alpha += alphaIncrement )
1384 {
1385 VECTOR2D pNextOuter( cos( alpha ) * ( aRadius + width ),
1386 sin( alpha ) * ( aRadius + width ) );
1387 VECTOR2D pNextInner( cos( alpha ) * ( aRadius - width ),
1388 sin( alpha ) * ( aRadius - width ) );
1389
1390 DrawLine( pOuter, pNextOuter );
1391 DrawLine( pInner, pNextInner );
1392
1393 pOuter = pNextOuter;
1394 pInner = pNextInner;
1395 }
1396
1397 // Draw the last missing part
1398 if( alpha != endAngle )
1399 {
1400 VECTOR2D pLastOuter( cos( endAngle ) * ( aRadius + width ),
1401 sin( endAngle ) * ( aRadius + width ) );
1402 VECTOR2D pLastInner( cos( endAngle ) * ( aRadius - width ),
1403 sin( endAngle ) * ( aRadius - width ) );
1404
1405 DrawLine( pOuter, pLastOuter );
1406 DrawLine( pInner, pLastInner );
1407 }
1408 }
1409
1410 if( m_isFillEnabled )
1411 {
1413 SetLineWidth( aWidth );
1414
1415 VECTOR2D p( cos( startAngle ) * aRadius, sin( startAngle ) * aRadius );
1416 double alpha;
1417
1418 int lineCount = 0;
1419
1420 for( alpha = startAngle + alphaIncrement; alpha <= endAngle; alpha += alphaIncrement )
1421 {
1422 lineCount++;
1423 }
1424
1425 // The last missing part
1426 if( alpha != endAngle )
1427 {
1428 lineCount++;
1429 }
1430
1431 reserveLineQuads( lineCount );
1432
1433 for( alpha = startAngle + alphaIncrement; alpha <= endAngle; alpha += alphaIncrement )
1434 {
1435 VECTOR2D p_next( cos( alpha ) * aRadius, sin( alpha ) * aRadius );
1436 drawLineQuad( p, p_next, false );
1437
1438 p = p_next;
1439 }
1440
1441 // Draw the last missing part
1442 if( alpha != endAngle )
1443 {
1444 VECTOR2D p_last( cos( endAngle ) * aRadius, sin( endAngle ) * aRadius );
1445 drawLineQuad( p, p_last, false );
1446 }
1447 }
1448
1449 Restore();
1450}
1451
1452
1453void OPENGL_GAL::DrawEllipse( const VECTOR2D& aCenterPoint, double aMajorRadius, double aMinorRadius,
1454 const EDA_ANGLE& aRotation )
1455{
1456 if( aMajorRadius <= 0 || aMinorRadius <= 0 )
1457 return;
1458
1459 const double alphaIncrement = calcAngleStep( aMajorRadius );
1460 const double cosPhi = std::cos( aRotation.AsRadians() );
1461 const double sinPhi = std::sin( aRotation.AsRadians() );
1462
1463 auto eval = [&]( double theta ) -> VECTOR2D
1464 {
1465 const double lx = aMajorRadius * std::cos( theta );
1466 const double ly = aMinorRadius * std::sin( theta );
1467 return VECTOR2D( lx * cosPhi - ly * sinPhi, lx * sinPhi + ly * cosPhi );
1468 };
1469
1470 Save();
1471 m_currentManager->Translate( aCenterPoint.x, aCenterPoint.y, 0.0 );
1472
1473 if( m_isFillEnabled )
1474 {
1476 m_currentManager->Shader( SHADER_NONE );
1477
1478 // Triangle fan from origin out to the ellipse boundary
1479 double alpha;
1480 for( alpha = 0.0; ( alpha + alphaIncrement ) < 2.0 * M_PI; )
1481 {
1482 const VECTOR2D p1 = eval( alpha );
1483 alpha += alphaIncrement;
1484 const VECTOR2D p2 = eval( alpha );
1485
1486 m_currentManager->Reserve( 3 );
1487 m_currentManager->Vertex( 0.0, 0.0, m_layerDepth );
1488 m_currentManager->Vertex( p1.x, p1.y, m_layerDepth );
1489 m_currentManager->Vertex( p2.x, p2.y, m_layerDepth );
1490 }
1491
1492 // Last wedge back to the start.
1493 const VECTOR2D p1 = eval( alpha );
1494 const VECTOR2D p2 = eval( 0.0 );
1495
1496 m_currentManager->Reserve( 3 );
1497 m_currentManager->Vertex( 0.0, 0.0, m_layerDepth );
1498 m_currentManager->Vertex( p1.x, p1.y, m_layerDepth );
1499 m_currentManager->Vertex( p2.x, p2.y, m_layerDepth );
1500 }
1501
1502 if( m_isStrokeEnabled )
1503 {
1505
1506 // Count quads for reservation.
1507 unsigned int lineCount = 0;
1508 double countAlpha;
1509
1510 for( countAlpha = alphaIncrement; countAlpha < 2.0 * M_PI; countAlpha += alphaIncrement )
1511 lineCount++;
1512
1513 lineCount++; // closing segment back to alpha = 0
1514
1515 reserveLineQuads( lineCount );
1516
1517 VECTOR2D p = eval( 0.0 );
1518 double alpha;
1519
1520 for( alpha = alphaIncrement; alpha < 2.0 * M_PI; alpha += alphaIncrement )
1521 {
1522 const VECTOR2D p_next = eval( alpha );
1523 drawLineQuad( p, p_next, false );
1524 p = p_next;
1525 }
1526
1527 // Closing segment
1528 drawLineQuad( p, eval( 0.0 ), false );
1529 }
1530
1531 Restore();
1532}
1533
1534
1535void OPENGL_GAL::DrawEllipseArc( const VECTOR2D& aCenterPoint, double aMajorRadius, double aMinorRadius,
1536 const EDA_ANGLE& aRotation, const EDA_ANGLE& aStartAngle, const EDA_ANGLE& aEndAngle )
1537{
1538 if( aMajorRadius <= 0 || aMinorRadius <= 0 )
1539 return;
1540
1541 double startAngle = aStartAngle.AsRadians();
1542 double endAngle = aEndAngle.AsRadians();
1543 normalize( startAngle, endAngle );
1544
1545 const double alphaIncrement = calcAngleStep( aMajorRadius );
1546 const double cosPhi = std::cos( aRotation.AsRadians() );
1547 const double sinPhi = std::sin( aRotation.AsRadians() );
1548
1549 auto eval = [&]( double theta ) -> VECTOR2D
1550 {
1551 const double lx = aMajorRadius * std::cos( theta );
1552 const double ly = aMinorRadius * std::sin( theta );
1553 return VECTOR2D( lx * cosPhi - ly * sinPhi, lx * sinPhi + ly * cosPhi );
1554 };
1555
1556 Save();
1557 m_currentManager->Translate( aCenterPoint.x, aCenterPoint.y, 0.0 );
1558
1559 if( m_isFillEnabled )
1560 {
1562 m_currentManager->Shader( SHADER_NONE );
1563
1564 // Pie slice fan from origin out to the arc curve.
1565 double alpha;
1566
1567 for( alpha = startAngle; ( alpha + alphaIncrement ) < endAngle; )
1568 {
1569 const VECTOR2D p1 = eval( alpha );
1570 alpha += alphaIncrement;
1571 const VECTOR2D p2 = eval( alpha );
1572
1573 m_currentManager->Reserve( 3 );
1574 m_currentManager->Vertex( 0.0, 0.0, m_layerDepth );
1575 m_currentManager->Vertex( p1.x, p1.y, m_layerDepth );
1576 m_currentManager->Vertex( p2.x, p2.y, m_layerDepth );
1577 }
1578
1579 // Last wedge to endAngle.
1580 const VECTOR2D p1 = eval( alpha );
1581 const VECTOR2D p2 = eval( endAngle );
1582
1583 m_currentManager->Reserve( 3 );
1584 m_currentManager->Vertex( 0.0, 0.0, m_layerDepth );
1585 m_currentManager->Vertex( p1.x, p1.y, m_layerDepth );
1586 m_currentManager->Vertex( p2.x, p2.y, m_layerDepth );
1587 }
1588
1589 if( m_isStrokeEnabled )
1590 {
1592
1593 unsigned int lineCount = 0;
1594 double countAlpha;
1595
1596 for( countAlpha = startAngle + alphaIncrement; countAlpha <= endAngle; countAlpha += alphaIncrement )
1597 lineCount++;
1598
1599 if( countAlpha != endAngle )
1600 lineCount++; // trailing partial segment
1601
1602 reserveLineQuads( lineCount );
1603
1604 VECTOR2D p = eval( startAngle );
1605 double alpha;
1606
1607 for( alpha = startAngle + alphaIncrement; alpha <= endAngle; alpha += alphaIncrement )
1608 {
1609 const VECTOR2D p_next = eval( alpha );
1610 drawLineQuad( p, p_next, false );
1611 p = p_next;
1612 }
1613
1614 // Trailing partial segment, if any
1615 if( alpha != endAngle )
1616 {
1617 const VECTOR2D p_last = eval( endAngle );
1618 drawLineQuad( p, p_last, false );
1619 }
1620 }
1621
1622 Restore();
1623}
1624
1625
1626void OPENGL_GAL::DrawRectangle( const VECTOR2D& aStartPoint, const VECTOR2D& aEndPoint )
1627{
1628 // Compute the diagonal points of the rectangle
1629 VECTOR2D diagonalPointA( aEndPoint.x, aStartPoint.y );
1630 VECTOR2D diagonalPointB( aStartPoint.x, aEndPoint.y );
1631
1632 // Fill the rectangle
1633 if( m_isFillEnabled )
1634 {
1635 m_currentManager->Reserve( 6 );
1636 m_currentManager->Shader( SHADER_NONE );
1638
1639 m_currentManager->Vertex( aStartPoint.x, aStartPoint.y, m_layerDepth );
1640 m_currentManager->Vertex( diagonalPointA.x, diagonalPointA.y, m_layerDepth );
1641 m_currentManager->Vertex( aEndPoint.x, aEndPoint.y, m_layerDepth );
1642
1643 m_currentManager->Vertex( aStartPoint.x, aStartPoint.y, m_layerDepth );
1644 m_currentManager->Vertex( aEndPoint.x, aEndPoint.y, m_layerDepth );
1645 m_currentManager->Vertex( diagonalPointB.x, diagonalPointB.y, m_layerDepth );
1646 }
1647
1648 // Stroke the outline
1649 if( m_isStrokeEnabled )
1650 {
1652 m_strokeColor.a );
1653
1654 // DrawLine (and DrawPolyline )
1655 // has problem with 0 length lines so enforce minimum
1656 if( aStartPoint == aEndPoint )
1657 {
1658 DrawLine( aStartPoint + VECTOR2D( 1.0, 0.0 ), aEndPoint );
1659 }
1660 else
1661 {
1662 std::deque<VECTOR2D> pointList;
1663
1664 pointList.push_back( aStartPoint );
1665 pointList.push_back( diagonalPointA );
1666 pointList.push_back( aEndPoint );
1667 pointList.push_back( diagonalPointB );
1668 pointList.push_back( aStartPoint );
1669 DrawPolyline( pointList );
1670 }
1671 }
1672}
1673
1674
1675void OPENGL_GAL::DrawSegmentChain( const std::vector<VECTOR2D>& aPointList, double aWidth )
1676{
1678 [&]( int idx )
1679 {
1680 return aPointList[idx];
1681 },
1682 aPointList.size(), aWidth );
1683}
1684
1685
1686void OPENGL_GAL::DrawSegmentChain( const SHAPE_LINE_CHAIN& aLineChain, double aWidth )
1687{
1688 auto numPoints = aLineChain.PointCount();
1689
1690 if( aLineChain.IsClosed() )
1691 numPoints += 1;
1692
1694 [&]( int idx )
1695 {
1696 return aLineChain.CPoint( idx );
1697 },
1698 numPoints, aWidth );
1699}
1700
1701
1702void OPENGL_GAL::DrawPolyline( const std::deque<VECTOR2D>& aPointList )
1703{
1705 [&]( int idx )
1706 {
1707 return aPointList[idx];
1708 },
1709 aPointList.size() );
1710}
1711
1712
1713void OPENGL_GAL::DrawPolyline( const std::vector<VECTOR2D>& aPointList )
1714{
1716 [&]( int idx )
1717 {
1718 return aPointList[idx];
1719 },
1720 aPointList.size() );
1721}
1722
1723
1724void OPENGL_GAL::DrawPolyline( const VECTOR2D aPointList[], int aListSize )
1725{
1727 [&]( int idx )
1728 {
1729 return aPointList[idx];
1730 },
1731 aListSize );
1732}
1733
1734
1736{
1737 auto numPoints = aLineChain.PointCount();
1738
1739 if( aLineChain.IsClosed() )
1740 numPoints += 1;
1741
1743 [&]( int idx )
1744 {
1745 return aLineChain.CPoint( idx );
1746 },
1747 numPoints );
1748}
1749
1750
1751void OPENGL_GAL::DrawPolylines( const std::vector<std::vector<VECTOR2D>>& aPointList )
1752{
1753 int lineQuadCount = 0;
1754
1755 for( const std::vector<VECTOR2D>& points : aPointList )
1756 lineQuadCount += points.size() - 1;
1757
1758 reserveLineQuads( lineQuadCount );
1759
1760 for( const std::vector<VECTOR2D>& points : aPointList )
1761 {
1763 [&]( int idx )
1764 {
1765 return points[idx];
1766 },
1767 points.size(), false );
1768 }
1769}
1770
1771
1772void OPENGL_GAL::DrawPolygon( const std::deque<VECTOR2D>& aPointList )
1773{
1774 wxCHECK( aPointList.size() >= 2, /* void */ );
1775 auto points = std::unique_ptr<GLdouble[]>( new GLdouble[3 * aPointList.size()] );
1776 GLdouble* ptr = points.get();
1777
1778 for( const VECTOR2D& p : aPointList )
1779 {
1780 *ptr++ = p.x;
1781 *ptr++ = p.y;
1782 *ptr++ = m_layerDepth;
1783 }
1784
1785 drawPolygon( points.get(), aPointList.size() );
1786}
1787
1788
1789void OPENGL_GAL::DrawPolygon( const VECTOR2D aPointList[], int aListSize )
1790{
1791 wxCHECK( aListSize >= 2, /* void */ );
1792 auto points = std::unique_ptr<GLdouble[]>( new GLdouble[3 * aListSize] );
1793 GLdouble* target = points.get();
1794 const VECTOR2D* src = aPointList;
1795
1796 for( int i = 0; i < aListSize; ++i )
1797 {
1798 *target++ = src->x;
1799 *target++ = src->y;
1800 *target++ = m_layerDepth;
1801 ++src;
1802 }
1803
1804 drawPolygon( points.get(), aListSize );
1805}
1806
1807
1809 bool aStrokeTriangulation )
1810{
1811 m_currentManager->Shader( SHADER_NONE );
1813
1814 if( m_isFillEnabled )
1815 {
1816 int totalTriangleCount = 0;
1817
1818 for( unsigned int j = 0; j < aPolySet.TriangulatedPolyCount(); ++j )
1819 {
1820 auto triPoly = aPolySet.TriangulatedPolygon( j );
1821
1822 totalTriangleCount += triPoly->GetTriangleCount();
1823 }
1824
1825 m_currentManager->Reserve( 3 * totalTriangleCount );
1826
1827 for( unsigned int j = 0; j < aPolySet.TriangulatedPolyCount(); ++j )
1828 {
1829 auto triPoly = aPolySet.TriangulatedPolygon( j );
1830
1831 for( size_t i = 0; i < triPoly->GetTriangleCount(); i++ )
1832 {
1833 VECTOR2I a, b, c;
1834 triPoly->GetTriangle( i, a, b, c );
1835 m_currentManager->Vertex( a.x, a.y, m_layerDepth );
1836 m_currentManager->Vertex( b.x, b.y, m_layerDepth );
1837 m_currentManager->Vertex( c.x, c.y, m_layerDepth );
1838 }
1839 }
1840 }
1841
1842 if( m_isStrokeEnabled )
1843 {
1844 for( int j = 0; j < aPolySet.OutlineCount(); ++j )
1845 {
1846 const auto& poly = aPolySet.Polygon( j );
1847
1848 for( const auto& lc : poly )
1849 {
1850 DrawPolyline( lc );
1851 }
1852 }
1853 }
1854
1855 if( ADVANCED_CFG::GetCfg().m_DrawTriangulationOutlines )
1856 {
1857 aStrokeTriangulation = true;
1858 SetStrokeColor( COLOR4D( 0.0, 1.0, 0.2, 1.0 ) );
1859 }
1860
1861 if( aStrokeTriangulation )
1862 {
1865
1866 for( unsigned int j = 0; j < aPolySet.TriangulatedPolyCount(); ++j )
1867 {
1868 auto triPoly = aPolySet.TriangulatedPolygon( j );
1869
1870 for( size_t i = 0; i < triPoly->GetTriangleCount(); i++ )
1871 {
1872 VECTOR2I a, b, c;
1873 triPoly->GetTriangle( i, a, b, c );
1874 DrawLine( a, b );
1875 DrawLine( b, c );
1876 DrawLine( c, a );
1877 }
1878 }
1879 }
1880}
1881
1882
1883void OPENGL_GAL::DrawPolygon( const SHAPE_POLY_SET& aPolySet, bool aStrokeTriangulation )
1884{
1885 if( aPolySet.IsTriangulationUpToDate() )
1886 {
1887 drawTriangulatedPolyset( aPolySet, aStrokeTriangulation );
1888 return;
1889 }
1890
1891 for( int j = 0; j < aPolySet.OutlineCount(); ++j )
1892 {
1893 const SHAPE_LINE_CHAIN& outline = aPolySet.COutline( j );
1894 DrawPolygon( outline );
1895 }
1896}
1897
1898
1900{
1901 if( aPolygon.PointCount() < 2 )
1902 return;
1903
1904 const int pointCount = aPolygon.SegmentCount() + 1;
1905 std::unique_ptr<GLdouble[]> points( new GLdouble[3 * pointCount] );
1906 GLdouble* ptr = points.get();
1907
1908 for( int i = 0; i < pointCount; ++i )
1909 {
1910 const VECTOR2I& p = aPolygon.CPoint( i );
1911 *ptr++ = p.x;
1912 *ptr++ = p.y;
1913 *ptr++ = m_layerDepth;
1914 }
1915
1916 drawPolygon( points.get(), pointCount );
1917}
1918
1919
1920void OPENGL_GAL::DrawCurve( const VECTOR2D& aStartPoint, const VECTOR2D& aControlPointA,
1921 const VECTOR2D& aControlPointB, const VECTOR2D& aEndPoint,
1922 double aFilterValue )
1923{
1924 std::vector<VECTOR2D> output;
1925 std::vector<VECTOR2D> pointCtrl;
1926
1927 pointCtrl.push_back( aStartPoint );
1928 pointCtrl.push_back( aControlPointA );
1929 pointCtrl.push_back( aControlPointB );
1930 pointCtrl.push_back( aEndPoint );
1931
1932 BEZIER_POLY converter( pointCtrl );
1933 converter.GetPoly( output, aFilterValue );
1934
1935 if( output.size() == 1 )
1936 output.push_back( output.front() );
1937
1938 DrawPolygon( &output[0], output.size() );
1939}
1940
1941
1942void OPENGL_GAL::DrawBitmap( const BITMAP_BASE& aBitmap, double alphaBlend )
1943{
1944 GLfloat alpha = std::clamp( alphaBlend, 0.0, 1.0 );
1945
1946 // We have to calculate the pixel size in users units to draw the image.
1947 // m_worldUnitLength is a factor used for converting IU to inches
1948 double scale = 1.0 / ( aBitmap.GetPPI() * m_worldUnitLength );
1949 double w = (double) aBitmap.GetSizePixels().x * scale;
1950 double h = (double) aBitmap.GetSizePixels().y * scale;
1951
1952 auto xform = m_currentManager->GetTransformation();
1953
1954 glm::vec4 v0 = xform * glm::vec4( -w / 2, -h / 2, 0.0, 0.0 );
1955 glm::vec4 v1 = xform * glm::vec4( w / 2, -h / 2, 0.0, 0.0 );
1956 glm::vec4 v2 = xform * glm::vec4( w / 2, h / 2, 0.0, 0.0 );
1957 glm::vec4 v3 = xform * glm::vec4( -w / 2, h / 2, 0.0, 0.0 );
1958 glm::vec4 trans = xform[3];
1959
1960 auto texture_id = m_bitmapCache->RequestBitmap( &aBitmap );
1961
1962 if( !glIsTexture( texture_id ) ) // ensure the bitmap texture is still valid
1963 return;
1964
1965 GLboolean depthMask = GL_TRUE;
1966 glGetBooleanv( GL_DEPTH_WRITEMASK, &depthMask );
1967
1968 if( alpha < 1.0f )
1969 glDepthMask( GL_FALSE );
1970
1971 glDepthFunc( GL_ALWAYS );
1972
1973 glAlphaFunc( GL_GREATER, 0.01f );
1974 glEnable( GL_ALPHA_TEST );
1975
1976 glMatrixMode( GL_TEXTURE );
1977 glPushMatrix();
1978 glTranslated( 0.5, 0.5, 0.5 );
1979 glRotated( aBitmap.Rotation().AsDegrees(), 0, 0, 1 );
1980 glTranslated( -0.5, -0.5, -0.5 );
1981
1982 glMatrixMode( GL_MODELVIEW );
1983 glPushMatrix();
1984 glTranslated( trans.x, trans.y, trans.z );
1985
1986 glEnable( GL_TEXTURE_2D );
1987 glActiveTexture( GL_TEXTURE0 );
1988 glBindTexture( GL_TEXTURE_2D, texture_id );
1989
1990 float texStartX = aBitmap.IsMirroredX() ? 1.0 : 0.0;
1991 float texEndX = aBitmap.IsMirroredX() ? 0.0 : 1.0;
1992 float texStartY = aBitmap.IsMirroredY() ? 1.0 : 0.0;
1993 float texEndY = aBitmap.IsMirroredY() ? 0.0 : 1.0;
1994
1995 glBegin( GL_QUADS );
1996 glColor4f( 1.0, 1.0, 1.0, alpha );
1997 glTexCoord2f( texStartX, texStartY );
1998 glVertex3f( v0.x, v0.y, m_layerDepth );
1999 glColor4f( 1.0, 1.0, 1.0, alpha );
2000 glTexCoord2f( texEndX, texStartY);
2001 glVertex3f( v1.x, v1.y, m_layerDepth );
2002 glColor4f( 1.0, 1.0, 1.0, alpha );
2003 glTexCoord2f( texEndX, texEndY);
2004 glVertex3f( v2.x, v2.y, m_layerDepth );
2005 glColor4f( 1.0, 1.0, 1.0, alpha );
2006 glTexCoord2f( texStartX, texEndY);
2007 glVertex3f( v3.x, v3.y, m_layerDepth );
2008 glEnd();
2009
2010 glBindTexture( GL_TEXTURE_2D, 0 );
2011
2012#ifdef DISABLE_BITMAP_CACHE
2013 glDeleteTextures( 1, &texture_id );
2014#endif
2015
2016 glPopMatrix();
2017
2018 glMatrixMode( GL_TEXTURE );
2019 glPopMatrix();
2020 glMatrixMode( GL_MODELVIEW );
2021
2022 glDisable( GL_ALPHA_TEST );
2023
2024 glDepthMask( depthMask );
2025
2026 glDepthFunc( GL_LESS );
2027}
2028
2029
2030void OPENGL_GAL::BitmapText( const wxString& aText, const VECTOR2I& aPosition,
2031 const EDA_ANGLE& aAngle )
2032{
2033 // Fallback to generic impl (which uses the stroke font) on cases we don't handle
2034 if( IsTextMirrored()
2035 || aText.Contains( wxT( "^{" ) )
2036 || aText.Contains( wxT( "_{" ) )
2037 || aText.Contains( wxT( "\n" ) ) )
2038 {
2039 return GAL::BitmapText( aText, aPosition, aAngle );
2040 }
2041
2042 const UTF8 text( aText );
2043 VECTOR2D textSize;
2044 float commonOffset;
2045 std::tie( textSize, commonOffset ) = computeBitmapTextSize( text );
2046
2047 const double SCALE = 1.4 * GetGlyphSize().y / textSize.y;
2048 double overbarHeight = textSize.y;
2049
2050 Save();
2051
2053 m_currentManager->Translate( aPosition.x, aPosition.y, m_layerDepth );
2054 m_currentManager->Rotate( aAngle.AsRadians(), 0.0f, 0.0f, -1.0f );
2055
2056 double sx = SCALE * ( m_globalFlipX ? -1.0 : 1.0 );
2057 double sy = SCALE * ( m_globalFlipY ? -1.0 : 1.0 );
2058
2059 m_currentManager->Scale( sx, sy, 0 );
2060 m_currentManager->Translate( 0, -commonOffset, 0 );
2061
2062 switch( GetHorizontalJustify() )
2063 {
2065 Translate( VECTOR2D( -textSize.x / 2.0, 0 ) );
2066 break;
2067
2069 //if( !IsTextMirrored() )
2070 Translate( VECTOR2D( -textSize.x, 0 ) );
2071 break;
2072
2074 //if( IsTextMirrored() )
2075 //Translate( VECTOR2D( -textSize.x, 0 ) );
2076 break;
2077
2079 wxFAIL_MSG( wxT( "Indeterminate state legal only in dialogs." ) );
2080 break;
2081 }
2082
2083 switch( GetVerticalJustify() )
2084 {
2086 break;
2087
2089 Translate( VECTOR2D( 0, -textSize.y / 2.0 ) );
2090 overbarHeight = 0;
2091 break;
2092
2094 Translate( VECTOR2D( 0, -textSize.y ) );
2095 overbarHeight = -textSize.y / 2.0;
2096 break;
2097
2099 wxFAIL_MSG( wxT( "Indeterminate state legal only in dialogs." ) );
2100 break;
2101 }
2102
2103 int overbarLength = 0;
2104 int overbarDepth = -1;
2105 int braceNesting = 0;
2106
2107 auto iterateString =
2108 [&]( const std::function<void( int aOverbarLength, int aOverbarHeight )>& overbarFn,
2109 const std::function<int( unsigned long aChar )>& bitmapCharFn )
2110 {
2111 for( UTF8::uni_iter chIt = text.ubegin(), end = text.uend(); chIt < end; ++chIt )
2112 {
2113 wxASSERT_MSG( *chIt != '\n' && *chIt != '\r',
2114 "No support for multiline bitmap text yet" );
2115
2116 if( *chIt == '~' && overbarDepth == -1 )
2117 {
2118 UTF8::uni_iter lookahead = chIt;
2119
2120 if( ++lookahead != end && *lookahead == '{' )
2121 {
2122 chIt = lookahead;
2123 overbarDepth = braceNesting;
2124 braceNesting++;
2125 continue;
2126 }
2127 }
2128 else if( *chIt == '{' )
2129 {
2130 braceNesting++;
2131 }
2132 else if( *chIt == '}' )
2133 {
2134 if( braceNesting > 0 )
2135 braceNesting--;
2136
2137 if( braceNesting == overbarDepth )
2138 {
2139 overbarFn( overbarLength, overbarHeight );
2140 overbarLength = 0;
2141
2142 overbarDepth = -1;
2143 continue;
2144 }
2145 }
2146
2147 if( overbarDepth != -1 )
2148 overbarLength += bitmapCharFn( *chIt );
2149 else
2150 bitmapCharFn( *chIt );
2151 }
2152 };
2153
2154 // First, calculate the amount of characters and overbars to reserve
2155
2156 int charsCount = 0;
2157 int overbarsCount = 0;
2158
2159 iterateString(
2160 [&overbarsCount]( int aOverbarLength, int aOverbarHeight )
2161 {
2162 overbarsCount++;
2163 },
2164 [&charsCount]( unsigned long aChar ) -> int
2165 {
2166 if( aChar != ' ' )
2167 charsCount++;
2168
2169 return 0;
2170 } );
2171
2172 m_currentManager->Reserve( 6 * charsCount + 6 * overbarsCount );
2173
2174 // Now reset the state and actually draw the characters and overbars
2175 overbarLength = 0;
2176 overbarDepth = -1;
2177 braceNesting = 0;
2178
2179 iterateString(
2180 [&]( int aOverbarLength, int aOverbarHeight )
2181 {
2182 drawBitmapOverbar( aOverbarLength, aOverbarHeight, false );
2183 },
2184 [&]( unsigned long aChar ) -> int
2185 {
2186 return drawBitmapChar( aChar, false );
2187 } );
2188
2189 // Handle the case when overbar is active till the end of the drawn text
2190 m_currentManager->Translate( 0, commonOffset, 0 );
2191
2192 if( overbarDepth != -1 && overbarLength > 0 )
2193 drawBitmapOverbar( overbarLength, overbarHeight );
2194
2195 Restore();
2196}
2197
2198
2200{
2202 m_compositor->SetBuffer( m_mainBuffer );
2203 m_nonCachedManager->EnableDepthTest( false );
2204
2205 const float minorLineWidth = gridMinorLineWidth( getWorldPixelSize(), GetScaleFactor() );
2206
2207 // Axes drawn first so grid lines at x/y=0 can skip on top of them.
2208 if( m_axesEnabled )
2209 {
2210 const VECTOR2D worldStartPoint = m_screenWorldMatrix * VECTOR2D( 0.0, 0.0 );
2211 const VECTOR2D worldEndPoint = m_screenWorldMatrix * VECTOR2D( m_screenSize );
2212
2213 SetLineWidth( minorLineWidth );
2215 DrawLine( VECTOR2D( worldStartPoint.x, 0 ), VECTOR2D( worldEndPoint.x, 0 ) );
2216 DrawLine( VECTOR2D( 0, worldStartPoint.y ), VECTOR2D( 0, worldEndPoint.y ) );
2217 m_nonCachedManager->EndDrawing();
2218 }
2219
2220 const bool renderGlobalGrid = m_gridVisibility && m_gridSize.x != 0 && m_gridSize.y != 0;
2221
2222 if( renderGlobalGrid )
2223 {
2224 GRID_SOURCE globalGrid;
2225 globalGrid.unbounded = true;
2226 globalGrid.axesEnabled = m_axesEnabled;
2228 globalGrid.origin = m_gridOrigin;
2229 globalGrid.pitch = GetVisibleGridSize();
2230 globalGrid.tick = static_cast<unsigned>( m_gridTick );
2231 globalGrid.style = m_gridStyle;
2232 globalGrid.color = m_gridColor;
2233 globalGrid.priority = 0;
2234
2235 // Appending keeps the precedence order SetGridSources established: every grid
2236 // item is bounded, and bounded beats unbounded, so the background grid belongs
2237 // last whatever its priority.
2238 m_gridSources.push_back( globalGrid );
2239 }
2240
2241 if( !m_gridSources.empty() )
2243
2244 if( renderGlobalGrid )
2245 m_gridSources.pop_back();
2246}
2247
2248
2250{
2251 if( m_gridSources.empty() )
2252 return;
2253
2254 // Pre-sorted by precedence; each bounded source stencils its coverage, so first drawn
2255 // wins. Selected grids go last: they ignore the stencil and draw over everything.
2256 std::vector<const GRID_SOURCE*> ordered;
2257 ordered.reserve( m_gridSources.size() );
2258
2259 for( const GRID_SOURCE& src : m_gridSources )
2260 {
2261 if( !src.highlighted )
2262 ordered.push_back( &src );
2263 }
2264
2265 for( const GRID_SOURCE& src : m_gridSources )
2266 {
2267 if( src.highlighted )
2268 ordered.push_back( &src );
2269 }
2270
2271 const float minorLineWidth = gridMinorLineWidth( getWorldPixelSize(), GetScaleFactor() );
2272 const float majorLineWidth = minorLineWidth * 2.0f;
2273 const float hairLineWidth = getWorldPixelSize() / GetScaleFactor();
2274
2275 glDisable( GL_DEPTH_TEST );
2276 glDisable( GL_TEXTURE_2D );
2277 m_nonCachedManager->EnableDepthTest( false );
2278
2279 glEnable( GL_STENCIL_TEST );
2280 glStencilMask( 0xFF );
2281 glClear( GL_STENCIL_BUFFER_BIT );
2282
2283 for( const GRID_SOURCE* srcPtr : ordered )
2284 {
2285 const GRID_SOURCE& src = *srcPtr;
2286
2287 // Selected grids let you see the dimmed grid below and do not get stamped out.
2288 const GLuint coverageMask = src.highlighted ? 0 : STENCIL_GRID_COVERAGE;
2289
2290 glStencilMask( 0x00 );
2291 glStencilFunc( GL_EQUAL, 0, coverageMask );
2292 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
2293
2294 if( src.highlighted )
2295 {
2296 COLOR4D dimming = m_clearColor;
2297 dimming.a = GRID_DIM_ALPHA;
2298
2299 SetIsFill( true );
2300 SetIsStroke( false );
2301 SetFillColor( dimming );
2302 drawGridCoverageShape( src );
2303 m_nonCachedManager->EndDrawing();
2304 }
2305
2306 const COLOR4D color = gridSourceColor( src );
2307 const GRID_LATTICE lattice = gridLattice( src );
2308
2309 glColor4d( color.r, color.g, color.b, color.a );
2310 SetStrokeColor( color );
2311
2312 Save();
2313 Translate( src.origin );
2314 // GAL Rotate is math-convention; grid orientation is screen-convention.
2315 Rotate( -src.orientation );
2316
2317 // SMALL_CROSS marker.
2318 auto drawCrossAt = [&]( const VECTOR2D& pos, bool aMajor, double aArmAngle )
2319 {
2320 const float w = aMajor ? majorLineWidth : minorLineWidth;
2321 const double len = 2.0 * w;
2322 const double c = std::cos( aArmAngle );
2323 const double s = std::sin( aArmAngle );
2324 const VECTOR2D arm1( c * len, s * len );
2325 const VECTOR2D arm2( -s * len, c * len );
2326
2327 SetIsFill( false );
2328 SetIsStroke( true );
2329 SetLineWidth( w );
2330 DrawLine( pos - arm1, pos + arm1 );
2331 DrawLine( pos - arm2, pos + arm2 );
2332 };
2333
2334 // LINES stroke setup.
2335 auto beginLines = [&]()
2336 {
2337 SetIsFill( false );
2338 SetIsStroke( true );
2339 };
2340
2341 // DOTS via stencil intersection.
2342 auto drawDotsViaStencil = [&]( auto&& aMarkAxis, auto&& aRenderAxis )
2343 {
2344 // Drop the previous source's markers, keeping its coverage claim.
2345 glStencilMask( STENCIL_DOTS_MARKER );
2346 glClear( GL_STENCIL_BUFFER_BIT );
2347
2348 // Mark pass: set marker where claim is clear.
2349 glColorMask( GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE );
2350 glStencilFunc( GL_EQUAL, STENCIL_DOTS_MARKER, coverageMask );
2351 glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
2352 SetIsFill( false );
2353 SetIsStroke( true );
2354 aMarkAxis();
2355 m_nonCachedManager->EndDrawing();
2356
2357 // Render pass: stroke where marker set and claim clear.
2358 glColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE );
2359 glStencilMask( 0x00 );
2360 glStencilFunc( GL_EQUAL, STENCIL_DOTS_MARKER, STENCIL_DOTS_MARKER | coverageMask );
2361 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
2362 aRenderAxis();
2363 m_nonCachedManager->EndDrawing();
2364 };
2365
2366 switch( src.kind )
2367 {
2369 {
2370 const double rMax = lattice.extent.x;
2371 const double phiMax = lattice.extent.y;
2372 const double dr = lattice.pitch.x;
2373 const double dPhi = lattice.pitch.y;
2374
2375 wxASSERT( dr > 0.0 && dPhi > 0.0 );
2376
2377 auto drawArcs = [&]()
2378 {
2379 int rIdx = 0;
2380 for( double r = 0; r <= rMax + 1e-6; r += dr, ++rIdx )
2381 {
2382 if( r == 0.0 )
2383 continue;
2384
2385 SetLineWidth( lattice.IsMajor( rIdx ) ? majorLineWidth : minorLineWidth );
2386 DrawArc( VECTOR2D( 0, 0 ), r, EDA_ANGLE( 0, RADIANS_T ), EDA_ANGLE( phiMax, RADIANS_T ) );
2387 }
2388 };
2389
2390 auto drawSpokes = [&]()
2391 {
2392 int pIdx = 0;
2393 for( double phi = 0; phi <= phiMax + 1e-6; phi += dPhi, ++pIdx )
2394 {
2395 SetLineWidth( lattice.IsMajor( pIdx ) ? majorLineWidth : minorLineWidth );
2396 const double cx = std::cos( phi );
2397 const double cy = std::sin( phi );
2398 DrawLine( VECTOR2D( 0, 0 ), VECTOR2D( rMax * cx, rMax * cy ) );
2399 }
2400 };
2401
2402 if( src.style == GRID_STYLE::LINES )
2403 {
2404 beginLines();
2405 drawArcs();
2406 drawSpokes();
2407 }
2408 else if( src.style == GRID_STYLE::DOTS )
2409 {
2410 drawDotsViaStencil( drawArcs, drawSpokes );
2411 }
2412 else // SMALL_CROSS
2413 {
2414 int rIdx = 0;
2415 for( double r = 0; r <= rMax + 1e-6; r += dr, ++rIdx )
2416 {
2417 int pIdx = 0;
2418 for( double phi = 0; phi <= phiMax + 1e-6; phi += dPhi, ++pIdx )
2419 {
2420 const bool major = lattice.IsMajor( rIdx ) && lattice.IsMajor( pIdx );
2421 const VECTOR2D pos( r * std::cos( phi ), r * std::sin( phi ) );
2422 drawCrossAt( pos, major, phi );
2423 }
2424 }
2425 }
2426 break;
2427 }
2428
2430 {
2431 const double dx = lattice.pitch.x;
2432 const double dy = lattice.pitch.y;
2433
2434 wxASSERT( dx > 0.0 && dy > 0.0 );
2435
2436 double xMin, xMax, yMin, yMax;
2437 int ixMin, ixMax, iyMin, iyMax;
2438
2439 BOX2D localBBox = gridScreenBBox( src );
2440
2441 // One-pitch bleed so off-screen grid lines still paint.
2442 localBBox.Inflate( dx, dy );
2443
2444 if( src.unbounded )
2445 {
2446 xMin = localBBox.GetLeft();
2447 xMax = localBBox.GetRight();
2448 yMin = localBBox.GetTop();
2449 yMax = localBBox.GetBottom();
2450
2451 ixMin = (int) std::floor( xMin / dx );
2452 ixMax = (int) std::ceil( xMax / dx );
2453 iyMin = (int) std::floor( yMin / dy );
2454 iyMax = (int) std::ceil( yMax / dy );
2455 }
2456 else
2457 {
2458 xMin = std::max( localBBox.GetLeft(), -src.extent.x );
2459 xMax = std::min( localBBox.GetRight(), src.extent.x );
2460 yMin = std::max( localBBox.GetTop(), -src.extent.y );
2461 yMax = std::min( localBBox.GetBottom(), src.extent.y );
2462 ixMin = (int) -( src.extent.x / dx );
2463 ixMax = (int) ( src.extent.x / dx );
2464 iyMin = (int) -( src.extent.y / dy );
2465 iyMax = (int) ( src.extent.y / dy );
2466 }
2467
2468 auto drawVerticals = [&]()
2469 {
2470 for( int ix = ixMin; ix <= ixMax; ++ix )
2471 {
2472 const double x = ix * dx;
2473
2474 // Skip line coincident with world Y axis when axes are drawn.
2475 if( src.axesEnabled && x + src.origin.x == 0.0 )
2476 continue;
2477
2478 SetLineWidth( lattice.IsMajor( ix ) ? majorLineWidth : minorLineWidth );
2479 DrawLine( VECTOR2D( x, yMin ), VECTOR2D( x, yMax ) );
2480 }
2481 };
2482
2483 auto drawHorizontals = [&]()
2484 {
2485 for( int iy = iyMin; iy <= iyMax; ++iy )
2486 {
2487 const double y = iy * dy;
2488
2489 if( src.axesEnabled && y + src.origin.y == 0.0 )
2490 continue;
2491
2492 SetLineWidth( lattice.IsMajor( iy ) ? majorLineWidth : minorLineWidth );
2493 DrawLine( VECTOR2D( xMin, y ), VECTOR2D( xMax, y ) );
2494 }
2495 };
2496
2497 if( src.style == GRID_STYLE::LINES )
2498 {
2499 beginLines();
2500 drawVerticals();
2501 drawHorizontals();
2502 }
2503 else if( src.style == GRID_STYLE::DOTS )
2504 {
2505 drawDotsViaStencil( drawVerticals, drawHorizontals );
2506 }
2507 else // SMALL_CROSS
2508 {
2509 for( int ix = ixMin; ix <= ixMax; ++ix )
2510 {
2511 for( int iy = iyMin; iy <= iyMax; ++iy )
2512 {
2513 const bool major = lattice.IsMajor( ix ) && lattice.IsMajor( iy );
2514 drawCrossAt( VECTOR2D( ix * dx, iy * dy ), major, 0.0 );
2515 }
2516 }
2517 }
2518 break;
2519 }
2520
2521 default: wxFAIL_MSG( wxT( "drawGridSources: unhandled GRID_SOURCE::KIND" ) ); break;
2522 }
2523
2524 Restore();
2525 m_nonCachedManager->EndDrawing();
2526
2527 // outline the coverage, so grids don't get lost no matter the pitch
2528 if( !src.unbounded )
2529 {
2530 glStencilMask( 0x00 );
2531 glStencilFunc( GL_EQUAL, 0, coverageMask );
2532 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
2533
2534 SetIsFill( false );
2535 SetIsStroke( true );
2537 SetLineWidth( hairLineWidth );
2538 drawGridCoverageShape( src );
2539 m_nonCachedManager->EndDrawing();
2540 }
2541
2542 // mask out the coverage unless unbounded (background) or highlighted (dimmed fill)
2543 if( !src.unbounded && !src.highlighted )
2544 {
2545 glColorMask( GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE );
2546 glStencilMask( STENCIL_GRID_COVERAGE );
2547 glStencilFunc( GL_ALWAYS, STENCIL_GRID_COVERAGE, STENCIL_GRID_COVERAGE );
2548 glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
2549
2550 SetIsFill( true );
2551 SetIsStroke( false );
2552 drawGridCoverageShape( src );
2553 m_nonCachedManager->EndDrawing();
2554
2555 glColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE );
2556 }
2557 }
2558
2559 glDisable( GL_STENCIL_TEST );
2560 m_nonCachedManager->EnableDepthTest( true );
2561 glEnable( GL_DEPTH_TEST );
2562 glEnable( GL_TEXTURE_2D );
2563}
2564
2565
2566void OPENGL_GAL::ResizeScreen( int aWidth, int aHeight )
2567{
2568 m_screenSize = VECTOR2I( aWidth, aHeight );
2569
2570 // Resize framebuffers
2571 const float scaleFactor = GetScaleFactor();
2572 m_compositor->Resize( aWidth * scaleFactor, aHeight * scaleFactor );
2574
2575 wxGLCanvas::SetSize( aWidth, aHeight );
2576}
2577
2578
2579bool OPENGL_GAL::Show( bool aShow )
2580{
2581 bool s = wxGLCanvas::Show( aShow );
2582
2583 if( aShow )
2584 wxGLCanvas::Raise();
2585
2586 return s;
2587}
2588
2589
2591{
2592 glFlush();
2593}
2594
2595
2597{
2598 // Clear screen
2600
2601 // NOTE: Black used here instead of m_clearColor; it will be composited later
2602 glClearColor( 0, 0, 0, 1 );
2603 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );
2604}
2605
2606
2607void OPENGL_GAL::Transform( const MATRIX3x3D& aTransformation )
2608{
2609 GLdouble matrixData[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
2610
2611 matrixData[0] = aTransformation.m_data[0][0];
2612 matrixData[1] = aTransformation.m_data[1][0];
2613 matrixData[2] = aTransformation.m_data[2][0];
2614 matrixData[4] = aTransformation.m_data[0][1];
2615 matrixData[5] = aTransformation.m_data[1][1];
2616 matrixData[6] = aTransformation.m_data[2][1];
2617 matrixData[12] = aTransformation.m_data[0][2];
2618 matrixData[13] = aTransformation.m_data[1][2];
2619 matrixData[14] = aTransformation.m_data[2][2];
2620
2621 glMultMatrixd( matrixData );
2622}
2623
2624
2625void OPENGL_GAL::Rotate( double aAngle )
2626{
2627 m_currentManager->Rotate( aAngle, 0.0f, 0.0f, 1.0f );
2628}
2629
2630
2631void OPENGL_GAL::Translate( const VECTOR2D& aVector )
2632{
2633 m_currentManager->Translate( aVector.x, aVector.y, 0.0f );
2634}
2635
2636
2637void OPENGL_GAL::Scale( const VECTOR2D& aScale )
2638{
2639 m_currentManager->Scale( aScale.x, aScale.y, 1.0f );
2640}
2641
2642
2644{
2645 m_currentManager->PushMatrix();
2646}
2647
2648
2650{
2651 m_currentManager->PopMatrix();
2652}
2653
2654
2656{
2657 m_isGrouping = true;
2658
2659 std::shared_ptr<VERTEX_ITEM> newItem = std::make_shared<VERTEX_ITEM>( *m_cachedManager );
2660 int groupNumber = getNewGroupNumber();
2661 m_groups.insert( std::make_pair( groupNumber, newItem ) );
2662
2663 return groupNumber;
2664}
2665
2666
2668{
2669 m_cachedManager->FinishItem();
2670 m_isGrouping = false;
2671}
2672
2673
2674void OPENGL_GAL::DrawGroup( int aGroupNumber )
2675{
2676 auto group = m_groups.find( aGroupNumber );
2677
2678 if( group != m_groups.end() )
2679 m_cachedManager->DrawItem( *group->second );
2680}
2681
2682
2683void OPENGL_GAL::ChangeGroupColor( int aGroupNumber, const COLOR4D& aNewColor )
2684{
2685 auto group = m_groups.find( aGroupNumber );
2686
2687 if( group != m_groups.end() )
2688 m_cachedManager->ChangeItemColor( *group->second, aNewColor );
2689}
2690
2691
2692void OPENGL_GAL::ChangeGroupDepth( int aGroupNumber, int aDepth )
2693{
2694 auto group = m_groups.find( aGroupNumber );
2695
2696 if( group != m_groups.end() )
2697 m_cachedManager->ChangeItemDepth( *group->second, aDepth );
2698}
2699
2700
2701void OPENGL_GAL::DeleteGroup( int aGroupNumber )
2702{
2703 // Frees memory in the container as well
2704 m_groups.erase( aGroupNumber );
2705}
2706
2707
2709{
2710 // Runs unlocked from VIEW::Clear, so deleting a lost group's texture names could hit another group's
2712 m_bitmapCache->Abandon();
2713
2714 m_bitmapCache = std::make_unique<GL_BITMAP_CACHE>();
2715
2716 m_groups.clear();
2717
2718 if( m_isInitialized )
2719 m_cachedManager->Clear();
2720}
2721
2722
2724{
2725 switch( aTarget )
2726 {
2727 default:
2732 }
2733
2734 m_currentTarget = aTarget;
2735}
2736
2737
2739{
2740 return m_currentTarget;
2741}
2742
2743
2745{
2746 // Save the current state
2747 unsigned int oldTarget = m_compositor->GetBuffer();
2748
2749 switch( aTarget )
2750 {
2751 // Cached and noncached items are rendered to the same buffer
2752 default:
2753 case TARGET_CACHED:
2754 case TARGET_NONCACHED:
2755 m_compositor->SetBuffer( m_mainBuffer );
2756 break;
2757
2758 case TARGET_TEMP:
2759 if( m_tempBuffer )
2760 m_compositor->SetBuffer( m_tempBuffer );
2761 break;
2762
2763 case TARGET_OVERLAY:
2764 if( m_overlayBuffer )
2765 m_compositor->SetBuffer( m_overlayBuffer );
2766 break;
2767 }
2768
2769 if( aTarget != TARGET_OVERLAY )
2770 m_compositor->ClearBuffer( m_clearColor );
2771 else if( m_overlayBuffer )
2772 m_compositor->ClearBuffer( COLOR4D::BLACK );
2773
2774 // Restore the previous state
2775 m_compositor->SetBuffer( oldTarget );
2776}
2777
2778
2780{
2781 switch( aTarget )
2782 {
2783 default:
2784 case TARGET_CACHED:
2785 case TARGET_NONCACHED: return true;
2786 case TARGET_OVERLAY: return ( m_overlayBuffer != 0 );
2787 case TARGET_TEMP: return ( m_tempBuffer != 0 );
2788 }
2789}
2790
2791
2793{
2794 wxLogTrace( traceGalXorMode, wxT( "OPENGL_GAL::StartDiffLayer() called" ) );
2795 wxLogTrace( traceGalXorMode, wxT( "StartDiffLayer(): m_tempBuffer=%u" ), m_tempBuffer );
2796
2797 m_currentManager->EndDrawing();
2798
2799 if( m_tempBuffer )
2800 {
2801 wxLogTrace( traceGalXorMode, wxT( "StartDiffLayer(): setting target to TARGET_TEMP" ) );
2804
2805 // ClearTarget restores the previous compositor buffer, so we need to explicitly
2806 // set the compositor to render to m_tempBuffer for the layer drawing
2807 m_compositor->SetBuffer( m_tempBuffer );
2808 wxLogTrace( traceGalXorMode, wxT( "StartDiffLayer(): TARGET_TEMP set and cleared, compositor buffer=%u" ),
2809 m_tempBuffer );
2810 }
2811 else
2812 {
2813 wxLogTrace( traceGalXorMode, wxT( "StartDiffLayer(): WARNING - no temp buffer!" ) );
2814 }
2815}
2816
2817
2819{
2820 wxLogTrace( traceGalXorMode, wxT( "OPENGL_GAL::EndDiffLayer() called" ) );
2821 wxLogTrace( traceGalXorMode, wxT( "EndDiffLayer(): m_tempBuffer=%u, m_mainBuffer=%u" ),
2823
2824 if( m_tempBuffer )
2825 {
2826 wxLogTrace( traceGalXorMode, wxT( "EndDiffLayer(): using temp buffer path" ) );
2827
2828 // End drawing to the temp buffer
2829 m_currentManager->EndDrawing();
2830
2831 wxLogTrace( traceGalXorMode, wxT( "EndDiffLayer(): calling DrawBufferDifference" ) );
2832
2833 // Use difference compositing for true XOR/difference mode:
2834 // - Where only one layer has content: shows that layer's color
2835 // - Where both layers overlap with identical content: cancels out (black)
2836 // - Where layers overlap with different content: shows the absolute difference
2837 m_compositor->DrawBufferDifference( m_tempBuffer, m_mainBuffer );
2838
2839 wxLogTrace( traceGalXorMode, wxT( "EndDiffLayer(): DrawBufferDifference returned" ) );
2840 }
2841 else
2842 {
2843 wxLogTrace( traceGalXorMode, wxT( "EndDiffLayer(): NO temp buffer, using fallback path" ) );
2844
2845 // Fall back to imperfect alpha blending on single buffer
2846 glBlendFunc( GL_SRC_ALPHA, GL_ONE );
2847 m_currentManager->EndDrawing();
2848 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
2849 }
2850
2851 wxLogTrace( traceGalXorMode, wxT( "OPENGL_GAL::EndDiffLayer() complete" ) );
2852}
2853
2854
2855bool OPENGL_GAL::SetNativeCursorStyle( KICURSOR aCursor, bool aHiDPI )
2856{
2857 // Store the current cursor type and get the wx cursor for it
2858 if( !GAL::SetNativeCursorStyle( aCursor, aHiDPI ) )
2859 return false;
2860
2862
2863#if wxCHECK_VERSION( 3, 3, 0 )
2864 wxWindow::SetCursorBundle( m_currentwxCursor );
2865#else
2866 wxWindow::SetCursor( m_currentwxCursor );
2867#endif
2868
2869 return true;
2870}
2871
2872
2873void OPENGL_GAL::onSetNativeCursor( wxSetCursorEvent& aEvent )
2874{
2875#if wxCHECK_VERSION( 3, 3, 0 )
2876 aEvent.SetCursor( m_currentwxCursor.GetCursorFor( this ) );
2877#else
2878 aEvent.SetCursor( m_currentwxCursor );
2879#endif
2880}
2881
2882
2883void OPENGL_GAL::DrawCursor( const VECTOR2D& aCursorPosition )
2884{
2885 // Now we should only store the position of the mouse cursor
2886 // The real drawing routines are in blitCursor()
2887 //VECTOR2D screenCursor = m_worldScreenMatrix * aCursorPosition;
2888 //m_cursorPosition = m_screenWorldMatrix * VECTOR2D( screenCursor.x, screenCursor.y );
2889 m_cursorPosition = aCursorPosition;
2890}
2891
2892
2893void OPENGL_GAL::drawLineQuad( const VECTOR2D& aStartPoint, const VECTOR2D& aEndPoint,
2894 const bool aReserve )
2895{
2896 /* Helper drawing: ____--- v3 ^
2897 * ____---- ... \ \
2898 * ____---- ... \ end \
2899 * v1 ____---- ... ____---- \ width
2900 * ---- ...___---- \ \
2901 * \ ___...-- \ v
2902 * \ ____----... ____---- v2
2903 * ---- ... ____----
2904 * start \ ... ____----
2905 * \... ____----
2906 * ----
2907 * v0
2908 * dots mark triangles' hypotenuses
2909 */
2910
2911 auto v1 = m_currentManager->GetTransformation()
2912 * glm::vec4( aStartPoint.x, aStartPoint.y, 0.0, 0.0 );
2913 auto v2 = m_currentManager->GetTransformation()
2914 * glm::vec4( aEndPoint.x, aEndPoint.y, 0.0, 0.0 );
2915
2916 VECTOR2D vs( v2.x - v1.x, v2.y - v1.y );
2917
2918 if( aReserve )
2919 reserveLineQuads( 1 );
2920
2921 // Line width is maintained by the vertex shader
2922 m_currentManager->Shader( SHADER_LINE_A, m_lineWidth, vs.x, vs.y );
2923 m_currentManager->Vertex( aStartPoint, m_layerDepth );
2924
2925 m_currentManager->Shader( SHADER_LINE_B, m_lineWidth, vs.x, vs.y );
2926 m_currentManager->Vertex( aStartPoint, m_layerDepth );
2927
2928 m_currentManager->Shader( SHADER_LINE_C, m_lineWidth, vs.x, vs.y );
2929 m_currentManager->Vertex( aEndPoint, m_layerDepth );
2930
2931 m_currentManager->Shader( SHADER_LINE_D, m_lineWidth, vs.x, vs.y );
2932 m_currentManager->Vertex( aEndPoint, m_layerDepth );
2933
2934 m_currentManager->Shader( SHADER_LINE_E, m_lineWidth, vs.x, vs.y );
2935 m_currentManager->Vertex( aEndPoint, m_layerDepth );
2936
2937 m_currentManager->Shader( SHADER_LINE_F, m_lineWidth, vs.x, vs.y );
2938 m_currentManager->Vertex( aStartPoint, m_layerDepth );
2939}
2940
2941
2942void OPENGL_GAL::reserveLineQuads( const int aLineCount )
2943{
2944 m_currentManager->Reserve( 6 * aLineCount );
2945}
2946
2947
2948void OPENGL_GAL::drawSemiCircle( const VECTOR2D& aCenterPoint, double aRadius, double aAngle )
2949{
2950 if( m_isFillEnabled )
2951 {
2953 drawFilledSemiCircle( aCenterPoint, aRadius, aAngle );
2954 }
2955
2956 if( m_isStrokeEnabled )
2957 {
2959 m_strokeColor.a );
2960 drawStrokedSemiCircle( aCenterPoint, aRadius, aAngle );
2961 }
2962}
2963
2964
2965void OPENGL_GAL::drawFilledSemiCircle( const VECTOR2D& aCenterPoint, double aRadius, double aAngle )
2966{
2967 Save();
2968
2969 m_currentManager->Reserve( 3 );
2970 m_currentManager->Translate( aCenterPoint.x, aCenterPoint.y, 0.0f );
2971 m_currentManager->Rotate( aAngle, 0.0f, 0.0f, 1.0f );
2972
2973 /* Draw a triangle that contains the semicircle, then shade it to leave only
2974 * the semicircle. Parameters given to Shader() are indices of the triangle's vertices
2975 * (if you want to understand more, check the vertex shader source [shader.vert]).
2976 * Shader uses these coordinates to determine if fragments are inside the semicircle or not.
2977 * v2
2978 * /\
2979 * /__\
2980 * v0 //__\\ v1
2981 */
2982 m_currentManager->Shader( SHADER_FILLED_CIRCLE, 4.0f );
2983 m_currentManager->Vertex( -aRadius * 3.0f / sqrt( 3.0f ), 0.0f, m_layerDepth ); // v0
2984
2985 m_currentManager->Shader( SHADER_FILLED_CIRCLE, 5.0f );
2986 m_currentManager->Vertex( aRadius * 3.0f / sqrt( 3.0f ), 0.0f, m_layerDepth ); // v1
2987
2988 m_currentManager->Shader( SHADER_FILLED_CIRCLE, 6.0f );
2989 m_currentManager->Vertex( 0.0f, aRadius * 2.0f, m_layerDepth ); // v2
2990
2991 Restore();
2992}
2993
2994
2995void OPENGL_GAL::drawStrokedSemiCircle( const VECTOR2D& aCenterPoint, double aRadius, double aAngle,
2996 bool aReserve )
2997{
2998 double outerRadius = aRadius + ( m_lineWidth / 2 );
2999
3000 Save();
3001
3002 if( aReserve )
3003 m_currentManager->Reserve( 3 );
3004
3005 m_currentManager->Translate( aCenterPoint.x, aCenterPoint.y, 0.0f );
3006 m_currentManager->Rotate( aAngle, 0.0f, 0.0f, 1.0f );
3007
3008 /* Draw a triangle that contains the semicircle, then shade it to leave only
3009 * the semicircle. Parameters given to Shader() are indices of the triangle's vertices
3010 * (if you want to understand more, check the vertex shader source [shader.vert]), the
3011 * radius and the line width. Shader uses these coordinates to determine if fragments are
3012 * inside the semicircle or not.
3013 * v2
3014 * /\
3015 * /__\
3016 * v0 //__\\ v1
3017 */
3018 m_currentManager->Shader( SHADER_STROKED_CIRCLE, 4.0f, aRadius, m_lineWidth );
3019 m_currentManager->Vertex( -outerRadius * 3.0f / sqrt( 3.0f ), 0.0f, m_layerDepth ); // v0
3020
3021 m_currentManager->Shader( SHADER_STROKED_CIRCLE, 5.0f, aRadius, m_lineWidth );
3022 m_currentManager->Vertex( outerRadius * 3.0f / sqrt( 3.0f ), 0.0f, m_layerDepth ); // v1
3023
3024 m_currentManager->Shader( SHADER_STROKED_CIRCLE, 6.0f, aRadius, m_lineWidth );
3025 m_currentManager->Vertex( 0.0f, outerRadius * 2.0f, m_layerDepth ); // v2
3026
3027 Restore();
3028}
3029
3030
3031void OPENGL_GAL::drawPolygon( GLdouble* aPoints, int aPointCount )
3032{
3033 if( m_isFillEnabled )
3034 {
3035 m_currentManager->Shader( SHADER_NONE );
3037
3038 // Any non convex polygon needs to be tesselated
3039 // for this purpose the GLU standard functions are used
3041 gluTessBeginPolygon( m_tesselator, &params );
3042 gluTessBeginContour( m_tesselator );
3043
3044 GLdouble* point = aPoints;
3045
3046 for( int i = 0; i < aPointCount; ++i )
3047 {
3048 gluTessVertex( m_tesselator, point, point );
3049 point += 3; // 3 coordinates
3050 }
3051
3052 gluTessEndContour( m_tesselator );
3053 gluTessEndPolygon( m_tesselator );
3054
3055 // Free allocated intersecting points
3056 m_tessIntersects.clear();
3057 }
3058
3059 if( m_isStrokeEnabled )
3060 {
3062 [&]( int idx )
3063 {
3064 return VECTOR2D( aPoints[idx * 3], aPoints[idx * 3 + 1] );
3065 },
3066 aPointCount );
3067 }
3068}
3069
3070
3071void OPENGL_GAL::drawPolyline( const std::function<VECTOR2D( int )>& aPointGetter, int aPointCount,
3072 bool aReserve )
3073{
3074 wxCHECK( aPointCount > 0, /* return */ );
3075
3077
3078 if( aPointCount == 1 )
3079 {
3080 drawLineQuad( aPointGetter( 0 ), aPointGetter( 0 ), aReserve );
3081 return;
3082 }
3083
3084 if( aReserve )
3085 {
3086 reserveLineQuads( aPointCount - 1 );
3087 }
3088
3089 for( int i = 1; i < aPointCount; ++i )
3090 {
3091 auto start = aPointGetter( i - 1 );
3092 auto end = aPointGetter( i );
3093
3094 drawLineQuad( start, end, false );
3095 }
3096}
3097
3098
3099void OPENGL_GAL::drawSegmentChain( const std::function<VECTOR2D( int )>& aPointGetter,
3100 int aPointCount, double aWidth, bool aReserve )
3101{
3102 wxCHECK( aPointCount >= 2, /* return */ );
3103
3105
3106 int vertices = 0;
3107
3108 for( int i = 1; i < aPointCount; ++i )
3109 {
3110 auto start = aPointGetter( i - 1 );
3111 auto end = aPointGetter( i );
3112
3113 float startx = start.x;
3114 float starty = start.y;
3115 float endx = end.x;
3116 float endy = end.y;
3117
3118 // Be careful about floating point rounding. As we draw segments in larger and larger
3119 // coordinates, the shader (which uses floats) will lose precision and stop drawing small
3120 // segments. In this case, we need to draw a circle for the minimal segment.
3121 // Check if the coordinate differences can be accurately represented as floats
3122
3123 if( startx == endx && starty == endy )
3124 {
3125 vertices += 3; // One circle
3126 continue;
3127 }
3128
3129 if( m_isFillEnabled || aWidth == 1.0 )
3130 {
3131 vertices += 6; // One line
3132 }
3133 else
3134 {
3135 vertices += 6 + 6 + 3 + 3; // Two lines and two half-circles
3136 }
3137 }
3138
3139 m_currentManager->Reserve( vertices );
3140
3141 for( int i = 1; i < aPointCount; ++i )
3142 {
3143 auto start = aPointGetter( i - 1 );
3144 auto end = aPointGetter( i );
3145
3146 drawSegment( start, end, aWidth, false );
3147 }
3148}
3149
3150
3151int OPENGL_GAL::drawBitmapChar( unsigned long aChar, bool aReserve )
3152{
3153 const float TEX_X = font_image.width;
3154 const float TEX_Y = font_image.height;
3155
3156 // handle space
3157 if( aChar == ' ' )
3158 {
3159 const double spaceWidth = SpaceAdvance();
3160
3161 Translate( VECTOR2D( spaceWidth, 0 ) );
3162 return KiROUND( spaceWidth );
3163 }
3164
3165 const FONT_GLYPH_TYPE* glyph = LookupGlyph( aChar );
3166
3167 // If the glyph is not found (happens for many esoteric unicode chars)
3168 // shows a '?' instead.
3169 if( !glyph )
3170 glyph = LookupGlyph( '?' );
3171
3172 if( !glyph ) // Should not happen.
3173 return 0;
3174
3175 const GLYPH_BOX box = ComputeGlyphBox( *glyph );
3176 const float X = box.atlasX;
3177 const float Y = box.atlasY;
3178 const float XOFF = box.x;
3179 const float YOFF = box.y;
3180 const float W = box.w;
3181 const float H = box.h;
3182 const float B = 0;
3183
3184 if( aReserve )
3185 m_currentManager->Reserve( 6 );
3186
3187 Translate( VECTOR2D( XOFF, YOFF ) );
3188
3189 /* Glyph:
3190 * v0 v1
3191 * +--+
3192 * | /|
3193 * |/ |
3194 * +--+
3195 * v2 v3
3196 */
3197 m_currentManager->Shader( SHADER_FONT, X / TEX_X, ( Y + H ) / TEX_Y );
3198 m_currentManager->Vertex( -B, -B, 0 ); // v0
3199
3200 m_currentManager->Shader( SHADER_FONT, ( X + W ) / TEX_X, ( Y + H ) / TEX_Y );
3201 m_currentManager->Vertex( W + B, -B, 0 ); // v1
3202
3203 m_currentManager->Shader( SHADER_FONT, X / TEX_X, Y / TEX_Y );
3204 m_currentManager->Vertex( -B, H + B, 0 ); // v2
3205
3206
3207 m_currentManager->Shader( SHADER_FONT, ( X + W ) / TEX_X, ( Y + H ) / TEX_Y );
3208 m_currentManager->Vertex( W + B, -B, 0 ); // v1
3209
3210 m_currentManager->Shader( SHADER_FONT, X / TEX_X, Y / TEX_Y );
3211 m_currentManager->Vertex( -B, H + B, 0 ); // v2
3212
3213 m_currentManager->Shader( SHADER_FONT, ( X + W ) / TEX_X, Y / TEX_Y );
3214 m_currentManager->Vertex( W + B, H + B, 0 ); // v3
3215
3216 Translate( VECTOR2D( -XOFF + glyph->advance, -YOFF ) );
3217
3218 return glyph->advance;
3219}
3220
3221
3222void OPENGL_GAL::drawBitmapOverbar( double aLength, double aHeight, bool aReserve )
3223{
3224 // To draw an overbar, simply draw an overbar
3225 const FONT_GLYPH_TYPE* glyph = LookupGlyph( '_' );
3226 wxCHECK( glyph, /* void */ );
3227
3228 const float H = glyph->maxy - glyph->miny;
3229
3230 Save();
3231
3232 Translate( VECTOR2D( -aLength, -aHeight ) );
3233
3234 if( aReserve )
3235 m_currentManager->Reserve( 6 );
3236
3238
3239 m_currentManager->Shader( 0 );
3240
3241 m_currentManager->Vertex( 0, 0, 0 ); // v0
3242 m_currentManager->Vertex( aLength, 0, 0 ); // v1
3243 m_currentManager->Vertex( 0, H, 0 ); // v2
3244
3245 m_currentManager->Vertex( aLength, 0, 0 ); // v1
3246 m_currentManager->Vertex( 0, H, 0 ); // v2
3247 m_currentManager->Vertex( aLength, H, 0 ); // v3
3248
3249 Restore();
3250}
3251
3252
3253std::pair<VECTOR2D, float> OPENGL_GAL::computeBitmapTextSize( const UTF8& aText ) const
3254{
3256}
3257
3258
3259void OPENGL_GAL::onPaint( wxPaintEvent& aEvent )
3260{
3261 PostPaint( aEvent );
3262}
3263
3264
3265void OPENGL_GAL::skipMouseEvent( wxMouseEvent& aEvent )
3266{
3267 // Post the mouse event to the event listener registered in constructor, if any
3268 if( m_mouseListener )
3269 wxPostEvent( m_mouseListener, aEvent );
3270}
3271
3272
3273void OPENGL_GAL::skipGestureEvent( wxGestureEvent& aEvent )
3274{
3275 // Post the gesture event to the event listener registered in constructor, if any
3276 if( m_mouseListener )
3277 wxPostEvent( m_mouseListener, aEvent );
3278}
3279
3280
3282{
3283 if( !IsCursorEnabled() )
3284 return;
3285
3287
3288 VECTOR2D cursorBegin;
3289 VECTOR2D cursorEnd;
3290 VECTOR2D cursorCenter = m_cursorPosition;
3291
3293 {
3294 cursorBegin = m_screenWorldMatrix * VECTOR2D( 0.0, 0.0 );
3295 cursorEnd = m_screenWorldMatrix * VECTOR2D( m_screenSize );
3296 }
3298 {
3299 const int cursorSize = 80;
3300 cursorBegin = m_cursorPosition - cursorSize / ( 2 * m_worldScale );
3301 cursorEnd = m_cursorPosition + cursorSize / ( 2 * m_worldScale );
3302 }
3303
3304 const COLOR4D color = getCursorColor();
3305
3306 GLboolean depthTestEnabled = glIsEnabled( GL_DEPTH_TEST );
3307 glDisable( GL_DEPTH_TEST );
3308
3309 glActiveTexture( GL_TEXTURE0 );
3310 glDisable( GL_TEXTURE_2D );
3311 glEnable( GL_BLEND );
3312 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
3313
3314 glLineWidth( 1.0 );
3315 glColor4d( color.r, color.g, color.b, color.a );
3316
3317 glMatrixMode( GL_PROJECTION );
3318 glPushMatrix();
3319 glTranslated( 0, 0, -0.5 );
3320
3321 glBegin( GL_LINES );
3322
3324 {
3325 // Calculate screen bounds in world coordinates
3326 VECTOR2D screenTopLeft = m_screenWorldMatrix * VECTOR2D( 0.0, 0.0 );
3327 VECTOR2D screenBottomRight = m_screenWorldMatrix * VECTOR2D( m_screenSize );
3328
3329 // For 45-degree lines passing through cursor position
3330 // Line equation: y = x + (cy - cx) for positive slope
3331 // Line equation: y = -x + (cy + cx) for negative slope
3332 double cx = m_cursorPosition.x;
3333 double cy = m_cursorPosition.y;
3334
3335 // Calculate intersections for positive slope diagonal (y = x + offset)
3336 double offset1 = cy - cx;
3337 VECTOR2D pos_start( screenTopLeft.x, screenTopLeft.x + offset1 );
3338 VECTOR2D pos_end( screenBottomRight.x, screenBottomRight.x + offset1 );
3339
3340 // Draw positive slope diagonal
3341 glVertex2d( pos_start.x, pos_start.y );
3342 glVertex2d( pos_end.x, pos_end.y );
3343
3344 // Calculate intersections for negative slope diagonal (y = -x + offset)
3345 double offset2 = cy + cx;
3346 VECTOR2D neg_start( screenTopLeft.x, offset2 - screenTopLeft.x );
3347 VECTOR2D neg_end( screenBottomRight.x, offset2 - screenBottomRight.x );
3348
3349 // Draw negative slope diagonal
3350 glVertex2d( neg_start.x, neg_start.y );
3351 glVertex2d( neg_end.x, neg_end.y );
3352 }
3353 else
3354 {
3355 glVertex2d( cursorCenter.x, cursorBegin.y );
3356 glVertex2d( cursorCenter.x, cursorEnd.y );
3357
3358 glVertex2d( cursorBegin.x, cursorCenter.y );
3359 glVertex2d( cursorEnd.x, cursorCenter.y );
3360 }
3361
3362 glEnd();
3363
3364 glPopMatrix();
3365
3366 if( depthTestEnabled )
3367 glEnable( GL_DEPTH_TEST );
3368}
3369
3370
3372{
3373 wxASSERT_MSG( m_groups.size() < std::numeric_limits<unsigned int>::max(),
3374 wxT( "There are no free slots to store a group" ) );
3375
3376 while( m_groups.find( m_groupCounter ) != m_groups.end() )
3378
3379 return m_groupCounter++;
3380}
3381
3382
3384{
3385 wxASSERT_MSG( m_isContextLocked, "This should only be called from within a locked context." );
3386
3387 // Check correct initialization from the constructor
3388 if( m_tesselator == nullptr )
3389 throw std::runtime_error( "Could not create the tesselator" );
3390
3392
3393 int glVersion = gladLoaderLoadGL();
3394
3395 if( glVersion == 0 )
3396 throw std::runtime_error( "Failed to load OpenGL via loader" );
3397
3398 m_glLoaded = true;
3399
3400 const char* vendor = (const char*) glGetString( GL_VENDOR );
3401 const char* renderer = (const char*) glGetString( GL_RENDERER );
3402 const char* version = (const char*) glGetString( GL_VERSION );
3403
3404 if( !version )
3405 throw std::runtime_error( "No GL context is current (glGetString returned NULL)" );
3406
3407 SetOpenGLInfo( vendor, renderer, version );
3408
3409 wxLogTrace( traceGalContext, wxS( "GL context %p ready on canvas %p: %s | %s | %s" ),
3410 m_glPrivContext, this, wxString::FromUTF8( vendor ),
3411 wxString::FromUTF8( renderer ), wxString::FromUTF8( version ) );
3412
3413 GLint resetStrategy = 0;
3414
3415 if( GLAD_GL_VERSION_4_5 || GLAD_GL_ARB_robustness || GLAD_GL_KHR_robustness )
3416 glGetIntegerv( GL_RESET_NOTIFICATION_STRATEGY, &resetStrategy );
3417
3418 wxLogTrace( traceGalContext, wxS( "GL context %p reset strategy 0x%x" ), m_glPrivContext, resetStrategy );
3419
3420 // Check the OpenGL version (minimum 2.1 is required)
3421 if( !GLAD_GL_VERSION_2_1 )
3422 throw std::runtime_error( "OpenGL 2.1 or higher is required!" );
3423
3424#if defined( __LINUX__ ) // calling enableGlDebug crashes opengl on some OS (OSX and some Windows)
3425#ifdef DEBUG
3426 if( glDebugMessageCallback )
3427 enableGlDebug( true );
3428#endif
3429#endif
3430
3431 // Framebuffers have to be supported
3432 if( !GLAD_GL_ARB_framebuffer_object )
3433 throw std::runtime_error( "Framebuffer objects are not supported!" );
3434
3435 // Vertex buffer has to be supported
3436 if( !GLAD_GL_ARB_vertex_buffer_object )
3437 throw std::runtime_error( "Vertex buffer objects are not supported!" );
3438
3439 // Prepare shaders
3440 if( !m_shader->IsLinked()
3441 && !m_shader->LoadShaderFromStrings( SHADER_TYPE_VERTEX,
3442 BUILTIN_SHADERS::glsl_kicad_vert ) )
3443 {
3444 throw std::runtime_error( "Cannot compile vertex shader!" );
3445 }
3446
3447 if( !m_shader->IsLinked()
3448 && !m_shader->LoadShaderFromStrings( SHADER_TYPE_FRAGMENT,
3449 BUILTIN_SHADERS::glsl_kicad_frag ) )
3450 {
3451 throw std::runtime_error( "Cannot compile fragment shader!" );
3452 }
3453
3454 if( !m_shader->IsLinked() && !m_shader->Link() )
3455 throw std::runtime_error( "Cannot link the shaders!" );
3456
3457 // Set up shader parameters after linking
3459
3460 // Check if video card supports textures big enough to fit the font atlas
3461 int maxTextureSize;
3462 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &maxTextureSize );
3463
3464 if( maxTextureSize < (int) font_image.width || maxTextureSize < (int) font_image.height )
3465 {
3466 // TODO implement software texture scaling
3467 // for bitmap fonts and use a higher resolution texture?
3468 throw std::runtime_error( "Requested texture size is not supported" );
3469 }
3470
3471#if wxCHECK_VERSION( 3, 3, 3 )
3472 wxGLCanvas::SetSwapInterval( -1 );
3473 m_swapInterval = wxGLCanvas::GetSwapInterval();
3474#else
3476#endif
3477
3478 m_cachedManager = new VERTEX_MANAGER( true );
3479 m_nonCachedManager = new VERTEX_MANAGER( false );
3480 m_overlayManager = new VERTEX_MANAGER( false );
3481 m_tempManager = new VERTEX_MANAGER( false );
3482
3483 // Make VBOs use shaders
3484 m_cachedManager->SetShader( *m_shader );
3485 m_nonCachedManager->SetShader( *m_shader );
3486 m_overlayManager->SetShader( *m_shader );
3487 m_tempManager->SetShader( *m_shader );
3488
3489 m_isInitialized = true;
3490}
3491
3492
3494{
3495 // Initialize shader uniform parameter locations
3496 ufm_fontTexture = m_shader->AddParameter( "u_fontTexture" );
3497 ufm_fontTextureWidth = m_shader->AddParameter( "u_fontTextureWidth" );
3498 ufm_worldPixelSize = m_shader->AddParameter( "u_worldPixelSize" );
3499 ufm_screenPixelSize = m_shader->AddParameter( "u_screenPixelSize" );
3500 ufm_pixelSizeMultiplier = m_shader->AddParameter( "u_pixelSizeMultiplier" );
3501 ufm_antialiasingOffset = m_shader->AddParameter( "u_antialiasingOffset" );
3502 ufm_minLinePixelWidth = m_shader->AddParameter( "u_minLinePixelWidth" );
3503}
3504
3505
3506// Callback functions for the tesselator. Compare Redbook Chapter 11.
3507void CALLBACK VertexCallback( GLvoid* aVertexPtr, void* aData )
3508{
3509 GLdouble* vertex = static_cast<GLdouble*>( aVertexPtr );
3510 OPENGL_GAL::TessParams* param = static_cast<OPENGL_GAL::TessParams*>( aData );
3511 VERTEX_MANAGER* vboManager = param->vboManager;
3512
3513 assert( vboManager );
3514 vboManager->Vertex( vertex[0], vertex[1], vertex[2] );
3515}
3516
3517
3518void CALLBACK CombineCallback( GLdouble coords[3], GLdouble* vertex_data[4], GLfloat weight[4],
3519 GLdouble** dataOut, void* aData )
3520{
3521 GLdouble* vertex = new GLdouble[3];
3522 OPENGL_GAL::TessParams* param = static_cast<OPENGL_GAL::TessParams*>( aData );
3523
3524 // Save the pointer so we can delete it later
3525 // Note, we use the default_delete for an array because macOS
3526 // decides to bundle an ancient libc++ that mismatches the C++17 support of clang
3527 param->intersectPoints.emplace_back( vertex, std::default_delete<GLdouble[]>() );
3528
3529 memcpy( vertex, coords, 3 * sizeof( GLdouble ) );
3530
3531 *dataOut = vertex;
3532}
3533
3534
3535void CALLBACK EdgeCallback( GLboolean aEdgeFlag )
3536{
3537 // This callback is needed to force GLU tesselator to use triangles only
3538}
3539
3540
3542{
3543 //throw std::runtime_error( std::string( "Tessellation error: " ) +
3544 //std::string( (const char*) gluErrorString( aErrorCode ) );
3545}
3546
3547
3548static void InitTesselatorCallbacks( GLUtesselator* aTesselator )
3549{
3550#if defined( _MSC_VER )
3551#pragma warning( push )
3552#pragma warning( disable : 4191 )
3553#endif
3554 gluTessCallback( aTesselator, GLU_TESS_VERTEX_DATA, (void( CALLBACK* )()) VertexCallback );
3555 gluTessCallback( aTesselator, GLU_TESS_COMBINE_DATA, (void( CALLBACK* )()) CombineCallback );
3556 gluTessCallback( aTesselator, GLU_TESS_EDGE_FLAG, (void( CALLBACK* )()) EdgeCallback );
3557 gluTessCallback( aTesselator, GLU_TESS_ERROR, (void( CALLBACK* )()) ErrorCallback );
3558#if defined( _MSC_VER )
3559#pragma warning( pop )
3560#endif
3561}
3562
3563
3564void OPENGL_GAL::EnableDepthTest( bool aEnabled )
3565{
3566 m_cachedManager->EnableDepthTest( aEnabled );
3567 m_nonCachedManager->EnableDepthTest( aEnabled );
3568 m_overlayManager->EnableDepthTest( aEnabled );
3569}
3570
3571
3572inline double round_to_half_pixel( double f, double r )
3573{
3574 return ( ceil( f / r ) - 0.5 ) * r;
3575}
3576
3577
3579{
3581 auto pixelSize = m_worldScale;
3582
3583 // we need -m_lookAtPoint == -k * pixelSize + 0.5 * pixelSize for OpenGL
3584 // meaning m_lookAtPoint = (k-0.5)*pixelSize with integer k
3587
3589}
3590
3591
3592void OPENGL_GAL::DrawGlyph( const KIFONT::GLYPH& aGlyph, int aNth, int aTotal )
3593{
3594 if( aGlyph.IsStroke() )
3595 {
3596 const auto& strokeGlyph = static_cast<const KIFONT::STROKE_GLYPH&>( aGlyph );
3597
3598 DrawPolylines( strokeGlyph );
3599 }
3600 else if( aGlyph.IsOutline() )
3601 {
3602 const auto& outlineGlyph = static_cast<const KIFONT::OUTLINE_GLYPH&>( aGlyph );
3603
3604 m_currentManager->Shader( SHADER_NONE );
3605 m_currentManager->Color( m_fillColor );
3606
3607 outlineGlyph.Triangulate(
3608 [&]( const VECTOR2D& aPt1, const VECTOR2D& aPt2, const VECTOR2D& aPt3 )
3609 {
3610 m_currentManager->Reserve( 3 );
3611
3612 m_currentManager->Vertex( aPt1.x, aPt1.y, m_layerDepth );
3613 m_currentManager->Vertex( aPt2.x, aPt2.y, m_layerDepth );
3614 m_currentManager->Vertex( aPt3.x, aPt3.y, m_layerDepth );
3615 } );
3616 }
3617}
3618
3619
3620void OPENGL_GAL::DrawGlyphs( const std::vector<std::unique_ptr<KIFONT::GLYPH>>& aGlyphs )
3621{
3622 if( aGlyphs.empty() )
3623 return;
3624
3625 bool allGlyphsAreStroke = true;
3626 bool allGlyphsAreOutline = true;
3627
3628 for( const std::unique_ptr<KIFONT::GLYPH>& glyph : aGlyphs )
3629 {
3630 if( !glyph->IsStroke() )
3631 {
3632 allGlyphsAreStroke = false;
3633 break;
3634 }
3635 }
3636
3637 for( const std::unique_ptr<KIFONT::GLYPH>& glyph : aGlyphs )
3638 {
3639 if( !glyph->IsOutline() )
3640 {
3641 allGlyphsAreOutline = false;
3642 break;
3643 }
3644 }
3645
3646 if( allGlyphsAreStroke )
3647 {
3648 // Optimized path for stroke fonts that pre-reserves line quads.
3649 int lineQuadCount = 0;
3650
3651 for( const std::unique_ptr<KIFONT::GLYPH>& glyph : aGlyphs )
3652 {
3653 const auto& strokeGlyph = static_cast<const KIFONT::STROKE_GLYPH&>( *glyph );
3654
3655 for( const std::vector<VECTOR2D>& points : strokeGlyph )
3656 lineQuadCount += points.size() - 1;
3657 }
3658
3659 reserveLineQuads( lineQuadCount );
3660
3661 for( const std::unique_ptr<KIFONT::GLYPH>& glyph : aGlyphs )
3662 {
3663 const auto& strokeGlyph = static_cast<const KIFONT::STROKE_GLYPH&>( *glyph );
3664
3665 for( const std::vector<VECTOR2D>& points : strokeGlyph )
3666 {
3668 [&]( int idx )
3669 {
3670 return points[idx];
3671 },
3672 points.size(), false );
3673 }
3674 }
3675
3676 return;
3677 }
3678 else if( allGlyphsAreOutline )
3679 {
3680 // Optimized path for outline fonts that pre-reserves glyph triangles.
3681 int triangleCount = 0;
3682
3683 for( const std::unique_ptr<KIFONT::GLYPH>& glyph : aGlyphs )
3684 {
3685 const auto& outlineGlyph = static_cast<const KIFONT::OUTLINE_GLYPH&>( *glyph );
3686
3687 for( unsigned int i = 0; i < outlineGlyph.TriangulatedPolyCount(); i++ )
3688 {
3690 outlineGlyph.TriangulatedPolygon( i );
3691
3692 triangleCount += polygon->GetTriangleCount();
3693 }
3694 }
3695
3696 m_currentManager->Shader( SHADER_NONE );
3697 m_currentManager->Color( m_fillColor );
3698
3699 m_currentManager->Reserve( 3 * triangleCount );
3700
3701 for( const std::unique_ptr<KIFONT::GLYPH>& glyph : aGlyphs )
3702 {
3703 const auto& outlineGlyph = static_cast<const KIFONT::OUTLINE_GLYPH&>( *glyph );
3704
3705 for( unsigned int i = 0; i < outlineGlyph.TriangulatedPolyCount(); i++ )
3706 {
3708 outlineGlyph.TriangulatedPolygon( i );
3709
3710 for( size_t j = 0; j < polygon->GetTriangleCount(); j++ )
3711 {
3712 VECTOR2I a, b, c;
3713 polygon->GetTriangle( j, a, b, c );
3714
3715 m_currentManager->Vertex( a.x, a.y, m_layerDepth );
3716 m_currentManager->Vertex( b.x, b.y, m_layerDepth );
3717 m_currentManager->Vertex( c.x, c.y, m_layerDepth );
3718 }
3719 }
3720 }
3721 }
3722 else
3723 {
3724 // Regular path
3725 for( size_t i = 0; i < aGlyphs.size(); i++ )
3726 DrawGlyph( *aGlyphs[i], i, aGlyphs.size() );
3727 }
3728}
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:985
BOX2< VECTOR2D > BOX2D
Definition box2.h:918
void SetOpenGLInfo(const char *aVendor, const char *aRenderer, const char *aVersion)
A setter for OpenGL info when it's initialized.
void SetOpenGLBackendInfo(wxString aBackend)
A setter for OpenGL backend info after the canvas is created.
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
Bezier curves to polygon converter.
void GetPoly(std::vector< VECTOR2I > &aOutput, int aMaxError=10)
Convert a Bezier curve to a polygon.
This class handle bitmap images in KiCad.
Definition bitmap_base.h:47
const wxImage * GetOriginalImageData() const
Definition bitmap_base.h:69
VECTOR2I GetSizePixels() const
EDA_ANGLE Rotation() const
bool IsMirroredX() const
bool IsMirroredY() const
KIID GetImageID() const
Definition bitmap_base.h:74
int GetPPI() const
constexpr BOX2< Vec > & Inflate(coord_type dx, coord_type dy)
Inflates the rectangle horizontally by dx and vertically by dy.
Definition box2.h:556
constexpr coord_type GetLeft() const
Definition box2.h:231
constexpr coord_type GetRight() const
Definition box2.h:220
constexpr coord_type GetTop() const
Definition box2.h:232
constexpr coord_type GetBottom() const
Definition box2.h:225
static const WX_CURSOR_TYPE GetCursor(KICURSOR aCursorType, bool aHiDPI=false)
Get a cursor bundle (wx 3.3+) or appropriate cursor (older versions)
Definition cursors.cpp:399
double AsDegrees() const
Definition eda_angle.h:115
double AsRadians() const
Definition eda_angle.h:119
void UnlockCtx(wxGLContext *aContext)
Allow other canvases to bind an OpenGL context.
void DestroyCtx(wxGLContext *aContext)
Destroy a managed OpenGL context.
bool LockCtx(wxGLContext *aContext, wxGLCanvas *aCanvas)
Set a context as current and prevents other canvases from switching it.
wxGLContext * CreateCtx(wxGLCanvas *aCanvas, const wxGLContext *aOther=nullptr)
Create a managed OpenGL context.
static int SetSwapInterval(wxGLCanvas *aCanvas, int aVal)
Attempt to set the OpenGL swap interval.
Definition gl_utils.cpp:78
static wxString DetectGLBackend(wxGLCanvas *aCanvas)
Definition gl_utils.cpp:50
HIDPI_GL_CANVAS(const KIGFX::VC_SETTINGS &aSettings, wxWindow *aParent, const wxGLAttributes &aGLAttribs, wxWindowID aId=wxID_ANY, const wxPoint &aPos=wxDefaultPosition, const wxSize &aSize=wxDefaultSize, long aStyle=0, const wxString &aName=wxGLCanvasName, const wxPalette &aPalette=wxNullPalette)
virtual wxSize GetNativePixelSize() const
double GetScaleFactor() const
Get the current scale factor.
virtual bool IsStroke() const
Definition glyph.h:40
virtual bool IsOutline() const
Definition glyph.h:39
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:101
double r
Red component.
Definition color4d.h:391
double g
Green component.
Definition color4d.h:392
COLOR4D Darkened(double aFactor) const
Return a color that is darker by a given factor, without modifying object.
Definition color4d.h:279
double a
Alpha component.
Definition color4d.h:394
static const COLOR4D BLACK
Definition color4d.h:404
double b
Blue component.
Definition color4d.h:393
void SetGridColor(const COLOR4D &aGridColor)
Set the grid color.
virtual void SetLayerDepth(double aLayerDepth)
Set the depth of the layer (position on the z-axis)
bool IsCursorEnabled() const
Return information about cursor visibility.
virtual void SetIsFill(bool aIsFillEnabled)
Enable/disable fill.
friend class GAL_CONTEXT_LOCKER
MATRIX3x3D m_worldScreenMatrix
World transformation.
VECTOR2D GetVisibleGridSize() const
Return the visible grid size in x and y directions.
double m_layerDepth
The actual layer depth.
COLOR4D gridSourceColor(const GRID_SOURCE &aSrc) const
The colour a grid source is drawn in, brightened while it is being edited.
MATRIX3x3D m_screenWorldMatrix
Screen transformation.
bool m_axesEnabled
Should the axes be drawn.
VECTOR2I m_screenSize
Screen size in screen (wx logical) coordinates.
GR_TEXT_H_ALIGN_T GetHorizontalJustify() const
void normalize(T &a, T &b)
Ensure that the first element is smaller than the second.
VECTOR2D m_depthRange
Range of the depth.
virtual void SetFillColor(const COLOR4D &aColor)
Set the fill color.
virtual bool SetNativeCursorStyle(KICURSOR aCursor, bool aHiDPI)
Set the cursor in the native panel.
GRID_STYLE m_gridStyle
Grid display style.
COLOR4D m_axesColor
Color of the axes.
const MATRIX3x3D & GetScreenWorldMatrix() const
Get the screen <-> world transformation matrix.
float m_lineWidth
The line width.
void computeWorldScale()
Compute the scaling factor for the world->screen matrix.
GRID_LATTICE gridLattice(const GRID_SOURCE &aSrc) const
Thin a grid source's pitch out until its lines are far enough apart on screen.
void drawGridCoverageShape(const GRID_SOURCE &aSrc)
Draw the area a grid source covers in its own frame with the current fill and stroke.
virtual void SetLineWidth(float aLineWidth)
Set the line width.
VECTOR2D m_gridSize
The grid size.
COLOR4D getCursorColor() const
Get the actual cursor color to draw.
COLOR4D m_fillColor
The fill color.
double m_worldUnitLength
The unit length of the world coordinates [inch].
virtual bool updatedGalDisplayOptions(const GAL_DISPLAY_OPTIONS &aOptions)
Handle updating display options.
void SetAxesColor(const COLOR4D &aAxesColor)
Set the axes color.
virtual void SetStrokeColor(const COLOR4D &aColor)
Set the stroke color.
BOX2D gridScreenBBox(const GRID_SOURCE &aSrc) const
VECTOR2D m_cursorPosition
Current cursor position (world coordinates)
virtual void SetIsStroke(bool aIsStrokeEnabled)
Enable/disable stroked outlines.
const VECTOR2I & GetGlyphSize() const
int m_gridTick
Every tick line gets the double width.
double m_worldScale
The scale factor world->screen.
VECTOR2D m_gridOrigin
The grid origin.
virtual void SetMinLineWidth(float aLineWidth)
Set the minimum line width in pixels.
KICURSOR m_currentNativeCursor
Current cursor.
bool m_globalFlipY
Flag for Y axis flipping.
float GetMinLineWidth() const
Get the minimum line width in pixels.
bool m_isFillEnabled
Is filling of graphic objects enabled ?
virtual void ComputeWorldScreenMatrix()
Compute the world <-> screen transformation matrix.
float gridMinorLineWidth(double aWorldPixelSize, double aScaleFactor) const
Compute the world width of a minor grid line.
COLOR4D m_gridColor
Color of the grid.
COLOR4D m_strokeColor
The color of the outlines.
bool m_isStrokeEnabled
Are the outlines stroked ?
std::vector< GRID_SOURCE > m_gridSources
Sources overlayed on the display grid.
GAL_DISPLAY_OPTIONS & m_options
bool m_gridVisibility
Should the grid be shown.
static constexpr int SEG_PER_CIRCLE_COUNT
The default number of segments approximating a full circle.
virtual void BitmapText(const wxString &aText, const VECTOR2I &aPosition, const EDA_ANGLE &aAngle)
Draw a text using a bitmap font.
bool m_globalFlipX
Flag for X axis flipping.
GR_TEXT_V_ALIGN_T GetVerticalJustify() const
KIGFX::CROSS_HAIR_MODE m_crossHairMode
Crosshair drawing mode.
VECTOR2D m_lookAtPoint
Point to be looked at in world space.
GAL(GAL_DISPLAY_OPTIONS &aOptions)
static double calcAngleStep(double aRadius)
Compute the angle step when drawing arcs/circles approximated with lines.
GLuint cacheBitmap(const BITMAP_BASE *aBitmap)
const size_t m_cacheMaxElements
GLuint RequestBitmap(const BITMAP_BASE *aBitmap)
void Abandon()
Drop the cached texture names without deleting them.
std::list< GLuint > m_freedTextureIds
std::map< const KIID, CACHED_BITMAP > m_bitmaps
std::list< KIID > m_cacheLru
Limit how often the OpenGL canvases are rebuilt after GPU resets.
static const unsigned int DIRECT_RENDERING
OpenGL implementation of the Graphics Abstraction Layer.
Definition opengl_gal.h:69
void Transform(const MATRIX3x3D &aTransformation) override
Transform the context.
void drawPolygon(GLdouble *aPoints, int aPointCount)
Draw a filled polygon.
void ChangeGroupDepth(int aGroupNumber, int aDepth) override
Change the depth (Z-axis position) of the group.
void skipMouseEvent(wxMouseEvent &aEvent)
Skip the mouse event to the parent.
void drawSegment(const VECTOR2D &aStartPoint, const VECTOR2D &aEndPoint, double aWidth, bool aReserve=true)
Internal method for segment drawing.
unsigned int m_groupCounter
Counter used for generating keys for groups.
Definition opengl_gal.h:379
void EndDiffLayer() override
Ends rendering of a differential layer.
VERTEX_MANAGER * m_overlayManager
Container for storing overlaid VERTEX_ITEMs.
Definition opengl_gal.h:384
void Scale(const VECTOR2D &aScale) override
Scale the context.
bool m_isInitialized
Basic initialization flag, has to be done when the window is visible.
Definition opengl_gal.h:404
VERTEX_MANAGER * m_currentManager
Currently used VERTEX_MANAGER (for storing VERTEX_ITEMs).
Definition opengl_gal.h:380
void drawCircle(const VECTOR2D &aCenterPoint, double aRadius, bool aReserve=true)
Internal method for circle drawing.
std::deque< std::shared_ptr< GLdouble > > m_tessIntersects
Definition opengl_gal.h:425
void DrawEllipseArc(const VECTOR2D &aCenterPoint, double aMajorRadius, double aMinorRadius, const EDA_ANGLE &aRotation, const EDA_ANGLE &aStartAngle, const EDA_ANGLE &aEndAngle) override
Draw an elliptical arc in world coordinates.
void DrawCircle(const VECTOR2D &aCenterPoint, double aRadius) override
Draw a circle using world coordinates.
bool IsInitialized() const override
Return the initialization status for the canvas.
Definition opengl_gal.h:102
void LockContext(int aClientCookie) override
Use GAL_CONTEXT_LOCKER RAII object unless you know what you're doing.
WX_CURSOR_TYPE m_currentwxCursor
wx cursor showing the current native cursor.
Definition opengl_gal.h:419
unsigned int m_mainBuffer
Main rendering target.
Definition opengl_gal.h:391
static std::set< OPENGL_GAL * > m_instances
Canvases to repaint after a reset.
Definition opengl_gal.h:363
std::unique_ptr< GL_BITMAP_CACHE > m_bitmapCache
Definition opengl_gal.h:421
std::pair< VECTOR2D, float > computeBitmapTextSize(const UTF8 &aText) const
Compute a size of text drawn using bitmap font with current text setting applied.
void SetTarget(RENDER_TARGET aTarget) override
Set the target for rendering.
void blitCursor()
Blit cursor into the current screen.
static wxString CheckFeatures(GAL_DISPLAY_OPTIONS &aOptions)
Check OpenGL features.
void ClearTarget(RENDER_TARGET aTarget) override
Clear the target for rendering.
void drawBitmapOverbar(double aLength, double aHeight, bool aReserve=true)
Draw an overbar over the currently drawn text.
void EndGroup() override
End the group.
bool m_isBitmapFontInitialized
Is the shader set to use bitmap fonts?
Definition opengl_gal.h:403
static GL_RESET_BUDGET m_resetBudget
Rate of resets tolerated before falling back.
Definition opengl_gal.h:361
void drawSegmentChain(const std::function< VECTOR2D(int)> &aPointGetter, int aPointCount, double aWidth, bool aReserve=true)
Generic way of drawing a chain of segments stored in different containers.
void DrawArcSegment(const VECTOR2D &aCenterPoint, double aRadius, const EDA_ANGLE &aStartAngle, const EDA_ANGLE &aAngle, double aWidth, double aMaxError) override
Draw an arc segment.
void BitmapText(const wxString &aText, const VECTOR2I &aPosition, const EDA_ANGLE &aAngle) override
Draw a text using a bitmap font.
bool updatedGalDisplayOptions(const GAL_DISPLAY_OPTIONS &aOptions) override
Update handler for OpenGL settings.
unsigned int m_overlayBuffer
Auxiliary rendering target (for menus etc.)
Definition opengl_gal.h:392
void PostPaint(wxPaintEvent &aEvent)
Post an event to m_paintListener.
OPENGL_COMPOSITOR * m_compositor
Handles multiple rendering targets.
Definition opengl_gal.h:390
VERTEX_MANAGER * m_cachedManager
Container for storing cached VERTEX_ITEMs.
Definition opengl_gal.h:382
void Translate(const VECTOR2D &aTranslation) override
Translate the context.
static bool m_glLoaded
GL entry points are loaded, so resets can be queried.
Definition opengl_gal.h:362
void DrawPolyline(const std::deque< VECTOR2D > &aPointList) override
Draw a polyline.
bool SetNativeCursorStyle(KICURSOR aCursor, bool aHiDPI) override
Set the cursor in the native panel.
void DrawCurve(const VECTOR2D &startPoint, const VECTOR2D &controlPointA, const VECTOR2D &controlPointB, const VECTOR2D &endPoint, double aFilterValue=0.0) override
Draw a cubic bezier spline.
void drawFilledSemiCircle(const VECTOR2D &aCenterPoint, double aRadius, double aAngle)
Draw a filled semicircle.
void onPaint(wxPaintEvent &aEvent)
This is the OnPaint event handler.
void DrawGroup(int aGroupNumber) override
Draw the stored group.
GLint ufm_minLinePixelWidth
Definition opengl_gal.h:414
void Restore() override
Restore the context.
int m_ownContextGroupId
Group this canvas' contexts were created in.
Definition opengl_gal.h:369
bool IsResetSettled() override
Check whether the driver has finished the reset that destroyed this canvas' context.
void DrawGrid() override
Draw the grid.
void DrawSegmentChain(const std::vector< VECTOR2D > &aPointList, double aWidth) override
Draw a chain of rounded segments.
static GL_RESET_BUDGET::CLOCK::time_point m_resetDetectedAt
When the last reset was detected, to stop waiting on a driver that never reports completion.
Definition opengl_gal.h:367
void drawStrokedSemiCircle(const VECTOR2D &aCenterPoint, double aRadius, double aAngle, bool aReserve=true)
Draw a stroked semicircle.
unsigned int getNewGroupNumber()
Return a valid key that can be used as a new group number.
void Flush() override
Force all remaining objects to be drawn.
GLint ufm_antialiasingOffset
Definition opengl_gal.h:413
void DeleteGroup(int aGroupNumber) override
Delete the group from the memory.
bool IsVisible() const override
Return true if the GAL canvas is visible on the screen.
Definition opengl_gal.h:108
wxEvtHandler * m_mouseListener
Definition opengl_gal.h:370
int m_swapInterval
Used to store swap interval information.
Definition opengl_gal.h:357
void ClearCache() override
Delete all data created during caching of graphic items.
double getWorldPixelSize() const
void DrawSegment(const VECTOR2D &aStartPoint, const VECTOR2D &aEndPoint, double aWidth) override
Draw a rounded segment.
GROUPS_MAP m_groups
Stores information about VBO objects (groups)
Definition opengl_gal.h:378
void endUpdate() override
Disable item update mode.
void ClearScreen() override
Clear the screen.
void ResizeScreen(int aWidth, int aHeight) override
Resizes the canvas.
GLint ufm_fontTextureWidth
Definition opengl_gal.h:416
void DrawPolygon(const std::deque< VECTOR2D > &aPointList) override
Draw a polygon.
void drawTriangulatedPolyset(const SHAPE_POLY_SET &aPoly, bool aStrokeTriangulation)
Draw a set of polygons with a cached triangulation.
void DrawCursor(const VECTOR2D &aCursorPosition) override
Draw the cursor.
void DrawRectangle(const VECTOR2D &aStartPoint, const VECTOR2D &aEndPoint) override
Draw a rectangle.
VERTEX_MANAGER * m_nonCachedManager
Container for storing non-cached VERTEX_ITEMs.
Definition opengl_gal.h:383
int drawBitmapChar(unsigned long aChar, bool aReserve=true)
Draw a single character using bitmap font.
GLUtesselator * m_tesselator
Definition opengl_gal.h:424
wxEvtHandler * m_paintListener
Definition opengl_gal.h:371
void StartDiffLayer() override
Begins rendering of a differential layer.
static bool m_resetSettled
Driver finished the last reset.
Definition opengl_gal.h:364
bool m_isContextLocked
Used for assertion checking.
Definition opengl_gal.h:407
void Save() override
Save the context.
void DrawHoleWall(const VECTOR2D &aCenterPoint, double aHoleRadius, double aWallWidth) override
Draw a hole wall ring.
bool m_isFramebufferInitialized
Are the framebuffers initialized?
Definition opengl_gal.h:401
void ComputeWorldScreenMatrix() override
Compute the world <-> screen transformation matrix.
void orphanContextGroup()
Abandon the shared context group so the next canvas created starts a fresh one.
bool Show(bool aShow) override
Shows/hides the GAL canvas.
void SetMinLineWidth(float aLineWidth) override
Set the minimum line width in pixels.
static GLuint g_fontTexture
Bitmap font texture handle (shared)
Definition opengl_gal.h:373
virtual bool HasTarget(RENDER_TARGET aTarget) override
Return true if the target exists.
GAL_CONTEXT_LOSS GetContextLoss() const override
Check whether a GPU reset destroyed this canvas' rendering context.
bool GetScreenshot(wxImage &aDstImage)
void reserveLineQuads(const int aLineCount)
Reserve specified number of line quads.
void DrawLine(const VECTOR2D &aStartPoint, const VECTOR2D &aEndPoint) override
Draw a line.
OPENGL_GAL(const KIGFX::VC_SETTINGS &aVcSettings, GAL_DISPLAY_OPTIONS &aDisplayOptions, wxWindow *aParent, wxEvtHandler *aMouseListener=nullptr, wxEvtHandler *aPaintListener=nullptr, const wxString &aName=wxT("GLCanvas"))
void beginUpdate() override
Enable item update mode.
void DrawEllipse(const VECTOR2D &aCenterPoint, double aMajorRadius, double aMinorRadius, const EDA_ANGLE &aRotation) override
Draw a closed ellipse.
virtual void DrawGlyph(const KIFONT::GLYPH &aGlyph, int aNth, int aTotal) override
Draw a polygon representing a font glyph.
bool m_isGrouping
Was a group started?
Definition opengl_gal.h:406
void BeginDrawing() override
Start/end drawing functions, draw calls can be only made in between the calls to BeginDrawing()/EndDr...
GLint ufm_screenPixelSize
Definition opengl_gal.h:411
void Rotate(double aAngle) override
Rotate the context.
int BeginGroup() override
Begin a group.
GLint ufm_pixelSizeMultiplier
Definition opengl_gal.h:412
VECTOR2D getScreenPixelSize() const
void drawGridSources()
Render m_gridSources priority-descending; each writes its coverage into the stencil so lower-priority...
static int m_contextGroupId
Changes each time a reset kills the shared group.
Definition opengl_gal.h:359
void DrawBitmap(const BITMAP_BASE &aBitmap, double alphaBlend=1.0) override
Draw a bitmap image.
void drawPolyline(const std::function< VECTOR2D(int)> &aPointGetter, int aPointCount, bool aReserve=true)
Generic way of drawing a polyline stored in different containers.
RENDER_TARGET GetTarget() const override
Get the currently used target for rendering.
void skipGestureEvent(wxGestureEvent &aEvent)
Skip the gesture event to the parent.
void UnlockContext(int aClientCookie) override
void drawSemiCircle(const VECTOR2D &aCenterPoint, double aRadius, double aAngle)
Draw a semicircle.
void drawLineQuad(const VECTOR2D &aStartPoint, const VECTOR2D &aEndPoint, bool aReserve=true)
Draw a quad for the line.
VERTEX_MANAGER * m_tempManager
Container for storing temp (diff mode) VERTEX_ITEMs.
Definition opengl_gal.h:387
virtual void DrawGlyphs(const std::vector< std::unique_ptr< KIFONT::GLYPH > > &aGlyphs) override
Draw polygons representing font glyphs.
void onSetNativeCursor(wxSetCursorEvent &aEvent)
Give the correct cursor image when the native widget asks for it.
void EnableDepthTest(bool aEnabled=false) override
void EndDrawing() override
End the drawing, needs to be called for every new frame.
SHADER * m_shader
There is only one shader used for different objects.
Definition opengl_gal.h:398
void DrawArc(const VECTOR2D &aCenterPoint, double aRadius, const EDA_ANGLE &aStartAngle, const EDA_ANGLE &aAngle) override
Draw an arc.
bool m_isContextValid
Did the last lock make us current?
Definition opengl_gal.h:408
void DrawPolylines(const std::vector< std::vector< VECTOR2D > > &aPointLists) override
Draw multiple polylines.
RENDER_TARGET m_currentTarget
Current rendering target.
Definition opengl_gal.h:394
wxGLContext * m_glPrivContext
Canvas-specific OpenGL context.
Definition opengl_gal.h:356
void ChangeGroupColor(int aGroupNumber, const COLOR4D &aNewColor) override
Change the color used to draw the group.
static bool m_isBitmapFontLoaded
Is the bitmap font texture loaded?
Definition opengl_gal.h:402
static bool m_resetBudgetExhausted
Resets came too often to keep using OpenGL.
Definition opengl_gal.h:360
static wxGLContext * m_glMainContext
Parent OpenGL context.
Definition opengl_gal.h:355
void setupShaderParameters()
Set up the shader parameters for OpenGL rendering.
unsigned int m_tempBuffer
Temporary rendering target (for diffing etc.)
Definition opengl_gal.h:393
void init()
Basic OpenGL initialization and feature checks.
static int m_instanceCounter
GL GAL instance counter.
Definition opengl_gal.h:358
Class to control vertex container and GPU with possibility of emulating old-style OpenGL 1....
bool Vertex(const VERTEX &aVertex)
Add a vertex with the given coordinates to the currently set item.
Definition kiid.h:46
VECTOR2< T > GetScale() const
Get the scale components of the matrix.
Definition matrix3x3.h:291
T m_data[3][3]
Definition matrix3x3.h:61
GL_CONTEXT_MANAGER * GetGLContextManager()
Definition pgm_base.h:114
A small class to help profiling.
Definition profile.h:46
void Stop()
Save the time when this function was called, and set the counter stane to stop.
Definition profile.h:86
void Start()
Start or restart the counter.
Definition profile.h:74
std::string to_string()
Definition profile.h:154
double msecs(bool aSinceLast=false)
Definition profile.h:148
Represent a polyline containing arcs as well as line segments: A chain of connected line and/or arc s...
bool IsClosed() const override
int PointCount() const
Return the number of points (vertices) in this line chain.
const VECTOR2I & CPoint(int aIndex) const
Return a reference to a given point in the line chain.
int SegmentCount() const
Return the number of segments in this line chain.
Represent a set of closed polygons.
bool IsTriangulationUpToDate() const
POLYGON & Polygon(int aIndex)
Return the aIndex-th subpolygon in the set.
const TRIANGULATED_POLYGON * TriangulatedPolygon(int aIndex) const
unsigned int TriangulatedPolyCount() const
Return the number of triangulated polygons.
int OutlineCount() const
Return the number of outlines in the set.
const SHAPE_LINE_CHAIN & COutline(int aIndex) const
uni_iter is a non-mutating iterator that walks through unicode code points in the UTF8 encoded string...
Definition utf8.h:226
An 8 bit string that is assuredly encoded in UTF8, and supplies special conversion support to and fro...
Definition utf8.h:67
T EuclideanNorm() const
Compute the Euclidean norm of the vector, which is defined as sqrt(x ** 2 + y ** 2).
Definition vector2d.h:281
@ BLUE
Definition color4d.h:52
KICURSOR
Definition cursors.h:41
@ RADIANS_T
Definition eda_angle.h:31
static constexpr EDA_ANGLE FULL_CIRCLE
Definition eda_angle.h:470
a few functions useful in geometry calculations.
int GetArcToSegmentCount(int aRadius, int aErrorMax, const EDA_ANGLE &aArcAngle)
const wxChar *const traceGalContext
Flag to enable debug output of GAL context binding.
const wxChar *const traceGalProfile
Flag to enable debug output of GAL performance profiling.
KIID niluuid(0)
This file contains miscellaneous commonly used macros and functions.
MATRIX3x3< double > MATRIX3x3D
Definition matrix3x3.h:469
#define H(x, y, z)
Definition md5_hash.cpp:17
std::pair< VECTOR2D, float > ComputeBitmapTextSize(const UTF8 &aText)
Size of a line of text in atlas units, and how far its glyphs sit above their lowest point.
double SpaceAdvance()
How far a space moves the pen.
const FONT_GLYPH_TYPE * LookupGlyph(unsigned int aCodepoint)
GAL_API FONT_IMAGE_TYPE font_image
GLYPH_BOX ComputeGlyphBox(const FONT_GLYPH_TYPE &aGlyph)
The Cairo implementation of the graphics abstraction layer.
Definition eda_group.h:30
std::vector< uint8_t > ImageToRgba(const wxImage &aImage)
The pixels of aImage as tightly packed RGBA, transparent where it has alpha or a mask.
constexpr double GRID_DIM_ALPHA
Opacity of the background wash laid over a selected grid item's area, to fade the grids showing throu...
GAL_CONTEXT_LOSS
State of a canvas' rendering context after a GPU reset.
@ REPEATED
Contexts keep being lost; stop using this backend.
@ RECOVERABLE
Context was lost; rebuild the canvas.
@ DOTS
Use dots for the grid.
@ LINES
Use lines for the grid.
@ SHADER_NONE
@ SHADER_LINE_C
@ SHADER_LINE_B
@ SHADER_FONT
@ SHADER_LINE_F
@ SHADER_LINE_E
@ SHADER_STROKED_CIRCLE
@ SHADER_HOLE_WALL
@ SHADER_LINE_A
@ SHADER_LINE_D
@ SHADER_FILLED_CIRCLE
@ SHADER_TYPE_VERTEX
Vertex shader.
Definition shader.h:42
@ SHADER_TYPE_FRAGMENT
Fragment shader.
Definition shader.h:43
RENDER_TARGET
RENDER_TARGET: Possible rendering targets.
Definition definitions.h:32
@ TARGET_NONCACHED
Auxiliary rendering target (noncached)
Definition definitions.h:34
@ TARGET_TEMP
Temporary target for drawing in separate layer.
Definition definitions.h:36
@ TARGET_CACHED
Main rendering target (cached)
Definition definitions.h:33
@ TARGET_OVERLAY
Items that may change while the view stays the same (noncached)
Definition definitions.h:35
constexpr size_t BITMAP_CACHE_MAX_BYTES
Texture memory the GPU canvases may hold for placed bitmaps before they evict the oldest.
wxImage FitImageToTexture(const wxImage &aImage, int aMaxTextureSize)
Fit an image into the largest texture a GPU can hold.
constexpr double GRID_EDGE_DARKEN
How far the hairline round a grid's coverage sits below its own colour.
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition eda_angle.h:461
static const wxChar *const traceGalXorMode
static void InitTesselatorCallbacks(GLUtesselator *aTesselator)
void CALLBACK CombineCallback(GLdouble coords[3], GLdouble *vertex_data[4], GLfloat weight[4], GLdouble **dataOut, void *aData)
static GLenum queryResetStatus()
void CALLBACK VertexCallback(GLvoid *aVertexPtr, void *aData)
void CALLBACK EdgeCallback(GLboolean aEdgeFlag)
static wxGLAttributes getGLAttribs()
void CALLBACK ErrorCallback(GLenum aErrorCode)
double round_to_half_pixel(double f, double r)
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
const int scale
std::vector< FAB_LAYER_COLOR > dummy
unsigned priority
Higher wins where grids overlap.
double orientation
Rotation about origin, radians CCW.
VECTOR2D extent
Cartesian: (dx, dy) = size/2 from origin.
VECTOR2D pitch
Cartesian: (dx, dy); polar: (dr, dPhi rad).
VECTOR2D origin
Where a glyph's quad sits and what it samples, in font units, which are also atlas texels.
float h
size of the quad and of its cell in the atlas
float atlasY
corner of the cell in the atlas, inside its smoothing border
float y
corner of the quad from the pen position
The spacing of a grid source's lattice as it is drawn at the current zoom.
VECTOR2D extent
as GRID_SOURCE::extent, with an unbounded polar grid reaching past the screen
VECTOR2D pitch
along x and y, or of radius and angle for a polar grid
Render-time projection of a grid: GRID_GEOMETRY (kind/origin/pitch/orientation/extent) plus rendering...
unsigned tick
Major-tick interval (0 = inherit default).
bool axesEnabled
Skip grid lines coincident with the world axes (only meaningful for unbounded cartesian).
bool highlighted
Render with edit-mode emphasis (selected grid).
bool unbounded
No extent; visible range derived from screen corners.
Parameters passed to the GLU tesselator.
Definition opengl_gal.h:343
VERTEX_MANAGER * vboManager
Manager used for storing new vertices.
Definition opengl_gal.h:345
std::deque< std::shared_ptr< GLdouble > > & intersectPoints
Intersect points, that have to be freed after tessellation.
Definition opengl_gal.h:348
Structure to keep VIEW_CONTROLS settings for easy store/restore operations.
VECTOR3I v1(5, 5, 5)
VECTOR2I end
VECTOR2I v2(1, 0)
VECTOR2I v3(-2, 1)
@ GR_TEXT_H_ALIGN_CENTER
@ GR_TEXT_H_ALIGN_RIGHT
@ GR_TEXT_H_ALIGN_LEFT
@ GR_TEXT_H_ALIGN_INDETERMINATE
@ GR_TEXT_V_ALIGN_BOTTOM
@ GR_TEXT_V_ALIGN_INDETERMINATE
@ GR_TEXT_V_ALIGN_CENTER
@ GR_TEXT_V_ALIGN_TOP
#define M_PI
wxLogTrace helper definitions.
void enableGlDebug(bool aEnable)
Enable or disable OpenGL driver messages output.
Definition utils.cpp:188
int checkGlError(const std::string &aInfo, const char *aFile, int aLine, bool aThrow)
Check if a recent OpenGL operation has failed.
Definition utils.cpp:45
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
VECTOR2< double > VECTOR2D
Definition vector2d.h:707
VECTOR2I ToVECTOR2I(const wxSize &aSize)
Definition vector2wx.h:26
static PIECE polygon(std::vector< VIA_CROSS_SECTION_GEOMETRY::POINT > aPoints, bool aMixed=false)
#define CALLBACK
unsigned int GLenum
Definition vrml_layer.h:43