LibreOffice Module vcl (master)  1
OpenGLHelper.cxx
Go to the documentation of this file.
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3  * This file is part of the LibreOffice project.
4  *
5  * This Source Code Form is subject to the terms of the Mozilla Public
6  * License, v. 2.0. If a copy of the MPL was not distributed with this
7  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8  */
9 
10 #include <vcl/opengl/GLMHelper.hxx>
12 
13 #include <osl/file.hxx>
14 #include <rtl/bootstrap.hxx>
15 #include <rtl/digest.h>
16 #include <rtl/strbuf.hxx>
17 #include <rtl/ustring.hxx>
18 #include <sal/log.hxx>
19 #include <tools/stream.hxx>
20 #include <config_folders.h>
21 #include <memory>
22 #include <vcl/pngwrite.hxx>
23 #include <vcl/svapp.hxx>
24 #include <officecfg/Office/Common.hxx>
25 #include <com/sun/star/util/XFlushable.hpp>
26 #include <com/sun/star/configuration/theDefaultProvider.hpp>
27 
28 #include <stdarg.h>
29 #include <vector>
30 #include <unordered_map>
31 
32 #include <opengl/zone.hxx>
33 #include <opengl/watchdog.hxx>
34 #include <osl/conditn.hxx>
37 #include <desktop/crashreport.hxx>
38 #include <bitmapwriteaccess.hxx>
39 
40 #if defined UNX && !defined MACOSX && !defined IOS && !defined ANDROID && !defined HAIKU
42 #elif defined (_WIN32)
44 #endif
45 
46 static bool volatile gbInShaderCompile = false;
49 
50 namespace {
51 
52 using namespace rtl;
53 
54 OUString getShaderFolder()
55 {
56  OUString aUrl("$BRAND_BASE_DIR/" LIBO_ETC_FOLDER);
57  rtl::Bootstrap::expandMacros(aUrl);
58 
59  return aUrl + "/opengl/";
60 }
61 
62 OString loadShader(const OUString& rFilename)
63 {
64  OUString aFileURL = getShaderFolder() + rFilename +".glsl";
65  osl::File aFile(aFileURL);
66  if(aFile.open(osl_File_OpenFlag_Read) == osl::FileBase::E_None)
67  {
68  sal_uInt64 nSize = 0;
69  aFile.getSize(nSize);
70  std::unique_ptr<char[]> content(new char[nSize+1]);
71  sal_uInt64 nBytesRead = 0;
72  aFile.read(content.get(), nSize, nBytesRead);
73  assert(nSize == nBytesRead);
74  content.get()[nBytesRead] = 0;
75  SAL_INFO("vcl.opengl", "Read " << nBytesRead << " bytes from " << aFileURL);
76  return content.get();
77  }
78  else
79  {
80  SAL_WARN("vcl.opengl", "Could not open " << aFileURL);
81  }
82 
83  return OString();
84 }
85 
86 OString& getShaderSource(const OUString& rFilename)
87 {
88  static std::unordered_map<OUString, OString> aMap;
89 
90  if (aMap.find(rFilename) == aMap.end())
91  {
92  aMap[rFilename] = loadShader(rFilename);
93  }
94 
95  return aMap[rFilename];
96 }
97 
98 }
99 
100 namespace {
101  int LogCompilerError(GLuint nId, const OUString &rDetail,
102  const OUString &rName, bool bShaderNotProgram)
103  {
104  OpenGLZone aZone;
105 
106  int InfoLogLength = 0;
107 
108  CHECK_GL_ERROR();
109 
110  if (bShaderNotProgram)
111  glGetShaderiv (nId, GL_INFO_LOG_LENGTH, &InfoLogLength);
112  else
113  glGetProgramiv(nId, GL_INFO_LOG_LENGTH, &InfoLogLength);
114 
115  CHECK_GL_ERROR();
116 
117  if ( InfoLogLength > 0 )
118  {
119  std::vector<char> ErrorMessage(InfoLogLength+1);
120  if (bShaderNotProgram)
121  glGetShaderInfoLog (nId, InfoLogLength, nullptr, ErrorMessage.data());
122  else
123  glGetProgramInfoLog(nId, InfoLogLength, nullptr, ErrorMessage.data());
124  CHECK_GL_ERROR();
125 
126  ErrorMessage.push_back('\0');
127  SAL_WARN("vcl.opengl", rDetail << " shader " << nId << " compile for " << rName << " failed : " << ErrorMessage.data());
128  }
129  else
130  SAL_WARN("vcl.opengl", rDetail << " shader: " << rName << " compile " << nId << " failed without error log");
131 
132 #ifdef DBG_UTIL
133  abort();
134 #endif
135  return 0;
136  }
137 }
138 
139 static void addPreamble(OString& rShaderSource, const OString& rPreamble)
140 {
141  if (rPreamble.isEmpty())
142  return;
143 
144  int nVersionStrStartPos = rShaderSource.indexOf("#version");
145 
146  if (nVersionStrStartPos == -1)
147  {
148  rShaderSource = rPreamble + "\n" + rShaderSource;
149  }
150  else
151  {
152  int nVersionStrEndPos = rShaderSource.indexOf('\n', nVersionStrStartPos);
153 
154  SAL_WARN_IF(nVersionStrEndPos == -1, "vcl.opengl", "syntax error in shader");
155 
156  if (nVersionStrEndPos == -1)
157  nVersionStrEndPos = nVersionStrStartPos + 8;
158 
159  OString aVersionLine = rShaderSource.copy(0, nVersionStrEndPos);
160  OString aShaderBody = rShaderSource.copy(nVersionStrEndPos + 1);
161 
162  rShaderSource = aVersionLine + "\n" + rPreamble + "\n" + aShaderBody;
163  }
164 }
165 
166 namespace
167 {
168  static const sal_uInt32 GLenumSize = sizeof(GLenum);
169 
170  OString getHexString(const sal_uInt8* pData, sal_uInt32 nLength)
171  {
172  static const char* const pHexData = "0123456789ABCDEF";
173 
174  bool bIsZero = true;
175  OStringBuffer aHexStr;
176  for(size_t i = 0; i < nLength; ++i)
177  {
178  sal_uInt8 val = pData[i];
179  if( val != 0 )
180  bIsZero = false;
181  aHexStr.append( pHexData[ val & 0xf ] );
182  aHexStr.append( pHexData[ val >> 4 ] );
183  }
184  if( bIsZero )
185  return OString();
186  else
187  return aHexStr.makeStringAndClear();
188  }
189 
190  OString generateMD5(const void* pData, size_t length)
191  {
192  sal_uInt8 pBuffer[RTL_DIGEST_LENGTH_MD5];
193  rtlDigestError aError = rtl_digest_MD5(pData, length,
194  pBuffer, RTL_DIGEST_LENGTH_MD5);
195  SAL_WARN_IF(aError != rtl_Digest_E_None, "vcl.opengl", "md5 generation failed");
196 
197  return getHexString(pBuffer, RTL_DIGEST_LENGTH_MD5);
198  }
199 
200  OString getDeviceInfoString()
201  {
202 #if defined( SAL_UNX ) && !defined( MACOSX ) && !defined( IOS )&& !defined( ANDROID ) && !defined( HAIKU )
203  const X11OpenGLDeviceInfo aInfo;
204  return aInfo.GetOS() +
205  aInfo.GetOSRelease() +
206  aInfo.GetRenderer() +
207  aInfo.GetVendor() +
208  aInfo.GetVersion();
209 #elif defined( _WIN32 )
210  const WinOpenGLDeviceInfo aInfo;
211  return OUStringToOString(aInfo.GetAdapterVendorID(), RTL_TEXTENCODING_UTF8) +
212  OUStringToOString(aInfo.GetAdapterDeviceID(), RTL_TEXTENCODING_UTF8) +
213  OUStringToOString(aInfo.GetDriverVersion(), RTL_TEXTENCODING_UTF8) +
214  OString::number(aInfo.GetWindowsVersion());
215 #else
216  return OString(reinterpret_cast<const char*>(glGetString(GL_VENDOR))) +
217  OString(reinterpret_cast<const char*>(glGetString(GL_RENDERER))) +
218  OString(reinterpret_cast<const char*>(glGetString(GL_VERSION)));
219 #endif
220  }
221 
222  OString getStringDigest( const OUString& rVertexShaderName,
223  const OUString& rFragmentShaderName,
224  const OString& rPreamble )
225  {
226  // read shaders source
227  OString aVertexShaderSource = getShaderSource( rVertexShaderName );
228  OString aFragmentShaderSource = getShaderSource( rFragmentShaderName );
229 
230  // get info about the graphic device
231  static const OString aDeviceInfo (getDeviceInfoString());
232 
233  OString aMessage;
234  aMessage += rPreamble;
235  aMessage += aVertexShaderSource;
236  aMessage += aFragmentShaderSource;
237  aMessage += aDeviceInfo;
238 
239  return generateMD5(aMessage.getStr(), aMessage.getLength());
240  }
241 
242  OString getCacheFolder()
243  {
244  OUString url("${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE("bootstrap") ":UserInstallation}/cache/");
245  rtl::Bootstrap::expandMacros(url);
246 
247  osl::Directory::create(url);
248 
249  return OUStringToOString(url, RTL_TEXTENCODING_UTF8);
250  }
251 
252 
253  bool writeProgramBinary( const OString& rBinaryFileName,
254  const std::vector<sal_uInt8>& rBinary )
255  {
256  osl::File aFile(OStringToOUString(rBinaryFileName, RTL_TEXTENCODING_UTF8));
257  osl::FileBase::RC eStatus = aFile.open(
258  osl_File_OpenFlag_Write | osl_File_OpenFlag_Create );
259 
260  if( eStatus != osl::FileBase::E_None )
261  {
262  // when file already exists we do not have to save it:
263  // we can be sure that the binary to save is exactly equal
264  // to the already saved binary, since they have the same hash value
265  if( eStatus == osl::FileBase::E_EXIST )
266  {
267  SAL_INFO( "vcl.opengl",
268  "No binary program saved. A file with the same hash already exists: '" << rBinaryFileName << "'" );
269  return true;
270  }
271  return false;
272  }
273 
274  sal_uInt64 nBytesWritten = 0;
275  aFile.write( rBinary.data(), rBinary.size(), nBytesWritten );
276 
277  assert( rBinary.size() == nBytesWritten );
278 
279  return true;
280  }
281 
282  bool readProgramBinary( const OString& rBinaryFileName,
283  std::vector<sal_uInt8>& rBinary )
284  {
285  osl::File aFile( OStringToOUString( rBinaryFileName, RTL_TEXTENCODING_UTF8 ) );
286  if(aFile.open( osl_File_OpenFlag_Read ) == osl::FileBase::E_None)
287  {
288  sal_uInt64 nSize = 0;
289  aFile.getSize( nSize );
290  rBinary.resize( nSize );
291  sal_uInt64 nBytesRead = 0;
292  aFile.read( rBinary.data(), nSize, nBytesRead );
293  assert( nSize == nBytesRead );
294  VCL_GL_INFO("Loading file: '" << rBinaryFileName << "': success" );
295  return true;
296  }
297  else
298  {
299  VCL_GL_INFO("Loading file: '" << rBinaryFileName << "': FAIL");
300  }
301 
302  return false;
303  }
304 
305  OString createFileName( const OUString& rVertexShaderName,
306  const OUString& rFragmentShaderName,
307  const OUString& rGeometryShaderName,
308  const OString& rDigest )
309  {
310  OString aFileName;
311  aFileName += getCacheFolder();
312  aFileName += OUStringToOString( rVertexShaderName, RTL_TEXTENCODING_UTF8 ) + "-";
313  aFileName += OUStringToOString( rFragmentShaderName, RTL_TEXTENCODING_UTF8 ) + "-";
314  if (!rGeometryShaderName.isEmpty())
315  aFileName += OUStringToOString( rGeometryShaderName, RTL_TEXTENCODING_UTF8 ) + "-";
316  aFileName += rDigest + ".bin";
317  return aFileName;
318  }
319 
320  GLint loadProgramBinary( GLuint nProgramID, const OString& rBinaryFileName )
321  {
322  GLint nResult = GL_FALSE;
323  GLenum nBinaryFormat;
324  std::vector<sal_uInt8> aBinary;
325  if( readProgramBinary( rBinaryFileName, aBinary ) && aBinary.size() > GLenumSize )
326  {
327  GLint nBinaryLength = aBinary.size() - GLenumSize;
328 
329  // Extract binary format
330  sal_uInt8* pBF = reinterpret_cast<sal_uInt8*>(&nBinaryFormat);
331  for( size_t i = 0; i < GLenumSize; ++i )
332  {
333  pBF[i] = aBinary[nBinaryLength + i];
334  }
335 
336  // Load the program
337  glProgramBinary( nProgramID, nBinaryFormat, aBinary.data(), nBinaryLength );
338 
339  // Check the program
340  glGetProgramiv(nProgramID, GL_LINK_STATUS, &nResult);
341  }
342  return nResult;
343  }
344 
345  void saveProgramBinary( GLint nProgramID, const OString& rBinaryFileName )
346  {
347  GLint nBinaryLength = 0;
348  GLenum nBinaryFormat = GL_NONE;
349 
350  glGetProgramiv( nProgramID, GL_PROGRAM_BINARY_LENGTH, &nBinaryLength );
351  if( nBinaryLength <= 0 )
352  {
353  SAL_WARN( "vcl.opengl", "Binary size is zero" );
354  return;
355  }
356 
357  std::vector<sal_uInt8> aBinary( nBinaryLength + GLenumSize );
358 
359  glGetProgramBinary( nProgramID, nBinaryLength, nullptr, &nBinaryFormat, aBinary.data() );
360 
361  const sal_uInt8* pBF = reinterpret_cast<const sal_uInt8*>(&nBinaryFormat);
362  aBinary.insert( aBinary.end(), pBF, pBF + GLenumSize );
363 
364  SAL_INFO("vcl.opengl", "Program id: " << nProgramID );
365  SAL_INFO("vcl.opengl", "Binary length: " << nBinaryLength );
366  SAL_INFO("vcl.opengl", "Binary format: " << nBinaryFormat );
367 
368  if( !writeProgramBinary( rBinaryFileName, aBinary ) )
369  SAL_WARN("vcl.opengl", "Writing binary file '" << rBinaryFileName << "': FAIL");
370  else
371  SAL_INFO("vcl.opengl", "Writing binary file '" << rBinaryFileName << "': success");
372  }
373 }
374 
375 OString OpenGLHelper::GetDigest( const OUString& rVertexShaderName,
376  const OUString& rFragmentShaderName,
377  const OString& rPreamble )
378 {
379  return getStringDigest(rVertexShaderName, rFragmentShaderName, rPreamble);
380 }
381 
382 GLint OpenGLHelper::LoadShaders(const OUString& rVertexShaderName,
383  const OUString& rFragmentShaderName,
384  const OUString& rGeometryShaderName,
385  const OString& preamble,
386  const OString& rDigest)
387 {
388  OpenGLZone aZone;
389 
390  gbInShaderCompile = true;
391 
392  bool bHasGeometryShader = !rGeometryShaderName.isEmpty();
393 
394  // create the program object
395  GLint ProgramID = glCreateProgram();
396 
397  // read shaders from file
398  OString aVertexShaderSource = getShaderSource(rVertexShaderName);
399  OString aFragmentShaderSource = getShaderSource(rFragmentShaderName);
400  OString aGeometryShaderSource;
401  if (bHasGeometryShader)
402  aGeometryShaderSource = getShaderSource(rGeometryShaderName);
403 
404  GLint bBinaryResult = GL_FALSE;
405  if (epoxy_has_gl_extension("GL_ARB_get_program_binary") && !rDigest.isEmpty())
406  {
407  OString aFileName =
408  createFileName(rVertexShaderName, rFragmentShaderName, rGeometryShaderName, rDigest);
409  bBinaryResult = loadProgramBinary(ProgramID, aFileName);
410  CHECK_GL_ERROR();
411  }
412 
413  if( bBinaryResult != GL_FALSE )
414  return ProgramID;
415 
416  if (bHasGeometryShader)
417  VCL_GL_INFO("Load shader: vertex " << rVertexShaderName << " fragment " << rFragmentShaderName << " geometry " << rGeometryShaderName);
418  else
419  VCL_GL_INFO("Load shader: vertex " << rVertexShaderName << " fragment " << rFragmentShaderName);
420  // Create the shaders
421  GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
422  GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
423  GLuint GeometryShaderID = 0;
424  if (bHasGeometryShader)
425  GeometryShaderID = glCreateShader(GL_GEOMETRY_SHADER);
426 
427  GLint Result = GL_FALSE;
428 
429  // Compile Vertex Shader
430  if( !preamble.isEmpty())
431  addPreamble( aVertexShaderSource, preamble );
432  char const * VertexSourcePointer = aVertexShaderSource.getStr();
433  glShaderSource(VertexShaderID, 1, &VertexSourcePointer , nullptr);
434  glCompileShader(VertexShaderID);
435 
436  // Check Vertex Shader
437  glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
438  if (!Result)
439  return LogCompilerError(VertexShaderID, "vertex",
440  rVertexShaderName, true);
441 
442  // Compile Fragment Shader
443  if( !preamble.isEmpty())
444  addPreamble( aFragmentShaderSource, preamble );
445  char const * FragmentSourcePointer = aFragmentShaderSource.getStr();
446  glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , nullptr);
447  glCompileShader(FragmentShaderID);
448 
449  // Check Fragment Shader
450  glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
451  if (!Result)
452  return LogCompilerError(FragmentShaderID, "fragment",
453  rFragmentShaderName, true);
454 
455  if (bHasGeometryShader)
456  {
457  // Compile Geometry Shader
458  if( !preamble.isEmpty())
459  addPreamble( aGeometryShaderSource, preamble );
460  char const * GeometrySourcePointer = aGeometryShaderSource.getStr();
461  glShaderSource(GeometryShaderID, 1, &GeometrySourcePointer , nullptr);
462  glCompileShader(GeometryShaderID);
463 
464  // Check Geometry Shader
465  glGetShaderiv(GeometryShaderID, GL_COMPILE_STATUS, &Result);
466  if (!Result)
467  return LogCompilerError(GeometryShaderID, "geometry",
468  rGeometryShaderName, true);
469  }
470 
471  // Link the program
472  glAttachShader(ProgramID, VertexShaderID);
473  glAttachShader(ProgramID, FragmentShaderID);
474  if (bHasGeometryShader)
475  glAttachShader(ProgramID, GeometryShaderID);
476 
477  if (epoxy_has_gl_extension("GL_ARB_get_program_binary") && !rDigest.isEmpty())
478  {
479  glProgramParameteri(ProgramID, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE);
480  glLinkProgram(ProgramID);
481  glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
482  if (!Result)
483  {
484  SAL_WARN("vcl.opengl", "linking failed: " << Result );
485  return LogCompilerError(ProgramID, "program", "<both>", false);
486  }
487  OString aFileName =
488  createFileName(rVertexShaderName, rFragmentShaderName, rGeometryShaderName, rDigest);
489  saveProgramBinary(ProgramID, aFileName);
490  }
491  else
492  {
493  glLinkProgram(ProgramID);
494  }
495 
496  glDeleteShader(VertexShaderID);
497  glDeleteShader(FragmentShaderID);
498  if (bHasGeometryShader)
499  glDeleteShader(GeometryShaderID);
500 
501  // Check the program
502  glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
503  if (!Result)
504  return LogCompilerError(ProgramID, "program", "<both>", false);
505 
506  CHECK_GL_ERROR();
507 
508  // Ensure we bump our counts before we leave the shader zone.
509  { OpenGLZone aMakeProgress; }
510  gbInShaderCompile = false;
511 
512  return ProgramID;
513 }
514 
515 GLint OpenGLHelper::LoadShaders(const OUString& rVertexShaderName,
516  const OUString& rFragmentShaderName,
517  const OString& preamble,
518  const OString& rDigest)
519 {
520  return LoadShaders(rVertexShaderName, rFragmentShaderName, OUString(), preamble, rDigest);
521 }
522 
523 GLint OpenGLHelper::LoadShaders(const OUString& rVertexShaderName,
524  const OUString& rFragmentShaderName,
525  const OUString& rGeometryShaderName)
526 {
527  return LoadShaders(rVertexShaderName, rFragmentShaderName, rGeometryShaderName, OString(), OString());
528 }
529 
530 GLint OpenGLHelper::LoadShaders(const OUString& rVertexShaderName,
531  const OUString& rFragmentShaderName)
532 {
533  return LoadShaders(rVertexShaderName, rFragmentShaderName, OUString(), "", "");
534 }
535 
536 void OpenGLHelper::renderToFile(long nWidth, long nHeight, const OUString& rFileName)
537 {
538  OpenGLZone aZone;
539 
540  std::unique_ptr<sal_uInt8[]> pBuffer(new sal_uInt8[nWidth*nHeight*4]);
541  glReadPixels(0, 0, nWidth, nHeight, OptimalBufferFormat(), GL_UNSIGNED_BYTE, pBuffer.get());
542  BitmapEx aBitmap = ConvertBufferToBitmapEx(pBuffer.get(), nWidth, nHeight);
543  try {
544  vcl::PNGWriter aWriter( aBitmap );
545  SvFileStream sOutput( rFileName, StreamMode::WRITE );
546  aWriter.Write( sOutput );
547  sOutput.Close();
548  } catch (...) {
549  SAL_WARN("vcl.opengl", "Error writing png to " << rFileName);
550  }
551 
552  CHECK_GL_ERROR();
553 }
554 
556 {
557 #ifdef _WIN32
558  return GL_BGRA; // OpenGLSalBitmap is internally ScanlineFormat::N24BitTcBgr
559 #else
560  return GL_RGBA; // OpenGLSalBitmap is internally ScanlineFormat::N24BitTcRgb
561 #endif
562 }
563 
564 BitmapEx OpenGLHelper::ConvertBufferToBitmapEx(const sal_uInt8* const pBuffer, long nWidth, long nHeight)
565 {
566  assert(pBuffer);
567  Bitmap aBitmap( Size(nWidth, nHeight), 24 );
568  AlphaMask aAlpha( Size(nWidth, nHeight) );
569 
570  {
571  BitmapScopedWriteAccess pWriteAccess( aBitmap );
572  AlphaScopedWriteAccess pAlphaWriteAccess( aAlpha );
573 #ifdef _WIN32
574  assert(pWriteAccess->GetScanlineFormat() == ScanlineFormat::N24BitTcBgr);
575  assert(pWriteAccess->IsTopDown());
576  assert(pAlphaWriteAccess->IsTopDown());
577 #else
578  assert(pWriteAccess->GetScanlineFormat() == ScanlineFormat::N24BitTcRgb);
579  assert(!pWriteAccess->IsTopDown());
580  assert(!pAlphaWriteAccess->IsTopDown());
581 #endif
582  assert(pAlphaWriteAccess->GetScanlineFormat() == ScanlineFormat::N8BitPal);
583 
584  size_t nCurPos = 0;
585  for( long y = 0; y < nHeight; ++y)
586  {
587 #ifdef _WIN32
588  Scanline pScan = pWriteAccess->GetScanline(y);
589  Scanline pAlphaScan = pAlphaWriteAccess->GetScanline(y);
590 #else
591  Scanline pScan = pWriteAccess->GetScanline(nHeight-1-y);
592  Scanline pAlphaScan = pAlphaWriteAccess->GetScanline(nHeight-1-y);
593 #endif
594  for( long x = 0; x < nWidth; ++x )
595  {
596  *pScan++ = pBuffer[nCurPos];
597  *pScan++ = pBuffer[nCurPos+1];
598  *pScan++ = pBuffer[nCurPos+2];
599 
600  nCurPos += 3;
601  *pAlphaScan++ = static_cast<sal_uInt8>( 255 - pBuffer[nCurPos++] );
602  }
603  }
604  }
605  return BitmapEx(aBitmap, aAlpha);
606 }
607 
608 const char* OpenGLHelper::GLErrorString(GLenum errorCode)
609 {
610  static const struct {
611  GLenum const code;
612  const char *string;
613  } errors[]=
614  {
615  /* GL */
616  {GL_NO_ERROR, "no error"},
617  {GL_INVALID_ENUM, "invalid enumerant"},
618  {GL_INVALID_VALUE, "invalid value"},
619  {GL_INVALID_OPERATION, "invalid operation"},
620  {GL_STACK_OVERFLOW, "stack overflow"},
621  {GL_STACK_UNDERFLOW, "stack underflow"},
622  {GL_OUT_OF_MEMORY, "out of memory"},
623  {GL_INVALID_FRAMEBUFFER_OPERATION, "invalid framebuffer operation"},
624 
625  {0, nullptr }
626  };
627 
628  int i;
629 
630  for (i=0; errors[i].string; i++)
631  {
632  if (errors[i].code == errorCode)
633  {
634  return errors[i].string;
635  }
636  }
637 
638  return nullptr;
639 }
640 
641 std::ostream& operator<<(std::ostream& rStrm, const glm::vec4& rPos)
642 {
643  rStrm << "( " << rPos[0] << ", " << rPos[1] << ", " << rPos[2] << ", " << rPos[3] << ")";
644  return rStrm;
645 }
646 
647 std::ostream& operator<<(std::ostream& rStrm, const glm::vec3& rPos)
648 {
649  rStrm << "( " << rPos[0] << ", " << rPos[1] << ", " << rPos[2] << ")";
650  return rStrm;
651 }
652 
653 std::ostream& operator<<(std::ostream& rStrm, const glm::mat4& rMatrix)
654 {
655  for(int i = 0; i < 4; ++i)
656  {
657  rStrm << "\n( ";
658  for(int j = 0; j < 4; ++j)
659  {
660  rStrm << rMatrix[j][i];
661  rStrm << " ";
662  }
663  rStrm << ")\n";
664  }
665  return rStrm;
666 }
667 
668 void OpenGLHelper::createFramebuffer(long nWidth, long nHeight, GLuint& nFramebufferId,
669  GLuint& nRenderbufferDepthId, GLuint& nRenderbufferColorId)
670 {
671  OpenGLZone aZone;
672 
673  // create a renderbuffer for depth attachment
674  glGenRenderbuffers(1, &nRenderbufferDepthId);
675  glBindRenderbuffer(GL_RENDERBUFFER, nRenderbufferDepthId);
676  glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, nWidth, nHeight);
677  glBindRenderbuffer(GL_RENDERBUFFER, 0);
678 
679  glGenTextures(1, &nRenderbufferColorId);
680  glBindTexture(GL_TEXTURE_2D, nRenderbufferColorId);
681  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
682  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
683  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
684  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
685  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, nWidth, nHeight, 0,
686  GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
687  glBindTexture(GL_TEXTURE_2D, 0);
688 
689  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
690  GL_TEXTURE_2D, nRenderbufferColorId, 0);
691 
692  // create a framebuffer object and attach renderbuffer
693  glGenFramebuffers(1, &nFramebufferId);
694  glCheckFramebufferStatus(GL_FRAMEBUFFER);
695  glBindFramebuffer(GL_FRAMEBUFFER, nFramebufferId);
696  // attach a renderbuffer to FBO color attachment point
697  glBindRenderbuffer(GL_RENDERBUFFER, nRenderbufferColorId);
698  glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, nRenderbufferColorId);
699  glCheckFramebufferStatus(GL_FRAMEBUFFER);
700  // attach a renderbuffer to depth attachment point
701  glBindRenderbuffer(GL_RENDERBUFFER, nRenderbufferDepthId);
702  glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, nRenderbufferDepthId);
703  GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
704  if (status != GL_FRAMEBUFFER_COMPLETE)
705  {
706  SAL_WARN("vcl.opengl", "invalid framebuffer status");
707  }
708  glBindRenderbuffer(GL_RENDERBUFFER, 0);
709  glBindFramebuffer(GL_FRAMEBUFFER, 0);
710 
711  CHECK_GL_ERROR();
712 }
713 
715 {
716  float fVersion = 1.0;
717  const GLubyte* aVersion = glGetString( GL_VERSION );
718  if( aVersion && aVersion[0] )
719  {
720  fVersion = aVersion[0] - '0';
721  if( aVersion[1] == '.' && aVersion[2] )
722  {
723  fVersion += (aVersion[2] - '0')/10.0;
724  }
725  }
726 
727  CHECK_GL_ERROR();
728  return fVersion;
729 }
730 
731 void OpenGLHelper::checkGLError(const char* pFile, size_t nLine)
732 {
733  OpenGLZone aZone;
734 
735  int nErrors = 0;
736  for (;;)
737  {
738  GLenum glErr = glGetError();
739  if (glErr == GL_NO_ERROR)
740  {
741  break;
742  }
743  const char* sError = OpenGLHelper::GLErrorString(glErr);
744  if (!sError)
745  sError = "no message available";
746 
747  SAL_WARN("vcl.opengl", "GL Error " << std::hex << std::setw(4) << std::setfill('0') << glErr << std::dec << std::setw(0) << std::setfill(' ') << " (" << sError << ") in file " << pFile << " at line " << nLine);
748 
749  // tdf#93798 - apitrace appears to sometimes cause issues with an infinite loop here.
750  if (++nErrors >= 8)
751  {
752  SAL_WARN("vcl.opengl", "Breaking potentially recursive glGetError loop");
753  break;
754  }
755  }
756 }
757 
759 {
760  static bool bSet = false;
761  static bool bBlacklisted = true; // assume the worst
762  if (!bSet)
763  {
764  OpenGLZone aZone;
765 
766 #if defined UNX && !defined MACOSX && !defined IOS && !defined ANDROID && !defined HAIKU
767  X11OpenGLDeviceInfo aInfo;
768  bBlacklisted = aInfo.isDeviceBlocked();
769  SAL_INFO("vcl.opengl", "blacklisted: " << bBlacklisted);
770 #elif defined( _WIN32 )
771  WinOpenGLDeviceInfo aInfo;
772  bBlacklisted = aInfo.isDeviceBlocked();
773 
774  if (aInfo.GetWindowsVersion() == 0x00060001 && /* Windows 7 */
775  (aInfo.GetAdapterVendorID() == "0x1002" || aInfo.GetAdapterVendorID() == "0x1022")) /* AMD */
776  {
777  SAL_INFO("vcl.opengl", "Relaxing watchdog timings.");
779  }
780 #else
781  bBlacklisted = false;
782 #endif
783  bSet = true;
784  }
785 
786  return bBlacklisted;
787 }
788 
790 {
791  static bool bDisableGL = !!getenv("SAL_DISABLEGL");
792  bool bBlacklisted = isDeviceBlacklisted();
793 
794  return !bDisableGL && !bBlacklisted;
795 }
796 
797 namespace {
798  static volatile bool gbWatchdogFiring = false;
799  static osl::Condition* gpWatchdogExit = nullptr;
800  static WatchdogTimings gWatchdogTimings;
801  static rtl::Reference<OpenGLWatchdogThread> gxWatchdog;
802 }
803 
805  : maTimingValues{
806  {{6, 20} /* 1.5s, 5s */, {20, 120} /* 5s, 30s */,
807  {60, 240} /* 15s, 60s */, {60, 240} /* 15s, 60s */}
808  }
809  , mbRelaxed(false)
810 {
811 }
812 
814  : salhelper::Thread("OpenGL Watchdog")
815 {
816 }
817 
819 {
820  int nUnchanged = 0; // how many unchanged nEnters
821  TimeValue aQuarterSecond(0, 1000*1000*1000*0.25);
822  bool bAbortFired = false;
823 
824  do {
825  sal_uInt64 nLastEnters = OpenGLZone::gnEnterCount;
826 
827  gpWatchdogExit->wait(&aQuarterSecond);
828 
829  if (OpenGLZone::isInZone())
830  {
831  // The shader compiler can take a long time, first time.
833  WatchdogTimingsValues aTimingValues = gWatchdogTimings.getWatchdogTimingsValues(eMode);
834 
835  if (nLastEnters == OpenGLZone::gnEnterCount)
836  nUnchanged++;
837  else
838  nUnchanged = 0;
839  SAL_INFO("vcl.opengl", "GL watchdog - unchanged " <<
840  nUnchanged << " enter count " <<
841  OpenGLZone::gnEnterCount << " type " <<
842  (eMode == WatchdogTimingMode::SHADER_COMPILE ? "in shader" : "normal gl") <<
843  "breakpoints mid: " << aTimingValues.mnDisableEntries <<
844  " max " << aTimingValues.mnAbortAfter);
845 
846  // Not making progress
847  if (nUnchanged >= aTimingValues.mnDisableEntries)
848  {
849  static bool bFired = false;
850  if (!bFired)
851  {
852  gbWatchdogFiring = true;
853  SAL_WARN("vcl.opengl", "Watchdog triggered: hard disable GL");
855  gbWatchdogFiring = false;
856  }
857  bFired = true;
858 
859  // we can hang using VCL in the abort handling -> be impatient
860  if (bAbortFired)
861  {
862  SAL_WARN("vcl.opengl", "Watchdog gave up: hard exiting");
863  _exit(1);
864  }
865  }
866 
867  // Not making even more progress
868  if (nUnchanged >= aTimingValues.mnAbortAfter)
869  {
870  if (!bAbortFired)
871  {
872  SAL_WARN("vcl.opengl", "Watchdog gave up: aborting");
873  gbWatchdogFiring = true;
874  std::abort();
875  }
876  // coverity[dead_error_line] - we might have caught SIGABRT and failed to exit yet
877  bAbortFired = true;
878  }
879  }
880  else
881  {
882  nUnchanged = 0;
883  }
884  } while (!gpWatchdogExit->check());
885 }
886 
888 {
889  assert (gxWatchdog == nullptr);
890  gpWatchdogExit = new osl::Condition();
891  gxWatchdog.set(new OpenGLWatchdogThread());
892  gxWatchdog->launch();
893 }
894 
896 {
897  if (gbWatchdogFiring)
898  return; // in watchdog thread
899 
900  if (gpWatchdogExit)
901  gpWatchdogExit->set();
902 
903  if (gxWatchdog.is())
904  {
905  gxWatchdog->join();
906  gxWatchdog.clear();
907  }
908 
909  delete gpWatchdogExit;
910  gpWatchdogExit = nullptr;
911 }
912 
918 {
919  // protect ourselves from double calling etc.
920  static bool bDisabled = false;
921  if (!bDisabled)
922  {
923  bDisabled = true;
924 
925  // Disable the OpenGL support
926  std::shared_ptr<comphelper::ConfigurationChanges> xChanges(
928  officecfg::Office::Common::VCL::UseOpenGL::set(false, xChanges);
929  xChanges->commit();
930 
931  // Force synchronous config write
932  css::uno::Reference< css::util::XFlushable >(
933  css::configuration::theDefaultProvider::get(
935  css::uno::UNO_QUERY_THROW)->flush();
936 
938  }
939 }
940 
942 {
943  gWatchdogTimings.setRelax(true);
944 }
945 
947 {
949 }
950 
951 namespace
952 {
953  bool bTempOpenGLDisabled = false;
954 }
955 
957 {
958  bTempOpenGLDisabled = true;
959 }
960 
962 {
963  bTempOpenGLDisabled = false;
964 }
965 
967 {
973  static bool bSet = false;
974  static bool bEnable = false;
975  static bool bForceOpenGL = false;
976 
977  // No hardware rendering, so no OpenGL
979  return false;
980 
981  //tdf#106155, disable GL while loading certain bitmaps needed for the initial toplevel windows
982  //under raw X (kde) vclplug
983  if (bTempOpenGLDisabled)
984  return false;
985 
986  if (bSet)
987  {
988  return bForceOpenGL || bEnable;
989  }
990  /*
991  * There are a number of cases that these environment variables cover:
992  * * SAL_FORCEGL forces OpenGL independent of any other option
993  * * SAL_DISABLEGL or a blacklisted driver avoid the use of OpenGL if SAL_FORCEGL is not set
994  */
995 
996  bSet = true;
997  bForceOpenGL = !!getenv("SAL_FORCEGL") || officecfg::Office::Common::VCL::ForceOpenGL::get();
998 
999  bool bRet = false;
1000  bool bSupportsVCLOpenGL = supportsVCLOpenGL();
1001  // always call supportsVCLOpenGL to de-zombie the glxtest child process on X11
1002  if (bForceOpenGL)
1003  {
1004  bRet = true;
1005  }
1006  else if (bSupportsVCLOpenGL)
1007  {
1008  static bool bEnableGLEnv = !!getenv("SAL_ENABLEGL");
1009 
1010  bEnable = bEnableGLEnv;
1011 
1012  if (officecfg::Office::Common::VCL::UseOpenGL::get())
1013  bEnable = true;
1014 
1015  // Force disable in safe mode
1017  bEnable = false;
1018 
1019  bRet = bEnable;
1020  }
1021 
1022  if (bRet)
1023  {
1024  if (!getenv("SAL_DISABLE_GL_WATCHDOG"))
1026  }
1027  CrashReporter::AddKeyValue("UseOpenGL", OUString::boolean(bRet));
1028 
1029  return bRet;
1030 }
1031 
1033 {
1035 }
1036 
1037 void OpenGLHelper::debugMsgStream(std::ostringstream const &pStream)
1038 {
1039  debugMsgPrint(0, "%x: %s", osl_getThreadIdentifier(nullptr), pStream.str().c_str());
1040 }
1041 
1042 void OpenGLHelper::debugMsgStreamWarn(std::ostringstream const &pStream)
1043 {
1044  debugMsgPrint(1, "%x: %s", osl_getThreadIdentifier(nullptr), pStream.str().c_str());
1045 }
1046 
1047 void OpenGLHelper::debugMsgPrint(const int nType, const char *pFormat, ...)
1048 {
1049  va_list aArgs;
1050  va_start (aArgs, pFormat);
1051 
1052  char pStr[1044];
1053 #ifdef _WIN32
1054 #define vsnprintf _vsnprintf
1055 #endif
1056  vsnprintf(pStr, sizeof(pStr), pFormat, aArgs);
1057  pStr[sizeof(pStr)-20] = '\0';
1058 
1059  bool bHasContext = OpenGLContext::hasCurrent();
1060  if (!bHasContext)
1061  strcat(pStr, " (no GL context)");
1062 
1063  if (nType == 0)
1064  {
1065  SAL_INFO("vcl.opengl", pStr);
1066  }
1067  else if (nType == 1)
1068  {
1069  SAL_WARN("vcl.opengl", pStr);
1070  }
1071 
1072  if (bHasContext)
1073  {
1074  OpenGLZone aZone;
1075 
1076  if (epoxy_has_gl_extension("GL_KHR_debug"))
1077  glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION,
1078  GL_DEBUG_TYPE_OTHER,
1079  1, // one[sic] id is as good as another ?
1080  // GL_DEBUG_SEVERITY_NOTIFICATION for >= GL4.3 ?
1081  GL_DEBUG_SEVERITY_LOW,
1082  strlen(pStr), pStr);
1083  else if (epoxy_has_gl_extension("GL_AMD_debug_output"))
1084  glDebugMessageInsertAMD(GL_DEBUG_CATEGORY_APPLICATION_AMD,
1085  GL_DEBUG_SEVERITY_LOW_AMD,
1086  1, // one[sic] id is as good as another ?
1087  strlen(pStr), pStr);
1088  }
1089 
1090  va_end (aArgs);
1091 }
1092 
1093 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
std::ostream & operator<<(std::ostream &rStrm, const glm::vec4 &rPos)
static void addPreamble(OString &rShaderSource, const OString &rPreamble)
Result
static bool volatile gbInShaderCompile
const OString & GetOSRelease() const
Scanline GetScanline(long nY) const
static bool IsBitmapRendering()
Determines if bitmap rendering is enabled.
Definition: svapp.cxx:1509
static bool supportsVCLOpenGL()
checks if the system supports all features that are necessary for the OpenGL VCL support ...
static void debugMsgStreamWarn(std::ostringstream const &pStream)
const OUString & GetAdapterDeviceID() const
OString getDeviceInfoString(cl_device_id aDeviceId, cl_device_info aDeviceInfo)
static void checkGLError(const char *aFile, size_t nLine)
static float getGLVersion()
Get OpenGL version (needs a context)
const OString & GetOS() const
float x
static void relaxWatchdogTimings()
static AtomicCounter gnEnterCount
how many times have we entered a GL zone
Definition: zone.hxx:39
static bool IsSafeModeEnabled()
Determines if safe mode is enabled.
Definition: svapp.cxx:1534
const OString & GetVersion() const
static void debugMsgPrint(const int nType, const char *pFormat,...)
Insert a glDebugMessage into the queue - helpful for debugging with apitrace to annotate the output a...
static OString GetDigest(const OUString &rVertexShaderName, const OUString &rFragmentShaderName, const OString &preamble)
static void debugMsgStream(std::ostringstream const &pStream)
int mnDisableEntries
delays to take various actions in 1/4 of a second increments.
Definition: watchdog.hxx:21
static std::shared_ptr< ConfigurationChanges > create(css::uno::Reference< css::uno::XComponentContext > const &context=comphelper::getProcessComponentContext())
static void makeVCLCurrent()
make a VCL context (any context) current, create it if necessary.
static bool isVCLOpenGLEnabled()
Returns true if VCL has OpenGL rendering enabled.
WatchdogTimingMode
Definition: watchdog.hxx:25
float y
#define SAL_CONFIGFILE(name)
sal_uInt8 * Scanline
Definition: Scanline.hxx:25
static bool isInZone()
Definition: zone.hxx:51
bool IsTopDown() const
static BitmapEx ConvertBufferToBitmapEx(const sal_uInt8 *const pBuffer, long nWidth, long nHeight)
The caller is responsible for allocating the memory for the buffer before calling this method...
int const mnAbortAfter
Definition: watchdog.hxx:22
static void hardDisable()
Called from a signal handler or watchdog thread if we get a crash or hang in some GL code...
#define VCL_GL_INFO(stream)
Helper to do a SAL_INFO as well as a GL log.
ScanlineFormat GetScanlineFormat() const
static void AddKeyValue(const OUString &rKey, const OUString &rValue)
const OUString & GetDriverVersion() const
static bool hasCurrent()
Is there a current GL context ?
const OString & GetRenderer() const
int i
virtual void execute() override
bool Write(SvStream &rStream)
Definition: pngwrite.cxx:708
sal_uInt32 GetWindowsVersion() const
static void createFramebuffer(long nWidth, long nHeight, GLuint &nFramebufferId, GLuint &nRenderbufferDepthId, GLuint &nRenderbufferColorId)
The caller is responsible for deleting the buffer objects identified by nFramebufferId, nRenderbufferDepthId and nRenderbufferColorId.
static GLint LoadShaders(const OUString &rVertexShaderName, const OUString &rFragmentShaderName, const OUString &rGeometryShaderName, const OString &preamble, const OString &rDigest)
virtual bool isDeviceBlocked() override
We want to be able to detect if a given crash came from the OpenGL code, so use this helper to track ...
Definition: zone.hxx:27
OString OUStringToOString(const OUString &str, ConnectionSettings const *settings)
static bool isDeviceBlacklisted()
checks if the device/driver pair is on our OpenGL blacklist
#define SAL_WARN_IF(condition, area, stream)
unsigned char sal_uInt8
#define SAL_INFO(area, stream)
Reference< XComponentContext > getProcessComponentContext()
const OUString & GetAdapterVendorID() const
const OString & GetVendor() const
#define SAL_WARN(area, stream)
std::atomic< std::make_unsigned_t< std::sig_atomic_t >> AtomicCounter
Definition: zone.hxx:38
#define CHECK_GL_ERROR()
static const char * GLErrorString(GLenum errorCode)
static bool isVCLOpenGLEnabled()
Returns true if VCL has OpenGL rendering enabled.
static void renderToFile(long nWidth, long nHeight, const OUString &rFileName)
static AtomicCounter gnLeaveCount
how many times have we left a new GL zone
Definition: zone.hxx:44
static GLenum OptimalBufferFormat()
Returns the optimal buffer format for OpenGL (GL_BGRA or GL_RGBA).
virtual bool isDeviceBlocked() override