Exemplo n.º 1
0
 def get_view_matrix(self):
     if TRACKING_CAMERA_VIEW:
         return matrix44.create_look_at(self.camera_pos, self.world_centre,
                                        self.camera_up)
     else:
         return matrix44.create_look_at(self.camera_pos,
                                        self.camera_pos + self.camera_front,
                                        self.camera_up)
Exemplo n.º 2
0
 def __init__(
     self,
     pos=np.array([0.0, 0.0, 0.0], dtype=np.float32),
     target=np.array([0.0, 0.0, 1.0], dtype=np.float32),
     aspect=1.0,
     fov=60.0,
 ):
     """Create camera."""
     self.fov = fov
     self.aspect = aspect
     if isinstance(pos, np.ndarray):
         self.pos = pos
     else:
         self.pos = np.array(pos, dtype=np.float32)
     self.target = target
     if isinstance(target, np.ndarray):
         self.target = target
     else:
         self.target = np.array(target, dtype=np.float32)
     self.V = matrix44.create_look_at(
         self.pos,  # position
         self.target,  # target
         np.array([0, 1, 0]),  # up vector
     )
     self.regen_view = False
     self.P = matrix44.create_perspective_projection(
         self.fov, aspect, 0.1, 300, dtype=np.float32
     )
     self.regen_prespective = False
Exemplo n.º 3
0
    def render(self):
        """Render the scene before post-processing."""
        visibility = self.visibility
        projection = matrix44.create_perspective_projection(self.fov,
                                                            self.width /
                                                            self.height,
                                                            3E-3,
                                                            visibility,
                                                            dtype=np.float32)
        view = matrix44.create_look_at(self.pos,
                                       self.pos + self.forward,
                                       self.upward,
                                       dtype=np.float32)
        vp = view @ projection

        # Render map
        self.maprog['visibility'].value = visibility
        self.maprog['mvp'].write(vp)
        self.mapva.render(moderngl.TRIANGLES)

        # Render picos and shards
        self.prog['visibility'].value = visibility
        self.prog['camera'].write(self.pos)
        self.prog['vp'].write(vp)
        for pico in self.picos.values():
            for shard in pico.shards.values():
                self.render_shard(shard)
            if pico is not self.camera: self.render_pico(pico)
Exemplo n.º 4
0
def generate_lines(obj: Object, camera: Camera, viewport: Polygon, front_brightness: float, back_brightness: float) -> List[Line]:
    # Create transformation matrix
    translation = Matrix44.from_translation(obj.translation)
    rotation = Matrix44.from_eulers(obj.rotation)
    projection = Matrix44.perspective_projection(
        camera.fovy, camera.aspect, camera.near, camera.far)
    cam = matrix44.create_look_at(camera.eye, camera.target, [0, 1.0, 0])
    matrix = projection * cam * translation * rotation

    # Transform vertices, remove hidden faces and get edges for faces
    # TODO: Make the rendering pipeline more generic
    vertices = [matrix * vertex for vertex in obj.mesh.vertices]
    front_faces = [face for face in obj.mesh.faces
                   if cull_face(vertices, face, 'front')]
    back_faces = [face for face in obj.mesh.faces
                  if cull_face(vertices, face, 'back')]
    front_edges = find_edges(front_faces, obj.mesh.edges)
    back_edges = find_edges(back_faces, obj.mesh.edges)

    # Clip lines
    lines = edges_to_lines(front_edges, vertices, front_brightness) + \
        edges_to_lines(back_edges, vertices, back_brightness)
    return [clipped
            for clipped in [clip_line(line, viewport) for line in lines]
            if clipped is not None]
Exemplo n.º 5
0
 def _regen_view(self):
     self.V = matrix44.create_look_at(
         np.array(self.pos),  # position
         np.array(self.target),  # target
         np.array([0, 1, 0]),  # up vector
     )
     self.regen_view = False
Exemplo n.º 6
0
    def test_create_look_at_determinant(self):
        m = matrix44.create_look_at(
            np.array((300.0, 200.0, 100.0)),
            np.array((0.0, 0.0, 0.0)),
            np.array((0.0, 0.0, 1.0)),
        )

        self.assertAlmostEqual(np.linalg.det(m), 1.0)
Exemplo n.º 7
0
    def test_create_look_at_determinant(self):
        m = matrix44.create_look_at(
            np.array((300.0, 200.0, 100.0)),
            np.array((0.0, 0.0, 0.0)),
            np.array((0.0, 0.0, 1.0)),
        )

        self.assertAlmostEqual(np.linalg.det(m), 1.0)
Exemplo n.º 8
0
    def update(self):
        projection = matrix44.create_perspective_projection(
            20.0, self.ratio, 0.1, 5000.0)
        look = matrix44.create_look_at(eye=[0, -self.distance, 0],
                                       target=[0, 0, 0],
                                       up=[0, 0, -1])

        self.matrix = numpy.matmul(look, projection)
Exemplo n.º 9
0
def drawAxis():
    global shaderProgram
    global vao
    global vbo
    global model
    global uMat
    global view
    global idProj
    global idView
    global projection

    glClearColor(0, 0, 0, 1)

    # carrega os shaders do axis
    vertex_code = readShaderFile('axis.vp')
    fragment_code = readShaderFile('axis.fp')

    # compila o shaders e program
    vertexShader = shaders.compileShader(vertex_code, GL_VERTEX_SHADER)
    fragmentShader = shaders.compileShader(fragment_code, GL_FRAGMENT_SHADER)
    shaderProgram = shaders.compileProgram(vertexShader, fragmentShader)

    # cria e faz o bind no vertex arrat object
    vao = GLuint(0)
    glGenVertexArrays(1, vao)
    glBindVertexArray(vao)

    #vertices
    x = np.array([[255, 0, 0], [0, 0, 0], [-255, 0, 0]], dtype='f')
    y = np.array([[0, 255, 0], [0, 0, 0], [0, -255, 0]], dtype='f')
    z = np.array([[0, 0, 255], [0, 0, 0], [0, 0, -255]], dtype='f')
    vertices = np.concatenate((x, y, z))

    vbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, vbo)
    glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW)
    glVertexAttribPointer(0, 3, GL_FLOAT, False, 0,
                          None)  # first 0 is the location in shader
    glBindAttribLocation(shaderProgram, 0, 'vertexPosition')
    glEnableVertexAttribArray(0)

    view = matrix44.create_look_at(poscam, lookat, [0.0, 1.0, 0.0])
    projection = matrix44.create_orthogonal_projection(-2.0, 2.0, -2.0, 2.0,
                                                       -2.0, 2.0)

    idView = glGetUniformLocation(shaderProgram, "view")
    idProj = glGetUniformLocation(shaderProgram, "projection")

    glBindBuffer(GL_ARRAY_BUFFER, 0)
    glBindVertexArray(0)
Exemplo n.º 10
0
    def loadobj(self, objfn, texfn):
        self.release()

        prog = self.ctx.program(vertex_shader=self.vert_shader,
                                fragment_shader=self.frag_shader)

        prog["is_background"].value = False
        prog["DirLight"].value = (-1, 1, 1)
        prog["dir_int"].value = 0.4
        prog["amb_int"].value = 1.0
        self.bufs['prog'] = prog

        self.vs = SimpleNamespace()
        self.vs.proj = matrix44.create_perspective_projection(
            30, 1.0, 0.1, 1000.0)
        self.vs.view = matrix44.create_look_at(
            [0, 0, 1.5],
            [0, 0, 0],
            [0, 1, 0],
        )

        self.bufs['fbo'] = fbo
        fbo.use()

        obj = Obj.open(objfn)
        tmp = obj.pack('vx vy vz nx ny nz tx ty')
        arr = np.array(np.frombuffer(tmp, dtype='f4')).reshape((-1, 8))

        # move obj center to the origin
        tmp = arr[:, :3]
        center = np.mean(tmp, axis=0)
        tmp -= center

        # scale obj to be within [-1, 1]
        a, b = tmp.min(), tmp.max()
        arr[:, :3] = tmp / (b - a)

        vbo = self.ctx.buffer(arr.flatten().astype("f4").tobytes())
        vao = self.ctx.simple_vertex_array(self.bufs['prog'], vbo, "in_vert",
                                           "in_norm", "in_text")
        self.bufs['vbo'] = vbo
        self.bufs['vao'] = vao

        img = Image.open(texfn).transpose(
            Image.FLIP_TOP_BOTTOM).convert("RGBA")
        texture = self.ctx.texture(img.size, 4, img.tobytes())
        texture.build_mipmaps()
        texture.use()
        self.bufs['texture'] = texture
Exemplo n.º 11
0
 def calc_projection(self):
     self.ortho = matrix44.create_orthogonal_projection(
         -self.hw / self._zoom, self.hw / self._zoom, -self.hh / self._zoom,
         self.hh / self._zoom, -100.0, 100.0)
     self.persp = matrix44.create_perspective_projection_matrix(
         50.0, self.width / self.height, 0.1, 200.0)
     if self.is_ortho:
         self.projection = self.ortho
     else:
         self.projection = self.persp
     self.default_proj = matrix44.create_orthogonal_projection(
         0, self.width, 0, self.height, -1, 1)
     self.view = matrix44.create_look_at((self.x, self.y, 10.0),
                                         (self.x, self.y, 0.0),
                                         (self.up_x, self.up_y, 0.0))
Exemplo n.º 12
0
    def test_create_look_at_4(self):
        m = matrix44.create_look_at(
            np.array((0.0, 0.0, 0.0)),
            np.array((0.0, 0.0, -1.0)),
            np.array((0.0, 1.0, 0.0)),
        )

        x, y, z, _ = matrix44.apply_to_vector(m, (1.0, 0.0, 0.0, 0.0))
        self.assertAlmostEqual(x, 1.0)
        self.assertAlmostEqual(y, 0.0)
        self.assertAlmostEqual(z, 0.0)

        x, y, z, _ = matrix44.apply_to_vector(m, (0.0, 1.0, 0.0, 0.0))
        self.assertAlmostEqual(x, 0.0)
        self.assertAlmostEqual(y, 1.0)
        self.assertAlmostEqual(z, 0.0)

        x, y, z, _ = matrix44.apply_to_vector(m, (0.0, 0.0, 1.0, 0.0))
        self.assertAlmostEqual(x, 0.0)
        self.assertAlmostEqual(y, 0.0)
        self.assertAlmostEqual(z, 1.0)
Exemplo n.º 13
0
    def test_create_look_at_4(self):
        m = matrix44.create_look_at(
            np.array((0.0, 0.0, 0.0)),
            np.array((0.0, 0.0, -1.0)),
            np.array((0.0, 1.0, 0.0)),
        )

        x, y, z, _ = matrix44.apply_to_vector(m, (1.0, 0.0, 0.0, 0.0))
        self.assertAlmostEqual(x, 1.0)
        self.assertAlmostEqual(y, 0.0)
        self.assertAlmostEqual(z, 0.0)

        x, y, z, _ = matrix44.apply_to_vector(m, (0.0, 1.0, 0.0, 0.0))
        self.assertAlmostEqual(x, 0.0)
        self.assertAlmostEqual(y, 1.0)
        self.assertAlmostEqual(z, 0.0)

        x, y, z, _ = matrix44.apply_to_vector(m, (0.0, 0.0, 1.0, 0.0))
        self.assertAlmostEqual(x, 0.0)
        self.assertAlmostEqual(y, 0.0)
        self.assertAlmostEqual(z, 1.0)
Exemplo n.º 14
0
    def test_create_look_at(self):
        m = matrix44.create_look_at(
            np.array((300.0, 200.0, 100.0)),
            np.array((0.0, 0.0, 10.0)),
            np.array((0.0, 0.0, 1.0)),
        )

        points = [
            (-10.0, -10.0, 0.0, 1.0),
            (-10.0, 10.0, 0.0, 1.0),
            (10.0, -10.0, 0.0, 1.0),
            (10.0, 10.0, 0.0, 1.0),
            (-10.0, -10.0, 20.0, 1.0),
            (-10.0, 10.0, 20.0, 1.0),
            (10.0, -10.0, 20.0, 1.0),
            (10.0, 10.0, 20.0, 1.0),
        ]

        for point in points:
            x, y, z, w = matrix44.apply_to_vector(m, point)
            self.assertTrue(-20.0 < x and x < 20.0)
            self.assertTrue(-20.0 < y and y < 20.0)
            self.assertTrue(z < 0.0)
            self.assertAlmostEqual(w, 1.0)
Exemplo n.º 15
0
    def test_create_look_at(self):
        m = matrix44.create_look_at(
            np.array((300.0, 200.0, 100.0)),
            np.array((0.0, 0.0, 10.0)),
            np.array((0.0, 0.0, 1.0)),
        )

        points = [
            (-10.0, -10.0, 0.0, 1.0),
            (-10.0, 10.0, 0.0, 1.0),
            (10.0, -10.0, 0.0, 1.0),
            (10.0, 10.0, 0.0, 1.0),
            (-10.0, -10.0, 20.0, 1.0),
            (-10.0, 10.0, 20.0, 1.0),
            (10.0, -10.0, 20.0, 1.0),
            (10.0, 10.0, 20.0, 1.0),
        ]

        for point in points:
            x, y, z, w = matrix44.apply_to_vector(m, point)
            self.assertTrue(-20.0 < x and x < 20.0)
            self.assertTrue(-20.0 < y and y < 20.0)
            self.assertTrue(z < 0.0)
            self.assertAlmostEqual(w, 1.0)
Exemplo n.º 16
0
    def initializeGL(self):
        # cube = [
        #     -0.5, -0.5,  0.5,  0.0,  0.0,  1.0, 0.0, 0.0,
        #      0.5, -0.5,  0.5,  0.0,  0.0,  1.0, 1.0, 0.0,
        #      0.5,  0.5,  0.5,  0.0,  0.0,  1.0, 1.0, 1.0,
        #     -0.5,  0.5,  0.5,  0.0,  0.0,  1.0, 0.0, 1.0,

        #     -0.5, -0.5, -0.5,  1.0,  0.0,  0.0, 0.0, 0.0,
        #      0.5, -0.5, -0.5,  1.0,  0.0,  0.0, 1.0, 0.0,
        #      0.5,  0.5, -0.5,  1.0,  0.0,  0.0, 1.0, 1.0,
        #     -0.5,  0.5, -0.5,  1.0,  0.0,  0.0, 0.0, 1.0,

        #      0.5, -0.5, -0.5,  0.0,  1.0,  0.0, 0.0, 0.0,
        #      0.5,  0.5, -0.5,  0.0,  1.0,  0.0, 1.0, 0.0,
        #      0.5,  0.5,  0.5,  0.0,  1.0,  0.0, 1.0, 1.0,
        #      0.5, -0.5,  0.5,  0.0,  1.0,  0.0, 0.0, 1.0,

        #     -0.5,  0.5, -0.5, -1.0,  0.0,  0.0, 0.0, 0.0,
        #     -0.5, -0.5, -0.5, -1.0,  0.0,  0.0, 1.0, 0.0,
        #     -0.5, -0.5,  0.5, -1.0,  0.0,  0.0, 1.0, 1.0,
        #     -0.5,  0.5,  0.5, -1.0,  0.0,  0.0, 0.0, 1.0,

        #     -0.5, -0.5, -0.5,  0.0, -1.0,  0.0, 0.0, 0.0,
        #      0.5, -0.5, -0.5,  0.0, -1.0,  0.0, 1.0, 0.0,
        #      0.5, -0.5,  0.5,  0.0, -1.0,  0.0, 1.0, 1.0,
        #     -0.5, -0.5,  0.5,  0.0, -1.0,  0.0, 0.0, 1.0,

        #      0.5,  0.5, -0.5,  0.0,  0.0, -1.0, 0.0, 0.0,
        #     -0.5,  0.5, -0.5,  0.0,  0.0, -1.0, 1.0, 0.0,
        #     -0.5,  0.5,  0.5,  0.0,  0.0, -1.0, 1.0, 1.0,
        #      0.5,  0.5,  0.5,  0.0,  0.0, -1.0, 0.0, 1.0
        # ]

        cube = [
            -0.7,
            -0.7,
            0,
            0,
            0,
            0,
            0,
            1,
            0.7,
            -0.7,
            0,
            0,
            0,
            0,
            1,
            1,
            0.7,
            0.7,
            0,
            0,
            0,
            0,
            1,
            0,
            -0.7,
            0.7,
            0,
            0,
            0,
            0,
            0,
            0,
        ]
        cube = np.array(cube, dtype=np.float32)

        # indices = [
        #     0, 1, 2,   2, 3, 0,
        #     4, 5, 6,   6, 7, 4,
        #     8, 9,10,  10,11, 8,
        #     12,13,14,  14,15,12,
        #     16,17,18,  18,19,16,
        #     20,21,22,  22,23,20
        # ]
        # indices = np.array(indices, dtype = np.uint32)
        VERTEX_SHADER = """
            #version 410 core

            layout (location = 0) in vec3 position;
            layout (location = 1) in vec3 color;
            layout (location = 2) in vec2 uv;
            
            uniform mat4 model; 
            uniform mat4 view; 
            uniform mat4 projection; 
            uniform sampler2D ourTexture;

            out VS_OUT {
                vec3 vertColor;
                vec2 uv;
            } vs_out;

            void main() {
                vs_out.vertColor = color;
                vs_out.uv = uv;
                gl_Position = projection * view * model * vec4(position, 1.0f);
            }
        """

        FRAGMENT_SHADER = """
            #version 410 core
            uniform sampler2D ourTexture;
            out vec4 outColor;

            in vec3 normal;
            in vec2 uv;
            in vec3 light_dir; 
            in vec3 camera_dir; 

            void main() {
                vec3 N = normalize(normal);
                vec3 V = normalize(camera_dir);
                vec3 L = normalize(light_dir);
                vec3 H = normalize(N + V);

                float spec = pow(max(0, dot(V, reflect(-L, N))), 16);

                float diff = max(0.0, dot(normalize(light_dir), normalize(normal)));
                vec3 col = texture(ourTexture, uv).xyz;
                //outColor = vec4(normal, 1.0);   
                outColor = vec4(vec3(spec + diff + 0.2) * col, 1.0);   
                //outColor = vec4(L, 1.0);   
            }

        """

        GEOMETRY_SHADER = """
            #version 410 core

            layout (triangles) in;
            layout (triangle_strip, max_vertices = 24) out;

            uniform mat4 model;
            uniform mat4 view; 
            uniform mat4 projection; 
            uniform float time;
            uniform sampler2D ourTexture;
            uniform vec3 camera_pos;

            in vec3 te_color[]; 
            in vec2 te_uv[];

            out vec3 normal;
            out vec2 uv;
            out vec3 light_dir;
            out vec3 camera_dir;

            // Define the 8 corners of a cube (back plane, front plane (counter clockwise))
            vec3 cube_corners[8] = vec3[]  (
                vec3(-1.0,  1.0, -1.0), // left top far
                vec3( 1.0,  1.0, -1.0), // right top far
                vec3(-1.0, -1.0, -1.0), // left bottom far
                vec3( 1.0, -1.0, -1.0), // right bottom far
                vec3( 1.0,  1.0,  1.0), // right top near
                vec3(-1.0,  1.0,  1.0), // left top near
                vec3(-1.0, -1.0,  1.0), // left bottom near
                vec3( 1.0, -1.0,  1.0)  // right bottom near
            );

            #define EMIT_V(POS, UV, NORMAL) \
                light_dir = vec3(cos(time_scaled), sin(time_scaled), sin(time_scaled)) - POS; \
                gl_Position = vec4(POS, 1.0); \
                camera_dir = camera_pos - POS; \
                normal = NORMAL; \
                uv = te_uv[0]; \
                EmitVertex()

            #define EMIT_QUAD(P1, P2, P3, P4, NORMAL) \
                EMIT_V(corners[P1], vec2(0.0, 0.0), NORMAL); \
                EMIT_V(corners[P2], vec2(1.0, 0.0), NORMAL); \
                EMIT_V(corners[P3], vec2(0.0, 1.0), NORMAL); \
                EMIT_V(corners[P4], vec2(1.0, 1.0), NORMAL); \
                EndPrimitive()

            #define CALC_NORMAL(p1, p2, p3, p4) \
                normalize(cross(corners[p1] - corners[p2], corners[p3] - corners[p2]))

            vec3 rotX(vec3 z, float s, float c) {
                vec3 newZ = z;
                newZ.yz = vec2(c*z.y + s*z.z, c*z.z - s*z.y);
                return newZ;
            }

            vec3 rotY(vec3 z, float s, float c) {
                vec3 newZ = z;
                newZ.xz = vec2(c*z.x - s*z.z, c*z.z + s*z.x);
                return newZ;
            }

            vec3 rotZ(vec3 z, float s, float c) {
                vec3 newZ = z;
                newZ.xy = vec2(c*z.x + s*z.y, c*z.y - s*z.x);
                return newZ;
            }

            vec3 rotX(vec3 z, float a) {
                return rotX(z, sin(a), cos(a));
            }
            vec3 rotY(vec3 z, float a) {
                return rotY(z, sin(a), cos(a));
            }

            vec3 rotZ(vec3 z, float a) {
                return rotZ(z, sin(a), cos(a));
            }

            mat4 rotX_mat(float a){
                mat4 m;
                m[0] = vec4(1,      0,       0, 0);
                m[1] = vec4(0, cos(a), -sin(a), 0);
                m[2] = vec4(0, sin(a),  cos(a), 0);
                m[3] = vec4(0,      0,      0,  1);
                return m;
            }

            mat4 rotY_mat(float a){
                mat4 m;
                m[0] = vec4( cos(a), 0,  sin(a), 0);
                m[1] = vec4(      0, 1,       0, 0);
                m[2] = vec4(-sin(a), 0,  cos(a), 0);
                m[3] = vec4(      0, 0,      0,  1);
                return m;
            }

            mat4 rotZ_mat(float a){
                mat4 m;
                m[0] = vec4(cos(a), -sin(a), 0, 0);
                m[1] = vec4(sin(a),  cos(a), 0, 0);
                m[2] = vec4(     0,       0, 1, 0);
                m[3] = vec4(     0,       0, 0, 1);
                return m;
            }

            void main()
            {
                // Calculate the 8 cube corners
                vec3 point = gl_in[0].gl_Position.xyz;
                
                vec3 corners[8];
                int i;
                vec3 tex_value = texture(ourTexture, te_uv[0].xy).xyz;
                vec3 rot_angle = ((tex_value - 0.5) * 2.0) * 3.14159265;
                mat4 rot = rotX_mat(rot_angle.x) * rotY_mat(rot_angle.y) * rotZ_mat(rot_angle.z);  
                for(i = 0; i < 8; i++)
                {
                    vec3 corner = cube_corners[i] * 0.05;
                    corner = (projection * view * model * rot * vec4(corner, 1)).xyz;
                    vec3 pos = point + corner;
                    
                    corners[i] = pos;
                }
                float time_scaled = time * 0.1;
                EMIT_QUAD(3, 2, 0, 1, CALC_NORMAL(3, 2, 0, 1)    ); // back
                EMIT_QUAD(6, 7, 5, 4, CALC_NORMAL(6, 7, 5, 4)    ); // front
                EMIT_QUAD(7, 3, 4, 0, CALC_NORMAL(7, 3, 4, 0)    ); // right
                EMIT_QUAD(2, 6, 1, 5, CALC_NORMAL(2, 6, 1, 5)    ); // left
                EMIT_QUAD(5, 4, 1, 0, CALC_NORMAL(5, 4, 1, 0)    ); // top
                EMIT_QUAD(2, 3, 6, 7, CALC_NORMAL(2, 3, 6, 7)    ); // bottom
                EndPrimitive();
            }        
            """

        TESS_CT_SHADER = """
        #version 410 core

        layout(vertices = 3) out;

        in VS_OUT {
            vec3 vertColor;`
            vec2 uv;
        } tc_in[];

        out vec3 tc_color[];
        out vec2 tc_uv[];

        void main(void)
        {
            gl_TessLevelOuter[0] =32.0;
            gl_TessLevelOuter[1] =32.0;
            gl_TessLevelOuter[2] =32.0;

            gl_TessLevelInner[0] =32.0;

            gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;
            tc_color[gl_InvocationID] = tc_in[gl_InvocationID].vertColor;
            tc_uv[gl_InvocationID] = tc_in[gl_InvocationID].uv;
        }
        """

        TESS_EV_SHADER = """
        #version 410 core

        layout(triangles, equal_spacing, ccw) in;
        in vec3 tc_color[];
        in vec2 tc_uv[];

        out vec3 te_color;
        out vec2 te_uv;

        void main()
        {	
            gl_Position.xyzw =	gl_in[0].gl_Position.xyzw * gl_TessCoord.x +
                                gl_in[1].gl_Position.xyzw * gl_TessCoord.y +
                                gl_in[2].gl_Position.xyzw * gl_TessCoord.z;
            te_color = tc_color[0] * gl_TessCoord.x + tc_color[1] * gl_TessCoord.y + tc_color[2] * gl_TessCoord.z;
            te_uv = tc_uv[0] * gl_TessCoord.x + tc_uv[1] * gl_TessCoord.y + tc_uv[2] * gl_TessCoord.z;
        }
        """

        TESS_CT_SHADER_QUAD = """
        #version 410 core

        layout(vertices = 4) out;

        in VS_OUT {
            vec3 vertColor;
            vec2 uv;
        } tc_in[];

        out vec3 tc_color[];
        out vec2 tc_uv[];

        void main(void)
        {
            gl_TessLevelOuter[0] =64.0;
            gl_TessLevelOuter[1] =64.0;
            gl_TessLevelOuter[2] =64.0;
            gl_TessLevelOuter[3] =64.0;

            gl_TessLevelInner[0] =64.0;
            gl_TessLevelInner[1] =64.0;

            gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;
            tc_color[gl_InvocationID] = tc_in[gl_InvocationID].vertColor;
            tc_uv[gl_InvocationID] = tc_in[gl_InvocationID].uv;
        }
        """

        TESS_EV_SHADER_QUAD = """
        #version 410 core

        layout(quads, equal_spacing, ccw) in;
        in vec3 tc_color[];
        in vec2 tc_uv[];

        out vec3 te_color;
        out vec2 te_uv;

        void main()
        {	
            vec3 p0 = mix(gl_in[0].gl_Position.xyz, gl_in[1].gl_Position.xyz, gl_TessCoord.x);
            vec3 p1 = mix(gl_in[3].gl_Position.xyz, gl_in[2].gl_Position.xyz, gl_TessCoord.x);
            vec3 p = mix(p0, p1, gl_TessCoord.y);

            gl_Position.xyzw =	vec4(p, 1);
            te_color = tc_color[0] * gl_TessCoord.x + tc_color[1] * gl_TessCoord.y + tc_color[2] * gl_TessCoord.z;
            vec2 uv0 = mix(tc_uv[0], tc_uv[1], gl_TessCoord.x);
            vec2 uv1 = mix(tc_uv[3], tc_uv[2], gl_TessCoord.x);
            te_uv = mix(uv0, uv1, gl_TessCoord.y);
        }
        """

        vert_shader = shaders.compileShader(FRAGMENT_SHADER,
                                            GL_FRAGMENT_SHADER)
        if glGetShaderiv(vert_shader, GL_COMPILE_STATUS) != GL_TRUE:
            info = glGetShaderInfoLog(vert_shader)
            print(info)
        frag_shader = shaders.compileShader(VERTEX_SHADER, GL_VERTEX_SHADER)
        if glGetShaderiv(frag_shader, GL_COMPILE_STATUS) != GL_TRUE:
            info = glGetShaderInfoLog(frag_shader)
            print(info)
        geometry_shader = shaders.compileShader(GEOMETRY_SHADER,
                                                GL_GEOMETRY_SHADER)
        if glGetShaderiv(geometry_shader, GL_COMPILE_STATUS) != GL_TRUE:
            info = glGetShaderInfoLog(geometry_shader)
            print(info)
        tess_control_shader = shaders.compileShader(TESS_CT_SHADER_QUAD,
                                                    GL_TESS_CONTROL_SHADER)
        if glGetShaderiv(tess_control_shader, GL_COMPILE_STATUS) != GL_TRUE:
            info = glGetShaderInfoLog(tess_control_shader)
            print(info)
        tess_eval_shader = shaders.compileShader(TESS_EV_SHADER_QUAD,
                                                 GL_TESS_EVALUATION_SHADER)

        # Compile The Program and shaders
        shader = glCreateProgram()
        glAttachShader(shader, frag_shader)
        glAttachShader(shader, vert_shader)
        glAttachShader(shader, geometry_shader)
        glAttachShader(shader, tess_control_shader)
        glAttachShader(shader, tess_eval_shader)
        glLinkProgram(shader)
        if glGetProgramiv(shader, GL_LINK_STATUS) != GL_TRUE:
            info = glGetShaderInfoLog(shader)
            print(info)

        print(glGetIntegerv(GL_MAX_PATCH_VERTICES))

        # Load texture
        self.texture = self.make_texture()

        # Create Buffer object in gpu
        VBO = glGenBuffers(1)
        # Bind the buffer
        glBindBuffer(GL_ARRAY_BUFFER, VBO)
        glBufferData(GL_ARRAY_BUFFER, cube.nbytes, cube, GL_STATIC_DRAW)

        #Create EBO
        # EBO = glGenBuffers(1)
        # glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
        # glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, GL_STATIC_DRAW)

        glUseProgram(shader)

        # get the position from shader
        position_loc = 0
        glEnableVertexAttribArray(position_loc)
        glVertexAttribPointer(position_loc, 3, GL_FLOAT, GL_FALSE,
                              4 * 3 + 4 * 3 + 4 * 2, ctypes.c_void_p(4 * 0))
        # glVertexAttribPointer(position_loc, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(4*0))

        # # get the color from shader
        color_loc = 1
        glEnableVertexAttribArray(color_loc)
        glVertexAttribPointer(color_loc, 3, GL_FLOAT, GL_FALSE,
                              4 * 3 + 4 * 3 + 4 * 2, ctypes.c_void_p(4 * 3))
        # glVertexAttribPointer(color_loc, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(4*3))

        uv_loc = 2
        glEnableVertexAttribArray(uv_loc)
        glVertexAttribPointer(uv_loc, 2, GL_FLOAT, GL_FALSE,
                              4 * 3 + 4 * 3 + 4 * 2,
                              ctypes.c_void_p(4 * 3 + 4 * 3))

        glClearColor(0.0, 0.0, 0.0, 1.0)
        glEnable(GL_DEPTH_TEST)
        glViewport(0, 0, self.screen_width, self.screen_height)
        # glViewport(0,0,100,100)
        self.time_loc = glGetUniformLocation(shader, "time")
        self.model_loc = glGetUniformLocation(shader, "model")
        self.view_loc = glGetUniformLocation(shader, "view")
        self.projection_loc = glGetUniformLocation(shader, "projection")
        self.normal_loc = glGetUniformLocation(shader, "normal_m")
        self.camera_loc = glGetUniformLocation(shader, "camera_pos")

        self.camera_pos = Vector3([0.0, 0.0, 0.1])
        self.camera_front = Vector3([0.0, 0.0, -1.0])
        self.camera_up = Vector3([0.0, 1.0, 0.0])
        self.camera_right = Vector3([1.0, 0.0, 0.0])

        self.view = matrix44.create_look_at(
            self.camera_pos, self.camera_pos + self.camera_front,
            self.camera_up)
        self.projection = pyrr.matrix44.create_perspective_projection_matrix(
            90, 1, 0.01, 200)
        glUniformMatrix4fv(self.view_loc, 1, GL_FALSE, self.view)
        glUniformMatrix4fv(self.projection_loc, 1, GL_FALSE, self.projection)
        glUniform3fv(self.camera_loc, 1, self.camera_loc)
Exemplo n.º 17
0
def init():
    global shaderProgram
    global vao
    global vbo
    global model
    global idMod
    global view
    global idView
    global projection
    global idProj
    global idColor
    global idLight
    global idLightPos
    global idViewPos
    global posCam

    glClearColor(0, 0, 0, 0)

    vertex_code = readShaderFile('cuboLuz.vp')
    fragment_code = readShaderFile('cuboLuz.fp')

    # compile shaders and program
    vertexShader = shaders.compileShader(vertex_code, GL_VERTEX_SHADER)
    fragmentShader = shaders.compileShader(fragment_code, GL_FRAGMENT_SHADER)
    shaderProgram = shaders.compileProgram(vertexShader, fragmentShader)

    # cria um vao
    vao = GLuint(0)
    glGenVertexArrays(1, vao)
    glBindVertexArray(vao)

    # dados do objeto q serao passados para o shaders (vertices e vetores normais)
    vertices = np.array(readVertexData(), dtype='f')
    print("vertices:", len(vertices) // 6)
    print(vertices)

    vbo = glGenBuffers(1)  # gera vbos
    glBindBuffer(GL_ARRAY_BUFFER, vbo)
    glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW)
    glVertexAttribPointer(0, 3, GL_FLOAT, False, 6 * sizeof(GLfloat),
                          ctypes.c_void_p(3 * sizeof(GLfloat)))  # vertices
    glVertexAttribPointer(1, 3, GL_FLOAT, False, 6 * sizeof(GLfloat),
                          ctypes.c_void_p(0))  # vertores normais

    # habilita os atributos
    glEnableVertexAttribArray(0)
    glEnableVertexAttribArray(1)

    # cria a matriz de transformação
    model = matrix44.create_identity()

    #ratacoes
    rotY = matrix44.create_from_y_rotation(math.radians(45))
    rotx = matrix44.create_from_x_rotation(math.radians(45))
    rotT = matrix44.multiply(rotY, rotx)

    model = matrix44.multiply(model, rotT)

    posCam = [0.0, 0.0, 0.0]
    view = matrix44.create_look_at(posCam, [0.0, 0.0, -0.1], [0.0, 1.0, 0.0])
    projection = matrix44.create_orthogonal_projection(-2.0, 2.0, -2.0, 2.0,
                                                       2.0,
                                                       -2.0)  # amplia a visao
    print(f'Model:\n{model}\n')
    print(f'View:\n{view}\n')
    print(f'Projection:\n{projection}\n')

    # atribui uma variavel uniforme para cada matriz
    idMod = glGetUniformLocation(shaderProgram, "model")
    idView = glGetUniformLocation(shaderProgram, "view")
    idProj = glGetUniformLocation(shaderProgram, "projection")

    # iluminação
    idColor = glGetUniformLocation(shaderProgram, "objectColor")
    idLight = glGetUniformLocation(shaderProgram, "lightColor")
    idLightPos = glGetUniformLocation(shaderProgram, "lightPos")
    idViewPos = glGetUniformLocation(shaderProgram, "viewPos")

    # Note that this is allowed, the call to glVertexAttribPointer registered VBO
    # as the currently bound vertex buffer object so afterwards we can safely unbind
    glBindBuffer(GL_ARRAY_BUFFER, 0)
    # Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs)
    glBindVertexArray(0)
Exemplo n.º 18
0
 def get_view_matrix(self):
     return matrix44.create_look_at(self.camera_pos, self.camera_pos + self.camera_front, self.camera_up)
Exemplo n.º 19
0
 def get_view_matrix(self):
     return matrix44.create_look_at(self.pos, self.pos + self.front,
                                    self.up)
Exemplo n.º 20
0
def init(obj, lista_obj):
    global shaderProgram
    global vao
    global vbo
    global shadingName
    # variaveis das tranformacoes
    global projection
    global idProj
    global idView
    global model
    global view
    global uMat
    global shear
    global shearFlag
    #camera e lookat
    global poscam
    global lookat
    # variaveis dos reflections
    global ambient
    global diffuse
    global specular
    global reflectionFlag
    global reflec
    # variaveis da luzes do uniform
    global idColor
    global idViewPos
    global idLight
    global idLightPos

    # variaveis das forcas do reflections
    global ambientForce
    global diffuseForce
    global specularForce

    glClearColor(0, 0, 0, 1)
    # carrega o shading baseado no nome que foi passado
    if (shadingName == 'phong'):
        for i in lista_obj:
            reflectionFlag = 1
            i.ambient = 1
            i.diffuse = 1
            i.specular = 1
            vertex_code = readShaderFile('reflect.vp')
            fragment_code = readShaderFile('reflect.fp')
    elif (shadingName == 'smooth'):
        for i in lista_obj:
            if (i.ambient == 1 or i.diffuse == 1 or i.specular == 1):
                # caso tenha sido feito o comando reflection atribuimos 1 para a flag e chamando o shaders das reflections
                reflectionFlag = 1
                vertex_code = readShaderFile('smooth.vp')
                fragment_code = readShaderFile('smooth.fp')
    elif (shadingName == 'flat'):
        for i in lista_obj:
            if (i.ambient == 1 or i.diffuse == 1 or i.specular == 1):
                # caso tenha sido feito o comando reflection atribuimos 1 para a flag e chamando o shaders das reflections
                reflectionFlag = 1
                vertex_code = readShaderFile('flat.vp')
                fragment_code = readShaderFile('flat.fp')

    else:
        vertex_code = readShaderFile('none.vp')
        fragment_code = readShaderFile('none.fp')

    for i in lista_obj:  # percorre a lista dos objetos, verificando os atributos das reflectons
        if (i.ambient == 1 or i.diffuse == 1 or i.specular == 1):
            # caso tenha sido feito o comando reflection atribuimos 1 para a flag e chamando o shaders das reflections
            reflectionFlag = 1
            vertex_code = readShaderFile('reflect.vp')
            fragment_code = readShaderFile('reflect.fp')
        else:
            vertex_code = readShaderFile('none.vp')
            fragment_code = readShaderFile('none.fp')

    # compile shaders and program
    vertexShader = shaders.compileShader(vertex_code, GL_VERTEX_SHADER)
    fragmentShader = shaders.compileShader(fragment_code, GL_FRAGMENT_SHADER)
    shaderProgram = shaders.compileProgram(vertexShader, fragmentShader)

    # Create and bind the Vertex Array Object
    vao = GLuint(0)
    glGenVertexArrays(1, vao)
    glBindVertexArray(vao)

    # lendo os obj pegando vertices e normais
    vertices = np.array(lendo_obj(obj), dtype='f')
    print("vertices:", len(vertices) // 6)

    vbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, vbo)
    glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW)
    glVertexAttribPointer(
        0, 3, GL_FLOAT, False, 6 * sizeof(GLfloat),
        ctypes.c_void_p(3 *
                        sizeof(GLfloat)))  # first 0 is the location in shader
    glVertexAttribPointer(
        1, 3, GL_FLOAT, False, 6 * sizeof(GLfloat),
        ctypes.c_void_p(0))  # first 0 is the location in shader
    glEnableVertexAttribArray(0)
    glEnableVertexAttribArray(1)

    #verifica em cada objeto a scala
    for i in lista_obj:
        i.model = pyrr.matrix44.create_identity()
        scale = pyrr.matrix44.create_from_scale(
            [i.scale_r, i.scale_g, i.scale_b], dtype='f')
        i.model = pyrr.matrix44.multiply(i.model, scale)

    #verifica em cada objeto se precisa fazer rotacao
    for i in lista_obj:
        if (i.rotate_x == 1):
            rotx = pyrr.matrix44.create_from_x_rotation(
                math.radians(i.rotate_grau))
        else:
            rotx = pyrr.matrix44.create_from_x_rotation(math.radians(0))

        if (i.rotate_y == 1):
            rotY = pyrr.matrix44.create_from_y_rotation(
                math.radians(i.rotate_grau))
        else:
            rotY = pyrr.matrix44.create_from_y_rotation(math.radians(0))

        if (i.rotate_z == 1):
            rotZ = pyrr.matrix44.create_from_z_rotation(
                math.radians(i.rotate_grau))
        else:
            rotZ = pyrr.matrix44.create_from_z_rotation(math.radians(0))

        rotT = pyrr.matrix44.multiply(rotY, rotx)
        rotT = pyrr.matrix44.multiply(rotT, rotZ)
        i.model = pyrr.matrix44.multiply(i.model, rotT)

    if (shearFlag == 1):
        for i in lista_obj:
            i.model = pyrr.matrix44.multiply(i.model, i.shear)

    #verifica em cada objeto a translacao
    for i in lista_obj:
        translate = pyrr.matrix44.create_from_translation(
            [i.translate_x, i.translate_y, i.translate_z])
        i.model = pyrr.matrix44.multiply(i.model, translate)

    #coloca os valores da view
    view = matrix44.create_look_at(poscam, lookat, [0.0, 1.0, 0.0])
    #redimenciona o mundo
    projection = matrix44.create_orthogonal_projection(-2.0, 2.0, -2.0, 2.0,
                                                       -2.0, 2.0)

    # atribui uma variavel uniforme para matriz de transformacao
    uMat = glGetUniformLocation(shaderProgram, "model")
    #atribui uma variavel uniforme para view
    idView = glGetUniformLocation(shaderProgram, "view")
    #atribui uma variavel uniform para projection
    idProj = glGetUniformLocation(shaderProgram, "projection")

    # verificando se a reflections foi ativada
    if (reflectionFlag == 1):
        # atribuindo os uniformes para uma variavel
        idColor = glGetUniformLocation(shaderProgram, "objectColor")
        idLight = glGetUniformLocation(shaderProgram, "lightColor")
        idLightPos = glGetUniformLocation(shaderProgram, "lightPos")
        idViewPos = glGetUniformLocation(shaderProgram, "viewPos")
        reflec = glGetUniformLocation(shaderProgram, "reflecc")
        ambientForce = glGetUniformLocation(shaderProgram, "ambientForce")
        diffuseForce = glGetUniformLocation(shaderProgram, "diffuseForce")
        specularForce = glGetUniformLocation(shaderProgram, "specularForce")

    # Note that this is allowed, the call to glVertexAttribPointer registered VBO
    # as the currently bound vertex buffer object so afterwards we can safely unbind
    glBindBuffer(GL_ARRAY_BUFFER, 0)
    # Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs)
    glBindVertexArray(0)
Exemplo n.º 21
0
def drawlight(lista_luz):
    global shaderProgram
    global vao
    global vbo
    global projection
    global idProj
    global idView
    global model
    global view
    global uMat
    global poscam
    global lookat
    global ambient
    global diffuse
    global specular
    global lightMode

    glClearColor(0, 0, 0, 1)

    vertex_code = readShaderFile('none.vp')
    fragment_code = readShaderFile('none.fp')

    # compile shaders and program
    vertexShader = shaders.compileShader(vertex_code, GL_VERTEX_SHADER)
    fragmentShader = shaders.compileShader(fragment_code, GL_FRAGMENT_SHADER)
    shaderProgram = shaders.compileProgram(vertexShader, fragmentShader)

    # Create and bind the Vertex Array Object
    vao = GLuint(0)
    glGenVertexArrays(1, vao)
    glBindVertexArray(vao)

    obj = 'cube'
    # lendo os obj pegando vertices e normais
    vertices = np.array(lendo_obj(obj), dtype='f')
    print("vertices:", len(vertices) // 6)

    vbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, vbo)
    glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW)
    glVertexAttribPointer(
        0, 3, GL_FLOAT, False, 6 * sizeof(GLfloat),
        ctypes.c_void_p(3 *
                        sizeof(GLfloat)))  # first 0 is the location in shader
    glVertexAttribPointer(
        1, 3, GL_FLOAT, False, 6 * sizeof(GLfloat),
        ctypes.c_void_p(0))  # first 0 is the location in shader
    glEnableVertexAttribArray(0)
    glEnableVertexAttribArray(1)

    #verifica em cada objeto a scala
    for i in lista_luz:
        i.model = pyrr.matrix44.create_identity()
        scale = pyrr.matrix44.create_from_scale([0.03, 0.03, 0.03], dtype='f')
        i.model = pyrr.matrix44.multiply(i.model, scale)

    #verifica em cada objeto a translacao
    for i in lista_luz:
        translate = pyrr.matrix44.create_from_translation([i.x, i.y, i.z])
        i.model = pyrr.matrix44.multiply(i.model, translate)

    #coloca os valores da view
    view = matrix44.create_look_at(poscam, lookat, [0.0, 1.0, 0.0])
    #redimenciona o mundo
    projection = matrix44.create_orthogonal_projection(-2.0, 2.0, -2.0, 2.0,
                                                       -2.0, 2.0)

    # atribui uma variavel uniforme para matriz de transformacao
    uMat = glGetUniformLocation(shaderProgram, "model")
    #atribui uma variavel uniforme para view
    idView = glGetUniformLocation(shaderProgram, "view")
    #atribui uma variavel uniform para projection
    idProj = glGetUniformLocation(shaderProgram, "projection")

    # Note that this is allowed, the call to glVertexAttribPointer registered VBO
    # as the currently bound vertex buffer object so afterwards we can safely unbind
    glBindBuffer(GL_ARRAY_BUFFER, 0)
    # Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs)
    glBindVertexArray(0)
Exemplo n.º 22
0
 def createView(self):
     self.view = mat4.create_look_at(self.camPos, self.camLookAt, [0.0, 1.0, 0.0])