
    _eK                        d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
mZmZ ddlZddlZ ej                  d      Zdd	l	mZmZ ddlZd
Z G d de      Zej.                  ZddlmZ dZej4                  r	 ddlmZmZmZmZ e, G d de      Z G d de      Z G d de      Z G d de      Zi Z"d Z#ddZ$y# e$ rZ ejC                  d       Y dZ [ SdZ [ ww xY w)a  VertexBufferObject helper class

Basic usage:

    my_data = numpy.array( data, 'f')
    my_vbo = vbo.VBO( my_data )
    ...
    my_vbo.bind()
    try:
        ...
        glVertexPointer( my_vbo, ... )
        ...
        glNormalPointer( my_vbo + 12, ... )
    finally:
        my_vbo.unbind()
    
    or 
    
    with my_vbo:
        ...
        glVertexPointer( my_vbo, ... )
        ...
        glNormalPointer( my_vbo + 12, ... )        

See the OpenGLContext shader tutorials for a gentle introduction on the 
usage of VBO objects:

    http://pyopengl.sourceforge.net/context/tutorials/shader_intro.xhtml

This implementation will choose either the ARB or Core (OpenGL 1.5) 
implementation of the VBO functions.
    )ArrayDatatype)FormatHandler)_types)error)bytesunicodeas_8_bitNzOpenGL.arrays.vbo)longinteger_types)VBO
VBOHandlermapVBOc                   |    e Zd ZdZg ZdZed        Zed        Zdj                         Z
dZd Zd Zd	 ZeZd
 Zi Zy)ImplementationzGAbstraction point for the various implementations that can be used
    Nc                 :    | j                   j                  |        y N)IMPLEMENTATION_CLASSESappend)clss    3/usr/lib/python3/dist-packages/OpenGL/arrays/vbo.pyregisterzImplementation.register2   s    ""))30    c                     | j                   2| j                  D ]#  } |       }|s|t        _          | j                   S  | j                   S r   )CHOSENr   r   )r   argspossibleimplementations       r   get_implementationz!Implementation.get_implementation6   sL    ::66 !),:N)zz
 zzr   a  glGenBuffers
    glBindBuffer 
    glBufferData 
    glBufferSubData 
    glDeleteBuffers
    glMapBuffer
    glUnmapBuffer
    GL_STATIC_DRAW
    GL_STATIC_READ
    GL_STATIC_COPY
    GL_DYNAMIC_DRAW
    GL_DYNAMIC_READ
    GL_DYNAMIC_COPY
    GL_STREAM_DRAW
    GL_STREAM_READ
    GL_STREAM_COPY
    GL_ARRAY_BUFFER
    GL_ELEMENT_ARRAY_BUFFER
    GL_UNIFORM_BUFFER
    GL_TEXTURE_BUFFER
    GL_TRANSFORM_FEEDBACK_BUFFERFc                     |j                  d      xr |j                  d      xs$ |j                  d      xr |j                  d      xr |dk7  S )NglARBGL_glInitVertexBufferObjectARB)
startswithendswithselfnames     r   _arbnamezImplementation._arbnameV   sQ    __d$?)? B__e%@$--*@6 44	6r   c                 ^    |j                  d      r|d d S |j                  d      r|d d S |S )N_ARBr!   )r%   r&   s     r   basenamezImplementation.basename[   s7    ==&"9]]E#9Kr   c                     | j                   S r   )	availabler'   s    r   __nonzero__zImplementation.__nonzero__b   s    ~~r   c                 b     t         j                  t        j                   fd}|S )z5Produce a deleter callback to delete the given bufferc                  2   r/	 j                         }	  |      }	j                  d|       r/	 	j
                  j                         y # t        t        f$ r
}Y d }~5d }~ww xY w# t        $ r
}Y d }~Hd }~ww xY w# t        $ r
}Y d }~y d }~ww xY w)N   )popglDeleteBuffersAttributeError	TypeError
IndexError
_DELETERS_KeyError)
r   namedbufferbuferrbuffersgluintkeynfer'   s
        r   doBufferDeletionz0Implementation.deleter.<locals>.doBufferDeletionk   s    $[[]F %f.,,Q4 ##S* +C;  "   s3   A- A B A*%A*-	B ;B 	BB)r   NullFunctionErrorr   GLuint)r'   rA   rC   rE   rB   rD   s   ``` @@r   deleterzImplementation.deletere   s+     %%	 	$  r   )__name__
__module____qualname____doc__r   r   classmethodr   r   splitEXPORTED_NAMESr0   r)   r.   r2   __bool__rH   r;    r   r   r   r   -   sr    F1 1  $( %*EG) * I6
H 2 Jr   r   )acceleratesupport)r   	VBOOffsetr   VBOOffsetHandlerz5Unable to load VBO accelerator from OpenGL_acceleratec                       e Zd ZdZdZdZ	 	 ddZdZ ee	      Z
d ZddZd Zd	 Zd
 Zd Zd Zd Zd Zd Zd Zd ZeZddZy)r   a'  Instances can be passed into array-handling routines

        You can check for whether VBOs are supported by accessing the implementation:

            if bool(vbo.get_implementation()):
                # vbo version of code
            else:
                # fallback version of code
        FTNc                 `    || _         | j                  ||       || _        g | _        g | _        y)a>  Initialize the VBO object 
            
            data -- PyOpenGL-compatible array-data structure, numpy arrays, ctypes arrays, etc.
            usage -- OpenGL usage constant describing expected data-flow patterns (this is a hint 
                to the GL about where/how to cache the data)
                
                GL_STATIC_DRAW_ARB
                GL_STATIC_READ_ARB
                GL_STATIC_COPY_ARB
                GL_DYNAMIC_DRAW_ARB
                GL_DYNAMIC_READ_ARB
                GL_DYNAMIC_COPY_ARB
                GL_STREAM_DRAW_ARB
                GL_STREAM_READ_ARB
                GL_STREAM_COPY_ARB
                
                DRAW constants suggest to the card that the data will be primarily used to draw 
                on the card.  READ that the data will be read back into the GL.  COPY means that 
                the data will be used both for DRAW and READ operations.
                
                STATIC suggests that the data will only be written once (or a small number of times).
                DYNAMIC suggests that the data will be used a small number of times before being 
                discarded.
                STREAM suggests that the data will be updated approximately every time that it is 
                used (that is, it will likely only be used once).
                
            target -- VBO target to which to bind (array or indices)
                GL_ARRAY_BUFFER -- array-data binding 
                GL_ELEMENT_ARRAY_BUFFER -- index-data binding
                GL_UNIFORM_BUFFER -- used to pass mid-size arrays of data packed into a buffer
                GL_TEXTURE_BUFFER -- used to pass large arrays of data as a pseudo-texture
                GL_TRANSFORM_FEEDBACK_BUFFER -- used to receive transformed vertices for processing
                
            size -- if not provided, will use arrayByteCount to determine the size of the data-array,
                thus this value (number of bytes) is required when using opaque data-structures,
                (such as ctypes pointers) as the array data-source.
            N)usage	set_arraytargetrA   _copy_segments)r'   datarW   rY   sizes        r   __init__zVBO.__init__   s0    R DJNND$( DKDL"$Dr   c                     t        |t        t        f      r/t        | j                  | j                  j                  |            S |S )z#Resolve string constant to constant)
isinstancer   r   getattrr   r.   r'   values     r   resolvezVBO.resolve   s:    55/2 3 3T5H5H5Q5QSX5Z\\Lr   c                     || _         d| _        ||| _        y| j                   %t        j                  | j                         | _        yy)a  Update our entire array with new data
            
            data -- PyOpenGL-compatible array-data structure, numpy arrays, ctypes arrays, etc.
            size -- if not provided, will use arrayByteCount to determine the size of the data-array,
                thus this value (number of bytes) is required when using opaque data-structures,
                (such as ctypes pointers) as the array data-source.
            FN)r[   copiedr\   r   arrayByteCount)r'   r[   r\   s      r   rX   zVBO.set_array   sD     DIDK 	&)88$))E	 'r   c                    |j                   r|j                   dk(  st        d      t        j                  |      }t        j                  |      }|j
                  xs d}|j                  xs t        | j                        }|dk  r%|t        | j                        z  }t        |df      }|dk  r%|t        | j                        z  }t        |df      }|| j                  |<   | j                  r| j                  r}||z
  t        | j                        k(  rd| _
        yt        |      rNt        j                  | j                  d         }||z  }||z  }| j                  j                  |||z
  |f       yyyy)a  Set slice of data on the array and vbo (if copied already)

            slice -- the Python slice object determining how the data should
                be copied into the vbo/array
            array -- something array-compatible that will be used as the
                source of the data, note that the data-format will have to
                be the same as the internal data-array to work properly, if
                not, the amount of data copied will be wrong.

            This is a reasonably complex operation, it has to have all sorts
            of state-aware changes to correctly map the source into the low-level
            OpenGL view of the buffer (which is just bytes as far as the GL
            is concerned).
            r5   z(Don't know how to map stepped arrays yetr   FN)stepNotImplementedr   asArrayrf   startstoplenr[   maxre   rA   rZ   r   )r'   slicearrayr[   data_lengthrk   rl   r\   s           r   __setitem__zVBO.__setitem__   sJ    zz%**/$&TVV ((%1D'66?K[[%AEJJ0#dii.DqyTYY'U1IaxDII&D8}!%DIIu{{t||:TYY/"'DKY )771GD TMEDLD''..U
T2 	  ,{r   c                 ,    t        | j                        S )z.Delegate length/truth checks to our data-array)rm   r[   r1   s    r   __len__zVBO.__len__  s    		##r   c                 L    |dvrt        | j                  |      S t        |      )z4Delegate failing attribute lookups to our data-array)r[   rW   rY   rA   re   _I_r   rZ   )r`   r[   r8   r'   rC   s     r   __getattr__zVBO.__getattr__  s'    pp		300$c++r   c           	         | j                   rJ d       t        | j                  j                  d            g| _         | j	                  | j
                        | _        | j	                  | j                        | _        t        j                  | | j                  j                  | j                   t        |                   | j                  j                  t        |       <   | j                   S )zCreate the internal buffer(s)zAlready created the bufferr5   )rA   r
   r   glGenBuffersrc   rY   rW   weakrefrefrH   idr;   r1   s    r   create_bufferszVBO.create_buffers  s    ||E%EE#!$"5"5"B"B1"EFHDL,,5DKtzz3DJ9@dDL_L_LgLgimiuiuwyz~w  MB  :CD**BtH6<<r   c                 \   | j                   sJ d       | j                  r| j                  rw| j                  rj| j                  j                  d      \  }}}t	        j
                  |      }| j                  j                  | j                  |||       | j                  riyyy| j                  0| j                  $t	        j                  | j                        | _
        | j                  j                  | j                  | j                  | j                  | j                         d| _        y)ab  Copy our data into the buffer on the GL side (if required)
            
            Ensures that the GL's version of the data in the VBO matches our 
            internal view of the data, either by copying the entire data-set 
            over with glBufferData or by updating the already-transferred 
            data with glBufferSubData.
            z)Should do create_buffers before copy_datar   NT)rA   re   rZ   r6   r   voidDataPointerr   glBufferSubDatarY   r[   r\   rf   glBufferDatarW   )r'   rk   r\   r[   dataptrs        r   	copy_datazVBO.copy_data   s     <<P!PP<{{&&--+/+>+>+B+B1+Ed4"/"?"?"G++;;DKKPTV]^ -- ' 99(TYY-> - < <dii IDI##00KKIIIIJJ	 #r   c                 
   | j                   rQ| j                   rD	 | j                  j                  d| j                   j                  d             | j                   rCyyy# t        t
        j                  f$ r
}Y d}~.d}~ww xY w)zDelete this buffer explicitlyr5   r   N)rA   r   r7   r6   r8   r   rF   )r'   r@   s     r   deletez
VBO.delete9  si    ||ll++;;At||?O?OPQ?RS ll  +5+B+BC s   5A B=Bc                 X    | j                   s| j                          | j                   d   S )zGet our VBO idr   )rA   r~   r1   s    r   __int__zVBO.__int__A  s#    <<##%<<?"r   c                     | j                   s| j                         }| j                  j                  | j                  | j                   d          | j                          y)zBind this buffer for use in vertex calls
            
            If we have not yet created our implementation-level VBO, then we 
            will create it before binding.  Once bound, calls self.copy_data()
            r   N)rA   r~   r   glBindBufferrY   r   )r'   rA   s     r   bindzVBO.bindF  sE     <<--/,,dkk4<<?KNNr   c                 P    | j                   j                  | j                  d       y)z7Unbind the buffer (make normal array operations active)r   N)r   r   rY   r1   s    r   unbindz
VBO.unbindP  s    ,,dkk!=r   c                 x    t        |d      r|j                  }t        |t              sJ d       t	        | |      S )z/Add an integer to this VBO (create a VBOOffset)offsetz)Only know how to add integer/long offsets)hasattrr   r_   r   rS   r'   others     r   __add__zVBO.__add__T  s8    x)um5f7ff5dE++r   c                 $    | j                          y)zContext manager exitF)r   )r'   exc_typeexc_valexc_tbs       r   __exit__zVBO.__exit__\  s    KKMr   )GL_DYNAMIC_DRAWGL_ARRAY_BUFFERNr   )NNN)rI   rJ   rK   rL   re   
_no_cache_r]   rv   propertyr   r   rc   rX   rr   rt   rx   r~   r   r   r   r   r   r   	__enter__r   rQ   r   r   r   r      s{    	 
/+/-	%\ !#58	
	F1	d	$	,	 	#2		#
			>	, 		r   r   c                   "    e Zd ZdZd Zd Zd Zy)rS   a  Offset into a VBO instance 
        
        This class is normally instantiated by doing a my_vbo + int operation,
        it can be passed to VBO requiring operations and will generate the 
        appropriate integer offset value to be passed in.
        c                      || _         || _        y)z<Initialize the offset with vbo and offset (unsigned integer)N)vbor   )r'   r   r   s      r   r]   zVBOOffset.__init__h  s    DH DKr   c                 V    |dk7  rt        | j                  |      S t        d|d      )z4Delegate any undefined attribute save vbo to our vbor   zNo z key in VBOOffset)r`   r   r8   rw   s     r   rx   zVBOOffset.__getattr__l  s(    e|#// C"ABBr   c                 x    t        |d      r|j                  }t        | j                  | j                  |z         S )zAllow adding integers or other VBOOffset instances 
            
            returns a VBOOffset to the this VBO with other.offset + self.offset
            or, if other has no offset, returns VBOOffset with self.offset + other
            r   )r   r   rS   r   r   s     r   r   zVBOOffset.__add__q  s1     x)dhhe(;==r   N)rI   rJ   rK   rL   r]   rx   r   rQ   r   r   rS   rS   a  s    		!	C
	>r   rS   c                   x    e Zd ZdZ ej
                  d      Zd ZddZd Z	e	Z
ddZd Zd	 Zdd
ZddZddZy)r   zHandles VBO instances passed in as array data
        
        This FormatHandler is registered with PyOpenGL on import of this module 
        to provide handling of VBO objects as array data-sources
        r   c                      y)z}Retrieve data-pointer from the instance's data

            Is always NULL, to indicate use of the bound pointer
            r   rQ   r'   instances     r   dataPointerzVBOHandler.dataPointer  s    
 r   Nc                     | j                   S )zAlways returns c_void_p(0))vp0r'   r   typeCodes      r   
from_paramzVBOHandler.from_param  s    88Or   c                     t        d      )zNot implementedz!Don't have VBO output support yet)ri   )r'   dimsr   s      r   zeroszVBOHandler.zeros  s     "IKKr   c                     |S )z.Given a value, convert to array representationrQ   r'   rb   r   s      r   rj   zVBOHandler.asArray  s    Lr   c                 @    t        j                  |j                        S )z=Given a value, guess OpenGL type of the corresponding pointer)r   arrayToGLTyper[   ra   s     r   r   zVBOHandler.arrayToGLType  s     ..

<<r   c                 @    t        j                  |j                        S r   )r   rf   r[   ra   s     r   rf   zVBOHandler.arrayByteCount  s     //==r   c                 @    t        j                  |j                        S )z6Given a data-value, calculate dimensions for the array)r   	arraySizer[   r   s      r   r   zVBOHandler.arraySize  s     **EJJ88r   c                 @    t        j                  |j                        S )z-Determine unit size of an array (if possible))r   unitSizer[   r   s      r   r   zVBOHandler.unitSize  s     ))5::77r   c                 @    t        j                  |j                        S )z<Determine dimensions of the passed array value (if possible))r   
dimensionsr[   r   s      r   r   zVBOHandler.dimensions  s     ++UZZ99r   r   )rI   rJ   rK   rL   ctypesc_void_pr   r   r   r   onesrj   r   rf   r   r   r   rQ   r   r   r   r   {  sN    	
 fooq"			L 		=	>	9	8	:r   r   c                       e Zd ZdZd ZddZy)rT   zHandles VBOOffset instances passed in as array data
        
        Registered on module import to provide support for VBOOffset instances 
        as sources for array data.
        c                     |j                   S )zaRetrieve data-pointer from the instance's data

            returns instance' offset
            )r   r   s     r   r   zVBOOffsetHandler.dataPointer  s    
 ??"r   Nc                 @    t        j                  |j                        S )z%Returns a c_void_p( instance.offset ))r   r   r   r   s      r   r   zVBOOffsetHandler.from_param  s    ??HOO55r   r   )rI   rJ   rK   rL   r   r   rQ   r   r   rT   rT     s    	
	#	6r   rT   c                       fd}|S )z=Construct a mapped-array cleaner function to unmap vbo.targetc                     	 t         j                         j                  j                  j                         y # t
        $ r
}Y d }~y d }~ww xY wr   )	_cleanersr6   r   glUnmapBufferrY   	Exception)r|   r@   r   s     r   cleanz_cleaner.<locals>.clean  sC    	;MM3  ,,cjj:  		s   > 	AArQ   )r   r   s   ` r   _cleanerr     s    ; Lr   c                 D   ddl m} | j                  j                  | j                  |      }t        j                  |t        j                  t
        j                  | j                  z              } ||d      }t        j                  |t        |             t        | <   |S )ax  Map the given buffer into a numpy array...

    Method taken from:
     http://www.mail-archive.com/numpy-discussion@lists.sourceforge.net/msg01161.html

    This should be considered an *experimental* API,
    it is not guaranteed to be available in future revisions
    of this library!
    
    Simplification to use ctypes cast from comment by 'sashimi' on my blog...
    r   )
frombufferB)numpyr   r   glMapBufferrY   r   castPOINTERc_byter\   r{   r|   r   r   )r   accessr   vpvp_arrayrp   s         r   r   r     st     !				'	'V	=B {{2v~~fmmCHH.DEGH#'E[[%39IcNLr   )i  )%rL   OpenGL.arrays.arraydatatyper   OpenGL.arrays.formathandlerr   OpenGL.raw.GLr   OpenGLr   OpenGL._bytesr   r   r	   r   logging	getLogger_logr
   r   r{   __all__objectr   r   rR   r   ACCELERATE_AVAILABLEOpenGL_accelerate.vborS   r   rT   ImportErrorr@   warningr   r   r   rQ   r   r   <module>r      s   @ 6 5    0 0 w-/ - 
'Qf Qf $66  $
))
	
 	
 ;Qv Qf>V >4$:m $:L6J 6  		i	  
C	
 	

s   9B= =CCC