示例#1
0
def drawPoint(color, point, pointSize=3.0, isRound=True):
    """
    Draw a point using GL_POINTS.
    @param point: The x,y,z coordinate array/ vector of the point
    @type point: A or V
    @param pointSize: The point size to be used by glPointSize
    @type pointSize: float
    @param isRound: If True, the point will be drawn round otherwise square
    @type isRound: boolean
    """
    glDisable(GL_LIGHTING)
    glColor3fv(color)
    glPointSize(float(pointSize))
    if isRound:
        glEnable(GL_POINT_SMOOTH)
    glBegin(GL_POINTS)
    glVertex3fv(point)
    glEnd()
    if isRound:
        glDisable(GL_POINT_SMOOTH)

    glEnable(GL_LIGHTING)
    if pointSize != 1.0:
        glPointSize(1.0)
    return
示例#2
0
def drawPoint(color, 
              point, 
              pointSize = 3.0,
              isRound = True):
    """
    Draw a point using GL_POINTS. 
    @param point: The x,y,z coordinate array/ vector of the point 
    @type point: A or V
    @param pointSize: The point size to be used by glPointSize
    @type pointSize: float
    @param isRound: If True, the point will be drawn round otherwise square
    @type isRound: boolean
    """
    glDisable(GL_LIGHTING)
    glColor3fv(color)
    glPointSize(float(pointSize))
    if isRound:
        glEnable(GL_POINT_SMOOTH)
    glBegin(GL_POINTS)
    glVertex3fv(point)       
    glEnd()
    if isRound:
        glDisable(GL_POINT_SMOOTH)

    glEnable(GL_LIGHTING)
    if pointSize != 1.0:
        glPointSize(1.0)
    return
示例#3
0
 def draw(self, i):
     glPointSize(7.0)
     glBegin(GL_POINTS)
     glColor3f(self.particles[i].r, self.particles[i].g,
               self.particles[i].b)
     glVertex3f(self.particles[i].x, self.particles[i].y,
                self.particles[i].z)
     glEnd()
示例#4
0
 def draw_doms(self, size=3):
     glPushMatrix()
     glPointSize(size)
     glColor3f(1.0, 1.0, 1.0)
     glBegin(GL_POINTS)
     for position in self.dom_positions:
         glVertex3f(position[0], position[1], position[2])
     glEnd()
     glPopMatrix()
示例#5
0
    def display(self):
        if self.world:
            self.world.drawGL()

        glPointSize(max(1, self.point_size))
        for point_list in self.point_lists:
            glCallList(point_list)

        for xform in self.xforms:
            gldraw.xform_widget(xform, 0.1, 0.01)
 def dibujar_puntos(self, cuadrante: str):
     for i in range(self.programa.lista_puntos.count()):
         punto = self.programa.lista_puntos.itemWidget(
             self.programa.lista_puntos.item(i))
         if punto.render.isChecked() and punto.cuadrante == cuadrante:
             glColor(punto.color)
             glPointSize(punto.grosor)
             glEnable(GL_POINT_SMOOTH)
             glBegin(GL_POINTS)
             glVertex(punto.x, punto.y, punto.z)
             glEnd()
示例#7
0
def paintLine(points, numsteps=None, **kwargs):
    '''Paint a line with current brush
    ::

        set_brush("mybrush.png", 10)
        paintLine((0, 0, 20, 50))
        paintLine((1, 2, 1, 5, 4, 6, 8, 7))

    '''
    if not __brush_texture:
        pymt.pymt_logger.warning('Graphx: No brush set to paint line, abort')
        return
    if len(points) % 2 == 1:
        raise Exception('Points list must be a pair length number (not impair)')
    kwargs.setdefault('sfactor', GL_SRC_ALPHA)
    kwargs.setdefault('dfactor', GL_ONE_MINUS_SRC_ALPHA)
    blending = GlBlending(sfactor=kwargs.get('sfactor'),
                          dfactor=kwargs.get('dfactor'))
    with DO(blending, gx_enable(GL_POINT_SPRITE_ARB),
            gx_enable(__brush_texture.target)):

        # prepare env
        set_texture(__brush_texture.id, target=__brush_texture.target)
        glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)
        glPointSize(__brush_size)

        # initialize outputList
        outputList = []

        # extract 4 points each 2 points
        for x1, y1, x2, y2 in zip(points[::2], points[1::2],
                                  points[2::2], points[3::2]):

            # calculate vector and distance
            dx, dy = x2 - x1, y2 - y1
            dist = sqrt(dx * dx + dy * dy)

            # determine step
            steps = numsteps
            if steps is None:
                steps = max(1, int(dist) / 4)

            # construct pointList
            for i in xrange(steps):
                outputList.extend([x1 + dx * (float(i) / steps),
                                   y1 + dy * (float(i) / steps)])

        # draw !
        if len(outputList) < 2:
            return
        with gx_begin(GL_POINTS):
            for x, y in zip(outputList[::2], outputList[1::2]):
                glVertex2f(x, y)
示例#8
0
 def draw_detector(self):
     glUseProgram(self.shader)
     try:
         self.dom_positions_vbo.bind()
         try:
             glEnableClientState(GL_VERTEX_ARRAY)
             glVertexPointerf(self.dom_positions_vbo)
             glPointSize(2)
             glDrawArrays(GL_POINTS, 0, len(self.dom_positions)*3)
         finally:
             self.dom_positions_vbo.unbind()
             glDisableClientState(GL_VERTEX_ARRAY)
     finally:
         glUseProgram(0)
示例#9
0
def plot():
    glClear(GL_COLOR_BUFFER_BIT)

    glPointSize(3.0)
    glColor3f(1.0, 0.0, 0.0)

    glBegin(GL_POINTS)

    x_lst, y_lst = circle(0, 0, 1, 100)
    for x, y in zip(x_lst, y_lst):
        glVertex2f(x, y)

    glEnd()

    glFlush()
示例#10
0
    def _render_points(cls, point_list: List[Vector3], size: float, color: List[float]):
        """Draws a collection of points in the OpenGL 3D worldspace.

        This function must be invoked inside the OpenGL render loop.

        :param point_list: the points to render in the view context
        :param size: the size in pixels of each point
        :param color: the color to render the points
        """
        glPointSize(size)
        cls._set_color(color)
        glBegin(GL_POINTS)
        for point in point_list:
            glVertex3f(point.x, point.y, point.z)
        glEnd()
示例#11
0
def draw_node(x, y, sizes, colors):
    '''
    Draw a node at the given position using max(len(sizes), len(colors))
    points having the specified sizes and colors.
    '''
    if not len(sizes) == len(colors):
        print "Size and colour count for node drawer not equal. Adjusting."
        align_lists(sizes, colors)

    for i, size in enumerate(sizes):
        color = colors[i]

        glPointSize(size)
        glColor4f(color[0], color[1], color[2], color[3])
        glBegin(GL_POINTS)
        glVertex2f(x, y)
        glEnd()
 def Render(self, arrow_head_length=0.3):
     from OpenGL.GL import glBegin, glEnd, glVertex2f, glColor3f, glPointSize, GL_POINTS
     for edge in self.edge_list:
         if edge[2] == PlanarGraphEdgeLabel.CUT:
             glColor3f(0.0, 1.0, 0.0)
         elif edge[2] == PlanarGraphEdgeLabel.REGION_BORDER:
             glColor3f(0.6, 0.6, 0.6)
         else:
             glColor3f(1.0, 0.0, 0.0)
         vector = self.EdgeVector(edge)
         point = self.vertex_list[edge[0]]
         vector.Render(point, arrow_head_length=arrow_head_length)
     glPointSize(2.0)
     glBegin(GL_POINTS)
     try:
         for point in self.vertex_list:
             glColor3f(0.0, 0.0, 0.0)
             glVertex2f(point.x, point.y)
     finally:
         glEnd()
示例#13
0
    def draw(self):
        '''
        Draw the point cloud.
        '''
        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        glMultMatrixf(self._pose.T)

        glDisable(GL_LIGHTING)
        glPointSize(2)

        if self._xyz_vbo:
            # ref: http://stackoverflow.com/questions/16558819/vertex-buffer-objects-in-pyopengl-vertex-index-and-colour
            with self._xyz_vbo:
                glEnableClientState(GL_VERTEX_ARRAY)
                glVertexPointerf(self._xyz_vbo)

                if self._rgb_vbo:
                    # check for dimension match to avoid segmentation faults
                    if len(self._rgb_vbo) != len(self._xyz_vbo):
                        raise RuntimeError(
                            'point cloud XYZ and RGB length mismatch: {} vs {}'
                            .format(len(self._xyz_vbo), len(self._rgb_vbo)))

                    with self._rgb_vbo:
                        # add color
                        glEnableClientState(GL_COLOR_ARRAY)
                        glColorPointerf(self._rgb_vbo)
                        glDrawArrays(GL_POINTS, 0, len(self._xyz_vbo))
                else:
                    # draw without color
                    glDrawArrays(GL_POINTS, 0, len(self._xyz_vbo))

        glDisableClientState(GL_COLOR_ARRAY)
        glDisableClientState(GL_VERTEX_ARRAY)

        glEnable(GL_LIGHTING)

        glPopMatrix()
示例#14
0
    def draw_mesh(m, lighting_on):

        # Supply vertices
        glEnableClientState(GL_VERTEX_ARRAY)
        m.vbo['v'].bind()
        glVertexPointer(3, GL_FLOAT, 0, m.vbo['v'])
        m.vbo['v'].unbind()

        # Supply normals
        if 'vn' in m.vbo.keys():
            glEnableClientState(GL_NORMAL_ARRAY)
            m.vbo['vn'].bind()
            glNormalPointer(GL_FLOAT, 0, m.vbo['vn'])
            m.vbo['vn'].unbind()
        else:
            glDisableClientState(GL_NORMAL_ARRAY)

        # Supply colors
        if 'vc' in m.vbo.keys():
            glEnableClientState(GL_COLOR_ARRAY)
            m.vbo['vc'].bind()
            glColorPointer(3, GL_FLOAT, 0, m.vbo['vc'])
            m.vbo['vc'].unbind()
        else:
            glDisableClientState(GL_COLOR_ARRAY)

        if ('vt' in m.vbo.keys()) and hasattr(m, 'textureID'):
            glEnable(GL_TEXTURE_2D)
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
            glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)
            glBindTexture(GL_TEXTURE_2D, m.textureID)

            glEnableClientState(GL_TEXTURE_COORD_ARRAY)
            m.vbo['vt'].bind()
            glTexCoordPointer(2, GL_FLOAT, 0, m.vbo['vt'])
            m.vbo['vt'].unbind()
        else:
            glDisable(GL_TEXTURE_2D)
            glDisableClientState(GL_TEXTURE_COORD_ARRAY)

        # Draw
        if len(m.f) > 0:
            # ie if it is triangulated
            if lighting_on:
                glEnable(GL_LIGHTING)
            else:
                glDisable(GL_LIGHTING)
            glDrawElementsui(GL_TRIANGLES, np.arange(m.f.size,
                                                     dtype=np.uint32))
        else:
            # not triangulated, so disable lighting
            glDisable(GL_LIGHTING)
            glPointSize(2)
            glDrawElementsui(GL_POINTS, np.arange(len(m.v), dtype=np.uint32))
        if hasattr(m, 'v_to_text'):

            glEnable(GL_TEXTURE_2D)
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
                            GL_LINEAR_MIPMAP_LINEAR)
            glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)

            # glEnable(GL_TEXTURE_GEN_S)
            # glEnable(GL_TEXTURE_GEN_T)
            # glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR)
            # glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR)

            bgcolor = np.array(glGetDoublev(GL_COLOR_CLEAR_VALUE))
            fgcolor = 1. - bgcolor

            from .lines import Lines
            sc = float(np.max(np.max(m.v, axis=0) - np.min(m.v, axis=0))) / 10.

            cur_mtx = np.linalg.pinv(glGetFloatv(GL_MODELVIEW_MATRIX).T)
            xdir = cur_mtx[:3, 0]
            ydir = cur_mtx[:3, 1]

            glEnable(GL_LINE_SMOOTH)
            glEnable(GL_BLEND)
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

            for vidx, text in m.v_to_text.items():
                pos0 = m.v[vidx].copy()
                pos1 = m.v[vidx].copy()
                if hasattr(m, 'vn'):
                    pos1 += m.vn[vidx] * sc
                glLineWidth(5.0)
                ln = Lines(v=np.vstack((pos0, pos1)), e=np.array([[0, 1]]))
                glEnable(GL_LIGHTING)
                glColor3f(1. - 0.8, 1. - 0.8, 1. - 1.00)
                MeshViewerSingle.draw_lines(ln)

                glDisable(GL_LIGHTING)

                texture_id = get_textureid_with_text(text, bgcolor, fgcolor)
                glBindTexture(GL_TEXTURE_2D, texture_id)

                glPushMatrix()
                glTranslatef(pos1[0], pos1[1], pos1[2])

                dx = xdir * .10
                dy = ydir * .10
                if False:
                    glBegin(GL_QUADS)

                    glTexCoord2f(1., 0.)
                    glVertex3f(*(+dx + dy))

                    glTexCoord2f(1., 1.)
                    glVertex3f(*(+dx - dy))

                    glTexCoord2f(0., 1.)
                    glVertex3f(*(-dx - dy))

                    glTexCoord2f(0., 0.)
                    glVertex3f(*(-dx + dy))

                    # gluSphere(quadratic,0.05,32,32)
                    glEnd()
                else:
                    glBegin(GL_POLYGON)

                    for r in np.arange(0, np.pi * 2., .01):
                        glTexCoord2f(np.cos(r) / 2. + .5, np.sin(r) / 2. + .5)
                        glVertex3f(*(dx * np.cos(r) + -dy * np.sin(r)))

                    glEnd()
                glPopMatrix()
示例#15
0
    def display(self):
        if self.knowledge_base:
            # update the world
            if self.knowledge_base.shelf_xform:
                # load the shelf once a transform is available
                if not self.shelf:
                    self.shelf = self.world.loadRigidObject("klampt_models/north_shelf/shelf_with_bins.obj")
                    logger.info("spawned shelf model")
                self.shelf.setTransform(*self.knowledge_base.shelf_xform)

            if self.knowledge_base.order_bin_xform:
                # load the order bin once a transform is available
                if not self.order_bin:
                    self.order_bin = self.world.loadRigidObject("klampt_models/apc_bin/apc_bin.obj")
                    logger.info("spawned order bin model")
                self.order_bin.setTransform(*self.knowledge_base.order_bin_xform)

            # spawn/update objects
            for (name, xform) in self.knowledge_base.object_xforms.items():
                # load the object once a transform is availale
                if name not in self.objects:
                    body = self.world.loadRigidObject("klampt_models/items/{0}/{0}.obj".format(name))
                    logger.info("spawned {} model".format(name))

                    # load the point cloud
                    if name in self.knowledge_base.object_clouds:
                        self.n += 1
                        display_list = glGenLists(self.n)

                        # compile the display list
                        glNewList(display_list, GL_COMPILE)
                        glDisable(GL_LIGHTING)
                        glBegin(GL_POINTS)
                        points = self.knowledge_base.object_clouds[name]
                        for point in points:
                            if len(point) == 2:
                                xyz = point[0]
                                rgb = point[1]
                            else:
                                xyz = point[:3]
                                if len(point) == 4:
                                    rgb = point[3]
                                elif len(point) > 3:
                                    rgb = point[3:6]
                                else:
                                    rgb = None

                            if rgb is not None:
                                glColor3f(*map(lambda x: x / 255.0, rgb))
                            else:
                                glColor3f(*colors[i % len(colors)])
                            glVertex3f(*xyz[:3])
                        glEnd()
                        glEndList()
                        logging.debug("compiled {} points for {}".format(len(points), name))
                    else:
                        display_list = None

                    self.objects[name] = {"body": body, "display_list": display_list}

                # self.objects[name]['body'].setTransform(*xform)

            # delete objects
            for (name, props) in self.objects.items():
                if name not in self.knowledge_base.object_xforms:
                    # remove the object
                    # XXX: cannot actually delete object... so move it far away... very far away
                    props["body"].setTransform(so3.identity(), [1e3, 1e3, 1e3])
                    del self.objects[name]

        # update the robot state
        if self.robot_state:
            try:
                self.robot.setConfig(self.robot_state.sensed_config)
            except TypeError as e:
                logger.error("error visualizing config: {}".format(self.robot_state.sensed_config))
                logger.error(traceback.format_exc())
                sys.exit(-1)

        self.world.drawGL()

        # draw commanded configurations
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, [0, 1, 0, 0.5])

        if self.robot_state:
            qi = self.robot.getConfig()
            self.robot.setConfig(self.robot_state.commanded_config)
            self.robot.drawGL(False)
            self.robot.setConfig(qi)

        glDisable(GL_BLEND)

        # draw the point clouds
        glPointSize(2)
        for (name, props) in self.objects.items():
            if "display_list" in props:
                glCallList(props["display_list"])

        # draw gripper link transforms
        for name in ["left_gripper", "right_gripper"]:
            gldraw.xform_widget(self.robot.getLink(name).getTransform(), 0.1, 0.01)
        # draw axis-aligned axes for reference
        gldraw.xform_widget((so3.identity(), [0, 0, 1]), 0.1, 0.01)
        # draw local origins of objects
        if self.knowledge_base:
            for xform in self.knowledge_base.object_xforms.values():
                gldraw.xform_widget(xform, 0.1, 0.01)
示例#16
0
    glDisableVertexAttribArray(0)
    glDisableVertexAttribArray(1)
    glutSwapBuffers()


def moveMouse(x, y, z, w):
    pass


glutInit()
glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH)
glutInitWindowSize(500, 500)
glutInitWindowPosition(100, 100)
wind = glutCreateWindow("OpenGL Window")
glPointSize(1)

vertshader = shaders.compileShader("""
    #version 330 core    
    layout (location = 0) in vec3 aPos;
    layout (location = 1) in vec3 aColor;

    uniform mat4 model;
    uniform mat4 view;
    uniform mat4 projection;

    out vec3 ourColor;

    void main()
    {
       gl_Position = model * vec4(aPos, 1.0);
示例#17
0
def main():
    global width
    global height
    global camera

    width = 1024
    height = 1024

    delta_time = 0.0
    last_frame = 0.0

    if not glfw.init():
        return

    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    glfw.window_hint(glfw.RESIZABLE, GL_FALSE)
    window = glfw.create_window(width, height, "opengl_lab1", None, None)

    glfw.set_key_callback(window, key_callback)
    glfw.set_cursor_pos_callback(window, mousemove_callback)
    glfw.set_mouse_button_callback(window, mouseclick_callback)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)

    fun1 = lambda x, z: math.sin(x+z)
    fun2 = lambda x, z: math.exp(-x*x - z*z)
    fun3 = lambda x, z: (x**2 + z**2) / (x*z)
    contour_plot = lambda x, z: 0.0
    heightmap_dummy_fun = lambda x, z: 0.0

    surface_size = 50

    (fun_vao1, ind_fun1) = create_surface(100, 100, surface_size, fun1, False)
    (fun_vao2, ind_fun2) = create_surface(100, 100, surface_size, fun2, False)
    (fun_vao3, ind_fun3) = create_surface(100, 100, surface_size, fun3, False)
    (grad_vao, grad_point_count) = create_grad(100, 100, surface_size)
    (contour_plot_vao, ind_con, vec_lines, vector_line_indexes) = create_surface(100, 100, surface_size, 0, False, True)
    (heightmap_vao, ind_hm) = create_surface(100,100, surface_size, heightmap_dummy_fun, True)
    (sphere_vao, sphere_ind, normals_for_glyph) = uv_sphere(22, 11)
    (torus_vao, torus_ind) = uv_torus(5, 10, 100, 100)
    (cm_vao, ind_cm) = create_surface(100, 100, surface_size, heightmap_dummy_fun, True)
    (cloud_vao, points_count) = read_ply()
    (perlin_vao, ind_perlin) = create_surface(100, 100, surface_size, heightmap_dummy_fun, False)
    (div_vao, ind_div) = create_surface(100, 100, surface_size, heightmap_dummy_fun, False)
    (traj_vao, ind_traj) = simple_cube()

    fun_shader_sources = [(GL_VERTEX_SHADER, "shaders/functions.vert"), (GL_FRAGMENT_SHADER, "shaders/functions.frag")]

    fun_program = ShaderProgram(fun_shader_sources)

    hm_shader_sources = [(GL_VERTEX_SHADER, "shaders/heightmap.vert"), (GL_FRAGMENT_SHADER, "shaders/heightmap.frag")]

    hm_program = ShaderProgram(hm_shader_sources)

    hm_texture = read_texture("1.jpg")

    contour_plot_shader_sources = [(GL_VERTEX_SHADER, "shaders/contourplot.vert"), (GL_FRAGMENT_SHADER, "shaders/contourplot.frag")]

    contour_plot_program = ShaderProgram(contour_plot_shader_sources)

    sphere_shader_sources = [(GL_VERTEX_SHADER, "shaders/sphere.vert"), (GL_FRAGMENT_SHADER, "shaders/sphere.frag")]
    sphere_program = ShaderProgram(sphere_shader_sources)

    glyph_shader_sources = [(GL_VERTEX_SHADER, "shaders/glyph.vert"), (GL_GEOMETRY_SHADER, "shaders/glyph.geom"), (GL_FRAGMENT_SHADER, "shaders/glyph.frag")]
    glyph_program = ShaderProgram(glyph_shader_sources)

    grad_shader_sources = [(GL_VERTEX_SHADER, "shaders/grad.vert"), (GL_GEOMETRY_SHADER, "shaders/grad.geom"), (GL_FRAGMENT_SHADER, "shaders/grad.frag")]
    grad_program = ShaderProgram(grad_shader_sources)

    cm_shader_sources = [(GL_VERTEX_SHADER, "shaders/colormap.vert"), (GL_FRAGMENT_SHADER, "shaders/colormap.frag")]
    cm_program = ShaderProgram( cm_shader_sources )

    perlin_shader_sources = [(GL_VERTEX_SHADER, "shaders/perlin.vert"), (GL_FRAGMENT_SHADER, "shaders/perlin.frag")]
    perlin_program = ShaderProgram(perlin_shader_sources)

    cloud_shader_sources = [(GL_VERTEX_SHADER, "shaders/ply.vert"), (GL_FRAGMENT_SHADER, "shaders/ply.frag")]
    cloud_program = ShaderProgram(cloud_shader_sources)

    vf_shader_sources = [(GL_VERTEX_SHADER, "shaders/vector_field.vert"), (GL_FRAGMENT_SHADER, "shaders/vector_field.frag")]
    vf_program = ShaderProgram(vf_shader_sources)

    traj_shader_sources = [(GL_VERTEX_SHADER, "shaders/trajectory.vert"),
                         (GL_FRAGMENT_SHADER, "shaders/trajectory.frag")]

    traj_program = ShaderProgram(traj_shader_sources)



    check_gl_errors()

    projection = projectionMatrixTransposed(60.0, float(width) / float(height), 1, 1000.0)

    HDR_TEXTURES_AMOUNT = 33

    cm_textures = read_cm_textures(HDR_TEXTURES_AMOUNT)

    cm_texture_num = 0

    cm_change_counter = 0

    hdr_textures_speed = 6

    perlin_time = 0.0
    perlin_time_step = 0.03



    cube_multiplier = 1.0
    cube_center = [0.0, 0.0, 0.0]
    traj_points_list = [ cube_center ]
    cube_edge_length = 2.0 * cube_multiplier

    offset = cube_edge_length / 10
    left_cube_pos = -25 * cube_edge_length
    cube_steps = -left_cube_pos / offset - 10
    traj_points_count = int(cube_steps)


    for i in range(traj_points_count):
        traj_points_list.append( [0.5*cube_edge_length * i, 0.0, 0.0] )

    traj_part_index = 0



    while not glfw.window_should_close(window):
        current_frame = glfw.get_time()
        delta_time = current_frame - last_frame
        last_frame = current_frame
        glfw.poll_events()

        doCameraMovement(camera, delta_time)

        model = translateM4x4(np.array([0.0, 0.0, 0.0]))
        view = camera.get_view_matrix()

        glClearColor(0.5, 0.5, 0.5, 1.0)
        glViewport(0, 0, width, height)
        glEnable(GL_DEPTH_TEST)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        fun_program.bindProgram()

        glUniform3fv(fun_program.uniformLocation("col"), 1 , [1.0, 0, 0] )

        glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniformMatrix4fv(fun_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(fun_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())

        glBindVertexArray(fun_vao1)
        glDrawElements(GL_TRIANGLE_STRIP, ind_fun1, GL_UNSIGNED_INT, None)

        model = translateM4x4(np.array([-1.5*surface_size,0.0 ,0.0 ]))
        glUniform3fv(fun_program.uniformLocation("col"), 1, [0.0, 1.0, 0])
        glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glBindVertexArray(fun_vao2)
        glDrawElements(GL_TRIANGLE_STRIP, ind_fun2, GL_UNSIGNED_INT, None)

        model = translateM4x4(np.array([1.5 * surface_size, 0.0, 0.0]))
        glUniform3fv(fun_program.uniformLocation("col"), 1, [0.0, 0.0, 1.0])
        glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glBindVertexArray(fun_vao3)
        glDrawElements(GL_TRIANGLE_STRIP, ind_fun3, GL_UNSIGNED_INT, None)

        cloud_program.bindProgram()

        translate_cloud = translateM4x4(np.array([-2.5*surface_size,0.0 ,0.0 ]))
        # rotate_cloud = rotateYM4x4(math.radians(180))
        model = translate_cloud
        # glUniform3fv(fun_program.uniformLocation("col"), 1, [0.0, 1.0, 0])
        glUniformMatrix4fv(cloud_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniformMatrix4fv(cloud_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(cloud_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())
        glBindVertexArray(cloud_vao)
        glDrawArrays(GL_POINTS, 0, points_count)

        sphere_program.bindProgram()

        sph_scale = scaleM4x4(np.array([sphere_radius, sphere_radius, sphere_radius]))
        sph_translate = translateM4x4(np.array([0.0, 0.0, 2.0 * surface_size]))

        glUniformMatrix4fv(sphere_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(sph_translate + sph_scale).flatten())
        glUniformMatrix4fv(sphere_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(sphere_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())
        glBindVertexArray(sphere_vao)
        glDrawElements(GL_TRIANGLES, sphere_ind, GL_UNSIGNED_INT, None)

        torus_translate = translateM4x4(np.array([0.0, 0.0, 3.0 * surface_size]))
        glUniformMatrix4fv(sphere_program.uniformLocation("model"), 1, GL_FALSE,
                           np.transpose(torus_translate + sph_scale).flatten())
        glBindVertexArray(torus_vao)
        glDrawElements(GL_TRIANGLES, torus_ind, GL_UNSIGNED_INT, None)

        glyph_program.bindProgram()
        sph_scale = scaleM4x4(np.array([sphere_radius, sphere_radius, sphere_radius]))
        sph_translate = translateM4x4(np.array([0.0, 0.0, 2.0 * surface_size]))

        glUniformMatrix4fv(glyph_program.uniformLocation("model"), 1, GL_FALSE,
                           np.transpose(sph_translate + sph_scale).flatten())
        glUniformMatrix4fv(glyph_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(glyph_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())

        vao = glGenVertexArrays(1)
        glBindVertexArray(vao)
        vbo = glGenBuffers(1)
        glBindBuffer(GL_ARRAY_BUFFER, vbo)
        glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(normals_for_glyph), normals_for_glyph.flatten(),
                     GL_STATIC_DRAW)
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)
        glEnableVertexAttribArray(0)
        glDrawArrays(GL_POINTS, 0, 10000)
        glBindVertexArray(0)

        contour_plot_program.bindProgram()

        model = translateM4x4(np.array([-1.5 * surface_size, 0.0, -1.5 * surface_size]))

        glUniformMatrix4fv(contour_plot_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniformMatrix4fv(contour_plot_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(contour_plot_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())
        glBindVertexArray(contour_plot_vao)
        glDrawElements(GL_TRIANGLE_STRIP, ind_con, GL_UNSIGNED_INT, None)

        fun_program.bindProgram()
        lines_vao = glGenVertexArrays(1)
        glBindVertexArray(lines_vao)
        vbo_lines = glGenBuffers(1)
        vbo_indices = glGenBuffers(1)
        glBindBuffer(GL_ARRAY_BUFFER, vbo_lines)
        glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vec_lines), vec_lines.flatten(),
                     GL_STATIC_DRAW)  #
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)
        glEnableVertexAttribArray(0)
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_indices)
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vector_line_indexes), vector_line_indexes.flatten(),
                     GL_STATIC_DRAW)

        glUniformMatrix4fv(fun_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniformMatrix4fv(fun_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(fun_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())
        glBindVertexArray(lines_vao)
        glDrawElements(GL_LINES, vector_line_indexes.size, GL_UNSIGNED_INT, None)

        hm_program.bindProgram()

        model = translateM4x4(np.array([0.0, 0.0, -1.5 * surface_size]))

        bindTexture(0, hm_texture)

        glUniform1i(hm_program.uniformLocation("tex"), 0)
        glUniformMatrix4fv(hm_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniformMatrix4fv(hm_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(hm_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())
        glBindVertexArray(heightmap_vao)
        glDrawElements(GL_TRIANGLE_STRIP, ind_hm, GL_UNSIGNED_INT, None)

        cm_program.bindProgram()

        model = translateM4x4(np.array([1.5 * surface_size, 0.0, -1.5 * surface_size]))

        cur_cm_texture = cm_textures[cm_texture_num % HDR_TEXTURES_AMOUNT]

        bindTexture(1, cur_cm_texture)

        if cm_change_counter % hdr_textures_speed == 0:
            cm_texture_num += 1

        cm_change_counter += 1

        glUniform1i(cm_program.uniformLocation("cm_switch"), False)

        glUniform1i(cm_program.uniformLocation("tex"), 1)
        glUniformMatrix4fv(cm_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniformMatrix4fv(cm_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(cm_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())
        glBindVertexArray(cm_vao)
        glDrawElements(GL_TRIANGLE_STRIP, ind_cm, GL_UNSIGNED_INT, None)

        # draw second animated hdr on the same shader
        model = translateM4x4(np.array([2.5 * surface_size, 0.0, -2.5 * surface_size]))
        glUniformMatrix4fv(cm_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniform1i(cm_program.uniformLocation("cm_switch"), True)
        glDrawElements(GL_TRIANGLE_STRIP, ind_cm, GL_UNSIGNED_INT, None)

        perlin_program.bindProgram()
        model = translateM4x4(np.array([0.0, 0.0, -3.5 * surface_size]))
        glUniformMatrix4fv(perlin_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniformMatrix4fv(perlin_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(perlin_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())
        glUniform1f(perlin_program.uniformLocation("time"), perlin_time)
        perlin_time += perlin_time_step

        glBindVertexArray(perlin_vao)
        glDrawElements(GL_TRIANGLE_STRIP, ind_perlin, GL_UNSIGNED_INT, None)

        grad_program.bindProgram()
        model = translateM4x4(np.array([-25.0, 0.0, -7.0 * surface_size]))
        glUniformMatrix4fv(grad_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniformMatrix4fv(grad_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(grad_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())
        glBindVertexArray(grad_vao)
        glDrawArrays(GL_LINES, 0, grad_point_count)

        vf_program.bindProgram()
        model = translateM4x4(np.array([0.0, 0.0, -5.5 * surface_size]))
        glUniformMatrix4fv(vf_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glUniformMatrix4fv(vf_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(vf_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())
        glUniform1i(vf_program.uniformLocation("cm_switch"), True)
        glBindVertexArray(div_vao)
        glDrawElements(GL_TRIANGLE_STRIP, ind_div, GL_UNSIGNED_INT, None)

        glUniform1i(vf_program.uniformLocation("cm_switch"), False)
        model = translateM4x4(np.array([1.0 * surface_size, 0.0, -6.5 * surface_size]))
        glUniformMatrix4fv(vf_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(model).flatten())
        glDrawElements(GL_TRIANGLE_STRIP, ind_div, GL_UNSIGNED_INT, None)


        traj_program.bindProgram()

        l_traj_part =[]
        r_traj_part =[]

        if offset > 0:
            traj_part_index = int(traj_points_count - cm_change_counter % cube_steps)
            r_traj_part = traj_points_list[0:traj_part_index]
            for traj_coords in r_traj_part:
                l_traj_part.append( [-x for x in traj_coords] )
        else:
            traj_part_index = int(traj_points_count - cm_change_counter % cube_steps)
            # traj_part_index = int(cm_change_counter % cube_steps)
            l_traj_part = traj_points_list[0:traj_part_index]
            for traj_coords in l_traj_part:
                r_traj_part.append([-x for x in traj_coords])

        l_traj_vec = np.array(l_traj_part, dtype=np.float32)
        r_traj_vec = np.array(r_traj_part, dtype=np.float32)

        indices_list = [i for i in range(len(r_traj_part))]
        indices_vec = np.array(indices_list, dtype=np.uint32)

        left_traj_vao = glGenVertexArrays(1)
        right_traj_vao = glGenVertexArrays(1)
        left_traj_vertices = glGenBuffers(1)
        left_traj_indices = glGenBuffers(1)
        right_traj_vertices = glGenBuffers(1)
        right_traj_indices = glGenBuffers(1)

        glBindVertexArray(left_traj_vao)
        glPointSize( 3.0 )

        glBindBuffer(GL_ARRAY_BUFFER, left_traj_vertices)
        glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(l_traj_vec), l_traj_vec.flatten(),
                     GL_STATIC_DRAW)
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)
        glEnableVertexAttribArray(0)

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, left_traj_indices)

        glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(indices_vec), indices_vec.flatten(),
                     GL_STATIC_DRAW)


        glBindVertexArray(right_traj_vao)

        glBindBuffer(GL_ARRAY_BUFFER, right_traj_vertices)
        glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(r_traj_vec), r_traj_vec.flatten(),
                     GL_STATIC_DRAW)
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)
        glEnableVertexAttribArray(0)

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, right_traj_indices)

        glBufferData(GL_ELEMENT_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(indices_vec), indices_vec.flatten(),
                     GL_STATIC_DRAW)

        glBindVertexArray(0)




        cube_scale_ = scaleM4x4(np.array([1.0, 1.0, 1.0]))

        left_cube_pos += offset

        left_translation = translateM4x4(np.array([left_cube_pos, 0.0, -7.5 * surface_size]))
        glUniformMatrix4fv(traj_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(left_translation).flatten())
        glUniformMatrix4fv(traj_program.uniformLocation("view"), 1, GL_FALSE, np.transpose(view).flatten())
        glUniformMatrix4fv(traj_program.uniformLocation("projection"), 1, GL_FALSE, projection.flatten())

        glBindVertexArray(left_traj_vao)
        glDrawElements(GL_LINE_STRIP, indices_vec.size, GL_UNSIGNED_INT, None)

        glBindVertexArray(traj_vao)
        glDrawElements(GL_TRIANGLE_STRIP, ind_traj, GL_UNSIGNED_INT, None)

        right_translation = translateM4x4(np.array([-left_cube_pos, 0.0, -8.5 * surface_size]))
        glUniformMatrix4fv(traj_program.uniformLocation("model"), 1, GL_FALSE, np.transpose(right_translation).flatten())
        glDrawElements(GL_TRIANGLE_STRIP, ind_traj, GL_UNSIGNED_INT, None)


        glBindVertexArray(right_traj_vao)
        glDrawElements(GL_LINE_STRIP, indices_vec.size, GL_UNSIGNED_INT, None)







        if not cm_change_counter % cube_steps:
            # left_cube_pos = left_cube_pos + offset * (cube_steps-1)
            offset *= -1
            # r_traj_part, l_traj_part = l_traj_part, r_traj_part


        traj_program.unbindProgram()

        glfw.swap_buffers(window)

    glfw.terminate()
示例#18
0
def landmark_visualizer(landmarks, cameras, left_landmarks, right_landmarks):
    glLineWidth(1.5)
    glBegin(GL_LINES)

    glColor3f(0.0, 1.0, 0.0)
    for landmark in landmarks:
        glVertex3fv(cameras[0])
        glVertex3fv(landmark)

    glColor3f(0.0, 0.0, 1.0)
    for landmark in landmarks:
        glVertex3fv(cameras[1])
        glVertex3fv(landmark)
    glEnd()

    glPointSize(3.0)
    glBegin(GL_POINTS)
    glColor3f(1.0, 0.0, 0.0)
    for i in range(len(landmarks)):
        glVertex3f(landmarks[i][0], landmarks[i][1], landmarks[i][2])
    glEnd()

    glPointSize(3.0)
    glBegin(GL_POINTS)
    glColor3f(1.0, 0.0, 0.0)
    for i in range(len(cameras)):
        glVertex3f(cameras[i][0], cameras[i][1], cameras[i][2])
    glEnd()

    glLineWidth(1.5)
    glBegin(GL_LINES)

    glColor3f(0.0, 1.0, 0.0)
    for landmark in left_landmarks:
        glVertex3fv(cameras[0])
        glVertex3fv(landmark)

    glColor3f(0.0, 0.0, 1.0)
    for landmark in right_landmarks:
        glVertex3fv(cameras[1])
        glVertex3fv(landmark)
    glEnd()

    glPointSize(3.0)
    glBegin(GL_POINTS)
    glColor3f(1.0, 0.0, 0.0)
    for i in range(len(left_landmarks)):
        glVertex3f(left_landmarks[i][0], left_landmarks[i][1],
                   left_landmarks[i][2])
    glEnd()

    glPointSize(3.0)
    glBegin(GL_POINTS)
    glColor3f(1.0, 0.0, 0.0)
    for i in range(len(right_landmarks)):
        glVertex3f(right_landmarks[i][0], right_landmarks[i][1],
                   right_landmarks[i][2])
    glEnd()

    glPointSize(3.0)
    glBegin(GL_POINTS)
    glColor3f(1.0, 0.0, 0.0)
    for i in range(len(cameras)):
        glVertex3f(cameras[i][0], cameras[i][1], cameras[i][2])
    glEnd()
示例#19
0
    def on_draw(self):
         
        glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA)

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glLoadIdentity()
        
        glTranslate(self.translatex, self.translatey, self.depth)
        
        if self.autoRun:
            glRotate(self.rotx,  0, 1, 0)
        
        else:
            # Perform arcball rotation.
            glScale(1,-1,1)
            glMultMatrixf(self.arcball.transform)
            glScale(1,-1,1)
        
        with displayListify("cubeTranslate") as shouldLeave:
            if shouldLeave: raise LeaveWith
                
            # Scale the co-ordinates so that they are correct
            glScale(2/128, 2/128, 2/128)
            
            glColor(0.25, 0.25, 0.25, 1)
            glutWireCube(255)
            
            glTranslate(-128, -128, -128)
        
        with displayListify("allPoints") as shouldLeave:
            if shouldLeave: raise LeaveWith
            
            with SaveMatrix():
                # Flip the co-ordinates and translate upwards
                glScale(1,-1,1)
                glColor(0.25, 0.25, 0.25, 0.5)
                glTranslate(0,-255,0)
                glPointSize(pointSize)
                for dat in reversed(vLists):
                    glTranslate(0., 0., 1./nChunks*255)
                    dat.draw(GL_POINTS)

        with displayListify("axisLabels") as shouldLeave:
            if shouldLeave: raise LeaveWith
        #if True:
            with SaveMatrix():
                glTranslate(128,0,0)
                self.makeLabel("End").draw()
                
                glTranslate(0,0,255)
                self.makeLabel("Beginning").draw()
                
                with SaveMatrix():
                    glTranslate(-128,128,0)
                    glRotate(90,0,0,1)
                    self.makeLabel("Byte 1").draw()
                
                glTranslate(0,255,0)
                self.makeLabel("Byte 2").draw()
        
        with displayListify("fileName") as shouldLeave:
            if shouldLeave: raise LeaveWith
            glLoadIdentity()
            
            with SaveMatrix():
                glColor(1,0,0)
                glTranslate(0,-2.2,-4)
                glScale(1/64, 1/64, 1/64)
                l = self.makeLabel(basename(currentInputFile))
                l.color = (0, 128, 230, 255)
                l.draw()
        
        glTranslate(0,0,-1)
        
        if self.autoRun:
        
            if self.rotx > 360 - 45:
                vlist = vertex_list(4, ('v2i', (-1, -1, 1, -1, 1, 1, -1, 1)))
                glColor(0,0,0,(self.rotx-(360-45))/45)
                vlist.draw(GL_QUADS)
                
            if self.rotx < 45:
                vlist = vertex_list(4, ('v2i', (-1, -1, 1, -1, 1, 1, -1, 1)))
                glColor(0,0,0,1-(self.rotx/45))
                vlist.draw(GL_QUADS)