当前位置: 首页>>代码示例>>Python>>正文


Python VBO.bind方法代码示例

本文整理汇总了Python中OpenGL.arrays.vbo.VBO.bind方法的典型用法代码示例。如果您正苦于以下问题:Python VBO.bind方法的具体用法?Python VBO.bind怎么用?Python VBO.bind使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在OpenGL.arrays.vbo.VBO的用法示例。


在下文中一共展示了VBO.bind方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: VolumeObject

# 需要导入模块: from OpenGL.arrays.vbo import VBO [as 别名]
# 或者: from OpenGL.arrays.vbo.VBO import bind [as 别名]
class VolumeObject(object):

    def __init__(self, stack, spacing):
        self.active = True
        self.stack_object = StackObject(stack, spacing)
        shape = self.stack_object.shape

        self.vao = glGenVertexArrays(1)
        glBindVertexArray(self.vao)

        tl = np.array((shape[2]*spacing[0],   # x
                       shape[1]*spacing[1],   # y
                       shape[0]*spacing[2]))  # z

        # Vertex buffer: corners of cube.
        # x, y, z, texture_x, texture_y, texture_z
        vb = [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0],  # Corner 0.
              [tl[0], 0.0, 0.0, 1.0, 0.0, 0.0],
              [0.0, tl[1], 0.0, 0.0, 1.0, 0.0],
              [tl[0], tl[1], 0.0, 1.0, 1.0, 0.0],
              [0.0, 0.0, tl[2], 0.0, 0.0, 1.0],
              [tl[0], 0.0, tl[2], 1.0, 0.0, 1.0],
              [0.0, tl[1], tl[2], 0.0, 1.0, 1.0],
              [tl[0], tl[1], tl[2], 1.0, 1.0, 1.0]]  # Corner 7.

        vb = np.array(vb, dtype=np.float32)
        vb = vb.flatten()

        # Triangles of cube.
        idx_out = np.array([[0, 2, 1], [2, 3, 1],  # Triangle 0, triangle 1.
                            [1, 4, 0], [1, 5, 4],
                            [3, 5, 1], [3, 7, 5],
                            [2, 7, 3], [2, 6, 7],
                            [0, 6, 2], [0, 4, 6],
                            [5, 6, 4], [5, 7, 6]],  # Triangle 10, triangle 11.
                           dtype=np.uint32)

        self.vtVBO = VBO(vb)
        self.vtVBO.bind()

        sc = 1.0/la.norm(tl)
        c = 0.5*tl

        self.transform = np.array(((sc, 0.0, 0.0, -sc*c[0]),
                                   (0.0, sc, 0.0, -sc*c[1]),
                                   (0.0, 0.0, sc, -sc*c[2]),
                                   (0.0, 0.0, 0.0, 1.0)))

        self.tex_transform = np.array(((1.0/tl[0], 0.0, 0.0, 0.0),
                                       (0.0, 1.0/tl[1], 0.0, 0.0),
                                       (0.0, 0.0, 1.0/tl[2], 0.0),
                                       (0.0, 0.0, 0.0, 1.0)))

        glBindVertexArray(0)

        self.elVBO = VBO(idx_out, target=GL_ELEMENT_ARRAY_BUFFER)
        self.elCount = len(idx_out.flatten())

    def update_stack(self, stack):
        self.stack_object.update_stack(stack)
开发者ID:jfozard,项目名称:pyvol,代码行数:62,代码来源:renderer.py

示例2: bind

# 需要导入模块: from OpenGL.arrays.vbo import VBO [as 别名]
# 或者: from OpenGL.arrays.vbo.VBO import bind [as 别名]
 def bind(self):
     """
     bind the vbo to the gl context.
     needs to be done before accessing the vbo.
     """
     GLVBO.bind(self)
     for att in self.attributes:
         gl.glEnableVertexAttribArray( att.location )
开发者ID:daniel-,项目名称:python-gl-engine,代码行数:10,代码来源:vbo.py

示例3: RenderBatch

# 需要导入模块: from OpenGL.arrays.vbo import VBO [as 别名]
# 或者: from OpenGL.arrays.vbo.VBO import bind [as 别名]
class RenderBatch(object):
    def __init__(self, draw_type=GL_QUADS):
        self.count = 0
        self.color_data = []
        self.position_data = []
        self.color_buffer = VBO(np.array([]))
        self.position_buffer = VBO(np.array([]))

        self.draw_type = draw_type


    def draw2d(self, points, color=(0, 0, 0, 1), rotation=0, center=(0, 0)):
        n = len(points)
        self.count += n

        if not isinstance(color[0], (tuple, list)):
            color = [color]*n

        if rotation:
            transform = psi.calc.rotation_matrix(rotation)

            temp = np.array(points) - center
            temp = transform.dot(temp.T).T + center
            points = temp.tolist()

        self.color_data.extend(color)
        self.position_data.extend(points)

    def clear(self):
        self.position_data = []
        self.color_data = []
        self.count = 0

    def render(self):
        self.color_buffer.set_array(np.array(self.color_data, dtype='float32'))
        self.position_buffer.set_array(np.array(self.position_data, dtype='float32'))

        self.color_buffer.bind()
        glColorPointer(4, GL_FLOAT, 0, self.color_buffer)

        self.position_buffer.bind()
        glVertexPointer(2, GL_FLOAT, 0, self.position_buffer)

        glEnableClientState(GL_VERTEX_ARRAY)
        glEnableClientState(GL_COLOR_ARRAY)
        glDrawArrays(self.draw_type, 0, self.count)
        glDisableClientState(GL_COLOR_ARRAY)
        glDisableClientState(GL_VERTEX_ARRAY)
开发者ID:renatopp,项目名称:psi-robotics,代码行数:50,代码来源:render_batch.py

示例4: RenderBatchOpt

# 需要导入模块: from OpenGL.arrays.vbo import VBO [as 别名]
# 或者: from OpenGL.arrays.vbo.VBO import bind [as 别名]
class RenderBatchOpt(object):
    def __init__(self, draw_type=GL_QUADS):
        self.count = 0
        self.color_buffer = VBO(np.array([]))
        self.vertex_buffer = VBO(np.array([]))
        self.draw_type = draw_type


    def draw2d(self, points, color=(0, 0, 0, 1), rotation=0, center=(0, 0)):
        n = points.shape[0]
        self.count += n

        if rotation:
            transform = psi.calc.rotation_matrix(rotation)

            temp = points - center
            temp = transform.dot(temp.T).T + center
            points = temp.tolist()

        self.color_buffer.set_array(color)
        self.vertex_buffer.set_array(points)

    def clear(self):
        self.color_buffer.set_array(np.array([]))
        self.vertex_buffer.set_array(np.array([]))
        self.count = 0

    def render(self):
        self.color_buffer.bind()
        glColorPointer(4, GL_FLOAT, 0, self.color_buffer)

        self.vertex_buffer.bind()
        glVertexPointer(2, GL_FLOAT, 0, self.vertex_buffer)

        glEnableClientState(GL_VERTEX_ARRAY)
        glEnableClientState(GL_COLOR_ARRAY)
        glDrawArrays(self.draw_type, 0, self.count)
        glDisableClientState(GL_COLOR_ARRAY)
        glDisableClientState(GL_VERTEX_ARRAY)
开发者ID:renatopp,项目名称:psi-robotics,代码行数:41,代码来源:render_batch.py

示例5: MeshObject

# 需要导入模块: from OpenGL.arrays.vbo import VBO [as 别名]
# 或者: from OpenGL.arrays.vbo.VBO import bind [as 别名]
class MeshObject(object):
    def __init__(self, fn, spacing):
        self.active = True
        m = GLMesh()
        self.mesh = m
        sc = m.load_ply(fn)
        v_out, n_out, col_out, idx_out = m.generate_arrays()

        vb = np.concatenate((v_out, n_out, col_out), axis=1)
        self.elVBO = VBO(idx_out, target=GL_ELEMENT_ARRAY_BUFFER)
        self.elCount = len(idx_out.flatten())

        self.vao = glGenVertexArrays(1)
        glBindVertexArray(self.vao)
        self.vtVBO = VBO(vb)
        self.vtVBO.bind()

        glBindVertexArray(0)

        c = np.array((0, 0, 0))
        self.transform = np.array(((sc, 0.0, 0.0, -sc*c[0]),
                                   (0.0, sc, 0.0, -sc*c[1]),
                                   (0.0, 0.0, sc, -sc*c[2]),
                                   (0.0, 0.0, 0.0, 1.0)))
开发者ID:jfozard,项目名称:pyvol,代码行数:26,代码来源:renderer.py

示例6: StlModel

# 需要导入模块: from OpenGL.arrays.vbo import VBO [as 别名]
# 或者: from OpenGL.arrays.vbo.VBO import bind [as 别名]
class StlModel(Model):
    """
    Model for displaying and manipulating STL data.
    """
    def load_data(self, model_data, callback=None):
        t_start = time.time()

        vertices, normals = model_data
        # convert python lists to numpy arrays for constructing vbos
        self.vertices = numpy.require(vertices, 'f')
        self.normals  = numpy.require(normals, 'f')

        self.scaling_factor = 1.0
        self.rotation_angle = {
            self.AXIS_X: 0.0,
            self.AXIS_Y: 0.0,
            self.AXIS_Z: 0.0,
        }

        self.mat_specular   = (1.0, 1.0, 1.0, 1.0)
        self.mat_shininess  = 50.0
        self.light_position = (20.0, 20.0, 20.0)

        self.initialized = False

        t_end = time.time()

        logging.info('Initialized STL model in %.2f seconds' % (t_end - t_start))
        logging.info('Vertex count: %d' % len(self.vertices))

    def normal_data_empty(self):
        """
        Return true if the model has no normal data.
        """
        empty = (self.normals.max() == 0 and self.normals.min() == 0)
        return empty

    def calculate_normals(self):
        """
        Calculate surface normals for model vertices.
        """
        a = self.vertices[0::3] - self.vertices[1::3]
        b = self.vertices[1::3] - self.vertices[2::3]
        cross = numpy.cross(a, b)

        # normalize the cross product
        magnitudes = numpy.apply_along_axis(numpy.linalg.norm, 1, cross).reshape(-1, 1)
        normals = cross / magnitudes

        # each of 3 facet vertices shares the same normal
        normals = normals.repeat(3, 0)
        return normals

    # ------------------------------------------------------------------------
    # DRAWING
    # ------------------------------------------------------------------------

    def init(self):
        """
        Create vertex buffer objects (VBOs).
        """
        self.vertex_buffer = VBO(self.vertices, 'GL_STATIC_DRAW')

        if self.normal_data_empty():
            logging.info('STL model has no normal data')
            self.normals = self.calculate_normals()

        self.normal_buffer = VBO(self.normals, 'GL_STATIC_DRAW')
        self.initialized = True

    def draw_facets(self):
        glPushMatrix()

        glEnable(GL_LIGHT0)
        glEnable(GL_LIGHT1)
        glShadeModel(GL_SMOOTH)

        # material properties (white plastic)
        glMaterial(GL_FRONT, GL_AMBIENT, (0.0, 0.0, 0.0, 1.0))
        glMaterial(GL_FRONT, GL_DIFFUSE, (0.55, 0.55, 0.55, 1.0))
        glMaterial(GL_FRONT, GL_SPECULAR, (0.7, 0.7, 0.7, 1.0))
        glMaterial(GL_FRONT, GL_SHININESS, 32.0)

        # lights properties
        glLight(GL_LIGHT0, GL_AMBIENT, (0.3, 0.3, 0.3, 1.0))
        glLight(GL_LIGHT0, GL_DIFFUSE, (0.3, 0.3, 0.3, 1.0))
        glLight(GL_LIGHT1, GL_DIFFUSE, (0.3, 0.3, 0.3, 1.0))

        # lights position
        glLightfv(GL_LIGHT0, GL_POSITION, self.light_position)
        glLightfv(GL_LIGHT1, GL_POSITION, (-20.0, -20.0, 20.0))

        glColor(1.0, 1.0, 1.0)

        ### VBO stuff

        self.vertex_buffer.bind()
        glVertexPointer(3, GL_FLOAT, 0, None)
        self.normal_buffer.bind()
        glNormalPointer(GL_FLOAT, 0, None)
#.........这里部分代码省略.........
开发者ID:kefir-,项目名称:tatlin,代码行数:103,代码来源:actors.py

示例7: instancingdemo

# 需要导入模块: from OpenGL.arrays.vbo import VBO [as 别名]
# 或者: from OpenGL.arrays.vbo.VBO import bind [as 别名]
class instancingdemo(df.demoplate):
    
    def init(self):
        print "OpenGL Information:"
        for prop in ["GL_VENDOR", "GL_RENDERER", "GL_VERSION", "GL_SHADING_LANGUAGE_VERSION"]:
            print "\t%s = %s" % (prop, glGetString(globals()[prop]))

        
        self.campos = np.array([2.5, 1.5, 1.5, 1], dtype = np.float32)
        self.center = np.array([0.0,0.0,0.0,1.0], dtype = np.float32)
        
        self.perspective_mat = None
        self.mvp = None
        # OpenGL Stuff
        glEnable(GL_DEPTH_TEST)
        #glEnable(GL_CULL_FACE)
        glClearColor(1, 1, 1, 0)
        glPointSize(5)
        # Shader Stuff.
        with open('shader.fs') as fs, open('shader.vs') as vs:            
            self.shader = su.Shader(list(vs), list(fs))
        
        self.shader.bindfragdata(0, 'fragcolor')
        self.mvploc = self.shader.uniformlocation('mvp')
        self.objploc = self.shader.uniformlocation('objp')
        self.objoffsetloc = self.shader.uniformlocation('objoffset')
        self.positionloc = self.shader.attributelocation('vs_position')
        self.normalloc = self.shader.attributelocation('vs_normal')
        
        self.loadsquirrel()
        self.buildobjoffsets()
        
    def buildobjoffsets(self):
        objoffset = np.zeros((5,5,5,4), dtype = np.float32)
        start = np.array([-1, -1, -1, 0], dtype = np.float32)
        steps = np.arange(0, 2.1, 0.5, dtype = np.float32)
        for x in range(5):
            for y in range(5):
                for z in range(5):
                    objoffset[x,y,z,] = start + np.array([steps[x], steps[y], steps[z], 0], dtype = np.float32)
        self.shader.use()
        glUniform4fv(self.objoffsetloc, 5 * 5 * 5, objoffset.flatten().tolist())
                
    def loadsquirrel(self):
        # When loading the data, pad the normals to 4 floats (16bytes) since GPUs hate unaligned memory.
        obj = wf.ObjFileParser("squirrel.obj", padnormals = 4)
        self.objscale = 1 / np.max(obj.scale / 2)
        self.objcenter = obj.minpos + (obj.scale / 2)
        
        self.obj_mat = hm.scale(hm.identity(),
                                [self.objscale * 0.2] * 3)
        self.obj_mat = hm.translation(self.obj_mat,
                                      -self.objcenter)

        # Generate a GL compatible indexed vertex buffer for the object
        self.vbdata, ibdata = obj.generateIndexedBuffer([0,1], np.uint16)
        vbdata = self.vbdata
        self.elementnum = np.shape(ibdata)[0]
        # VAO
        self.vertobj = glGenVertexArrays(1)
        glBindVertexArray(self.vertobj)
        # Setup the VBO for the vertex data.
        self.vertbuf = VBO(vbdata, GL_STATIC_DRAW, GL_ARRAY_BUFFER)
        self.vertbuf.bind()
        glVertexAttribPointer(self.positionloc, 4, GL_FLOAT, GL_TRUE, 8 * 4, ctypes.c_void_p(0))
        glVertexAttribPointer(self.normalloc, 4, GL_FLOAT, GL_TRUE, 8 * 4, ctypes.c_void_p(16))
        glEnableVertexAttribArray(self.positionloc)
        glEnableVertexAttribArray(self.normalloc)
        # Indexbuffer
        self.indexbuf = VBO(ibdata, GL_STATIC_DRAW, GL_ELEMENT_ARRAY_BUFFER)
        self.indexbuf.bind()
        
        glBindVertexArray(0)
        self.vertbuf.unbind()
        self.indexbuf.unbind()
        #Animation init...
        self.rotation = 0

                
    def resize(self, width, height):
        glViewport(0, 0, width, height)
        self.perspective_mat = hm.perspective(hm.identity(),
                                              60,
                                              float(width) / height,
                                              0.1,
                                              6.0)
        self.modelview_mat = hm.lookat(hm.identity(),
                                       self.campos,
                                       self.center)
        
        self.mvp = np.dot(self.perspective_mat, self.modelview_mat)
    
    def display(self, timediff):

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        self.shader.use()
        glUniformMatrix4fv(self.objploc, 1, GL_TRUE,
                           np.dot(hm.rotation(hm.identity(), self.rotation, [0,1,0]), self.obj_mat).tolist())
        glUniformMatrix4fv(self.mvploc, 1, GL_TRUE,
                           hm.rotation(self.mvp, self.rotation / 4, [0.577350269189626] * 3).tolist())
#.........这里部分代码省略.........
开发者ID:rpls,项目名称:instancing,代码行数:103,代码来源:main.py

示例8: GcodeModel

# 需要导入模块: from OpenGL.arrays.vbo import VBO [as 别名]
# 或者: from OpenGL.arrays.vbo.VBO import bind [as 别名]

#.........这里部分代码省略.........
        # for every pair of vertices of the model, there are 3 vertices for the arrow
        assert len(self.arrows) == ((len(self.vertices) // 2) * 3), \
            'The 2:3 ratio of model vertices to arrow vertices does not hold.'

        self.max_layers         = len(self.layer_stops) - 1
        self.num_layers_to_draw = self.max_layers
        self.arrows_enabled     = True
        self.initialized        = False

        t_end = time.time()

        logging.info('Initialized Gcode model in %.2f seconds' % (t_end - t_start))
        logging.info('Vertex count: %d' % len(self.vertices))

    def movement_color(self, move):
        """
        Return the color to use for particular type of movement.
        """
        # default movement color is gray
        color = [0.6, 0.6, 0.6, 0.6]

        extruder_on = (move.flags & Movement.FLAG_EXTRUDER_ON or
                       move.delta_e > 0)
        outer_perimeter = (move.flags & Movement.FLAG_PERIMETER and
                           move.flags & Movement.FLAG_PERIMETER_OUTER)

        if extruder_on and outer_perimeter:
            color = [0.0, 0.875, 0.875, 0.6] # cyan
        elif extruder_on and move.flags & Movement.FLAG_PERIMETER:
            color = [0.0, 1.0, 0.0, 0.6] # green
        elif extruder_on and move.flags & Movement.FLAG_LOOP:
            color = [1.0, 0.875, 0.0, 0.6] # yellow
        elif extruder_on:
            color = [1.0, 0.0, 0.0, 0.6] # red

        return color

    # ------------------------------------------------------------------------
    # DRAWING
    # ------------------------------------------------------------------------

    def init(self):
        self.vertex_buffer       = VBO(self.vertices, 'GL_STATIC_DRAW')
        self.vertex_color_buffer = VBO(self.colors.repeat(2, 0), 'GL_STATIC_DRAW') # each pair of vertices shares the color

        if self.arrows_enabled:
            self.arrow_buffer       = VBO(self.arrows, 'GL_STATIC_DRAW')
            self.arrow_color_buffer = VBO(self.colors.repeat(3, 0), 'GL_STATIC_DRAW') # each triplet of vertices shares the color

        self.initialized = True

    def display(self, mode_2d=False):
        glPushMatrix()
        glTranslate(self.offset_x, self.offset_y, 0)
        glEnableClientState(GL_VERTEX_ARRAY)
        glEnableClientState(GL_COLOR_ARRAY)

        self._display_movements(mode_2d)

        if self.arrows_enabled:
            self._display_arrows()

        glDisableClientState(GL_COLOR_ARRAY)
        glDisableClientState(GL_VERTEX_ARRAY)
        glPopMatrix()

    def _display_movements(self, mode_2d=False):
        self.vertex_buffer.bind()
        glVertexPointer(3, GL_FLOAT, 0, None)

        self.vertex_color_buffer.bind()
        glColorPointer(4, GL_FLOAT, 0, None)

        if mode_2d:
            glScale(1.0, 1.0, 0.0) # discard z coordinates
            start = self.layer_stops[self.num_layers_to_draw - 1]
            end   = self.layer_stops[self.num_layers_to_draw] - start
        else: # 3d
            start = 0
            end   = self.layer_stops[self.num_layers_to_draw]

        glDrawArrays(GL_LINES, start, end)

        self.vertex_buffer.unbind()
        self.vertex_color_buffer.unbind()

    def _display_arrows(self):
        self.arrow_buffer.bind()
        glVertexPointer(3, GL_FLOAT, 0, None)

        self.arrow_color_buffer.bind()
        glColorPointer(4, GL_FLOAT, 0, None)

        start = (self.layer_stops[self.num_layers_to_draw - 1] // 2) * 3
        end   = (self.layer_stops[self.num_layers_to_draw] // 2) * 3

        glDrawArrays(GL_TRIANGLES, start, end - start)

        self.arrow_buffer.unbind()
        self.arrow_color_buffer.unbind()
开发者ID:kefir-,项目名称:tatlin,代码行数:104,代码来源:actors.py

示例9: GcodeModel

# 需要导入模块: from OpenGL.arrays.vbo import VBO [as 别名]
# 或者: from OpenGL.arrays.vbo.VBO import bind [as 别名]

#.........这里部分代码省略.........
        self.vertex_color_buffer = VBO(self.colors.repeat(2, 0), 'GL_STATIC_DRAW') # each pair of vertices shares the color

        if self.arrows_enabled:
            self.arrow_buffer       = VBO(self.arrows, 'GL_STATIC_DRAW')
            self.arrow_color_buffer = VBO(self.colors.repeat(3, 0), 'GL_STATIC_DRAW') # each triplet of vertices shares the color

        self.layer_marker_buffer = VBO(self.layer_markers, 'GL_STATIC_DRAW')

        self.initialized = True

    def display(self, elevation=0, eye_height=0, mode_ortho=False, mode_2d=False):
        glPushMatrix()

        offset_z = self.offset_z if not mode_2d else 0
        glTranslate(self.offset_x, self.offset_y, offset_z)

        glEnableClientState(GL_VERTEX_ARRAY)
        glEnableClientState(GL_COLOR_ARRAY)

        self._display_movements(elevation, eye_height, mode_ortho, mode_2d)

        if self.arrows_enabled:
            self._display_arrows()

        glDisableClientState(GL_COLOR_ARRAY)

        if self.arrows_enabled:
            self._display_layer_markers()

        glDisableClientState(GL_VERTEX_ARRAY)
        glPopMatrix()

    def _display_movements(self, elevation=0, eye_height=0, mode_ortho=False, mode_2d=False):
        self.vertex_buffer.bind()
        glVertexPointer(3, GL_FLOAT, 0, None)

        self.vertex_color_buffer.bind()
        glColorPointer(4, GL_FLOAT, 0, None)

        if mode_2d:
            glScale(1.0, 1.0, 0.0) # discard z coordinates
            start = self.layer_stops[self.num_layers_to_draw - 1]
            end   = self.layer_stops[self.num_layers_to_draw]

            glDrawArrays(GL_LINES, start, end - start)

        elif mode_ortho:
            if elevation >= 0:
                # draw layers in normal order, bottom to top
                start = 0
                end   = self.layer_stops[self.num_layers_to_draw]

                glDrawArrays(GL_LINES, start, end - start)

            else:
                # draw layers in reverse order, top to bottom
                stop_idx = self.num_layers_to_draw - 1
                while stop_idx >= 0:
                    start = self.layer_stops[stop_idx]
                    end   = self.layer_stops[stop_idx + 1]

                    glDrawArrays(GL_LINES, start, end - start)

                    stop_idx -= 1

        else: # 3d projection mode
开发者ID:SHINOTECH,项目名称:tatlin,代码行数:70,代码来源:actors.py

示例10: GcodeModel

# 需要导入模块: from OpenGL.arrays.vbo import VBO [as 别名]
# 或者: from OpenGL.arrays.vbo.VBO import bind [as 别名]

#.........这里部分代码省略.........

                arrow = self.arrow
                # position the arrow with respect to movement
                arrow = vector.rotate(arrow, movement.angle(), 0.0, 0.0, 1.0)
                arrow_list.extend(arrow)

                vertex_color = self.movement_color(movement)
                color_list.append(vertex_color)

            self.layer_stops.append(len(vertex_list))

        self.vertices = numpy.array(vertex_list, 'f')
        self.colors = numpy.array(color_list, 'f')
        self.arrows = numpy.array(arrow_list, 'f')
        # by translating the arrow vertices outside of the loop, we achieve a
        # significant performance gain thanks to numpy. it would be really nice
        # if we could rotate in a similar fashion...
        self.arrows = self.arrows + self.vertices[1::2].repeat(3, 0)

        # for every pair of vertices of the model, there are 3 vertices for the arrow
        assert len(self.arrows) == ((len(self.vertices) // 2) * 3), \
            'The 2:3 ratio of model vertices to arrow vertices does not hold.'

    def movement_color(self, movement):
        """
        Return the color to use for particular type of movement.
        """
        if not movement.extruder_on:
            color = self.color_map['gray']
        elif movement.is_loop:
            color = self.color_map['yellow']
        elif movement.is_perimeter and movement.is_perimeter_outer:
            color = self.color_map['cyan']
        elif movement.is_perimeter:
            color = self.color_map['green']
        else:
            color = self.color_map['red']

        return color

    # ------------------------------------------------------------------------
    # DRAWING
    # ------------------------------------------------------------------------

    def init(self):
        self.vertex_buffer       = VBO(self.vertices, 'GL_STATIC_DRAW')
        self.vertex_color_buffer = VBO(self.colors.repeat(2, 0), 'GL_STATIC_DRAW') # each pair of vertices shares the color

        if self.arrows_enabled:
            self.arrow_buffer       = VBO(self.arrows, 'GL_STATIC_DRAW')
            self.arrow_color_buffer = VBO(self.colors.repeat(3, 0), 'GL_STATIC_DRAW') # each triplet of vertices shares the color

        self.initialized = True

    def display(self, mode_2d=False):
        glEnableClientState(GL_VERTEX_ARRAY)
        glEnableClientState(GL_COLOR_ARRAY)

        self._display_movements(mode_2d)

        if self.arrows_enabled:
            self._display_arrows()

        glDisableClientState(GL_COLOR_ARRAY)
        glDisableClientState(GL_VERTEX_ARRAY)

    def _display_movements(self, mode_2d=False):
        self.vertex_buffer.bind()
        glVertexPointer(3, GL_FLOAT, 0, None)

        self.vertex_color_buffer.bind()
        glColorPointer(4, GL_FLOAT, 0, None)

        if mode_2d:
            glScale(1.0, 1.0, 0.0) # discard z coordinates
            start = self.layer_stops[self.num_layers_to_draw - 1]
            end   = self.layer_stops[self.num_layers_to_draw] - start
        else: # 3d
            start = 0
            end   = self.layer_stops[self.num_layers_to_draw]

        glDrawArrays(GL_LINES, start, end)

        self.vertex_buffer.unbind()
        self.vertex_color_buffer.unbind()

    def _display_arrows(self):
        self.arrow_buffer.bind()
        glVertexPointer(3, GL_FLOAT, 0, None)

        self.arrow_color_buffer.bind()
        glColorPointer(4, GL_FLOAT, 0, None)

        start = (self.layer_stops[self.num_layers_to_draw - 1] // 2) * 3
        end   = (self.layer_stops[self.num_layers_to_draw] // 2) * 3

        glDrawArrays(GL_TRIANGLES, start, end - start)

        self.arrow_buffer.unbind()
        self.arrow_color_buffer.unbind()
开发者ID:jmil,项目名称:tatlin,代码行数:104,代码来源:actors.py

示例11: __init__

# 需要导入模块: from OpenGL.arrays.vbo import VBO [as 别名]
# 或者: from OpenGL.arrays.vbo.VBO import bind [as 别名]
class PolygonVBOPair:
    __RESTART_INDEX = 2 ** 32 - 1

    def __init__(self, view):
        """
        :type gls: pcbre.ui.gl.glshared.GLShared
        :param gls:
        :return:
        """
        self.__view = view
        self.__gls = view.gls

        self.__position_list = []
        self.__position_lookup = {}

        # Known_polys is a list of (start,end) indicies in self.__index_list
        self.__tri_draw_ranges = {}
        self.__outline_draw_ranges = {}

        self.__tri_index_list = []
        self.__outline_index_list = []

        self.__vert_vbo_current = False
        self.__index_vbo_current = False

        self.restart()
        

    def restart(self):
        self.__deferred_tri_render_ranges = defaultdict(list)
        self.__deferred_line_render_ranges = defaultdict(list)

        
    def initializeGL(self):
        self.__vao = VAO()

        # Lookup for vertex positions
        self.__vert_vbo_dtype = numpy.dtype([("vertex", numpy.float32, 2)])
        self.__vert_vbo = VBO(numpy.ndarray(0, dtype=self.__vert_vbo_dtype),
                              GL.GL_DYNAMIC_DRAW)
        self.__vert_vbo_current = False

        self.__index_vbo_dtype = numpy.uint32
        self.__index_vbo = VBO(numpy.ndarray(0, dtype=self.__index_vbo_dtype), GL.GL_DYNAMIC_DRAW, GL.GL_ELEMENT_ARRAY_BUFFER)
        self.__index_vbo_current = False

        self.__shader = self.__gls.shader_cache.get("vert2", "frag1")
        
        with self.__vao, self.__vert_vbo:
            vbobind(self.__shader, self.__vert_vbo_dtype, "vertex").assign()
            self.__index_vbo.bind()

    def __update_vert_vbo(self):
        if self.__vert_vbo_current or not len(self.__position_list):
            return

        ar = numpy.ndarray(len(self.__position_list), dtype=self.__vert_vbo_dtype)
        ar["vertex"] = self.__position_list
        self.__vert_vbo.data = ar
        self.__vert_vbo.size = None
        self.__vert_vbo.copied = False
        self.__vert_vbo.bind()
        self.__vert_vbo_current = True

    def __update_index_vbo(self):
        if self.__index_vbo_current or not len(self.__tri_index_list):
            return

        self.__outline_index_offset = len(self.__tri_index_list)
        self.__index_vbo.data = numpy.array(self.__tri_index_list + self.__outline_index_list, dtype=self.__index_vbo_dtype)
        self.__index_vbo.size = None
        self.__index_vbo.copied = False
        self.__index_vbo.bind()
        self.__index_vbo_current = True

    def __get_position_index(self, point):
        """
        Get the index in the point VBO for a given Point2 coordinate
        :type point: pcbre.matrix.Point2
        :param point:
        :return:
        """
        norm_pos = point.intTuple()

        try:
            return self.__position_lookup[norm_pos]
        except KeyError:
            self.__position_lookup[norm_pos] = len(self.__position_list)
            self.__position_list.append(norm_pos)
            self.__vert_vbo_current = False

        return self.__position_lookup[norm_pos]


    def __add(self, polygon):
        tris = polygon.get_tris_repr()
        tri_index_first = len(self.__tri_index_list)

        for t in tris:
            for p in t.a, t.b, t.c:
#.........这里部分代码省略.........
开发者ID:deactivated,项目名称:pcbre,代码行数:103,代码来源:cachedpolygonrenderer.py

示例12: __init__

# 需要导入模块: from OpenGL.arrays.vbo import VBO [as 别名]
# 或者: from OpenGL.arrays.vbo.VBO import bind [as 别名]
class _THBatch:
    def __init__(self, parent):
        self.parent = parent
        self.restart()
        self.initialized = False

    def restart(self):
        self.__deferred_list_filled = []
        self.__deferred_list_outline = []

    def _initializeGL(self):
        self.initialized = True

        self.__filled_vao = VAO()
        self.__outline_vao = VAO()

        with self.__filled_vao, self.parent._sq_vbo:
            vbobind(self.parent._filled_shader, self.parent._sq_vbo.data.dtype, "vertex").assign()

        # Use a fake array to get a zero-length VBO for initial binding
        filled_instance_array = numpy.ndarray(0, dtype=self.parent._filled_instance_dtype)
        self.filled_instance_vbo = VBO(filled_instance_array)

        with self.__filled_vao, self.filled_instance_vbo:
            vbobind(self.parent._filled_shader, self.parent._filled_instance_dtype, "pos", div=1).assign()
            vbobind(self.parent._filled_shader, self.parent._filled_instance_dtype, "r", div=1).assign()
            vbobind(self.parent._filled_shader, self.parent._filled_instance_dtype, "r_inside_frac_sq", div=1).assign()
            vbobind(self.parent._filled_shader, self.parent._filled_instance_dtype, "color", div=1).assign()

        with self.__outline_vao, self.parent._outline_vbo:
            vbobind(self.parent._outline_shader, self.parent._outline_vbo.data.dtype, "vertex").assign()

        # Build instance for outline rendering
        # We don't have an inner 'r' for this because we just do two instances per vertex

        # Use a fake array to get a zero-length VBO for initial binding
        outline_instance_array = numpy.ndarray(0, dtype=self.parent._outline_instance_dtype)
        self.outline_instance_vbo = VBO(outline_instance_array)

        with self.__outline_vao, self.outline_instance_vbo:
            vbobind(self.parent._outline_shader, self.parent._outline_instance_dtype, "pos", div=1).assign()
            vbobind(self.parent._outline_shader, self.parent._outline_instance_dtype, "r", div=1).assign()
            vbobind(self.parent._outline_shader, self.parent._outline_instance_dtype, "color", div=1).assign()

    def deferred(self, center, r1, r2, rs, render_hint=RENDER_HINT_NORMAL):
        if rs & RENDER_OUTLINES:
            self.__deferred_list_outline.append((center, r1, r2, rs))
        else:
            self.__deferred_list_filled.append((center, r1, r2, rs))

    def prepare(self):
        self.__prepare_filled()
        self.__prepare_outline()

    def __prepare_filled(self):
        if not self.initialized:
            self._initializeGL()

        count = len(self.__deferred_list_filled)
        self.__filled_count = count

        if count == 0:
            return

        # Resize instance data array
        instance_array = numpy.ndarray(count, dtype = self.parent._filled_instance_dtype)

        color_a = [0.6, 0.6, 0.6, 1]

        for n, (center, r1, r2, rs) in enumerate(self.__deferred_list_filled):

            # HACK, color object
            color_mod = self.parent.parent.sel_colormod(rs & RENDER_SELECTED, color_a)

            # frag shader uses pythag to determine is frag is within
            # shaded area. Precalculate comparison term
            r_frac_sq = (r2 / r1) ** 2
            instance_array[n] = (center, r1, r_frac_sq, color_mod)

        self.filled_instance_vbo.data = instance_array
        self.filled_instance_vbo.size = None
        self.filled_instance_vbo.copied = False
        self.filled_instance_vbo.bind()

    def __prepare_outline(self):
        count = 0
        for center, r1, r2, rs in self.__deferred_list_outline:
            if r2 == 0:
                count += 1
            else:
                count += 2

        self.__outline_count = count
        if count == 0:
            return


        # Resize instance data array
        instance_array = numpy.ndarray(count, dtype = self.parent._outline_instance_dtype)

#.........这里部分代码省略.........
开发者ID:0nelight,项目名称:pcbre,代码行数:103,代码来源:viaview.py

示例13: __init__

# 需要导入模块: from OpenGL.arrays.vbo import VBO [as 别名]
# 或者: from OpenGL.arrays.vbo.VBO import bind [as 别名]
class model:

    ''' class for STL file / 3d model '''

    def __init__(self, stl_data, batchh=None):
        ''' initialise model data'''
        vert, norm = stl_data
        self.vertices = numpy.array(vert, dtype=GLfloat)
        self.normals = numpy.array(norm, dtype=GLfloat)
        self.vertex_buffer = VBO(self.vertices, 'GL_STATIC_DRAW')
        self.normal_buffer = VBO(self.normals, 'GL_STATIC_DRAW')

        # calculate model scale
        self.corner = self.vertices.transpose().min(1)
        self.corner2 = self.vertices.transpose().max(1)
        self.scale = abs(self.corner) + abs(self.corner2)
        self.scale = max(self.scale[0], self.scale[1], self.scale[2])
        print 'STL File loaded in: ', loadtime
        print 'Object information'
        print 'corner 1: ', self.corner
        print 'corner 2: ', self.corner2
        print 'object scale: ', self.scale

    def draw(self):
        ''' draw model on screen '''
        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        glLoadIdentity()

        # center the model
        glTranslate(window.width/2, window.height/2, -150)

        # scale the model
        glScale(150/self.scale, 150/self.scale, 150/self.scale)

        # draw grid and coordinate lines
        draw_grid()
        draw_xyz(0, 0, 0, -20, -20)

        # demo rotation
        glRotate(rot, 1, 0, 0)
        glRotate(rot2, 0, 1, 0)
        glRotate(rot3, 0, 0, 1)

        self.vertex_buffer.bind()
        glVertexPointer(3, GL_FLOAT, 0, None)
        self.normal_buffer.bind()
        glNormalPointer(GL_FLOAT, 0, None)

        glEnableClientState(GL_VERTEX_ARRAY)
        glEnableClientState(GL_NORMAL_ARRAY)

        glDrawArrays(GL_TRIANGLES, 0, len(self.vertices))

        glDisableClientState(GL_NORMAL_ARRAY)
        glDisableClientState(GL_VERTEX_ARRAY)

        self.normal_buffer.unbind()
        self.vertex_buffer.unbind()

        glPopMatrix()
开发者ID:vluttine,项目名称:3d-printer-robot,代码行数:63,代码来源:gui.py

示例14: MSGLCanvas2D

# 需要导入模块: from OpenGL.arrays.vbo import VBO [as 别名]
# 或者: from OpenGL.arrays.vbo.VBO import bind [as 别名]

#.........这里部分代码省略.........
        reset the different translation to 0
        """
        self.trans_x_ =0.
        self.trans_y_ =0.
        self.counter_trans_x=0.
        self.counter_trans_y=0.
    
    
    
    def normalizeAngle(self,angle):
            while (angle < 0):
                    angle += 360 * 16
            while (angle > 360 * 16):
                    angle -= 360 * 16


########DRAWING METHODS##################################################

    def drawLine(self, point_, point):
        glBegin(GL_LINES)
        glVertex2d(point_.x(), point_.y())
        glVertex2d(point.x(), point.y())
        glEnd()
    
    def drawRect(self, p_1, p_2, p_3=None, p_4 = None):
        pass
    
    def drawOnePoint(self, point, colour= Qt.yellow):
        pass
    
    def scatterPlot(self):
        """ Draw Data (x, y)"""
        if self.vertexes is not None and self.colors is not None:
            self.vertexes.bind()
            glEnableClientState(GL_VERTEX_ARRAY)
            glVertexPointerf(self.vertexes)
            self.colors.bind()                  
            glEnableClientState(GL_COLOR_ARRAY)
            glColorPointerf(self.colors)
            glDrawArrays(GL_LINES, 0, len(self.vertexes))
            self.vertexes.unbind()
            self.colors.unbind()
            #self.textures.unbind()
            glDisableClientState(GL_VERTEX_ARRAY)
            glDisableClientState(GL_COLOR_ARRAY)
    
    def spectrumPlot(self, points):
        pass
    
    def histogramPlot(self, points, bin = 5.):
        pass
        
    def barPlot(points, width =2.):pass

    


########MOUSE AND KEYBOARDS EVENTS###########################################################################
    
    
    def wheelEvent(self, event):
        if event.delta() >0:
            self.zoom_ -= .05    
        else:
            self.zoom_ += .05
        glMatrixMode(GL_PROJECTION)
开发者ID:jerkos,项目名称:metms,代码行数:70,代码来源:MetGLCanvas2D.py

示例15: Mesh

# 需要导入模块: from OpenGL.arrays.vbo import VBO [as 别名]
# 或者: from OpenGL.arrays.vbo.VBO import bind [as 别名]
class Mesh(Component):
    meshes = dict()  # cache to reuse meshes
    
    @classmethod
    def fromXMLElement(cls, xmlElement, actor=None):
        return cls.getMesh(xmlElement.get('src', 'Empty'), actor)
        # NOTE If src attribute is not found in XML element, special 'Empty' mesh is used
    
    @classmethod
    def getMesh(cls, src, actor=None):
        if not src in cls.meshes:
            if src == 'Empty':
                cls.meshes[src] = EmptyMesh()  # special empty mesh to be used as a placeholder, and for empty actors
            else:
                cls.meshes[src] = Mesh(src)  # NOTE Meshes are currently shared, therefore not linked to individual actors
        return cls.meshes[src]
    
    def __init__(self, src, actor=None):
        Component.__init__(self, actor)

        # TODO Include a mesh name (e.g. 'Dragon') as ID as well as src (e.g. '../res/models/Dragon.obj')
        self.src = src
        self.filepath = Context.getInstance().getResourcePath('models', src)
        
        # OpenGL version-dependent code (NOTE assumes major version = 3)
        self.vao = None
        if Context.getInstance().GL_version_minor > 0:  # 3.1 (or greater?)
          self.vao = glGenVertexArrays(1)
        else:  # 3.0 (or less?)
          self.vao = GLuint(0)
          glGenVertexArrays(1, self.vao)
        glBindVertexArray(self.vao)

        self.loadModel(self.filepath)

        self.vbo = VBO(self.meshData, GL_STATIC_DRAW)
        self.vbo.bind()

        glEnableVertexAttribArray(0)
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6*4, self.vbo+0)

        glEnableVertexAttribArray(1)
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6*4, self.vbo+12)
        
        self.ebo = glGenBuffers(1)
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.ebo)
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, len(self.elements)*4, self.elements, GL_STATIC_DRAW)

    def loadModel(self, filename):
        f = open(filename, 'r')
        self.meshData = []
        self.elements = []
        vertices = []
        normals = []
        texCoords = []

        for line in f:
            s = line.split()
            if len(s) > 0:
                if s[0] == 'v':
                    v = np.array([s[1], s[2], s[3]], dtype = np.float32)
                    vertices.append(v)
                elif s[0] == 'vn':
                    v = np.array([s[1], s[2], s[3]], dtype = np.float32)
                    normals.append(v)
                elif s[0] == 'vt':
                    v = np.array([s[1], s[2]], dtype = np.float32)
                    texCoords.append(v)
                elif s[0] == 'f':
                    for i in xrange(1, 4):
                        l = s[i].split('/')
                        self.meshData.append(float(vertices[int(l[0]) - 1][0]))
                        self.meshData.append(float(vertices[int(l[0]) - 1][1]))
                        self.meshData.append(float(vertices[int(l[0]) - 1][2]))
                        self.meshData.append(float(normals[int(l[2]) - 1][0]))
                        self.meshData.append(float(normals[int(l[2]) - 1][1]))
                        self.meshData.append(float(normals[int(l[2]) - 1][2]))
                        self.elements.append(len(self.elements))

        self.meshData = np.array(self.meshData, dtype = np.float32)
        self.elements = np.array(self.elements, dtype = np.uint32)

    def render(self):
        glBindVertexArray(self.vao)
        glDrawElements(GL_TRIANGLES, self.elements.size, GL_UNSIGNED_INT, None)
    
    def toXMLElement(self):
        xmlElement = Component.toXMLElement(self)
        xmlElement.set('src', self.src)
        return xmlElement
    
    def toString(self, indent=""):
        return indent + "Mesh: { src: \"" + self.src + "\" }"
    
    def __str__(self):
        return self.toString()
开发者ID:Pallavistar,项目名称:pyTANG,代码行数:98,代码来源:Mesh.py


注:本文中的OpenGL.arrays.vbo.VBO.bind方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。