home *** CD-ROM | disk | FTP | other *** search
/ Hackers Magazine 57 / CdHackersMagazineNr57.iso / Software / Multimedia / k3d-setup-0.7.11.0.exe / lib / site-packages / OpenGL / error.py < prev    next >
Encoding:
Python Source  |  2008-12-07  |  6.7 KB  |  234 lines

  1. """Implementation of OpenGL errors/exceptions
  2.  
  3. Note that OpenGL-ctypes will also throw standard errors,
  4. such as TypeError or ValueError when appropriate.
  5.  
  6. ErrorChecker is an _ErrorChecker instance that allows you
  7. to register a new error-checking function for use 
  8. throughout the system.
  9. """
  10. import OpenGL
  11. from OpenGL import platform
  12. __all__ = (
  13.     "Error",'GLError','GLUError','GLUTError','glCheckError',
  14.     'GLerror','GLUerror','GLUTerror',
  15. )
  16.  
  17. class Error( Exception ):
  18.     """Base class for all PyOpenGL-specific exception classes"""
  19. class CopyError( Error ):
  20.     """Raised to indicate that operation requires data-copying
  21.     
  22.     Currently only supported by the numpy array formathandler,
  23.     if you set:
  24.  
  25.         OpenGL.arrays.numpymodule.NumpyHandler.ERROR_ON_COPY = True 
  26.     
  27.     this error will be raised when the Numpy handler is passed
  28.     a numpy array that requires copying to be passed to ctypes.
  29.     """
  30.  
  31. class NullFunctionError( Error ):
  32.     """Error raised when an undefined function is called"""
  33.  
  34. class GLError( Error ):
  35.     """OpenGL core error implementation class
  36.     
  37.     Primary purpose of this error class is to allow for 
  38.     annotating an error with more details about the calling 
  39.     environment so that it's easier to debug errors in the
  40.     wrapping process.
  41.     
  42.     Attributes:
  43.     
  44.         err -- the OpenGL error code for the error 
  45.         result -- the OpenGL result code for the operation
  46.         baseOperation -- the "function" being called
  47.         pyArgs -- the translated set of Python arguments
  48.         cArgs -- the Python objects matching 1:1 the C arguments
  49.         cArguments -- ctypes-level arguments to the operation,
  50.             often raw integers for pointers and the like
  51.         description -- OpenGL description of the error (textual)
  52.     """
  53.     def __init__( 
  54.         self, 
  55.         err=None, 
  56.         result=None, 
  57.         cArguments=None, 
  58.         baseOperation=None, 
  59.         pyArgs=None, 
  60.         cArgs=None,
  61.         description=None,
  62.     ):
  63.         """Initialise the GLError, storing metadata for later display"""
  64.         (
  65.             self.err, self.result, self.cArguments, 
  66.             self.baseOperation, self.pyArgs, self.cArgs,
  67.             self.description
  68.         ) = (
  69.             err, result, cArguments,
  70.             baseOperation, pyArgs, cArgs,
  71.             description
  72.         )
  73.     DISPLAY_ORDER = (
  74.         'err', 
  75.         'description',
  76.         'baseOperation',
  77.         'pyArgs', 
  78.         'cArgs',
  79.         'cArguments',
  80.         'result', 
  81.     )
  82.     def __str__( self ):
  83.         """Create a fully formatted representation of the error"""
  84.         args = []
  85.         for property in self.DISPLAY_ORDER:
  86.             value = getattr( self, property, None )
  87.             if value is not None or property=='description':
  88.                 formatFunction = 'format_%s'%(property)
  89.                 if hasattr( self, formatFunction ):
  90.                     args.append( getattr(self,formatFunction)( property, value ))
  91.                 else:
  92.                     args.append( '%s = %s'%(
  93.                         property,
  94.                         self.shortRepr( value ),
  95.                     ))
  96.         return '%s(\n\t%s\n)'%(self.__class__.__name__, ',\n\t'.join(
  97.             [x for x in args if x]
  98.         ))
  99.     def __repr__( self ):
  100.         """Produce a much shorter version of the error as a string"""
  101.         return '%s( %s )'%(
  102.             self.__class__.__name__,
  103.             ", ".join([x for x in [
  104.                 'err=%s'%(self.err),
  105.                 self.format_description( 'description', self.description ) or '',
  106.                 self.format_baseOperation( 'baseOperation', self.baseOperation ) or '',
  107.             ] if x])
  108.         )
  109.     def format_description( self, property, value ):
  110.         """Format description using GLU's gluErrorString"""
  111.         if value is None and self.err is not None:
  112.             try:
  113.                 from OpenGL.GLU import gluErrorString
  114.                 self.description = value = gluErrorString( self.err )
  115.             except Exception, err:
  116.                 return None
  117.         if value is None:
  118.             return None
  119.         return '%s = %s'%(
  120.             property,
  121.             self.shortRepr( value ),
  122.         )
  123.     def shortRepr( self, value, firstLevel=True ):
  124.         """Retrieve short representation of the given value"""
  125.         if isinstance( value, (list,tuple) ) and value and len(repr(value))>=40:
  126.             if isinstance( value, list ):
  127.                 template = '[\n\t\t%s\n\t]'
  128.             else:
  129.                 template = '(\n\t\t%s,\n\t)'
  130.             return template%( ",\n\t\t".join(
  131.                 [
  132.                     self.shortRepr(x,False) for x in value
  133.                 ]
  134.             ))
  135.         r = repr( value )
  136.         if len(r) < 40:
  137.             return r
  138.         else:
  139.             return r[:37] + '...'
  140.     def format_baseOperation( self, property, value ):
  141.         """Format a baseOperation reference for display"""
  142.         if hasattr( value, '__name__' ):
  143.             return '%s = %s'%( property, value.__name__ )
  144.         else:
  145.             return '%s = %r'%( property, value )
  146.  
  147. class GLUError( Error ):
  148.     """GLU error implementation class"""
  149.  
  150. class GLUTError( Error ):
  151.     """GLUT error implementation class"""
  152.  
  153.  
  154. if OpenGL.ERROR_CHECKING:
  155.     
  156.     class _ErrorChecker( object ):
  157.         """Global error-checking object
  158.         
  159.         Attributes:
  160.             _registeredChecker -- the checking function enabled when 
  161.                 not doing onBegin/onEnd processing
  162.             safeGetError -- platform safeGetError function as callable method
  163.             _currentChecker -- currently active checking function
  164.         """
  165.         _currentChecker = _registeredChecker = safeGetError = staticmethod( 
  166.             platform.safeGetError 
  167.         )
  168.         def glCheckError( 
  169.             self,
  170.             result,
  171.             baseOperation=None,
  172.             cArguments=None,
  173.             *args
  174.         ):
  175.             """Base GL Error checker compatible with new ctypes errcheck protocol
  176.             
  177.             This function will raise a GLError with just the calling information
  178.             available at the C-calling level, i.e. the error code, cArguments,
  179.             baseOperation and result.  Higher-level code is responsible for any 
  180.             extra annotations.
  181.             
  182.             Note:
  183.                 glCheckError relies on glBegin/glEnd interactions to 
  184.                 prevent glGetError being called during a glBegin/glEnd 
  185.                 sequence.  If you are calling glBegin/glEnd in C you 
  186.                 should call onBegin and onEnd appropriately.
  187.             """
  188.             err = self._currentChecker()
  189.             if err: # GL_NO_ERROR's guaranteed value is 0
  190.                 raise GLError(
  191.                     err,
  192.                     result,
  193.                     cArguments = cArguments,
  194.                     baseOperation = baseOperation,
  195.                 )
  196.             return result
  197.         def nullGetError( self ):
  198.             """Used as error-checker when inside begin/end set"""
  199.             return None
  200.         def currentChecker( self ):
  201.             """Return the current error-checking function"""
  202.             return self._currentChecker
  203.         def registerChecker( self, checker=None ):
  204.             """Explicitly register an error checker
  205.             
  206.             This allows you to, for instance, disable error checking 
  207.             entirely.  onBegin and onEnd will switch between 
  208.             nullGetError and the value registered here.  If checker 
  209.             is None then the default 
  210.             """
  211.             if checker is None:
  212.                 checker = self.safeGetError
  213.             self._registeredChecker = checker
  214.             return checker
  215.         def onBegin( self, target=None ):
  216.             """Called by glBegin to record the fact that glGetError won't work"""
  217.             self._currentChecker = self.nullGetError
  218.         def onEnd( self, target=None ):
  219.             """Called by glEnd to record the fact that glGetError will work"""
  220.             self._currentChecker = self._registeredChecker
  221.     
  222.     ErrorChecker = _ErrorChecker()
  223.     
  224.     glCheckError = ErrorChecker.glCheckError
  225.     onBegin = ErrorChecker.onBegin
  226.     onEnd = ErrorChecker.onEnd
  227. else:
  228.     glCheckError = platform.safeGetError
  229.  
  230. # Compatibility with PyOpenGL 2.x series
  231. GLUerror = GLUError
  232. GLerror = GLError 
  233. GLUTerror = GLUTError
  234.