Exemple #1
0
    def __init__(self, parent=None):
        # Говорим Qt выбрать OpenGL 3.3 core
        fmt = QtOpenGL.QGLFormat()
        fmt.setVersion(3, 3)
        fmt.setProfile(QtOpenGL.QGLFormat.CoreProfile)
        fmt.setSampleBuffers(True)

        super().__init__(fmt, parent)
        self.setMouseTracking(True)
        self.setFocusPolicy(QtCore.Qt.StrongFocus)

        self.camera = Camera()
        self.light = Light(pr.Vector3([0.0, 0.0, -10.0]),
                           pr.Vector3([1.0, 1.0, 1.0]))
        self.reflectivity: float = 0.5
        self.colorFactor: float = 1.0  # Общий коофицент цвета

        self.figure = None
        # Обьект, отвечающий за автоматические операции над кубиком
        self.figureAlgorithms = CubeAlgorithms()
        # Харакетеристики мыши
        self.previousMousePos = [0, 0]
        self.mouseButtons = {}
        # Функция, вызываемая при смене позиции камеры, тк в основном окне есть соответствующие слайдеры
        self.cameraCallback = lambda x, y: None
        # Время последнего обновления (отрисовки)
        self.lastTime = time.time()
Exemple #2
0
def test_model_setter():
    a = radiant.Object3D()
    assert a.dirty is True
    a.update()
    assert a.dirty is False

    # define expectations
    expected_scale = pyrr.Vector3([1, 1, 2], dtype='f4')
    expected_rotation = pyrr.Quaternion.from_y_rotation(np.pi, dtype='f4')
    expected_translation = pyrr.Vector3([10, 0, -5], dtype='f4')
    expected_model = pyrr.Matrix44([
        [-1, 0, 0, 0],
        [0, 1, 0, 0],
        [0, 0, -2, 0],
        [10, 0, -5, 1],
    ], dtype='f4')

    # call setter
    a.model = expected_model
    assert a.dirty is True
    a.update()
    assert a.dirty is False

    # assertions
    npt.assert_almost_equal(a.scale, expected_scale)
    assert a.scale.dtype == expected_scale.dtype
    npt.assert_almost_equal(a.rotation, expected_rotation)
    assert a.rotation.dtype == expected_rotation.dtype
    npt.assert_almost_equal(a.position, expected_translation)
    assert a.position.dtype == expected_translation.dtype
Exemple #3
0
def display_setup(x_max, y_max, _):
    shader = compile_shader(vertex_shader, fragment_shader)
    glUseProgram(shader)

    glClearColor(80 / 255, 91 / 255, 103 / 255, 1)

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

    projection = pyrr.matrix44.create_perspective_projection_matrix(
        45, 1280 / 720, 0.1, x_max * 2)

    view = pyrr.matrix44.create_look_at(pyrr.Vector3([y_max * -6, 0, 0]),
                                        pyrr.Vector3([0, 0, 0]),
                                        pyrr.Vector3([0, 1, 0]))

    model_loc = glGetUniformLocation(shader, "model")
    proj_loc = glGetUniformLocation(shader, "projection")
    view_loc = glGetUniformLocation(shader, "view")

    glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)
    glUniformMatrix4fv(view_loc, 1, GL_FALSE, view)

    return model_loc, proj_loc, view_loc, shader
Exemple #4
0
    def __init__(self, data_filepath, major=4, minor=4):
        super(Window, self).__init__(major=major, minor=minor)
        # self.resize(width, height)
        self.points = []
        self.point_size = 1
        self.background_color = (0.3, 0.3, 0.1, 1)
        self.deltaTime = 0
        self.lastFrame = 0
        self.lastX = 0
        self.lastY = 0
        self.cameraMode = False
        self.first_mouse = True
        self.keys = [False] * 17000000
        self.vao = None
        self.camera = Camera(width=self.width(),
                             height=self.height(),
                             zNear=0.1,
                             zFar=1000.0,
                             position=pyrr.Vector3([0.0, 0.0, 40.0]),
                             up=pyrr.Vector3([0, 1, 0]))

        self.projection = self.camera.GetPerspectiveMatrix()
        self.view = self.camera.GetViewMatrix()
        self.model = pyrr.matrix44.create_identity()

        self.data_filepath = data_filepath
Exemple #5
0
    def UpdatePowerUps(self, dt):
        for powerUp in self.PowerUps:
            powerUp.pos += powerUp.velocity * dt
            if powerUp.Activated:
                powerUp.Duration -= dt
                if powerUp.Duration <= 0:
                    powerUp.Activated = GL_FALSE
                    if powerUp.Type == "sticky":
                        if not IsOtherPowerUpActive(self.PowerUps, "sticky"):
                            self.Ball.Sticky = GL_FALSE
                            self.Player.color = pyrr.Vector3([1., 1., 1.])
                    elif powerUp.Type == "pass-through":
                        if not IsOtherPowerUpActive(self.PowerUps,
                                                    "pass-through"):
                            self.Ball.PassThrough = GL_FALSE
                            self.Ball.color = pyrr.Vector3([1., 1., 1.])

                    elif powerUp.Type == "confuse":
                        if not IsOtherPowerUpActive(self.PowerUps, "confuse"):
                            self.postEffect.Confuse = GL_FALSE

                    elif powerUp.Type == "chaos":
                        if not IsOtherPowerUpActive(self.PowerUps, "chaos"):
                            self.postEffect.Chaos = GL_FALSE

        return [
            i for i in self.PowerUps if (not i.destroyed or not i.Activated)
        ]  # list comprehension
Exemple #6
0
def test_decompose():
    # define expectations
    expected_scale = pyrr.Vector3([1, 1, 2], dtype='f4')
    expected_rotation = pyrr.Quaternion.from_y_rotation(np.pi, dtype='f4')
    expected_translation = pyrr.Vector3([10, 0, -5], dtype='f4')
    expected_model = pyrr.Matrix44([
        [-1, 0, 0, 0],
        [0, 1, 0, 0],
        [0, 0, -2, 0],
        [10, 0, -5, 1],
    ],
                                   dtype='f4')

    # compose matrix using Pyrr
    s = pyrr.Matrix44.from_scale(expected_scale, dtype='f4')
    r = pyrr.Matrix44.from_quaternion(expected_rotation, dtype='f4')
    t = pyrr.Matrix44.from_translation(expected_translation, dtype='f4')
    model = t * r * s
    npt.assert_almost_equal(model, expected_model)
    assert model.dtype == expected_model.dtype

    # decompose matrix
    scale, rotation, translation = maths.decompose(model)
    npt.assert_almost_equal(scale, expected_scale)
    assert scale.dtype == expected_scale.dtype
    npt.assert_almost_equal(rotation, expected_rotation)
    assert rotation.dtype == expected_rotation.dtype
    npt.assert_almost_equal(translation, expected_translation)
    assert translation.dtype == expected_translation.dtype
Exemple #7
0
    def __init__(self, translation: Tuple[float] = (0, 0, 0), rotation: Tuple[float] = (0, 0, 0),
                 scale: Tuple[float] = (1, 1, 1), name: str = "Untitled"):
        self.__translation = np.array(translation, dtype=np.float32)
        self.__rotation = np.array(rotation, dtype=np.float32)
        self.__scale = np.array(scale, dtype=np.float32)

        self.__trans_matrix = pyrr.matrix44.create_from_translation(pyrr.Vector3(translation))
        self.__trans_matrix_valid = True
        self.__rotation_matrix = pyrr.matrix44.create_from_eulers(pyrr.Vector3(rotation))
        self.__rotation_matrix_valid = True
        self.__scale_matrix = pyrr.matrix44.create_from_scale(pyrr.Vector3(scale))
        self.__scale_matrix_valid = True

        self.__matrix = self.__trans_matrix @ self.__rotation_matrix @ self.__scale_matrix

        self.__inverse_matrix = pyrr.matrix44.inverse(self.__matrix)
        self.__inverse_matrix_valid = True

        self.__children: Set[GameObject] = set()
        self.__parent: Union[GameObject, None] = None
        self.name = name

        self.__components: Dict[str, Component] = {}

        self.__transformation_matrix = None
Exemple #8
0
    def updateRotationWithCursor(self, xpos, ypos):
        deltaX = xpos - self.lastX
        deltaY = self.lastY - ypos
        self.lastX = xpos
        self.lastY = ypos

        deltaX *= self.sensitivity
        deltaY *= self.sensitivity

        self.yaw += deltaX
        self.pitch += deltaY

        if self.pitch > 89:
            self.pitch = 89
        elif self.pitch < -89:
            self.pitch = -89

        front = pyrr.Vector3([
            cos(radians(self.pitch)) * cos(radians(self.yaw)),
            sin(radians(self.pitch)),
            cos(radians(self.pitch)) * sin(radians(self.yaw))
        ])

        self.cameraFront = pyrr.vector3.normalize(front)
        self.cameraRight = pyrr.vector3.normalize(
            pyrr.vector3.cross(pyrr.Vector3([0, 1, 0], dtype=np.float32), self.direction))
        self.cameraUp = pyrr.vector3.normalize(pyrr.vector3.cross(self.direction, self.cameraRight))
Exemple #9
0
def get_arrow_triangles(vector, height=0.2):
    normal = pyrr.vector3.normalize(vector)

    base_v = pyrr.Vector3(vector) - normal * height

    p_tmp = [0.0, 0.0, 0.0]
    min_index = vector.index(min(vector))
    p_tmp[min_index] = 1.0

    p_tmp = pyrr.Vector3(p_tmp)

    p1 = pyrr.vector3.cross(p_tmp, base_v)
    p2 = pyrr.vector3.cross(base_v, p1)

    p1 = pyrr.vector3.normalize(p1)
    p2 = pyrr.vector3.normalize(p2)

    p1_a = base_v + p1 * (height / 2.0)
    p1_b = base_v - p1 * (height / 2.0)

    p2_a = base_v + p2 * (height / 2.0)
    p2_b = base_v - p2 * (height / 2.0)

    triangles = [
        vector,
        p1_a.tolist(),
        p1_b.tolist(), vector,
        p2_a.tolist(),
        p2_b.tolist()
    ]

    return triangles
Exemple #10
0
 def Init(self, tileData, levelWidth, levelHeight):
     height = len(tileData)
     width = len(tileData[0])
     unit_width, unit_height = levelWidth / width, levelHeight / height
     for y in range(height):
         for x in range(width):
             # pos = pyrr.Vector3([unit_width * x, unit_height * y, 0.])
             # size = pyrr.Vector3([unit_width, unit_height, 0.])
             if tileData[y][x] == 1:  # solid tile
                 pos = pyrr.Vector3([unit_width * x, unit_height * y, 0.])
                 size = pyrr.Vector3([unit_width, unit_height, 0.])
                 color = pyrr.Vector3([0.8, 0.8, 0.7])
                 obj = GameObject("gameobject_image/block_solid.png", pos,
                                  size, color)
                 obj.is_solid = True
                 self.Bricks.append(obj)
             elif tileData[y][x] > 1:
                 color = pyrr.Vector3([1., 1., 1.])
                 if tileData[y][x] == 2:
                     color = pyrr.Vector3([0.2, 0.6, 1.0])
                 elif tileData[y][x] == 3:
                     color = pyrr.Vector3([0.0, 0.7, 0.0])
                 elif tileData[y][x] == 4:
                     color = pyrr.Vector3([0.8, 0.8, 0.4])
                 elif tileData[y][x] == 5:
                     color = pyrr.Vector3([1., 0.5, 0.])
                 pos = pyrr.Vector3([unit_width * x, unit_height * y, 0.])
                 size = pyrr.Vector3([unit_width, unit_height, 0.])
                 obj = GameObject("gameobject_image/block.png", pos, size,
                                  color)
                 self.Bricks.append(obj)
Exemple #11
0
def display(shader, vertex_array_object, aspect_ratio, obj):
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    rot_x = pyrr.matrix44.create_from_x_rotation(
        0.5 * pygame.time.get_ticks() / 1000, dtype=numpy.float32)
    rot_y = pyrr.matrix44.create_from_y_rotation(
        0.8 * pygame.time.get_ticks() / 1000, dtype=numpy.float32)
    transform_location = glGetUniformLocation(shader, 'transformation')
    glUniformMatrix4fv(transform_location, 1, GL_FALSE, rot_x @ rot_y)

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

    view_loc = glGetUniformLocation(shader, 'view')
    proj_loc = glGetUniformLocation(shader, 'projection')
    modl_loc = glGetUniformLocation(shader, 'model')

    glUniformMatrix4fv(view_loc, 1, GL_FALSE, view)
    glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)
    glUniformMatrix4fv(modl_loc, 1, GL_FALSE, model)

    glBindVertexArray(vertex_array_object)
    glDrawArrays(GL_TRIANGLES, 0, len(obj.vertex_index))
    # glDrawElements(GL_TRIANGLES, len(obj.vertex_index), GL_UNSIGNED_INT, None)
    glBindVertexArray(0)
def display(shader, vertex_array_object, aspect_ratio, obj):
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    rot_x = pyrr.matrix44.create_from_x_rotation(
        0.5 * pygame.time.get_ticks() / 1000, dtype=numpy.float32)
    rot_y = pyrr.matrix44.create_from_y_rotation(
        0.8 * pygame.time.get_ticks() / 1000, dtype=numpy.float32)
    view = pyrr.matrix44.create_from_translation(pyrr.Vector3([0.0, 0.0,
                                                               -5.0]))
    projection = pyrr.matrix44.create_perspective_projection_matrix(
        45.0, aspect_ratio, 0.1, 100.0)
    model = pyrr.matrix44.create_from_translation(pyrr.Vector3([0.0, 0.0,
                                                                0.0]))
    mv = pyrr.matrix44.multiply(model, view)
    mvp = pyrr.matrix44.multiply(mv, projection)

    transform_location = glGetUniformLocation(shader, 'transformation')
    mvp_loc = glGetUniformLocation(shader, 'mvp')
    light_loc = glGetUniformLocation(shader, 'lightPosition')

    glUniformMatrix4fv(transform_location, 1, GL_FALSE, rot_x @ rot_y)
    glUniformMatrix4fv(mvp_loc, 1, GL_FALSE, mvp)
    glUniformMatrix4fv(light_loc, 1, GL_FALSE, rot_x @ rot_y)

    glBindVertexArray(vertex_array_object)
    glDrawArrays(GL_TRIANGLES, 0, len(obj.vertex_index))
    glBindVertexArray(0)
Exemple #13
0
def sun_shadowmap_matrix(sun_from_world_matrix, view_from_world_matrix, near,
                         far):
    INFINITY = float('inf')
    aabb = {
        'min': pyrr.Vector3([INFINITY, INFINITY, INFINITY]),
        'max': pyrr.Vector3([-INFINITY, -INFINITY, -INFINITY])
    }

    for corner in frustum_corners(view_from_world_matrix, near, far):
        corner = sun_from_world_matrix * corner
        aabb['min'].x = min(aabb['min'].x, corner.x)
        aabb['min'].y = min(aabb['min'].y, corner.y)
        aabb['min'].z = min(aabb['min'].z, corner.z)
        aabb['max'].x = max(aabb['max'].x, corner.x)
        aabb['max'].y = max(aabb['max'].y, corner.y)
        aabb['max'].z = max(aabb['max'].z, corner.z)

    world_from_light_space = sun_from_world_matrix.inverse

    size = aabb['max'] - aabb['min']
    aabb['min'] = world_from_light_space * pyrr.Vector4(
        [*aabb['min'].tolist(), 1.0])
    aabb['max'] = world_from_light_space * pyrr.Vector4(
        [*aabb['max'].tolist(), 1.0])
    center = (aabb['min'] + aabb['max']) / 2.0
    center = pyrr.Vector3(center.tolist()[:3])

    scale = pyrr.Matrix44.from_scale(size)
    translate = pyrr.Matrix44.from_translation(center)

    matrix = translate * world_from_light_space * scale

    screen = pyrr.Matrix44([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1])

    return screen * matrix.inverse
Exemple #14
0
    def draw_gl(self, modelview=None, projection=None, model=None):

        if modelview is None:
            modelview = pyrr.matrix44.create_from_translation(pyrr.Vector3(pyrr.Vector3([0.0, 0.0, 0.0])))

        if projection is None:
            projection = pyrr.matrix44.create_perspective_projection_matrix(45.0, 1, 0.1, 100)

        if model is None:
            model = pyrr.matrix44.create_from_translation(pyrr.Vector3(self.position))
        else:
            model = model @ pyrr.matrix44.create_from_translation(pyrr.Vector3(self.position))

        glUseProgram(self.shader)
        glBindVertexArray(self.vao)

        glUniformMatrix4fv(self.modelview_loc, 1, GL_FALSE, modelview)
        glUniformMatrix4fv(self.proj_loc, 1, GL_FALSE, projection)
        glUniformMatrix4fv(self.model_loc, 1, GL_FALSE, model)
        print(np.float32(time.time() - self.starttime))
        glUniform1f(self.time_pos, time.time() - self.starttime)
        # glEnable(GL_POINT_SMOOTH)
        glPointSize(self.size)

        glDrawArrays(GL_POINTS, 0, self.num_points)
        glBindVertexArray(0)
        glUseProgram(0)
Exemple #15
0
    def Init(self):
        # create shader
        self.shader = Shader()
        self.shader_ = Shader()
        self.post_processing_shader = Shader()

        # Compile shader
        self.shader.Compile(sprite_shader_dict)
        self.shader_.Compile(particle_shader_dict)
        self.post_processing_shader.Compile(post_processing_dict)
        projection = pyrr.matrix44.create_orthogonal_projection(
            0, self.width, self.height, 0, -1., 1.)
        self.shader.Use()
        # self.shader_.Use()
        self.shader.SetMatrix4("projection", projection)
        self.shader.SetInteger("sprite", 0)
        self.shader_.Use()
        self.shader_.SetMatrix4("projection", projection)
        self.shader_.SetInteger("sprite", 0)
        self.texture = Texture2D()  # for sprite
        self.texture_ = Texture2D()  # for particle
        self.texture.Generate("gameobject_image/background.jpg")
        self.texture_.Generate("gameobject_image/particle.png")
        # self.texture_back = Texture2D()
        # self.texture_back.Generate("background.jpg")
        self.Renderer = SpriteRender(self.shader)
        self.Particles = ParticleGenerator(self.shader_, self.texture_, 500)
        self.postEffect = PostProcessing(self.post_processing_shader,
                                         self.width, self.height)
        # self.postEffect = PostProcessing(self.post_processing_shader, custom_width, custom_height)
        game_level_one = GameLevel()
        game_level_one.Load("tiledata/one.txt", self.width, self.height * 0.5)
        game_level_two = GameLevel()
        game_level_two.Load("tiledata/two.txt", self.width, self.height * 0.5)
        game_level_three = GameLevel()
        game_level_three.Load("tiledata/three.txt", self.width,
                              self.height * 0.5)
        game_level_four = GameLevel()
        game_level_four.Load("tiledata/four.txt", self.width,
                             self.height * 0.5)
        self.Levels.append(game_level_one)
        self.Levels.append(game_level_two)
        self.Levels.append(game_level_three)
        self.Levels.append(game_level_four)
        # self.Level = 0
        playerPos = pyrr.Vector3([
            self.width / 2 - PLAYER_SIZE.x / 2, self.height - PLAYER_SIZE.y, 0.
        ])
        ballPos = playerPos + pyrr.Vector3(
            [PLAYER_SIZE.x / 2 - BALL_RADIUS, -2 * BALL_RADIUS, 0.])
        # global Player, Ball
        self.Player = GameObject("gameobject_image/paddle.png",
                                 pos=playerPos,
                                 size=PLAYER_SIZE)
        self.Ball = BallObject("gameobject_image/awesomeface.png",
                               pos=ballPos,
                               velocity=INITIAL_BALL_VELOCITY)
        PlayBackgroundSound(
            "./gamesound/breakout.mp3")  # Play as background music
Exemple #16
0
    def __init__(self, res):

        self.mesh = ObjLoader()
        self.mesh.load_model(res)

        num_verts = len(self.mesh.model_vertices) // 3

        self.verts = pyglet.graphics.vertex_list(
            num_verts, ('v3f', self.mesh.model_vertices),
            ('t2f', self.mesh.model_textures),
            ('n3f', self.mesh.model_normals))

        shader = ShaderLoader.compile_shader("model_vert", "model_frag")

        glUseProgram(shader)

        # vertices
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, self.verts.vertices)
        glEnableVertexAttribArray(0)
        # textures
        glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0,
                              self.verts.tex_coords)
        glEnableVertexAttribArray(1)
        # normals
        glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, self.verts.normals)
        glEnableVertexAttribArray(2)

        projection = pyrr.matrix44.create_perspective_projection_matrix(
            45.0, 1280 / 720, 0.1, 100.0).flatten().astype("float32")
        view = pyrr.matrix44.create_from_translation(
            pyrr.Vector3([0.0, 0.0, -2.0])).flatten().astype("float32")
        model = pyrr.matrix44.create_from_translation(
            pyrr.Vector3([0.0, 0.0, -1.0])).flatten().astype("float32")

        c_projection = numpy.ctypeslib.as_ctypes(projection)
        c_view = numpy.ctypeslib.as_ctypes(view)
        c_model = numpy.ctypeslib.as_ctypes(model)

        view_loc = glGetUniformLocation(shader, b"view")
        proj_loc = glGetUniformLocation(shader, b"projection")
        self.model_loc = glGetUniformLocation(shader, b"model")
        self.rotate_loc = glGetUniformLocation(shader, b'rotate')
        self.light_loc = glGetUniformLocation(shader, b"light")

        glUniformMatrix4fv(view_loc, 1, GL_FALSE, c_view)
        glUniformMatrix4fv(proj_loc, 1, GL_FALSE, c_projection)
        glUniformMatrix4fv(self.model_loc, 1, GL_FALSE, c_model)

        # texture settings and loading
        texture = GLuint(0)
        glGenTextures(1, texture)
        glBindTexture(GL_TEXTURE_2D, texture)
        # set the texture wrapping
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
        # set the texture filtering
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
Exemple #17
0
 def m44Decompose(m=('Matrix44Pin', pyrr.Matrix44()),
                  t=("Reference", ('FloatVector3Pin', pyrr.Vector3())),
                  r=("Reference", ('QuatPin', pyrr.Quaternion())),
                  s=("Reference", ('FloatVector3Pin', pyrr.Vector3()))):
     '''Decomposes an affine transformation matrix into its scale, rotation and translation components.'''
     _s, _r, _t = pyrr.matrix44.decompose(m)
     t(pyrr.Vector3(_t))
     r(pyrr.Quaternion(_r))
     s(pyrr.Vector3(_s))
Exemple #18
0
 def __init__(self):
     self.SPEED = 0.1
     self.TURN_SPEED = 1
     self.position = pyrr.Vector3((0, 0, 0))
     self.headAngle = 0
     self.headDirection = pyrr.Vector3(
         (np.sin(self.headAngle), 0, -np.cos(self.headAngle)))
     self.upVector = pyrr.Vector3((0, 1, 0))
     self.indices, self.buffer = MyObjLoader.load_model('meshes/pig.obj')
Exemple #19
0
 def v3Normalize(v=(DataTypes.FloatVector3, pyrr.Vector3()), result=(DataTypes.Reference, (DataTypes.Bool, False))):
     '''Normalizes a single vector to unit length.\nIf zero-length - returns original one.'''
     try:
         res = pyrr.Vector3(pyrr.vector.normalize(v))
         result(True)
         return res
     except:
         result(False)
         return v
Exemple #20
0
 def __init__(self):
     self.SPEED = 0
     self.TURN_DELTA = np.pi / 45
     self.headAngle = np.sin(0)
     self.headVector = pyrr.Vector3(
         (np.sin(self.headAngle), 0, -np.cos(self.headAngle)))
     self.position = pyrr.Vector3((0, 0, 0))
     self.upVector = pyrr.Vector3((0, 1, 0))
     self.indices, self.buffer = MyObjLoader.load_model('meshes/car.obj')
Exemple #21
0
    def __init__(self, vertex_data, x, y, z):
        self.vertex_data = vertex_data

        self.position = pyrr.Vector3([x, y, z])
        self.scale = pyrr.Vector3([1.0, 1.0, 1.0])

        self.scalemat = pyrr.Matrix44.from_scale(self.scale)
        self.posmat = pyrr.Matrix44.from_translation(self.position)
        self.transformmat = self.scalemat * self.posmat
class Light:
    position = pyrr.Vector3([0, 0, 0])
    colour = [1, 1, 1]
    attenuation = pyrr.Vector3([1, 0, 0])

    def __init__(self, position, colour, attenuation):
        self.position = position
        self.colour = colour
        self.attenuation = attenuation
Exemple #23
0
 def v3Normalize(v=('FloatVector3Pin', pyrr.Vector3()),
                 result=("Reference", ('BoolPin', False))):
     '''Normalizes a single vector to unit length.\nIf zero-length - returns original one.'''
     try:
         res = pyrr.Vector3(pyrr.vector.normalize(v))
         result(True)
         return res
     except:
         result(False)
         return v
Exemple #24
0
 def __init__(self):
     self.SPEED = 0.1
     self.TURN_DELTA = np.pi/45
     self.headAngle = 0
     self.headVector = pyrr.Vector3((0, 0, -1))
     self.positionVector = pyrr.Vector3((0, 0, 0))
     self.accelerationVector = pyrr.Vector3((0, 0, 1))
     self.velocityVector = pyrr.Vector3((0, 0, 0))
     self.upVector = pyrr.Vector3((0, 1, 0))
     self.indices, self.buffer = MyObjLoader.load_model('meshes/car.obj')
Exemple #25
0
def position_matrix(theta, pos, scale, reverse=False):
    pos_matrix = pyrr.matrix44.create_from_translation(pyrr.Vector3(pos))
    scale_matrix = pyrr.matrix44.create_from_scale(pyrr.Vector3(scale))
    rot_x = pyrr.Matrix44.from_x_rotation(theta[0])
    rot_y = pyrr.Matrix44.from_y_rotation(theta[1])
    rot_z = pyrr.Matrix44.from_z_rotation(theta[2])

    if reverse:
        return scale_matrix @ pos_matrix @ rot_z @ rot_y @ rot_x
    return rot_x @ rot_y @ rot_z @ pos_matrix @ scale_matrix
Exemple #26
0
    def __init__(self):
        # * sets camera init
        self.camera_pos = pyrr.Vector3([0.0, 4.0, 3.0])
        self.camera_front = pyrr.Vector3([0.0, 0.0, -1])
        self.camera_up = pyrr.Vector3([0.0, 1.0, 0.0])
        self.camera_right = pyrr.Vector3([1.0, 0.0, 0.0])

        self.mouse_sensitivity = 0.35
        self.jaw = -90
        self.pitch = 0
        self.jump = -1
Exemple #27
0
 def m44Decompose(m=(DataTypes.Matrix44, pyrr.Matrix44()),
                  t=(DataTypes.Reference, (DataTypes.FloatVector3,
                                           pyrr.Vector3())),
                  r=(DataTypes.Reference, (DataTypes.Quaternion,
                                           pyrr.Quaternion())),
                  s=(DataTypes.Reference, (DataTypes.FloatVector3,
                                           pyrr.Vector3()))):
     '''Decomposes an affine transformation matrix into its scale, rotation and translation components.'''
     _s, _r, _t = pyrr.matrix44.decompose(m)
     t(pyrr.Vector3(_t))
     r(pyrr.Quaternion(_r))
     s(pyrr.Vector3(_s))
Exemple #28
0
    def __init__(self):
        self.position = pyrr.Vector3([0.0, 0.0, -100.0])
        self.rotation = pyrr.Vector3([0.0, 0.0, 0.0])
        self.direction = pyrr.Vector3([0.0, 0.0, 0.0])

        self.dirty = False
        self.permat = pyrr.Matrix44.perspective_projection(
            45.0, 1280 / 1024, 0.01, 1000.0)
        self.posmat = pyrr.Matrix44.from_translation(self.position)
        self.dirmat = pyrr.Matrix44.from_translation(self.direction)
        self.combined_mat = pyrr.Matrix44.identity(
        ) * self.dirmat * self.posmat
    def setupViewport(self, width, height):
        if self.matrixNotSet:
            translation = pyrr.Vector3([0.375, 0.375, 0])
            rotation = 0.0
            scale = pyrr.Vector3([1.0, 1.0, 1.0])
            mvp = self.build_model_view_projection_matrix(translation, rotation, scale)

            mvp_uniform_location = GL.glGetUniformLocation(self.quad_shader, "mvp")
            GL.glUniformMatrix4fv(mvp_uniform_location, 1, GL.GL_FALSE, mvp)

            self.matrixNotSet = False

        GL.glDisable(GL.GL_DEPTH_TEST)  # we do 2D, we need no depth test !
Exemple #30
0
    def update_camera_vectors(self):

        front = pyrr.Vector3([0.0, 0.0, 0.0])
        front.x = cos(radians(self.jaw) * cos(radians(self.pitch)))
        front.y = sin(radians(self.pitch))
        front.z = sin(radians(self.jaw)) * cos(radians(self.pitch))

        self.camera_front = pyrr.vector.normalise(front)
        self.camera_right = pyrr.vector.normalise(
            pyrr.vector3.cross(self.camera_front, pyrr.Vector3([0.0, 1.0,
                                                                0.0])))
        self.camera_up = pyrr.vector.normalise(
            pyrr.vector3.cross(self.camera_right, self.camera_front))