Esempio n. 1
0
 def initialize(self):
     if os.name == "nt":
         ctypes.windll.shcore.SetProcessDpiAwareness(1)
     sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING)
     IMG_Init(IMG_INIT_PNG)
     # Ugly hack to determine resolution scaling factor as early as possible.
     win = sdl2.SDL_CreateWindow(
         "ResolutionTest".encode("utf-8"),
         sdl2.SDL_WINDOWPOS_UNDEFINED,
         sdl2.SDL_WINDOWPOS_UNDEFINED,
         100,
         100,
         sdl2.SDL_WINDOW_HIDDEN | sdl2.SDL_WINDOW_ALLOW_HIGHDPI,
     )
     rend = sdl2.SDL_CreateRenderer(win, -1, sdl2.SDL_RENDERER_ACCELERATED)
     win_w = ctypes.c_int()
     rend_w = ctypes.c_int()
     sdl2.SDL_GetWindowSize(win, ctypes.byref(win_w), None)
     sdl2.SDL_GetRendererOutputSize(rend, ctypes.byref(rend_w), None)
     # Windows HiDPI is silly like this. You get back different window sizes than you put in.
     self.win_scale = win_w.value / 100.0
     Environment.scale.default = rend_w.value / 100.0
     sdl2.SDL_DestroyRenderer(rend)
     sdl2.SDL_DestroyWindow(win)
     # Initialize our font cache and calculate DPI scaling.
     Font.initialize()
Esempio n. 2
0
def main():
    sdl2.sdl2_load(ctypes.util.find_library('SDL2'), # '/usr/local/lib/libSDL2.dylib'
                   ttf_libpath = ctypes.util.find_library('SDL2_ttf'),
                   img_libpath = ctypes.util.find_library('SDL2_image')
                   )
    sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING)

    WINDOW_W = 640
    WINDOW_H = 360
    window = sdl2.SDL_CreateWindow(b"Minimal SDL_Image Test via python-sdl2", 0, 0, WINDOW_W, WINDOW_H, sdl2.SDL_WINDOW_OPENGL)

    renderer = sdl2.SDL_CreateRenderer(window, -1, 0)

    sdl2.IMG_Init(sdl2.IMG_INIT_JPG|sdl2.IMG_INIT_PNG|sdl2.IMG_INIT_TIF|sdl2.IMG_INIT_WEBP)

    rwops_ptr = sdl2.SDL_RWFromFile(bytes(sys.argv[1], 'utf-8'), b"rb")

    print("PNG?: %s" % ('true' if sdl2.IMG_isPNG(rwops_ptr) else 'false'))

    texture = sdl2.IMG_LoadTexture_RW(renderer, rwops_ptr, 1)

    wh = 300
    pos = sdl2.SDL_Rect()
    pos.x = int((WINDOW_W - wh) / 2)
    pos.y = int((WINDOW_H - wh) / 2)
    pos.w = wh
    pos.h = wh

    sdl2.SDL_RenderCopy(renderer, texture, None, ctypes.byref(pos))

    sdl2.SDL_RenderPresent(renderer)

    fpsdelay = 100
    count = 0
    event = sdl2.SDL_Event()
    done = False
    while not done:
        while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0:
            # 'type' and 'timestamp' are common members for all SDL Event structs.
            event_type = event.common.type
            event_timestamp = event.common.timestamp
            # print("Event : type=0x%s, timestamp=%s" % (event_type, event_timestamp) )

            if event_type == sdl2.SDL_KEYDOWN:
                if event.key.keysym.sym == sdl2.SDLK_ESCAPE:
                    done = True

        sdl2.SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF)
        sdl2.SDL_RenderClear(renderer)
        sdl2.SDL_RenderCopy(renderer, texture, None, ctypes.byref(pos))
        sdl2.SDL_RenderPresent(renderer)

        sdl2.SDL_Delay(fpsdelay)

    sdl2.IMG_Quit()
    sdl2.SDL_DestroyRenderer(renderer)
    sdl2.SDL_DestroyWindow(window)
    sdl2.SDL_Quit()
Esempio n. 3
0
    def quit(self):
        self.is_running = False
        # Give time for the other thread to end
        ti.sleep(0.05)

        # Destroy the SDL context
        sdl2.SDL_DestroyRenderer(self.renderer)
        sdl2.SDL_HideWindow(self.window)
        sdl2.SDL_DestroyWindow(self.window)
        sdl2.SDL_Quit()
Esempio n. 4
0
 def __del__(self):
     del self.joysticks_interface
     if self.has_sdl_gamecontroller:
         sdl2.SDL_QuitSubSystem(sdl2.SDL_INIT_GAMECONTROLLER)
     if self.has_sdl_joystick:
         sdl2.SDL_QuitSubSystem(sdl2.SDL_INIT_JOYSTICK)
     if self.has_sdl_audio:
         sdl2.SDL_CloseAudioDevice(self.audio_dev)
         sdl2.SDL_QuitSubSystem(sdl2.SDL_INIT_AUDIO)
     sdl2.SDL_DestroyTexture(self.texture)
     sdl2.SDL_DestroyRenderer(self.renderer)
     sdl2.SDL_DestroyWindow(self.screen)
     sdl2.SDL_Quit()
Esempio n. 5
0
 def __exit__(self, exc_type, exc_value, traceback):
     sdl2.SDL_DestroyTexture(self.texture_graph)
     sdl2.SDL_DestroyTexture(self.texture_text)
     sdl2.SDL_DestroyTexture(self.texture_scroll)
     sdl2.SDL_DestroyTexture(self.font_text)
     sdl2.SDL_DestroyTexture(self.font_text_inverted)
     sdl2.SDL_DestroyTexture(self.font_graph)
     sdl2.SDL_DestroyTexture(self.font_graph_inverted)
     # clean up stored picts
     for pict in list(self.picts.values()):
         sdl2.SDL_DestroyTexture(pict)
     sdl2.SDL_DestroyWindow(self.window)
     sdl2.SDL_DestroyRenderer(self.renderer)
     sdl2.SDL_Quit()
Esempio n. 6
0
def main():
    sdl2.sdl2_load(
        ctypes.util.find_library('SDL2'),  # '/usr/local/lib/libSDL2.dylib'
        ttf_libpath=ctypes.util.find_library('SDL2_ttf'))
    sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING)

    WINDOW_W = 640
    WINDOW_H = 360
    window = sdl2.SDL_CreateWindow(b"Minimal SDL_TTF Test via python-sdl2", 0,
                                   0, WINDOW_W, WINDOW_H,
                                   sdl2.SDL_WINDOW_OPENGL)

    renderer = sdl2.SDL_CreateRenderer(window, -1, 0)

    rect = sdl2.SDL_Rect()
    rect.x = 0
    rect.y = 0
    rect.w = WINDOW_W
    rect.h = WINDOW_H

    sdl2.TTF_Init()
    rwops_ptr = sdl2.SDL_RWFromFile(
        bytes(sys.argv[1], 'utf-8'), b"rb"
    )  # rwops = ctypes.cast(rwops_ptr, ctypes.POINTER(sdl2.SDL_RWops)).contents
    font = sdl2.TTF_OpenFontRW(rwops_ptr, 0, 42)

    fg = sdl2.SDL_Color()
    fg.r = 96
    fg.g = 96
    fg.b = 96
    fg.a = 255

    bg = sdl2.SDL_Color()
    bg.r = 0xE0
    bg.g = 0xE0
    bg.b = 0xE0
    bg.a = 255

    pos = [
        sdl2.SDL_Rect(),
        sdl2.SDL_Rect(),
    ]
    pos[0].x = 20
    pos[0].y = 120
    pos[0].w = 600
    pos[0].h = 60

    pos[1].x = 20
    pos[1].y = 180
    pos[1].w = 600
    pos[1].h = 60

    surfaces = [
        sdl2.TTF_RenderUTF8_Shaded(font, bytes("志於道、據於徳、依於仁、游於藝", 'utf-8'), fg,
                                   bg),
        sdl2.TTF_RenderUTF8_Shaded(font, bytes("SCORE 123456780", 'utf-8'), fg,
                                   bg),
    ]

    texture = [
        sdl2.SDL_CreateTextureFromSurface(renderer, surfaces[0]),
        sdl2.SDL_CreateTextureFromSurface(renderer, surfaces[1]),
    ]

    sdl2.SDL_SetRenderDrawColor(renderer, bg.r, bg.g, bg.b, bg.a)
    sdl2.SDL_RenderFillRect(renderer, ctypes.byref(rect))
    sdl2.SDL_RenderCopy(renderer, texture[0], None, ctypes.byref(pos[0]))
    sdl2.SDL_RenderCopy(renderer, texture[1], None, ctypes.byref(pos[1]))

    sdl2.SDL_RenderPresent(renderer)

    sdl2.SDL_FreeSurface(surfaces[0])
    sdl2.SDL_FreeSurface(surfaces[1])

    fpsdelay = 100
    count = 0
    event = sdl2.SDL_Event()
    done = False
    while not done:
        while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0:
            # 'type' and 'timestamp' are common members for all SDL Event structs.
            event_type = event.common.type
            event_timestamp = event.common.timestamp
            # print("Event : type=0x%s, timestamp=%s" % (event_type, event_timestamp) )

            if event_type == sdl2.SDL_KEYDOWN:
                if event.key.keysym.sym == sdl2.SDLK_ESCAPE:
                    done = True

        sdl2.SDL_Delay(fpsdelay)

    sdl2.TTF_Quit()
    sdl2.SDL_DestroyRenderer(renderer)
    sdl2.SDL_DestroyWindow(window)
    sdl2.SDL_Quit()
Esempio n. 7
0
def main():

    nodes = None
    edges = None

    if len(sys.argv) >= 2 and Path(sys.argv[1]).exists():
        map_file = Path(sys.argv[1])
        with map_file.open() as roadmap_input:
            nodes, edges = read_map(roadmap_input)
            # print(nodes, edges)
    else:
        nodes = [
            Vector(100.0, 100.0),
            Vector(200.0, 200.0),
            Vector(300.0, 100.0),
            Vector(400, 200)
        ]
        edges = [[0, 1], [1, 2], [2, 0], [1, 3], [2, 3]]

    wps = []
    for n in nodes:
        wps.append(WayPoint(n.x, n.y))

    for e in edges:
        edge = WayPointEdge(wps[e[0]], wps[e[1]])
        wps[e[0]].neighbors.append(edge)
        wps[e[1]].neighbors.append(edge)
        # print(Vector.distance(wps[e[0]].pos, wps[e[1]].pos))

    rp = RoutePlanner(wps)
    start = Vector(0.0, 0.0)
    goal = Vector(500.0, 200.0)
    route_plan = rp.plan(start, goal)

    sdl2.sdl2_load(
        ctypes.util.find_library('SDL2'),  # '/usr/local/lib/libSDL2.dylib'
        gfx_libpath=ctypes.util.find_library('SDL2_gfx'))
    sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING)

    window = sdl2.SDL_CreateWindow(b"A* demonstration", 0, 0, WINDOW_W,
                                   WINDOW_H, sdl2.SDL_WINDOW_OPENGL)

    renderer = sdl2.SDL_CreateRenderer(window, -1, 0)

    mouse_x = ctypes.c_int()
    mouse_y = ctypes.c_int()

    fps_delay = 100
    event = sdl2.SDL_Event()
    done = False
    while not done:
        while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0:
            # 'type' and 'timestamp' are common members for all SDL Event structs.
            event_type = event.common.type
            # event_timestamp = event.common.timestamp
            # print("Event : type=0x%s, timestamp=%s" % (event_type, event_timestamp) )

            if event_type == sdl2.SDL_KEYDOWN:
                if event.key.keysym.sym == sdl2.SDLK_ESCAPE:
                    done = True
                if event.key.keysym.sym == sdl2.SDLK_SPACE:
                    route_plan = rp.plan(start, goal)

        sdl2.SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF)
        sdl2.SDL_RenderClear(renderer)

        mouse_state = sdl2.SDL_GetMouseState(ctypes.byref(mouse_x),
                                             ctypes.byref(mouse_y))
        if mouse_state == (1 << (sdl2.SDL_BUTTON_LEFT - 1)):
            prev_x = start.x
            prev_y = start.y
            start.x = float(mouse_x.value)
            start.y = float(mouse_y.value)
            if start.x != prev_x or start.y != prev_y:
                route_plan = rp.plan(start, goal)
        elif mouse_state == (1 << (sdl2.SDL_BUTTON_RIGHT - 1)):
            prev_x = goal.x
            prev_y = goal.y
            goal.x = float(mouse_x.value)
            goal.y = float(mouse_y.value)
            if goal.x != prev_x or goal.y != prev_y:
                route_plan = rp.plan(start, goal)

        map_renderer.render_waypoints(renderer, wps)
        map_renderer.render_route_plan(renderer, start, goal, route_plan)
        sdl2.SDL_RenderPresent(renderer)

        sdl2.SDL_Delay(fps_delay)

    sdl2.SDL_DestroyRenderer(renderer)
    sdl2.SDL_DestroyWindow(window)
    sdl2.SDL_Quit()
Esempio n. 8
0
 def terminate(self):
     if self.renderer is not None:
         sdl2.SDL_DestroyRenderer(self.renderer)
     if self.window is not None:
         sdl2.SDL_DestroyWindow(self.window)
     sdl2.SDL_Quit()
Esempio n. 9
0
def main():
    sdl2.sdl2_load(
        ctypes.util.find_library('SDL2'),  # '/usr/local/lib/libSDL2.dylib'
        ttf_libpath=ctypes.util.find_library('SDL2_ttf'),
        img_libpath=ctypes.util.find_library('SDL2_image'),
        gfx_libpath=ctypes.util.find_library('SDL2_gfx'))
    sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING)

    WINDOW_W = 640
    WINDOW_H = 360
    window = sdl2.SDL_CreateWindow(b"Minimal SDL2_gfx Test via python-sdl2", 0,
                                   0, WINDOW_W, WINDOW_H,
                                   sdl2.SDL_WINDOW_OPENGL)

    renderer = sdl2.SDL_CreateRenderer(window, -1, 0)

    fpsdelay = 100
    count = 0
    event = sdl2.SDL_Event()
    done = False
    while not done:
        while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0:
            # 'type' and 'timestamp' are common members for all SDL Event structs.
            event_type = event.common.type
            # event_timestamp = event.common.timestamp
            # print("Event : type=0x%s, timestamp=%s" % (event_type, event_timestamp) )

            if event_type == sdl2.SDL_KEYDOWN:
                if event.key.keysym.sym == sdl2.SDLK_ESCAPE:
                    done = True

        sdl2.SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF)
        sdl2.SDL_RenderClear(renderer)

        sdl2.pixelColor(renderer, 100, 100,
                        0xFFFFFFFF)  # Uint32 color = 0x[AA][BB][GG][RR]
        sdl2.pixelRGBA(renderer, 101, 100, 0xFF, 0x00, 0x00, 0xFF)

        sdl2.hlineColor(renderer, 0, 100, 50, 0xFFFFFFFF)
        sdl2.vlineColor(renderer, 50, 0, 100, 0xFFFF00FF)

        sdl2.rectangleColor(renderer, 5, 5, 95, 95, 0xFF00FFFF)
        sdl2.rectangleRGBA(renderer, 10, 10, 90, 90, 0, 0, 0xFF, 0xFF)

        sdl2.circleColor(renderer, 150, 150, 50, 0xFF00FF00)
        sdl2.filledCircleRGBA(renderer, 150, 150, 45, 0x00, 0xFF, 0x00, 0xFF)

        sdl2.aalineColor(renderer, 200, 200, 300, 300, 0xFFFFFFFF)
        sdl2.aalineColor(renderer, 300, 200, 200, 300, 0xFFFFFFFF)

        sdl2.aacircleColor(renderer, 300, 200, 25, 0xFF00FF00)
        sdl2.pieColor(renderer, 200, 300, 25, 0, 270, 0xFF00FF00)

        sdl2.SDL_RenderPresent(renderer)

        sdl2.SDL_Delay(fpsdelay)

    sdl2.IMG_Quit()
    sdl2.SDL_DestroyRenderer(renderer)
    sdl2.SDL_DestroyWindow(window)
    sdl2.SDL_Quit()
Esempio n. 10
0
 def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
     sdl2.SDL_DestroyRenderer(self.sdlrenderer)
Esempio n. 11
0
	def close(self):
		sdl2.SDL_DestroyWindow(self.window)
		sdl2.SDL_DestroyRenderer(self.sdl_renderer)
		sdl2.sdlttf.TTF_Quit()
		sdl2.SDL_Quit()
Esempio n. 12
0
 def cleanup(self):
     sdl2.SDL_DestroyRenderer(self.renderer)
     sdl2.SDL_DestroyWindow(self.win)
Esempio n. 13
0
def start_system() -> None:
    sdl(sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING))
    window = sdl(
        sdl2.SDL_CreateWindow(b"Overwritten by game loop",
                              sdl2.SDL_WINDOWPOS_UNDEFINED,
                              sdl2.SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH,
                              SCREEN_HEIGHT, sdl2.SDL_WINDOW_OPENGL))
    renderer = sdl(
        sdl2.SDL_CreateRenderer(window, -1, sdl2.SDL_RENDERER_ACCELERATED))

    entities.initialize_bullet_pool(renderer)
    entities.Entities.append(entities.create_player(renderer))

    for i in range(5):
        for j in range(3):
            x = (i / 5) * SCREEN_WIDTH + (entities.ENEMY_SIZE / 2)
            y = j * entities.ENEMY_SIZE + \
                (entities.ENEMY_SIZE / 2)
            entities.Entities.append(
                entities.create_enemy(renderer, Vec2f(x, y)))

    event = sdl2.SDL_Event()
    running = True
    while running:
        frame_start_time = sdl2.SDL_GetTicks()
        while sdl(sdl2.SDL_PollEvent(ctypes.byref(event))) != 0:
            if event.type == sdl2.SDL_QUIT:
                running = False
                break

        sdl(sdl2.SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255))
        sdl(sdl2.SDL_RenderClear(renderer))

        # Start draw and update subsystem. In a naïve ECS implementation every
        # system iterates through the complete list of entities. Below we
        # operate on only the active subset of entities.
        for entity in entities.Entities:
            if entity.active:
                entity.draw(renderer)
                entity.update()

        # Start collision subsystem
        check_collisions()
        sdl(sdl2.SDL_RenderPresent(renderer))

        # Add artificial wait to simulate running game on slow computer
        # sdl2.SDL_Delay(100)

        # If we're running at half TARGET_TICKS_PER_SECOND, delta is 2. If we're
        # running at double TARGET_TICKS_PER_SECOND, delta becomes 0.5.
        frame_render_time = sdl2.SDL_GetTicks() - frame_start_time

        # Alternatively, we could store just frame_render_time in delta_time and
        # defer calculation below to each component.
        config.delta_time = (frame_render_time / 1000) * \
            TARGET_TICKS_PER_SECOND

        sdl2.SDL_SetWindowTitle(
            window,
            f"""Space Invaders - Delta: {config.delta_time:.2f}, Render: {frame_render_time} ms"""
            .encode())

    sdl(sdl2.SDL_DestroyRenderer(renderer))
    sdl(sdl2.SDL_DestroyWindow(window))
Esempio n. 14
0
current_scene_index = menu_scene_index
sceneList[current_scene_index].Pause = False

# Clear Screen to Black
sdl2.SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255)
sdl2.SDL_RenderClear(renderer)

# Main Game Loop
while sceneList[current_scene_index].Running:
    # Process Events
    sceneList[current_scene_index].process_events()

    if sceneList[current_scene_index].RequestChange:
        sceneList[current_scene_index].RequestChange = False
        if current_scene_index == menu_scene_index:
            current_scene_index = game_scene_index
            sceneList[current_scene_index].init_as_game(None)
        else:
            current_scene_index = menu_scene_index

    # Render Graphics
    perform_rendering(renderer, sceneList[current_scene_index].entities)
    pass

# Clean up
for scene in sceneList:
    scene.stop_entities()
sdl2.SDL_DestroyRenderer(renderer)
sdl2.SDL_DestroyWindow(window)
sdl2.SDL_Quit()
Esempio n. 15
0
 def close(self):
     sdl2.SDL_DestroyRenderer(self.renderer)
     sdl2.SDL_DestroyWindow(self.window)
Esempio n. 16
0
 def finish(self):
     if self.window:
         sdl2.SDL_DestroyTexture(self.texture)
         sdl2.SDL_DestroyRenderer(self.renderer)
         sdl2.SDL_DestroyWindow(self.window)
     sdl2.SDL_Quit()
Esempio n. 17
0
    def __init__(self,
                 config=None,
                 canvas=None,
                 renderer=None,
                 main=None,
                 loop=None):
        # TODO:
        self.SCW = 640
        self.SCH = 480

        self.debug('#===== Включён режим отладки =====#', 'color:gray;')
        self.debug(self.JsMobileBasic['name'], 'background:gray;color:yellow;')
        self.debug('v. ' + self.JsMobileBasic['version'],
                   'background:gray;color:yellow;')
        self.debug('by ' + self.JsMobileBasic['author'],
                   'background:gray;color:yellow;')
        self.debug(self.JsMobileBasic['url'], 'background:gray;color:yellow;')

        self.debug('// ======Инициализация рабочей среды======//',
                   'color:gray;')

        if config:
            if 'name' in config:
                self.Instance['name'] = config['name']

            if 'Debug' in config:
                self.JsMobileBasic['Debug'] = config['Debug']

        self.debug('Используется графика!', 'background:black;color:yellow;')

        # TODO: Read screen size from config
        self.JsMobileBasic[
            'canvas'] = self.c = canvas if canvas else SDL.SDL_CreateWindow(
                bytes(self.Instance['name'], 'utf-8'),
                SDL.SDL_WINDOWPOS_UNDEFINED, SDL.SDL_WINDOWPOS_UNDEFINED,
                self.SCW, self.SCH, SDL.SDL_WINDOW_SHOWN)

        # TODO: SDL_WINDOW_FULLSCREEN

        self.ctx = renderer if renderer else SDL.SDL_CreateRenderer(
            self.c, -1, SDL.SDL_RENDERER_ACCELERATED
            | SDL.SDL_RENDERER_PRESENTVSYNC)

        self.setLineWidth(1)
        self.setColor([255, 0, 0, 0])
        self.fillScreen(255, 255, 255, 255)
        self.repaint()

        self.debug('Имя проекта: ' + self.Instance['name'],
                   'background:brown;color:yellow;')

        self.Player = [None]

        self.debug('// ======Инициализация интерпретатора======//',
                   'color:gray;')

        self._main = main
        self._loop = loop

        if self._main:
            self._main(self)

        event = SDL.SDL_Event()

        running = True

        while running:
            while SDL.SDL_PollEvent(ctypes.byref(event)) != 0:
                if event.type == SDL.SDL_QUIT:
                    running = False
                    break

            if self._loop:
                self._loop(self)  # TODO: Send keycode

        SDL.SDL_DestroyRenderer(self.ctx)
        SDL.SDL_DestroyWindow(self.c)
        SDL.SDL_Quit()