示例#1
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)
示例#2
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        if self.wnd.name != 'pygame2':
            raise RuntimeError(
                'This example only works with --window pygame2 option')

        self.pg_res = (160, 160)
        # Create a 24bit (rgba) offscreen surface pygame can render to
        self.pg_screen = pygame.Surface(self.pg_res, flags=pygame.SRCALPHA)
        # 24 bit (rgba) moderngl texture
        self.pg_texture = self.ctx.texture(self.pg_res, 4)
        self.pg_texture.filter = moderngl.NEAREST, moderngl.NEAREST

        # Simple geometry and shader to render
        self.cube = geometry.cube(size=(2.0, 2.0, 2.0))
        self.texture_prog = self.load_program(
            'programs/cube_simple_texture.glsl')
        self.texture_prog['m_proj'].write(
            matrix44.create_perspective_projection(60,
                                                   self.wnd.aspect_ratio,
                                                   1,
                                                   100,
                                                   dtype='f4'))
        self.texture_prog['m_model'].write(
            matrix44.create_identity(dtype='f4'))
示例#3
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
示例#4
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)
示例#5
0
 def __init__(self):
     # Два главных аттрибута камеры
     self.viewMatrix: Matrix44 = Matrix44.identity(dtype=np.float32)
     self.projectionMatrix: Matrix44 = matrix44.create_perspective_projection(
         FOV, 1, NEAR_PLANE, FAR_PLANE, dtype=np.float32)
     # X, Y
     self.pitch: float = 0
     self.yaw: float = 0
     # Переменные с плавным переходом
     self.angleAroundPlayer = SmoothFloat(0, 10)
     self.distanceFromPlayer = SmoothFloat(20, 5)
示例#6
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
示例#7
0
moderngl_window.resources.register_dir(
    Path(__file__).resolve().parent / 'resources')

quad = geometry.quad_2d(size=(800 / 600, 1.0))
fbo = ctx.framebuffer(color_attachments=ctx.texture((window_x, window_y),
                                                    components=4),
                      # depth_attachment=ctx.depth_texture((800, 600)),
                      )
texture_program = moderngl_window.resources.programs.load(
    meta.ProgramDescription(path='texture.glsl'))
scene = moderngl_window.resources.scenes.load(
    #    meta.SceneDescription(path='VC/glTF/VC.gltf')
    meta.SceneDescription(path='Sponza/glTF/Sponza.gltf'))
projection = matrix44.create_perspective_projection(90,
                                                    window_x / window_y,
                                                    0.1,
                                                    1000,
                                                    dtype='f4')


def init():
    global score, num_asteroids

    score = 0
    score_label.text = "Score: " + str(score)

    num_asteroids = 3
    reset_level(2)


def reset_level(num_lives=2):
示例#8
0
 def _regen_prespective(self):
     self.P = matrix44.create_perspective_projection(
         self.fov, self.aspect, 0.1, 100, dtype=np.float32
     )
     self.regen_prespective = False