Example #1
0
    def randomize_living_geometry(self, side):
        if side:
            area_pos = np.array([1.75 - 0.5 * random.random(), 0, -1.75])
        else:
            area_pos = np.array([1.75 - 0.5 * random.random(), 0, 1.25])

        if random.random() < 0.125:
            area_pos[1] = -3
            for sofa in self.geometry["sofas"]:
                sofa.visible = False
            self.geometry["armchair"][0].visible = False
            self.geometry["rug"][0].visible = False
            for coffee_table in self.geometry["coffee_tables"]:
                coffee_table.visible = False

        self.living_pos = area_pos
        living_transform = m44.multiply(m44.create_from_y_rotation(random.random() * 2 * np.pi), m44.create_from_translation(area_pos))
        
        # Select sofa and transform
        sofa_index = int(random.random() * len(self.geometry["sofas"]))
        sofa_transform = m44.multiply(m44.create_from_y_rotation(0.5 * np.pi), m44.create_from_translation(np.array([1.05, 0, 0.05])))
        for idx in range(len(self.geometry["sofas"])):
            if idx == sofa_index:
                self.geometry["sofas"][idx].transform = m44.multiply(sofa_transform, living_transform)
                self.geometry["sofas"][idx].visible = True
            else:
                self.geometry["sofas"][idx].transform = self.hide_transform
                self.geometry["sofas"][idx].visible = False
        
        armchair_transform = m44.multiply(m44.create_from_y_rotation(-0.83 * np.pi + 0.1 * np.pi * (random.random() - 0.5)), m44.create_from_translation(np.array([-0.9, 0, 0.65])))
        self.geometry["armchair"][0].transform = m44.multiply(armchair_transform, living_transform)
        self.geometry["armchair"][0].visible = True

        rug_transform = m44.multiply(m44.create_from_y_rotation(0.05 * np.pi * (random.random() - 0.5)), m44.create_from_translation(np.array([0, 0.005, 0])))
        self.geometry["rug"][0].transform = m44.multiply(rug_transform, living_transform)
        self.geometry["rug"][0].visible = True

        # Select coffee table and transform
        coffee_table_transform = m44.multiply(m44.create_from_y_rotation(-0.5 * np.pi), m44.create_from_translation(np.array([0.1, 0.006, 0])))
        coffee_table_index = int(random.random() * len(self.geometry["coffee_tables"]))
        for idx in range(len(self.geometry["coffee_tables"])):
            if idx == coffee_table_index:
                self.geometry["coffee_tables"][idx].transform = m44.multiply(coffee_table_transform, living_transform)
                self.geometry["coffee_tables"][idx].visible = True
            else:
                self.geometry["coffee_tables"][idx].transform = self.hide_transform
                self.geometry["coffee_tables"][idx].visible = False
Example #2
0
 def test_create_from_y_rotation(self):
     mat = matrix44.create_from_y_rotation(np.pi / 2.)
     self.assertTrue(
         np.allclose(np.dot([1., 0., 0., 1.], mat), [0., 0., 1., 1.]))
     self.assertTrue(
         np.allclose(np.dot([0., 1., 0., 1.], mat), [0., 1., 0., 1.]))
     self.assertTrue(
         np.allclose(np.dot([0., 0., 1., 1.], mat), [-1., 0., 0., 1.]))
Example #3
0
 def update_view_matrix(self):
     self.viewMatrix = matrix44.multiply(
         matrix44.create_from_x_rotation(math.radians(self.pitch)),
         matrix44.create_from_y_rotation(math.radians(self.yaw)))
     self.viewMatrix = matrix44.multiply(
         self.viewMatrix,
         matrix44.create_from_translation(
             Vector3([0, 0, -self.distanceFromPlayer.actual])))
Example #4
0
def init():
    global shaderProgram
    global vao
    global vbo
    global mvp

    glClearColor(0, 0, 0, 0)

    vertex_code = readShaderFile('piramide.vp')
    fragment_code = readShaderFile('piramide.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)

    # Create and bind the Vertex Buffer Object
    vbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, vbo)
    glBufferData(GL_ARRAY_BUFFER, piramide['vertices'], GL_STATIC_DRAW)
    glVertexAttribPointer(
        0, 3, GL_FLOAT, False, 6 * sizeof(GLfloat),
        ctypes.c_void_p(0))  # first 0 is the location in shader
    glVertexAttribPointer(
        1, 3, GL_FLOAT, False, 6 * sizeof(GLfloat),
        ctypes.c_void_p(3 *
                        sizeof(GLfloat)))  # first 0 is the location in shader

    glEnableVertexAttribArray(0)
    # 0=location do atributo, tem que ativar todos os atributos inicialmente sao desabilitados por padrao
    glEnableVertexAttribArray(1)
    # 1=location do atributo, tem que ativar todos os atributos inicialmente sao desabilitados por padrao

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

    # rotacao
    rot = matrix44.create_from_y_rotation(math.radians(10))

    mvp['model'] = matrix44.multiply(mvp['model'], rot)  # matrix model
    mvp['view'] = matrix44.create_identity()  # matrix view
    mvp['projection'] = matrix44.create_identity()  # matrix projection

    # atribui uma variavel uniforme para cada matriz
    mvp['idMod'] = glGetUniformLocation(shaderProgram, "model")
    mvp['idView'] = glGetUniformLocation(shaderProgram, "view")
    mvp['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)
Example #5
0
    def randomize_dining_geometry(self, side):
        if side:
            area_pos = np.array([1.75 - 0.5 * random.random(), 0, 1.55])
        else:
            area_pos = np.array([1.75 - 0.5 * random.random(), 0, -1.75])

        if random.random() < 0.125:
            area_pos[1] = -3
            for table in self.geometry["tables"]:
                table.visible = False
            for chair in self.geometry["chairs"]:
                chair.visible = False

        self.dining_pos = area_pos
        dining_transform = m44.multiply(m44.create_from_y_rotation(random.random() * 2 * np.pi), m44.create_from_translation(area_pos))

        # Randomize table
        self.table_index = int(random.random() * len(self.geometry["tables"])) 
        for idx in range(len(self.geometry["tables"])):
            if idx == self.table_index:
                self.geometry["tables"][idx].transform = dining_transform
                self.geometry["tables"][idx].visible = True
            else:
                self.geometry["tables"][idx].transform = self.hide_transform
                self.geometry["tables"][idx].visible = False

        # Randomize chairs
        chairTranslations = np.array([[-0.45, 0, -0.75], [0.25, 0, -0.75], [-.45, 0, 0.75], [0.25, 0, 0.75]])
        chairTransformations = [m44.create_from_translation(x) for x in chairTranslations]
        chair_index = int(random.random() * self.num_chair_models)
        counter = 0
        for idx in range(len(self.geometry["chairs"])):
            if idx // self.num_chair_models == chair_index and random.random() > 0.25:
                matrix = chairTransformations[counter]
                if counter < 2:
                    matrix = m44.multiply(m44.create_from_y_rotation(np.pi), matrix)
                matrix = m44.multiply(m44.create_from_y_rotation((random.random() - 0.5) * np.pi / 6), matrix)
                matrix = m44.multiply(matrix, dining_transform)
                self.geometry["chairs"][idx].transform = matrix
                self.geometry["chairs"][idx].visible = True
                counter += 1
            else:
                self.geometry["chairs"][idx].transform = self.hide_transform
                self.geometry["chairs"][idx].visible = False
Example #6
0
        def rotated_y():
            quat = quaternion.create_from_y_rotation( math.pi )
            result = matrix44.create_from_quaternion( quat )

            expected = matrix44.create_from_y_rotation( math.pi )

            self.assertTrue(
                numpy.allclose( result, expected ),
                "Matrix44 from quaternion incorrect with PI rotation about Y"
                )
Example #7
0
        def rotated_y():
            mat = matrix44.create_from_y_rotation( math.pi )
            vec = vector3.unit.x

            result = matrix44.apply_to_vector( mat, vec )

            expected = -vec

            self.assertTrue(
                numpy.allclose( result, expected ),
                "Matrix44 apply_to_vector incorrect with rotation about Y"
                )
Example #8
0
    def model_matrix(terrain):
        translation_matrix = np.matrix([[1, 0, 0, terrain.x], [0, 1, 0, 0],
                                        [0, 0, 1, terrain.z], [0, 0, 0, 1]])
        rotation_matrix_x = matrix44.create_from_x_rotation(np.radians(0))
        rotation_matrix_y = matrix44.create_from_y_rotation(np.radians(0))
        rotation_matrix_z = matrix44.create_from_z_rotation(np.radians(0))
        scale_matrix = matrix44.create_from_scale([1, 1, 1])

        tx = matrix44.multiply(translation_matrix, rotation_matrix_x)
        txy = matrix44.multiply(tx, rotation_matrix_y)
        tr = matrix44.multiply(txy, rotation_matrix_z)
        model_matrix = matrix44.multiply(tr, scale_matrix)

        return model_matrix
 def batch_render(self, list_translasi, vertical=True): # me-render banyak fence dengan tekstur sama
     glBindVertexArray(self.vao_fence)
     glBindTexture(GL_TEXTURE_2D, self.texture)
     model_loc = ObjectShader.model_loc
     if not vertical:
         rotate = matrix44.create_from_y_rotation(numpy.pi/2) # 90 degree rotation
         
     for translasi in list_translasi:
         fence_model = matrix44.create_from_translation(Vector3(translasi)) #this is the model transformation matrix
         if not vertical:
             fence_model = matrix44.multiply(rotate, fence_model)
         c_fence_model = numpy.ctypeslib.as_ctypes(fence_model.flatten().astype('float32'))
         glUniformMatrix4fv(model_loc, 1, GL_FALSE, c_fence_model)
         glDrawArrays(GL_TRIANGLES, 0, Fence.num_verts)
     glBindVertexArray(0)
Example #10
0
    def randomize_geometry(self):
        indices = list(range(len(self.geometry["objs"])))
        random.shuffle(indices)

        taken_positions = []

        # Place objects randomly in the scene while avoiding intersections
        for l in range(len(self.geometry["objs"])):
            index = indices[l]
            visibility = random.random() > 0.5
            position = np.array([0, 0])
            if visibility:
                occupied = False
                k = 0
                while k < 5:
                    occupied = False
                    position[0] = random.random() * 4.5 - 2.25
                    position[1] = random.random() * 4.5 - 2.25

                    # See if there are any intersections
                    for taken in taken_positions:
                        length = np.linalg.norm(position - taken)
                        if length < 1.55:
                            occupied = True
                            break
                    
                    k += 1

                    # Found an empty position
                    if not occupied:
                        break

                if not occupied:
                    taken_positions.append(position*1)
                else:
                    visibility = False
            
            if visibility:
                translation = m44.create_from_translation(np.array([position[0], -0.5, position[1]]))
                rotation = m44.create_from_y_rotation(2 * math.pi * random.random())
                transform = m44.multiply(rotation, translation)
                self.geometry["objs"][index].visible = True
            else:
                transform = m44.create_from_translation(np.array([0, -5, 0]))
                self.geometry["objs"][index].visible = False

            self.geometry["objs"][index].transform = transform
Example #11
0
    def randomize_teapot_geometry(self, side):
        r = random.random()
        # Put on living room table
        if r < 0.5:
            pos = np.array([0.1, 0.45, 0]) + self.living_pos
        # Put on dining room table
        else:
            if self.table_index == 0:
                pos = np.array([0, 0.7, 0]) + self.dining_pos
            elif self.table_index == 1 or self.table_index == 2:
                pos = np.array([0, 0.72, 0]) + self.dining_pos
            else:
                pos = np.array([0, 0.64, 0]) + self.dining_pos

        if pos[1] < 0:
            pos[1] = 0

        self.geometry["teapot"][0].transform = m44.multiply(m44.create_from_y_rotation(2 * np.pi * random.random()), m44.create_from_translation(pos))
Example #12
0
    def view_matrix(camera):
        translation_matrix = np.matrix([[1, 0, 0, -camera.position[0]],
                                        [0, 1, 0, -camera.position[1]],
                                        [0, 0, 1, -camera.position[2]],
                                        [0, 0, 0, 1]])
        rotation_matrix_x = matrix44.create_from_x_rotation(
            np.radians(camera.pitch))
        rotation_matrix_y = matrix44.create_from_y_rotation(
            np.radians(camera.yaw))
        rotation_matrix_z = matrix44.create_from_z_rotation(
            np.radians(camera.roll))

        rot = np.dot(rotation_matrix_x,
                     np.dot(rotation_matrix_y, rotation_matrix_z))
        txy = matrix44.multiply(rot, translation_matrix)
        view_matrix = matrix44.multiply(txy, rotation_matrix_z)

        return view_matrix
Example #13
0
    def model_matrix(thing):
        translation_matrix = np.matrix([[1, 0, 0, thing.position[0]],
                                        [0, 1, 0, thing.position[1]],
                                        [0, 0, 1, thing.position[2]],
                                        [0, 0, 0, 1]])
        rotation_matrix_x = matrix44.create_from_x_rotation(
            np.radians(thing.rotX))
        rotation_matrix_y = matrix44.create_from_y_rotation(
            np.radians(thing.rotY))
        rotation_matrix_z = matrix44.create_from_z_rotation(
            np.radians(thing.rotZ))
        scale_matrix = matrix44.create_from_scale(thing.scale)

        tx = matrix44.multiply(translation_matrix, rotation_matrix_x)
        txy = matrix44.multiply(tx, rotation_matrix_y)
        tr = matrix44.multiply(txy, rotation_matrix_z)
        model_matrix = matrix44.multiply(tr, scale_matrix)

        return model_matrix
Example #14
0
def on_draw():
    global time
    time += 0.01
    game_window.clear()
    ctx.screen.use()

    trans = matrix44.create_from_translation(
        (math.cos(time), math.sin(time / 5) * 5 - 6, 0))
    rot = matrix44.create_from_y_rotation(math.pi / 2)
    mat = matrix44.multiply(trans, rot)

    ctx.enable(moderngl.DEPTH_TEST | moderngl.CULL_FACE)
    scene.draw(
        projection_matrix=projection,
        camera_matrix=mat,
    )

    fbo.use()
    fbo.clear()

    gl.glUseProgram(0)
    gl.glBindVertexArray(0)

    main_batch.draw()
    counter.draw()

    trans = matrix44.create_from_translation([0, 0, -1])
    rot = matrix44.create_from_axis_rotation(
        [math.sin(time) / 4,
         math.cos(time) / 4,
         math.sin(time) / 20],
        math.sin(time) / 5)
    mat = matrix44.multiply(trans, rot)

    ctx.screen.use()
    fbo.color_attachments[0].use(location=0)
    texture_program['scale'].value = (800 / window_x, 600 / window_y)
    texture_program['m_proj'].write(projection)
    texture_program['m_view'].write(mat.astype('f4').tobytes())
    quad.render(texture_program)
Example #15
0
    def test_translation_with_rotation( self ):
        root = SceneNode( '/root' )
        child = SceneNode( '/child' )
        
        root.add_child( child )

        #
        # Rotate 180 deg (1 * pi) about the Y axis (yaw)
        #
        root.transform.object.rotate_y( math.pi )

        identity = matrix44.identity()
        root_matrix = matrix44.create_from_y_rotation( math.pi )

        #
        # Translate the child node
        #
        child.transform.translation = [1.0, 1.0, 1.0]

        test_translation( self, root.transform, [0.0, 0.0, 0.0] )
        test_translation( self, root.world_transform, [0.0, 0.0, 0.0] )
        test_translation( self, child.transform, [1.0, 1.0, 1.0] )
        # Y does not invert
        test_translation( self, child.world_transform, [-1.0, 1.0,-1.0] )
Example #16
0
def main():

    # initialize glfw
    if not glfw.init():
        return

    w_width, w_height = 800, 600
    aspect_ratio = w_width / w_height

    window = glfw.create_window(w_width, w_height, "My OpenGL window", None,
                                None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    glfw.set_window_size_callback(window, window_resize)
    glfw.set_key_callback(window, key_callback)
    glfw.set_cursor_pos_callback(window, mouse_callback)

    obj = ObjLoader()
    obj.load_model("objects/sphere.obj")

    texture_offset = len(obj.vertex_index) * 12
    normal_offset = (texture_offset + len(obj.texture_index) * 8)

    shader = ShaderLoader.compile_shader("shaders/main_vert.vs",
                                         "shaders/main_frag.fs")

    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, obj.model.itemsize * len(obj.model),
                 obj.model, GL_STATIC_DRAW)

    #positions
    position = glGetAttribLocation(shader, "position")
    glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE,
                          obj.model.itemsize * 3, ctypes.c_void_p(0))
    glEnableVertexAttribArray(position)
    #textures
    texCoords = glGetAttribLocation(shader, "inTexCoords")
    glVertexAttribPointer(texCoords, 2, GL_FLOAT, GL_FALSE,
                          obj.model.itemsize * 2,
                          ctypes.c_void_p(texture_offset))
    glEnableVertexAttribArray(texCoords)
    #normals
    normals = glGetAttribLocation(shader, "vertNormal")
    glVertexAttribPointer(normals, 3, GL_FLOAT,
                          GL_FALSE, obj.model.itemsize * 3,
                          ctypes.c_void_p(normal_offset))
    glEnableVertexAttribArray(normals)

    for planet in planets:
        texture = TextureLoader.load_texture(planets[planet]['image_path'])
        planets[planet]['texture'] = texture

        #initial position
        if planet == 'sun' or planet == 'stars':
            distance_from_sun = planets[planet]['distance_from_sun']
            planets[planet]['initial_position'] = [
                distance_from_sun, 0.0, distance_from_sun
            ]
        else:
            distance_from_sun = 30.0 + planets[planet]['distance_from_sun']
            x = round(random.uniform(-distance_from_sun, distance_from_sun), 3)
            z = round(math.sqrt((distance_from_sun**2) - (x**2)), 3)
            planets[planet]['initial_position'] = [x, 0.0, z]

    glEnable(GL_TEXTURE_2D)

    glUseProgram(shader)

    glClearColor(0.0, 0.2, 0.2, 1.0)
    glEnable(GL_DEPTH_TEST)

    projection = pyrr.matrix44.create_perspective_projection_matrix(
        65.0, w_width / w_height, 0.1, 10000.0)
    scale = pyrr.matrix44.create_from_scale(pyrr.Vector3([0.1, 0.1, 0.1]))

    view_loc = glGetUniformLocation(shader, "view")
    proj_loc = glGetUniformLocation(shader, "projection")
    model_loc = glGetUniformLocation(shader, "model")
    normal_loc = glGetUniformLocation(shader, "normalMatrix")
    scale_loc = glGetUniformLocation(shader, "scale")
    scale_planet_loc = glGetUniformLocation(shader, "scale_planet")

    glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)
    glUniformMatrix4fv(scale_loc, 1, GL_FALSE, scale)

    Global_ambient_loc = glGetUniformLocation(shader, "Global_ambient")
    Light_ambient_loc = glGetUniformLocation(shader, "Light_ambient")
    Light_diffuse_loc = glGetUniformLocation(shader, "Light_diffuse")
    Light_specular_loc = glGetUniformLocation(shader, "Light_specular")
    Light_location_loc = glGetUniformLocation(shader, "Light_location")
    Material_ambient_loc = glGetUniformLocation(shader, "Material_ambient")
    Material_diffuse_loc = glGetUniformLocation(shader, "Material_diffuse")
    Material_specular_loc = glGetUniformLocation(shader, "Material_specular")
    Material_shininess_loc = glGetUniformLocation(shader, "Material_shininess")

    glUniform4f(Global_ambient_loc, 0.8, 0.8, 0.9, 0.1)
    glUniform4f(Light_ambient_loc, 0.3, 0.3, 0.3, 1.0)
    glUniform4f(Light_diffuse_loc, 0.25, 0.25, 0.25, 1.0)
    glUniform4f(Light_specular_loc, 0.9, 0.9, 0.9, 1.0)
    glUniform3f(Light_location_loc, 0, 0, 0)

    # *******************************************************************************************

    # obj2 = ObjLoader()
    # obj2.load_model("objects/cruiser.obj")
    #
    # shader2 = ShaderLoader.compile_shader("shaders/vert.vs", "shaders/frag.fs")
    #
    # VBO2 = glGenBuffers(1)
    # glBindBuffer(GL_ARRAY_BUFFER, VBO2)
    # glBufferData(GL_ARRAY_BUFFER, obj2.model.itemsize * len(obj2.model), obj2.model, GL_STATIC_DRAW)
    #
    # # positions
    # position2 = glGetAttribLocation(shader, "position")
    # glVertexAttribPointer(position2, 3, GL_FLOAT, GL_FALSE, obj2.model.itemsize * 3, ctypes.c_void_p(0))
    # glEnableVertexAttribArray(position2)
    # # textures
    # texCoords2 = glGetAttribLocation(shader2, "inTexCoords")
    # glVertexAttribPointer(texCoords2, 2, GL_FLOAT, GL_FALSE, obj2.model.itemsize * 2, ctypes.c_void_p(texture_offset))
    # glEnableVertexAttribArray(texCoords2)
    # # normals
    # normals2 = glGetAttribLocation(shader2, "vertNormal")
    # glVertexAttribPointer(normals2, 3, GL_FLOAT, GL_FALSE, obj2.model.itemsize * 3, ctypes.c_void_p(normal_offset))
    # glEnableVertexAttribArray(normals2)
    #
    #
    # texture2 = TextureLoader.load_texture(planets['cruiser']['image_path'])
    # distance_from_sun = planets['cruiser']['distance_from_sun']
    # planets['cruiser']['initial_position'] = [distance_from_sun, 0.0, distance_from_sun]
    #
    # glUseProgram(shader2)
    #
    #
    # Global_ambient_loc = glGetUniformLocation(shader, "Global_ambient")
    # Light_ambient_loc = glGetUniformLocation(shader, "Light_ambient")
    # Light_diffuse_loc = glGetUniformLocation(shader, "Light_diffuse")
    # Light_specular_loc = glGetUniformLocation(shader, "Light_specular")
    # Light_location_loc = glGetUniformLocation(shader, "Light_location")
    # Material_ambient_loc = glGetUniformLocation(shader, "Material_ambient")
    # Material_diffuse_loc = glGetUniformLocation(shader, "Material_diffuse")
    # Material_specular_loc = glGetUniformLocation(shader, "Material_specular")
    # Material_shininess_loc = glGetUniformLocation(shader, "Material_shininess")
    #
    # glUniform4f(Global_ambient_loc, 0.8, 0.8, 0.9, 0.1)
    # glUniform4f(Light_ambient_loc, 0.3, 0.3, 0.3, 1.0)
    # glUniform4f(Light_diffuse_loc, 0.25, 0.25, 0.25, 1.0)
    # glUniform4f(Light_specular_loc, 0.9, 0.9, 0.9, 1.0)
    # glUniform3f(Light_location_loc, 0, 0, 0)
    # glUniform4f(Material_ambient_loc, 0.4, 0.4, 0.4, 1.0)
    # glUniform4f(Material_diffuse_loc, 0.15, 0.15, 0.15, 1.0)
    # glUniform4f(Material_specular_loc, 1.0, 1.0, 1.0, 1.0)
    # glUniform1f(Material_shininess_loc, .95)

    # ******************************************************************************************

    while not glfw.window_should_close(window):
        glfw.poll_events()

        do_movement()
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        time = glfw.get_time()

        view = cam.get_view_matrix()
        glUniformMatrix4fv(view_loc, 1, GL_FALSE, view)

        # **********************************planets****************************************
        for planet in planets:
            if planet == 'cruiser':
                glBindTexture(GL_TEXTURE_2D, texture2)
            else:
                glBindTexture(GL_TEXTURE_2D, planets[planet]['texture'])

            revolution_speed = time * planets[planet][
                'revolution_ratio_relative_to_earth']
            rotation_speed = time * planets[planet][
                'rotation_ratio_relative_to_earth']
            # scale planet
            scale_factor = planets[planet]['size_ratio_relative_to_earth']
            scale_planet = matrix44.create_from_scale(
                pyrr.Vector3([scale_factor, scale_factor, scale_factor]))
            glUniformMatrix4fv(scale_planet_loc, 1, GL_FALSE, scale_planet)

            # translation
            model = matrix44.create_from_translation(
                pyrr.Vector3(planets[planet]['initial_position']))
            revolution = matrix44.create_from_y_rotation(revolution_speed)
            rotation = matrix44.create_from_y_rotation(rotation_speed)
            # revolution about z axis
            model = matrix44.multiply(model, revolution)
            # rotation about own axis
            model = matrix44.multiply(rotation, model)

            glUniformMatrix4fv(model_loc, 1, GL_FALSE, model)

            # ----create normalMatrix--
            modelView = numpy.matmul(view, model)
            # modelView = numpy.matmul(modelView, scale_planet)
            # modelView = numpy.matmul(modelView, scale)
            modelView33 = modelView[0:-1, 0:-1]
            normalMatrix = numpy.transpose(numpy.linalg.inv(modelView33))
            # -----------------
            glUniformMatrix3fv(normal_loc, 1, GL_FALSE, normalMatrix)

            a, b, c, d = planets[planet]['Material_ambient']
            glUniform4f(Material_ambient_loc, a, b, c, d)
            a, b, c, d = planets[planet]['Material_diffuse']
            glUniform4f(Material_diffuse_loc, a, b, c, d)
            a, b, c, d = planets[planet]['Material_specular']
            glUniform4f(Material_specular_loc, a, b, c, d)
            s = planets[planet]['Material_shininess'][0]
            glUniform1f(Material_shininess_loc, s)

            if planet == 'cruiser':
                glDrawArrays(GL_TRIANGLES, 0, len(obj2.vertex_index))
            else:
                glDrawArrays(GL_TRIANGLES, 0, len(obj.vertex_index))

        # *******************************************************************************

        glfw.swap_buffers(window)

    glfw.terminate()
Example #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)
Example #18
0
def main():
    # initialize glfw
    if not glfw.init():
        return

    w_width, w_height = 1280, 720
    aspect_ratio = w_width / w_height

    window = glfw.create_window(w_width, w_height, "My OpenGL window", None, None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    glfw.set_window_size_callback(window, window_resize)

    #        positions        texture_coords
    cube = [-0.5, -0.5, 0.5, 0.0, 0.0,
            0.5, -0.5, 0.5, 1.0, 0.0,
            0.5, 0.5, 0.5, 1.0, 1.0,
            -0.5, 0.5, 0.5, 0.0, 1.0,

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

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

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

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

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

    cube = numpy.array(cube, dtype=numpy.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 = numpy.array(indices, dtype=numpy.uint32)

    vertex_shader = """
    #version 330
    in layout(location = 0) vec3 position;
    in layout(location = 1) vec2 texture_cords;
    uniform mat4 vp;
    uniform mat4 model;
    out vec2 textures;
    void main()
    {
        gl_Position =  vp * model * vec4(position, 1.0f);
        textures = texture_cords;
    }
    """

    fragment_shader = """
    #version 330
    in vec2 textures;
    out vec4 color;
    uniform sampler2D tex_sampler;
    void main()
    {
        color = texture(tex_sampler, textures);
    }
    """
    shader = OpenGL.GL.shaders.compileProgram(OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER),
                                              OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER))

    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube, GL_STATIC_DRAW)

    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices), indices, GL_STATIC_DRAW)

    # position
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 5, ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)

    # textures
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube.itemsize * 5, ctypes.c_void_p(12))
    glEnableVertexAttribArray(1)

    crate = TextureLoader.load_texture("resources/images/planks_brown_10_diff_1k.jpg")
    metal = TextureLoader.load_texture("resources/images/green_metal_rust_diff_1k.jpg")
    brick = TextureLoader.load_texture("resources/images/castle_brick_07_diff_1k.jpg")

    glUseProgram(shader)

    glClearColor(0.5, 0.1, 0.2, 1.0)
    glEnable(GL_DEPTH_TEST)

    view = matrix44.create_from_translation(Vector3([0.0, 0.0, -4.0]))
    projection = matrix44.create_perspective_projection_matrix(45.0, aspect_ratio, 0.1, 100.0)

    vp = matrix44.multiply(view, projection)

    vp_loc = glGetUniformLocation(shader, "vp")
    model_loc = glGetUniformLocation(shader, "model")

    # cube_positions = [(1.0, 0.0, 0.0), (2.0, 5.0, -15.0), (-1.5, -1.2, -2.5), (-8.8, -2.0, -12.3)]
    cube_positions = [(1.0, 0.0, 0.0), (2.0, 5.0, -15.0), (-1.5, -1.2, -2.5), (-8.8, -2.0, -12.3), (-2.0, 2.0, -5.5),
                      (-4.0, 2.0, -3.0)]
    # cube_positions = [(-1.5, 1.0, -0.5), (0.0, 1.0, -0.5), (1.5, 1.0, -0.5), (-1.5, -1.0, -0.5), (0.0, -1.0, -0.5), (1.5, -1.0, -0.5)]

    glUniformMatrix4fv(vp_loc, 1, GL_FALSE, vp)

    while not glfw.window_should_close(window):
        glfw.poll_events()

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        time = glfw.get_time()

        rot_x = matrix44.create_from_x_rotation(sin(time) * 2)
        rot_y = matrix44.create_from_y_rotation(time * 0.5)
        rot_z = matrix44.create_from_z_rotation(time)

        for i in range(len(cube_positions)):
            model = matrix44.create_from_translation(cube_positions[i])
            if i < 2:
                glBindTexture(GL_TEXTURE_2D, crate)
                rotX = matrix44.multiply(rot_x, model)
                glUniformMatrix4fv(model_loc, 1, GL_FALSE, rotX)
            elif i == 2 or i == 3:
                glBindTexture(GL_TEXTURE_2D, metal)
                rotY = matrix44.multiply(rot_y, model)
                glUniformMatrix4fv(model_loc, 1, GL_FALSE, rotY)
            else:
                glBindTexture(GL_TEXTURE_2D, brick)
                rotZ = matrix44.multiply(rot_z, model)
                glUniformMatrix4fv(model_loc, 1, GL_FALSE, rotZ)

            glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None)

        glfw.swap_buffers(window)

    glfw.terminate()
Example #19
0
    def test_rotation( self ):
        """
        Rotation and Inheritance
        """

        # we'll add a child to a root node
        # we'll move the child
        # rotate the root
        # and check the child is where it should be
        # the child should be moved somewhere that will
        # make it easy to check

        root = SceneNode( '/root' )
        child = SceneNode( '/child' )
        
        root.add_child( child )

        #
        # Rotate 180 deg (1 * pi) about the Y axis (yaw)
        #
        root.transform.object.rotate_y( math.pi )

        identity = matrix44.identity()
        root_matrix = matrix44.create_from_y_rotation( math.pi )

        # root object
        test_axis( self, root.transform.object, root_matrix )
        test_axis( self, root.transform.inertial, identity )
        test_axis( self, root.world_transform.object, root_matrix )
        test_axis( self, root.world_transform.inertial, identity )

        child_matrix = matrix44.identity()
        test_axis( self, child.transform.object, child_matrix )
        test_axis( self, child.transform.inertial, identity )
        test_axis( self, child.world_transform.object, root_matrix )
        test_axis( self, child.world_transform.inertial, identity )


        # check the node matrix matches what we're seeing in
        # the transform axis values
        self.assertTrue(
            numpy.allclose( root.transform.matrix, root_matrix ),
            "Root Local Matrix incorrect"
            )
        self.assertTrue(
            numpy.allclose( root.world_transform.matrix, root_matrix ),
            "Root RootMatrix incorrect"
            )

        self.assertTrue(
            numpy.allclose( child.transform.matrix, identity ),
            "Child Local Matrix incorrect"
            )
        self.assertTrue(
            numpy.allclose( child.world_transform.matrix, root_matrix ),
            "Child RootMatrix incorrect"
            )


        #
        # Rotate 180 deg (1 * pi) about the X axis (pitch)
        #
        # rotate 180 deg / 1pi about the x axis (pitch)
        child.transform.object.rotate_x( math.pi )

        child_matrix = matrix44.multiply(
            matrix44.create_from_x_rotation( math.pi ),
            child_matrix
            )

        child_world = matrix44.multiply( child_matrix, root_matrix )

        # root object
        test_axis( self, root.transform.object, root_matrix )
        test_axis( self, root.transform.inertial, identity )
        test_axis( self, root.world_transform.object, root_matrix )
        test_axis( self, root.world_transform.inertial, identity )

        test_axis( self, child.transform.object, child_matrix )
        test_axis( self, child.transform.inertial, identity )
        test_axis( self, child.world_transform.object, child_world )
        test_axis( self, child.world_transform.inertial, identity )

        # check the node matrix matches what we're seeing in
        # the transform axis values
        self.assertTrue(
            numpy.allclose( root.transform.matrix, root_matrix ),
            "Root Local Matrix incorrect"
            )
        self.assertTrue(
            numpy.allclose( root.world_transform.matrix, root_matrix ),
            "Root RootMatrix incorrect"
            )

        self.assertTrue(
            numpy.allclose( child.transform.matrix, child_matrix ),
            "Child Local Matrix incorrect"
            )
        self.assertTrue(
            numpy.allclose( child.world_transform.matrix, child_world ),
            "Child RootMatrix incorrect"
            )
Example #20
0
 def test_multiply_rotation(self):
     m1 = matrix44.create_from_x_rotation(np.pi)
     m2 = matrix44.create_from_y_rotation(np.pi / 2.0)
     result = matrix44.multiply(m1, m2)
     self.assertTrue(np.allclose(result, np.dot(m1,m2)))
Example #21
0
 def test_inverse(self):
     m = matrix44.create_from_y_rotation(np.pi)
     result = matrix44.inverse(m)
     self.assertTrue(np.allclose(result, matrix44.create_from_y_rotation(-np.pi)))
Example #22
0
 def test_apply_to_vector_y_rotation(self):
     mat = matrix44.create_from_y_rotation(np.pi)
     result = matrix44.apply_to_vector(mat, [1.,0.,0.])
     np.testing.assert_almost_equal(result, [-1.,0.,0.], decimal=5)
Example #23
0
 def test_create_from_y_rotation(self):
     mat = matrix44.create_from_y_rotation(np.pi / 2.)
     self.assertTrue(np.allclose(np.dot([1.,0.,0.,1.], mat), [0.,0.,1.,1.]))
     self.assertTrue(np.allclose(np.dot([0.,1.,0.,1.], mat), [0.,1.,0.,1.]))
     self.assertTrue(np.allclose(np.dot([0.,0.,1.,1.], mat), [-1.,0.,0.,1.]))
Example #24
0
 def test_inverse(self):
     m = matrix44.create_from_y_rotation(np.pi)
     result = matrix44.inverse(m)
     self.assertTrue(
         np.allclose(result, matrix44.create_from_y_rotation(-np.pi)))
Example #25
0
 def test_multiply_rotation(self):
     m1 = matrix44.create_from_x_rotation(np.pi)
     m2 = matrix44.create_from_y_rotation(np.pi / 2.0)
     result = matrix44.multiply(m1, m2)
     self.assertTrue(np.allclose(result, np.dot(m1, m2)))
Example #26
0
 def randomize_mirror_geometry(self):
     pos = np.array([3.505, 1.4, (random.random() - 0.5) * 4])
     transform = m44.multiply(m44.create_from_y_rotation(0.5 * np.pi), m44.create_from_translation(pos))
     for obj in self.geometry["mirror"]:
         obj.transform = transform
         
Example #27
0
 def test_apply_to_vector_y_rotation(self):
     mat = matrix44.create_from_y_rotation(np.pi)
     result = matrix44.apply_to_vector(mat, [1., 0., 0.])
     np.testing.assert_almost_equal(result, [-1., 0., 0.], decimal=5)
Example #28
0
 def rotate(self, xrot, yrot, zrot):
     xrot_mat = matrix44.create_from_x_rotation(radians(xrot))
     yrot_mat = matrix44.create_from_y_rotation(radians(yrot))
     zrot_mat = matrix44.create_from_z_rotation(radians(zrot))
     self.rotation_matrix = xrot_mat * yrot_mat * zrot_mat