Ejemplo n.º 1
0
    def start(self):
        imgui.create_context()
        io = imgui.get_io()
        # io.fonts.add_font_default()
        io.fonts.add_font_from_file_ttf(
            "./res/font/Roboto-Medium.ttf", 14,
            io.fonts.get_glyph_ranges_chinese_full())
        io.fonts.add_font_from_file_ttf(
            "./res/font/FZY3JW.ttf", 13,
            io.fonts.get_glyph_ranges_chinese_full(), True)
        self.window = App._impl_glfw_init()
        impl = GlfwRenderer(self.window)

        while not glfw.window_should_close(self.window):
            glfw.poll_events()
            impl.process_inputs()
            imgui.new_frame()
            # imgui.show_test_window()

            self.update()

            gl.glClearColor(1., 1., 1., 1)
            gl.glClear(gl.GL_COLOR_BUFFER_BIT)

            imgui.render()
            impl.render(imgui.get_draw_data())
            glfw.swap_buffers(self.window)

        self.main_view and self.main_view.on_close()
        impl.shutdown()
        glfw.terminate()
Ejemplo n.º 2
0
def main(recfile):
    imgui.create_context()
    window = impl_glfw_init()
    impl = GlfwRenderer(window)
    slamgui = SLAMGUI(recfile)

    while not glfw.window_should_close(window):
        glfw.poll_events()
        impl.process_inputs()
        imgui.new_frame()

        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):
                clicked_quit, _ = imgui.menu_item("Quit", 'Cmd+Q', False, True)
                if clicked_quit:
                    exit(0)
                imgui.end_menu()
            imgui.end_main_menu_bar()

        slamgui.render()
        gl.glClearColor(0, 0, 0, 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        impl.render(imgui.get_draw_data())
        glfw.swap_buffers(window)

    impl.shutdown()
    glfw.terminate()
Ejemplo n.º 3
0
def app(render, width=1280, height=720, window_name="Maldives"):
    """

    :param render:
    :param width:
    :param height:
    :param window_name:
    :return:
    """
    imgui.create_context()
    window = impl_glfw_init(width, height, window_name)
    impl = GlfwRenderer(window)

    while not glfw.window_should_close(window):
        glfw.poll_events()
        gl.glClearColor(0.3, 0.5, 0.4, 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        impl.process_inputs()
        imgui.new_frame()
        render()
        imgui.render()
        impl.render(imgui.get_draw_data())
        glfw.swap_buffers(window)
    impl.shutdown()
    glfw.terminate()
Ejemplo n.º 4
0
async def async_main(window, config):
    await asyncjob.start_worker()

    imgui_impl = GlfwRenderer(window)

    renderer = WorldRenderer()

    app = StarboundMap(renderer)
    frame_size = np.ones(2)
    while not glfw.window_should_close(window):
        glfw.poll_events()
        if G.minimized:  # do not render zero sized frame
            continue

        imgui_impl.process_inputs()
        frame_size = np.array(glfw.get_framebuffer_size(window))

        gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)
        gl.glViewport(0, 0, frame_size[0], frame_size[1])

        gl.glClearColor(0.1, 0.1, 0.2, 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        app.gui()

        glfw.swap_buffers(window)

        await asyncio.sleep(0)

    config[CONFIG_WIDTH] = str(int(frame_size[0]))
    config[CONFIG_HEIGHT] = str(int(frame_size[1]))

    imgui_impl.shutdown()
    imgui.shutdown()
Ejemplo n.º 5
0
def main():
    window = impl_glfw_init()
    impl = GlfwRenderer(window)
    font_scaling_factor = fb_to_window_factor(window)

    io = impl.io

    # clear font atlas to avoid downscaled default font
    # on highdensity screens. First font added to font
    # atlas will become default font.
    io.fonts.clear()

    # set global font scaling
    io.font_global_scale = 1. / font_scaling_factor

    # dictionary of font objects from our font directory
    fonts = {
        os.path.split(font_path)[-1]: io.fonts.add_font_from_file_ttf(
            font_path, FONT_SIZE_IN_PIXELS * font_scaling_factor,
            io.fonts.get_glyph_ranges_latin())
        for font_path in FONTS_DIR
    }
    secondary_window_main_font = random.choice(list(fonts.values()))

    impl.refresh_font_texture()

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

        imgui.new_frame()

        imgui.begin("Window with multiple custom fonts", True)
        imgui.text("This example showcases font usage on text() widget")

        for font_name, font in fonts.items():
            imgui.separator()

            imgui.text("Font:{}".format(font_name))

            with imgui.font(font):
                imgui.text("This text uses '{}' font.".format(font_name))

        imgui.end()

        with imgui.font(secondary_window_main_font):
            imgui.begin("Window one main custom font", True)
            imgui.text("This window uses same custom font for all widgets")
            imgui.end()

        gl.glClearColor(1., 1., 1., 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        impl.render(imgui.get_draw_data())
        glfw.swap_buffers(window)

    impl.shutdown()
    glfw.terminate()
Ejemplo n.º 6
0
class Application:
    def __init__(self, args):
        imgui.create_context()
        self._window = self._glfw_init()
        self._renderer = GlfwRenderer(self._window)
        self._scene = TinyRendererEditor()
        self.main_loop()

    def main_loop(self):
        while not glfw.window_should_close(self._window):
            glfw.poll_events()
            self._renderer.process_inputs()

            imgui.new_frame()

            gl.glClearColor(0.2, 0.2, 0.2, 1.0)
            gl.glClear(gl.GL_COLOR_BUFFER_BIT)

            self._scene.update()

            imgui.render()
            draw_data = imgui.get_draw_data()
            if draw_data.valid:
                self._renderer.render(draw_data)
            glfw.swap_buffers(self._window)

        self._renderer.shutdown()
        glfw.terminate()

    def _glfw_init(self):
        """
        Initializes the glfw an OpenGL context and returns a window
        """
        width, height = 1600, 900
        window_name = "Computer Graphics Playground"

        if not glfw.init():
            print("Could not initialize OpenGL context")
            exit(1)

        # OS X supports only forward-compatible core profiles from 3.2
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE)

        # Create a windowed mode window and its OpenGL context
        window = glfw.create_window(int(width), int(height), window_name, None,
                                    None)
        glfw.make_context_current(window)

        if not window:
            glfw.terminate()
            print("Could not initialize Window")
            exit(1)

        return window
Ejemplo n.º 7
0
def main():
    imgui.create_context()
    window = impl_glfw_init()
    impl = GlfwRenderer(window)
    _ = gl.glGenFramebuffers(1)

    videoWindows = []

    def dropFile(window, files):
        for file in files:
            videoWindows.append(VideoPlayer(file))

    glfw.set_drop_callback(window, dropFile)

    while not glfw.window_should_close(window):

        glfw.poll_events()
        impl.process_inputs()

        imgui.new_frame()

        videoWindows = [x for x in videoWindows if x.open]
        if len(videoWindows) > 0:
            for videoWindow in videoWindows:
                videoWindow.render()
        else:
            imgui.core.set_next_window_position(10, 10)
            winw, winh = glfw.get_window_size(window)
            imgui.core.set_next_window_size(winw - 20, 10)

            imgui.begin("##Message",
                        True,
                        flags=imgui.WINDOW_NO_SCROLLBAR
                        | imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_TITLE_BAR
                        | imgui.WINDOW_NO_MOVE)
            imgui.text("Drop one or more video files onto this window to play")
            imgui.end()

        gl.glClearColor(0., 0., 0., 1.)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        impl.render(imgui.get_draw_data())
        glfw.swap_buffers(window)

    for videoWindow in videoWindows:
        videoWindow.terminate()
    impl.shutdown()
    glfw.terminate()
Ejemplo n.º 8
0
def main():
    window = impl_glfw_init()
    impl = GlfwRenderer(window)

    box1 = box2 = box3 = True

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

        imgui.new_frame()

        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):

                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", 'Cmd+Q', False, True)

                if clicked_quit:
                    exit(1)

                imgui.end_menu()
            imgui.end_main_menu_bar()

        imgui.begin("Scope Test")

        box1 = imgui.checkbox("Checkbox", box1)[1]

        with imgui.scope(2):
            imgui.new_line()
            imgui.text("Same name, different scope:")
            box2 = imgui.checkbox("Checkbox", box2)[1]

        imgui.new_line()
        imgui.text("Same name, same scope:")
        imgui.text("(This will not work right)")
        box3 = imgui.checkbox("Checkbox", box3)[1]

        imgui.end()

        gl.glClearColor(1., 1., 1., 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        glfw.swap_buffers(window)

    impl.shutdown()
    imgui.shutdown()
    glfw.terminate()
Ejemplo n.º 9
0
def main():
    imgui.create_context()
    window = impl_glfw_init()
    impl = GlfwRenderer(window)
    ip_address = "localhost:3333"
    #imgui.set_window_font_scale(1.0)
    comms = MouseSocket()
    click_guard = True

    while not glfw.window_should_close(window):
        glfw.poll_events()
        impl.process_inputs()
        imgui.new_frame()
        imgui.set_next_window_size(300, 120)
        imgui.set_next_window_position(10, 0)
        imgui.begin("", False, imgui.WINDOW_NO_RESIZE)
        changed, ip_address = imgui.input_text(label="IP:PORT",
                                               value=ip_address,
                                               buffer_length=30)
        clicked = imgui.button(label="CONNECT")
        if clicked:
            comms.connect(ip_address)

        max_x, max_y = glfw.get_window_size(window)
        x, y = glfw.get_cursor_pos(window)

        norm_x = x / max_x
        norm_y = y / max_y

        state = glfw.get_mouse_button(window, glfw.MOUSE_BUTTON_LEFT)
        if state == glfw.PRESS:
            click_guard = False
        elif state == glfw.RELEASE and not click_guard:
            click_guard = True
            comms.send_click(norm_x, norm_y)

        comms.send_mouse_coords(norm_x, norm_y)

        imgui.text("Mouse Coords: {:.2f}, {:.2f}".format(norm_x, norm_y))
        imgui.text("Connected: {}".format(comms.is_connected))
        imgui.end()

        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        imgui.render()
        impl.render(imgui.get_draw_data())
        glfw.swap_buffers(window)

    impl.shutdown()
    glfw.terminate()
Ejemplo n.º 10
0
def main():
    desktop = Desktop()
    imgui.create_context()
    window = core.impl_glfw_init()
    impl = GlfwRenderer(window)
    imgui.core.style_colors_light()

    app_list = list(get_app_list())

    # figure = plt.figure()
    # img = Image.open('./test.png')
    # texture, width, height = readImage(img)

    def update():
        imgui.new_frame()
        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("System", True):
                for app in app_list:
                    clicked, selected = imgui.menu_item(
                        app.__name__, '', False, True)
                    if clicked:
                        desktop.add(app())
                imgui.separator()
                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", '', False, True)

                if clicked_quit:
                    exit(1)

                imgui.end_menu()
            imgui.end_main_menu_bar()

        desktop.render()

    while not glfw.window_should_close(window):
        glfw.poll_events()
        impl.process_inputs()
        update()

        gl.glClearColor(1., 1., 1., 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        imgui.render()
        data = imgui.get_draw_data()
        impl.render(data)

        glfw.swap_buffers(window)

    impl.shutdown()
    glfw.terminate()
Ejemplo n.º 11
0
def main():
    imgui.create_context()
    window = impl_glfw_init()

    impl = GlfwRenderer(window)

    io = imgui.get_io()
    jb = io.fonts.add_font_from_file_ttf(path_to_font, 30) if path_to_font is not None else None
    impl.refresh_font_texture()

    while not glfw.window_should_close(window):
        render_frame(impl, window, jb)

    impl.shutdown()
    glfw.terminate()
Ejemplo n.º 12
0
def main():
    ctx = imgui.create_context()
    implot.create_context()
    implot.set_imgui_context(ctx)

    window = impl_glfw_init()
    impl = GlfwRenderer(window)

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

        imgui.new_frame()

        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):

                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", 'Cmd+Q', False, True)

                if clicked_quit:
                    exit(1)

                imgui.end_menu()
            imgui.end_main_menu_bar()

        imgui.begin("Custom window", True)
        imgui.text("Bar")
        imgui.text_ansi("B\033[31marA\033[mnsi ")
        imgui.text_ansi_colored("Eg\033[31mgAn\033[msi ", 0.2, 1., 0.)
        imgui.extra.text_ansi_colored("Eggs", 0.2, 1., 0.)
        imgui.end()

        # show_test_window()
        imgui.show_test_window()
        implot.show_demo_window()

        gl.glClearColor(1., 1., 1., 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        impl.render(imgui.get_draw_data())
        glfw.swap_buffers(window)

    impl.shutdown()
    glfw.terminate()
Ejemplo n.º 13
0
def main():
    window = impl_glfw_init()
    imgui.create_context()
    impl = GlfwRenderer(window)

    plot_values = array('f', [sin(x * C) for x in range(L)])
    histogram_values = array('f', [random() for _ in range(20)])

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

        imgui.new_frame()

        imgui.begin("Plot example")
        imgui.plot_lines(
            "Sin(t)",
            plot_values,
            overlay_text="SIN() over time",
            # offset by one item every milisecond, plot values
            # buffer its end wraps around
            values_offset=int(time() * 100) % L,
            # 0=autoscale => (0, 50) = (autoscale width, 50px height)
            graph_size=(0, 50),
        )

        imgui.plot_histogram(
            "histogram(random())",
            histogram_values,
            overlay_text="random histogram",
            # offset by one item every milisecond, plot values
            # buffer its end wraps around
            graph_size=(0, 50),
        )

        imgui.end()

        gl.glClearColor(1., 1., 1., 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        impl.render(imgui.get_draw_data())
        glfw.swap_buffers(window)

    impl.shutdown()
    glfw.terminate()
Ejemplo n.º 14
0
def replay(fname):
    imgui.create_context()
    window = impl_glfw_init()
    impl = GlfwRenderer(window)
    replaygui = ReplayGUI(fname)

    while not glfw.window_should_close(window):
        glfw.poll_events()
        impl.process_inputs()
        imgui.new_frame()

        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):
                clicked_quit, _ = imgui.menu_item(
                    "Quit", 'Cmd+Q', False, True)
                if clicked_quit:
                    exit(0)
                imgui.end_menu()
            if imgui.begin_menu("View", True):
                _, replaygui.show_frontview = imgui.menu_item(
                    "Front view", selected=replaygui.show_frontview)
                imgui.end_menu()
            if imgui.begin_menu("Tools", True):
                clicked, _ = imgui.menu_item("Learn control params")
                if clicked:
                    replaygui.learn_controls = True
                clicked, _ = imgui.menu_item("Lap timer")
                if clicked:
                    replaygui.lap_timer = True
                imgui.end_menu()
            imgui.end_main_menu_bar()

        replaygui.render()
        gl.glClearColor(0, 0, 0, 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        impl.render(imgui.get_draw_data())
        glfw.swap_buffers(window)

    impl.shutdown()
    glfw.terminate()
Ejemplo n.º 15
0
class Gui:

    def __init__(self, window):
        imgui.create_context()
        self.impl = GlfwRenderer(window)
        self.color = 0.45, 0.55, 0.60, 1.00


    def NewFrame(self):
        self.impl.process_inputs()
        imgui.new_frame()
    
    def EndFrame(self):
        imgui.end_frame()
        imgui.render()
        self.impl.render(imgui.get_draw_data())


    def endGui(self):
        self.impl.shutdown()
Ejemplo n.º 16
0
class Gui(object, IRuntimeModule):
    def __init__(self):
        super(Gui, self).__init__()
        self.impl = None  # type: Optional[GlfwRenderer]
        self.on_gui = None
        self.io = None
        self.on_gui_editor = None

    # ---------------------------------------------------
    # IRuntimeModule
    # ---------------------------------------------------
    @logger
    def initialize(self):
        imgui.create_context()
        self.io = imgui.get_io()
        # TODO 这些枚举搜不到,需要式再说
        # 		io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;           // Enable Docking
        # 		io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;         // Enable Multi-Viewport / Platform Windows
        # self.io.config_flags |= imgui.CONFIG_NAV_ENABLE_KEYBOARD  # Enable Keyboard Controls TODO cause error
        window = G.appm.window_handle
        self.impl = GlfwRenderer(
            window, attach_callbacks=False
        )  # NOTE otherwise imgui will register glfw callbacks
        imgui.style_colors_dark()
        self.on_gui = G.appm.on_gui
        self.on_gui_editor = G.editorm.on_gui

    @logger
    def finalize(self):
        self.impl.shutdown()
        imgui.destroy_context()

    def update(self):
        self.impl.process_inputs()
        imgui.new_frame()

        self.on_gui and self.on_gui()
        self.on_gui_editor and self.on_gui_editor()

        imgui.render()
        self.impl.render(imgui.get_draw_data())
Ejemplo n.º 17
0
def sim():
    imgui.create_context()
    window = impl_glfw_init()
    impl = GlfwRenderer(window)

    sg = SimGUI()
    t0 = time.time()
    play = True
    while not glfw.window_should_close(window):
        glfw.poll_events()
        impl.process_inputs()
        imgui.new_frame()

        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):
                clicked_quit, _ = imgui.menu_item("Quit", 'Cmd+Q', False, True)
                if clicked_quit:
                    exit(0)
                imgui.end_menu()
            imgui.end_main_menu_bar()

        t = time.time()
        if play:
            sg.step(min(t - t0, 0.03))
        else:
            sg.idle()
        t0 = t
        play = sg.render(play)

        gl.glClearColor(0, 0, 0, 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        impl.render(imgui.get_draw_data())
        glfw.swap_buffers(window)

    impl.shutdown()
    glfw.terminate()
Ejemplo n.º 18
0
def main():
    window = impl_glfw_init()
    impl = GlfwRenderer(window)

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

        imgui.new_frame()

        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):

                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", 'Cmd+Q', False, True)

                if clicked_quit:
                    exit(1)

                imgui.end_menu()
            imgui.end_main_menu_bar()

        imgui.show_test_window()

        imgui.begin("Custom window", True)
        imgui.text("Bar")
        imgui.text_colored("Eggs", 0.2, 1., 0.)
        imgui.end()

        gl.glClearColor(1., 1., 1., 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        glfw.swap_buffers(window)

    impl.shutdown()
    imgui.shutdown()
    glfw.terminate()
Ejemplo n.º 19
0
def main_glfw():
    def glfw_init():
        width, height = 1280, 720
        window_name = "minimal ImGui/GLFW3 example"
        if not glfw.init():
            print("Could not initialize OpenGL context")
            exit(1)
        # OS X supports only forward-compatible core profiles from 3.2
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE)
        # Create a windowed mode window and its OpenGL context
        window = glfw.create_window(
            int(width), int(height), window_name, None, None
        )
        glfw.make_context_current(window)
        if not window:
            glfw.terminate()
            print("Could not initialize Window")
            exit(1)
        return window
    window = glfw_init()
    impl = GlfwRenderer(window)
    while not glfw.window_should_close(window):
        glfw.poll_events()
        impl.process_inputs()
        imgui.new_frame()
        on_frame()
        gl.glClearColor(1., 1., 1., 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        imgui.render()
        impl.render(imgui.get_draw_data())
        glfw.swap_buffers(window)
    impl.shutdown()
    glfw.terminate()
Ejemplo n.º 20
0
def main():
    init()

    imgui.create_context()
    window = impl_glfw_init()
    impl = GlfwRenderer(window)

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

        imgui.new_frame()

        draw(imgui)

        gl.glClearColor(1., 1., 1., 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        impl.render(imgui.get_draw_data())
        glfw.swap_buffers(window)

    impl.shutdown()
    glfw.terminate()
Ejemplo n.º 21
0
class ImGuiPlayer:

    # ---------------------------------------------------------------------------
    # --------------------------- class variables -------------------------------
    # ---------------------------------------------------------------------------

    window = None
    impl: GlfwRenderer = None

    app: ImGuiPlayerApp = None

    quit_requested: bool = None

    def __init__(self, app: ImGuiPlayerApp):

        self.app = app

        #initialize window and GUI
        imgui.create_context()

        self.window = self.impl_glfw_init()
        self.impl = GlfwRenderer(self.window)

        self.quit_requested = False

    def impl_glfw_init(self):
        width, height = 1200, 1200
        window_name = "RefocusApp"

        if not glfw.init():
            print("Could not initialize OpenGL context")
            exit(1)

        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 2)

        # the OPENGL_COMPAT_PROFILE enables the mix between pyimgui and glumpy
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_COMPAT_PROFILE)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE)

        window = glfw.create_window(int(width), int(height), window_name, None,
                                    None)
        glfw.make_context_current(window)

        if not window:
            glfw.terminate()
            print("Could not initialize Window")
            sys.exit(1)

        self.app.window_size_callback(window, 1200, 1200)

        return window

    # ---------------------------------------------------------------------------
    # --------------------------- class methods - gui and menu   ----------------
    # ---------------------------------------------------------------------------

    def key_callback(self, window, key, scancode, action, mods):

        io = imgui.get_io()
        self.impl.keyboard_callback(window, key, scancode, action, mods)

        if io.want_capture_keyboard:
            print("imgui handles")
        else:
            #print("processed by app: key pressed")

            if key == glfw.KEY_ESCAPE and action == glfw.RELEASE:
                self.quit_requested = True

            if key == glfw.KEY_Q and np.bitwise_and(mods, glfw.MOD_CONTROL):
                self.quit_requested = True

            self.app.key_callback(window, key, scancode, action, mods)

    def mouse_cursor_pos_callback(self, window, xpos, ypos):
        io = imgui.get_io()

        if not io.want_capture_mouse:
            self.app.mouse_cursor_pos_callback(window, xpos, ypos)

    def mouse_button_callback(self, window, button, action, mods):
        io = imgui.get_io()

        if io.want_capture_mouse:
            print("imgui handles")
        else:
            self.app.mouse_button_callback(window, button, action, mods)

    def mouse_scroll_callback(self, window, xoffset, yoffset):
        io = imgui.get_io()

        if io.want_capture_mouse:
            print("imgui handles")
        else:
            #print( "processed by app: scroll: {},{}".format( xoffset, yoffset ));

            self.app.mouse_scroll_callback(window, xoffset, yoffset)

    def window_size_callback(self, window, width, height):
        self.app.window_size_callback(window, width, height)

    def run(self):

        glfw.set_key_callback(self.window, self.key_callback)
        glfw.set_cursor_pos_callback(self.window,
                                     self.mouse_cursor_pos_callback)
        glfw.set_mouse_button_callback(self.window, self.mouse_button_callback)
        glfw.set_scroll_callback(self.window, self.mouse_scroll_callback)
        glfw.set_window_size_callback(self.window, self.window_size_callback)

        while not glfw.window_should_close(
                self.window) and not self.quit_requested:
            self.app.on_draw()

            glfw.poll_events()
            self.impl.process_inputs()

            self.app.menu()

            gl.glClearColor(0., 0., 0.2, 1)
            gl.glClear(gl.GL_COLOR_BUFFER_BIT)

            self.app.on_draw()

            imgui.render()
            self.impl.render(imgui.get_draw_data())
            glfw.swap_buffers(self.window)

        self.impl.shutdown()
        glfw.terminate()
Ejemplo n.º 22
0
def main():
    loadFlightData()

    imgui.create_context()
    window = impl_glfw_init()
    impl = GlfwRenderer(window)

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

        # get the style object and edit the object to make it look decent with GLFW
        style = imgui.get_style()
        style.window_rounding = 0
        style.frame_rounding = 0

        #create the main ImGuI frame to then use to display the actual GUI on
        imgui.new_frame()

        flags = imgui.WINDOW_NO_MOVE | imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_COLLAPSE | imgui.WINDOW_NO_TITLE_BAR | imgui.WINDOW_MENU_BAR

        imgui.set_next_window_size(window_width, window_height)
        imgui.set_next_window_position(0, 0)

        # Start the beginning of the ImGui window, drone flight logger being an ID
        imgui.begin("Drone Flight Logger", False, flags=flags)

        if imgui.button("Add new Flight"):
            imgui.open_popup("test")

        imgui.same_line()

        imgui.text("Total Flight Time: " + str(flights.getTotalFlightTime()) +
                   "h")

        imgui.same_line()

        imgui.text("| Total Batteries Used: " +
                   str(flights.getTotalBatteriesUsed()))

        # Main Menu Bar Code
        mainMenuBar()

        # create a child window in the inital window to divide the window up so there can be a preview on the left
        imgui.begin_child("flight_selector",
                          width=window_width / 5 * 2,
                          border=True)

        # loop through all flights and assign flight as the key value
        for flight in flights.getFlights():
            # get the flight data based off the flight name
            flight_data = flights.getFlights()[flight]
            # if the flight location is in the List variable of currently selected locations show it
            if currentSelectedLocations[flight_data.getLocationName()]:
                # flight drop down code, passing in the flight name and flight data
                flightDropDown(flight, flight_data)

        imgui.end_child()

        imgui.same_line()

        # create the preview sidepane of the main window
        imgui.begin_child("flight_info", border=True)

        # if there is the key preview in currentviewingflightdata show the image. Done this way as I will eventually add in the flight location and other stats to the sidepane as well
        if "preview" in currentViewingFlightData:
            imgui.image(currentViewingFlightData["preview"]['image'],
                        currentViewingFlightData["preview"]['width'] / 6,
                        currentViewingFlightData["preview"]['height'] / 6)

        imgui.end_child()

        if imgui.begin_popup_modal("test")[0]:
            addNewFlightData["date"] = imgui.input_text(
                "Flight date", addNewFlightData["date"], 2046)[1]
            addNewFlightData["batteries_used"] = imgui.input_int(
                'Batteries used', addNewFlightData["batteries_used"])[1]
            addNewFlightData["flight_time"] = imgui.input_int(
                'Flight time in minutes', addNewFlightData["flight_time"])[1]
            addNewFlightData["location_name"] = imgui.input_text(
                "Flight location", addNewFlightData["location_name"], 2046)[1]
            addNewFlightData["copyFromFolder"] = imgui.input_text(
                "Folder with new flight media",
                addNewFlightData["copyFromFolder"], 2046)[1]

            if imgui.button("test"):
                handleAddNewFlight()
                imgui.close_current_popup()

            # imgui.text("Select an option:")
            # imgui.separator()
            # imgui.selectable("One")
            # imgui.selectable("Two")
            # imgui.selectable("Three")
            imgui.end_popup()

        imgui.end()

        gl.glClearColor(1., 1., 1., 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        impl.render(imgui.get_draw_data())
        glfw.swap_buffers(window)

    impl.shutdown()
    glfw.terminate()
Ejemplo n.º 23
0
def main(mapim):
    imgui.create_context()
    window = impl_glfw_init()
    impl = GlfwRenderer(window)

    mw = TrackplanWindow(cv2.imread(mapim))

    status = 'Ready'
    while not glfw.window_should_close(window):
        glfw.poll_events()
        impl.process_inputs()

        imgui.new_frame()

        loaded = False
        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):
                load1, _ = imgui.menu_item("Load pts")
                if load1:
                    try:
                        f = open("trackstate.pkl", "rb")
                        rwstate = pickle.load(f)
                        mw.setstate(rwstate)
                        loaded = True
                        f.close()
                    except IOError:
                        status = 'Unable to load ptlist.pkl'

                save1, _ = imgui.menu_item("Save pts")
                if save1:
                    f = open("trackstate.pkl", "wb")
                    pickle.dump((mw.getstate()), f)
                    f.close()
                    status = 'Saved point list'

                exportlm, _ = imgui.menu_item("Export cones / home")
                if exportlm:
                    mw.save_cones("lm.txt")
                    status = 'Exported lm.txt'

                exporttrack, _ = imgui.menu_item("Export track definition")
                if exporttrack:
                    mw.save_track("trackdef.txt")
                    status = 'Exported trackdef.txt'

                exportraceline, _ = imgui.menu_item("Export race line")
                if exportraceline:
                    if mw.opttrack is None:
                        status = 'Optimized track not defined!'
                    else:
                        mw.save_raceline("track.txt")
                        status = 'Exported track.txt'

                clicked_quit, _ = imgui.menu_item("Quit", 'Cmd+Q', False, True)
                if clicked_quit:
                    exit(0)

                imgui.end_menu()
            imgui.end_main_menu_bar()

        mw.render(loaded)

        imgui.set_next_window_position(0, imgui.get_io().display_size[1] - 30)
        imgui.begin("status", flags=0x7f)
        imgui.text(status)
        imgui.end()

        gl.glClearColor(0., 0., 0., 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        impl.render(imgui.get_draw_data())
        glfw.swap_buffers(window)

    impl.shutdown()
    glfw.terminate()
Ejemplo n.º 24
0
def main():
    global width_library
    global width_shematic
    global width_context
    global height_window

    global previous_key_callback
    global selected_link
    global selected_node
    global iggraph
    global node_library
    global debug_is_mouse_dragging
    
    global show_debug_window

    # states -------------------------
    
    scrolling = imgui.Vec2(0, 0)

    iggraph = IGGraph(node_library)

    # iggraph.reset()

    node_hovered_in_scene = -1
    parameter_link_start = None
    selected_parameter = None

    io_hovered = None 
    io_anchors_width_not_hovered = 10
    io_anchors_width_hovered = 15 
    right_splitter_is_active = False
    left_splitter_is_active = False
    
    image_width = 0
    image_height = 0
    image_texture = None

    # states -------------------------

    imgui.create_context()
    window = impl_glfw_init()
    impl = GlfwRenderer(window)
    io = imgui.get_io()
    previous_key_callback = glfw.set_key_callback(window,key_event)
    init_textures()

    assign_parameter_colors(node_library)

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

        imgui.new_frame()
        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):
                clicked_new, selected_new = imgui.menu_item(
                    "New", 'Cmd+N', False, True
                )
                if clicked_new:
                    iggraph = IGGraph(node_library)
                clicked_load, selected_load = imgui.menu_item(
                    "Load", 'Cmd+L', False, True
                )
                if clicked_load:
                    root = tk.Tk()
                    root.withdraw()
                    filename = filedialog.askopenfilename()
                    if filename :
                        f=open(filename)
                        iggraph.from_json(json.load(f))
                        f.close()
                clicked_save, selected_save = imgui.menu_item(
                    "Save", 'Cmd+S', False, True
                )
                if clicked_save:
                    iggraph.reset()
                    graph_json = iggraph.to_json()
                    text2save = json.dumps(graph_json, indent=4, sort_keys=True)
                    root = tk.Tk()
                    root.withdraw()
                    f = filedialog.asksaveasfile(mode='w', defaultextension=".json")
                    if f is None: # asksaveasfile return `None` if dialog closed with "cancel".
                        return
                    f.write(text2save)
                    f.close()
                clicked_quit, selected_quit = imgui.menu_item(
                    "Quit", 'Cmd+Q', False, True
                )
                if clicked_quit:
                    exit(0)
                imgui.end_menu()
            if imgui.begin_menu("Debug", True):
                show_debug_window_clicked,  show_debug_window_selected = imgui.menu_item(
                    "Show Debug window", 'Cmd+D', show_debug_window, True
                )
                if show_debug_window_clicked:
                    show_debug_window = not show_debug_window
                catch_exceptions_clicked,  catch_exceptions_selected = imgui.menu_item(
                    "Catch Exceptions", '', iggraph.catch_exceptions, True
                )
                if catch_exceptions_clicked:
                    iggraph.catch_exceptions = not iggraph.catch_exceptions
                imgui.separator()
                imgui.menu_item(
                    "Examples", '', False, False
                )
                show_example_mosaic_clicked,  show_example_mosaic_selected = imgui.menu_item(
                    "Mosaic", '', False, True
                )
                if show_example_mosaic_clicked:
                    example_mosaic(iggraph)
                imgui.end_menu()
            imgui.end_main_menu_bar()

        height_window = io.display_size.y - 18  # imgui.get_cursor_pos_y()

        imgui.push_style_var(imgui.STYLE_ITEM_SPACING, imgui.Vec2(0,0))
        imgui.set_next_window_size(io.display_size.x, height_window)
        imgui.set_next_window_position(0, 18)
        imgui.push_style_var(imgui.STYLE_WINDOW_ROUNDING, 0)
        imgui.begin("Splitter test", False, imgui.WINDOW_NO_TITLE_BAR | imgui.WINDOW_NO_RESIZE | imgui.WINDOW_NO_MOVE | imgui.WINDOW_NO_BRING_TO_FRONT_ON_FOCUS)
        imgui.pop_style_var()
        imgui.pop_style_var()

        width_shematic = io.display_size.x - separator_width  - width_context - separator_width - width_library

        # ==============================================================================
        # Library
        # ==============================================================================

        imgui.push_style_var(imgui.STYLE_CHILD_BORDERSIZE, 0)
        imgui.begin_child("Library", width_library, 0, True)
        for node_name in node_library.nodes:
            if imgui.button(node_name, width_library):
                iggraph.create_node(node_name)
        imgui.end_child()
        imgui.pop_style_var()

        imgui.same_line()
        imgui.button("left_splitter", separator_width, height_window - 20)
        left_splitter_is_active = imgui.is_item_active()
        if (left_splitter_is_active):
            width_library += io.mouse_delta.x
            scrolling = imgui.Vec2(scrolling.x - io.mouse_delta.x, scrolling.y)
        if (imgui.is_item_hovered()):
            imgui.set_mouse_cursor(imgui.MOUSE_CURSOR_RESIZE_EW)
        
        imgui.same_line()

        # ==============================================================================
        # Shematic
        # ==============================================================================
        imgui.push_style_var(imgui.STYLE_CHILD_BORDERSIZE, 0)
        imgui.begin_child("shematic", width_shematic, 0, True)

        if show_inputs_popup(iggraph):
            imgui.open_popup("Outputs")
        show_outputs_popup(iggraph)

        # create our child canvas
        if iggraph.get_state() == iggraph.STATE_IDLE:
            imgui.text("status: edit | ")
        elif iggraph.get_state() == iggraph.STATE_RUNNING:
            imgui.text("status: run  | ")
        imgui.same_line()
        if iggraph.get_state() == iggraph.STATE_IDLE:
            if imgui.button("run"):
                #TODO if not running
                iggraph.set_state(iggraph.STATE_RUNNING)
                iggraph.prepare_to_run()
                imgui.open_popup("User Input")
            imgui.same_line()
            if imgui.button("run one step"):
                iggraph.set_state(iggraph.STATE_RUNNING)
                iggraph.prepare_to_run()
                iggraph.run_one_step()
        elif iggraph.get_state() == iggraph.STATE_RUNNING:
            if imgui.button("stop running"):
                iggraph.reset()
                iggraph.set_state(iggraph.STATE_IDLE)
            imgui.same_line()
            if imgui.button("run one step"):
                iggraph.set_state(iggraph.STATE_RUNNING)
                iggraph.run_one_step()
        # imgui.same_line(imgui.get_window_width() - 100)
        imgui.push_style_var(imgui.STYLE_FRAME_PADDING, imgui.Vec2(1, 1))
        imgui.push_style_var(imgui.STYLE_WINDOW_PADDING, imgui.Vec2(0, 0))
        imgui.begin_child("scrolling_region", 0, 0, True, imgui.WINDOW_NO_SCROLLBAR | imgui.WINDOW_NO_MOVE)
        imgui.pop_style_var()
        imgui.pop_style_var()
        imgui.push_item_width(120.0)

        offset = add(imgui.get_cursor_screen_pos(), scrolling)
        draw_list = imgui.get_window_draw_list()

        # Display links
        draw_list.channels_split(2)
        draw_list.channels_set_current(0)
        for link in iggraph.links:
            draw_link_param_to_param(draw_list, offset, link.output_parameter, link.input_parameter, selected_link == link)

        # Display nodes
        parameter_link_end = None
        one_parameter_hovered = False
        one_node_moving_active = False
        for node in iggraph.nodes:
            imgui.push_id(str(node.id))
            node_rect_min = add(offset, node.pos)
            draw_list.channels_set_current(1) # foreground
            old_any_active = imgui.is_any_item_active()

            #display node content first
            # todo
            test = add(node_rect_min, NODE_WINDOW_PADDING)
            imgui.set_cursor_screen_position(add(node_rect_min, NODE_WINDOW_PADDING))
            imgui.begin_group()
            imgui.text("")
            imgui.text(node.name)
            imgui.text("")
            imgui.end_group()

            # save size
            node_widgets_active = False # (not old_any_active and imgui.is_any_item_active())
            node.size = add( add( imgui.get_item_rect_size(), NODE_WINDOW_PADDING) , NODE_WINDOW_PADDING)
            node_rect_max = add(node.size, node_rect_min) 
            
            #display node box
            draw_list.channels_set_current(0) # background
            imgui.set_cursor_screen_position(node_rect_min)
            imgui.invisible_button(str(node.id), node.size.x, node.size.y)
            if imgui.is_item_hovered():
                node_hovered_in_scene = node.id
            else:
                node_hovered_in_scene = None
            node_moving_active = imgui.is_item_active()
            use_hovered_color = node_hovered_in_scene or selected_node == node
            draw_list.add_rect_filled(node_rect_min.x, node_rect_min.y, node_rect_max.x, node_rect_max.y, get_node_color(node, iggraph, use_hovered_color), 5)
            if node_hovered_in_scene and iggraph.is_error(node):
                imgui.begin_tooltip()
                imgui.text(iggraph.error_nodes[node])
                imgui.end_tooltip()

            # input parameters
            for parameter_name in node.inputs:
                parameter = node.inputs[parameter_name]
                center = node.get_intput_slot_pos(parameter)
                center_with_offset = add(offset, center)
                if io_hovered == parameter:
                    io_anchors_width = io_anchors_width_hovered
                else:
                    io_anchors_width = io_anchors_width_not_hovered
                imgui.set_cursor_pos(imgui.Vec2(center.x-io_anchors_width/2, center.y-io_anchors_width/2))
                imgui.push_id(str(str(node.id) + "input" + parameter.id))
                if (imgui.invisible_button("input", io_anchors_width, io_anchors_width)):
                    selected_parameter = parameter
                # imgui.is_item_hovered() does not work when dragging
                is_hovering = ((io.mouse_pos.x-offset.x>center.x-io_anchors_width/2) and 
                               (io.mouse_pos.x-offset.x<center.x+io_anchors_width/2) and
                               (io.mouse_pos.y-offset.y>center.y-io_anchors_width/2) and
                               (io.mouse_pos.y-offset.y<center.y+io_anchors_width/2))
                if is_hovering:
                    io_hovered = parameter
                    one_parameter_hovered = True
                    imgui.begin_tooltip()
                    imgui.text(parameter_name)
                    imgui.end_tooltip()
                if is_hovering and imgui.is_mouse_released(0):
                    parameter_link_end = parameter
                imgui.pop_id()
                draw_list.add_circle_filled(center_with_offset.x, center_with_offset.y, io_anchors_width/2, get_parameter_color(parameter))

            # output parameters
            for parameter_name in node.outputs:
                parameter = node.outputs[parameter_name]
                center = node.get_output_slot_pos(parameter)
                center_with_offset = add(offset, center)
                if io_hovered == parameter:
                    io_anchors_width = io_anchors_width_hovered
                else:
                    io_anchors_width = io_anchors_width_not_hovered
                imgui.set_cursor_pos(imgui.Vec2(center.x-io_anchors_width/2, center.y-io_anchors_width/2))
                imgui.push_id(str(str(node.id) + "output" + parameter.id))
                if (imgui.invisible_button("output", io_anchors_width, io_anchors_width)):
                    selected_parameter = parameter
                is_hovering = ((io.mouse_pos.x-offset.x>center.x-io_anchors_width/2) and 
                    (io.mouse_pos.x-offset.x<center.x+io_anchors_width/2) and
                    (io.mouse_pos.y-offset.y>center.y-io_anchors_width/2) and
                    (io.mouse_pos.y-offset.y<center.y+io_anchors_width/2))
                if is_hovering:
                    io_hovered = parameter
                    one_parameter_hovered = True
                    imgui.begin_tooltip()
                    imgui.text(parameter_name)
                    imgui.end_tooltip()
                draw_list.add_circle_filled(center_with_offset.x, center_with_offset.y, io_anchors_width/2, get_parameter_color(parameter))
                imgui.pop_id()
                # cannot use imgui.is_item_active, seems buggy with the scroll
                if is_hovering and imgui.is_mouse_down(0):
                    parameter_link_start = parameter

            if node_widgets_active or node_moving_active:
                selected_node = node
                one_node_moving_active = True
            if node_moving_active and imgui.is_mouse_dragging(0) and node.id==selected_node.id:
               node.pos = add(node.pos, io.mouse_delta)

            debug_is_mouse_dragging = imgui.is_mouse_dragging(0)

            imgui.pop_id()
        draw_list.channels_merge()
        if not one_parameter_hovered:
            io_hovered = None

        # scrolling
        mouse_is_in_schematic = (io.mouse_pos.x > width_library) and\
                                (io.mouse_pos.x < (width_library + width_shematic)) and\
                                (io.mouse_pos.y < height_window) and\
                                (io.mouse_pos.y > 18)
        if not one_node_moving_active and\
           not parameter_link_start and\
           imgui.is_mouse_dragging(0) and\
           mouse_is_in_schematic and\
           not left_splitter_is_active and\
           not right_splitter_is_active and\
           imgui.is_window_focused():
            scroll_offset = imgui.Vec2(io.mouse_delta.x, io.mouse_delta.y)
            scrolling = add(scrolling, scroll_offset)
        # link creation
        if parameter_link_start and parameter_link_end:
            iggraph.add_link(parameter_link_start, parameter_link_end)
        # creating link
        elif parameter_link_start and imgui.is_mouse_dragging(0):
            draw_link_param_to_point(draw_list, offset, parameter_link_start, io.mouse_pos.x, io.mouse_pos.y, True)
        # mouse release
        if imgui.is_mouse_released(0):
            parameter_link_start = None

        imgui.pop_item_width()
        imgui.end_child()

        # mouse click on the scene
        if imgui.is_mouse_clicked(0):
            mouse_pos = imgui.get_mouse_pos()
            local_mouse_pos = imgui.Vec2(mouse_pos.x - offset.x, mouse_pos.y - offset.y)
            selected_link = None
            for link in iggraph.links:
                start_node = link.output_parameter.owner
                start_pos = start_node.get_output_slot_pos(link.output_parameter)
                end_node = link.input_parameter.owner
                end_pos = end_node.get_intput_slot_pos(link.input_parameter)
                distance_mouse_start = math.sqrt(((local_mouse_pos.x-start_pos.x)**2) + ((local_mouse_pos.y-start_pos.y)**2))
                distance_mouse_end = math.sqrt(((local_mouse_pos.x-end_pos.x)**2) + ((local_mouse_pos.y-end_pos.y)**2))
                distance_start_end = math.sqrt(((start_pos.x-end_pos.x)**2) + ((start_pos.y-end_pos.y)**2))
                if ((distance_mouse_start + distance_mouse_end) - distance_start_end) < 0.1:
                    selected_link = link
                
        imgui.end_child()
        imgui.pop_style_var()

        imgui.same_line()
        imgui.button("right_splitter", separator_width, height_window - 20)
        right_splitter_is_active = imgui.is_item_active()
        if (right_splitter_is_active):
            width_context -= io.mouse_delta.x
        if (imgui.is_item_hovered()):
            imgui.set_mouse_cursor(imgui.MOUSE_CURSOR_RESIZE_EW)

        # ==============================================================================
        # Context
        # ==============================================================================

        imgui.same_line()
        imgui.push_style_var(imgui.STYLE_CHILD_BORDERSIZE, 0)
        imgui.begin_child("child3", width_context, 0, True);
        if selected_node:
            if selected_node.handle_dynamic_parameters():
                if imgui.button("add parameter"):
                    selected_node.add_dynamic_parameter()
            if imgui.tree_node("Inputs"):
                for parameter_name in selected_node.inputs:
                    parameter = selected_node.inputs[parameter_name]
                    if imgui.tree_node(parameter.id):
                        display_parameter(parameter, True)
                        imgui.tree_pop()
                imgui.tree_pop()
            if imgui.tree_node("Output"):
                for parameter_name in selected_node.outputs:
                    parameter = selected_node.outputs[parameter_name]
                    if imgui.tree_node(parameter.id):
                        display_parameter(parameter, False)
                        imgui.tree_pop()
                imgui.tree_pop()
        imgui.end_child()
        imgui.pop_style_var()

        # 
        imgui.end()

        # ==============================================================================
        # Debug Window
        # ==============================================================================
        if show_debug_window:
            debug_window_expanded, show_debug_window = imgui.begin("Debug", True)
            if parameter_link_start:
                imgui.text("parameter_link_start: " + parameter_link_start.id)
            else:
                imgui.text("parameter_link_start: " + "None")
            if selected_parameter:
                imgui.text("selected_parameter: " + selected_parameter.id)
            else:
                imgui.text("selected_parameter: " + "None")
            imgui.text("is_mouse_dragging: " + str(debug_is_mouse_dragging))
            imgui.text("mouse: (" + str(io.mouse_pos.x) + ", " + str(io.mouse_pos.y) + ")")
            imgui.end()

        gl.glClearColor(1., 1., 1., 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        impl.render(imgui.get_draw_data())
        glfw.swap_buffers(window)

    impl.shutdown()
    glfw.terminate()
Ejemplo n.º 25
0
def run_reloadable_imgui_app(app_module, no_reload=()):

    no_reload = no_reload + (__name__, )
    settings = getattr(app_module, '__settings__', {})

    window_title = settings.get('window_title', DEFAULT_WINDOW_TITLE)
    initial_window_size = settings.get('initital_window_size',
                                       DEFAULT_WINDOW_SIZE)
    target_framerate = settings.get('target_framerate',
                                    DEFAULT_TARGET_FRAMERATE)
    num_active_frames_after_input = 2 * target_framerate  # arbitrary

    window = impl_glfw_init(window_title=window_title,
                            window_size=initial_window_size)
    renderer = GlfwRenderer(window)
    io = imgui.get_io()

    max_frame_dur = 1 / target_framerate

    frame_start = 0.
    frame_end = 0.
    frame_dur = 0.
    wait_dur = 0.

    prev_mouse_pos = (0, 0)
    mouse_pos = (0, 0)
    prev_mouse_down_0 = False
    prev_frame_click_0_finished = False

    frames_since_last_input = 0

    # TODO:
    def got_input() -> bool:
        """
		Checks if the user sent any left-mouse mouse inputs, like moving/clicking the mouse
		"""
        nonlocal mouse_pos
        nonlocal prev_mouse_pos
        nonlocal prev_mouse_down_0
        nonlocal prev_frame_click_0_finished

        mouse_pos = io.mouse_pos
        mouse_moved = (mouse_pos != prev_mouse_pos)
        mouse_changed = io.mouse_down[0] != prev_mouse_down_0
        click_0_finished = prev_mouse_down_0 and (
            not io.mouse_down[0])  # mouse was down previous frame, now it's up
        # key_clicked = any(io.keys_down)
        result = mouse_moved or mouse_changed or io.mouse_down[
            0] or prev_frame_click_0_finished  # or key_clicked

        prev_mouse_pos = mouse_pos
        prev_mouse_down_0 = io.mouse_down[0]
        prev_frame_click_0_finished = click_0_finished
        return result

    m_request = None
    setattr(app_module, '__was_reloaded__', False)
    # reload loop
    while True:
        # This isn't the render loop yet.
        # This one is to enable reloading,
        # in which case we need to run init
        # and start the render loop again.

        # ========================
        if hasattr(app_module, '__app_init__'):
            app_module.__app_init__()
        # ========================

        # render loop
        while True:

            frame_start = glfw.get_time()  # seconds
            # debug_log("frame_start_ms", frame_start*1000) # miliseconds

            glfw.poll_events()
            renderer.process_inputs()

            if got_input():
                frames_since_last_input = 0
            else:
                frames_since_last_input += 1

            if frames_since_last_input <= num_active_frames_after_input:

                imgui.new_frame()

                # =========================
                if hasattr(
                        app_module, '__pre_frame__'
                ):  # TODO: should this run before imgui.new_frame(?)
                    app_module.__pre_frame__()

                app_module.__draw__()

                if hasattr(
                        app_module, '__post_frame__'
                ):  # TODO: should this run before imgui.end_frame(?)
                    m_request = app_module.__post_frame__()
                    # the app's request is processed at the end of the loop
                # =========================

                gl.glClearColor(1., 1., 1., 1)
                gl.glClear(gl.GL_COLOR_BUFFER_BIT)

                imgui.render()
                renderer.render(imgui.get_draw_data())
                glfw.swap_buffers(window)

            frame_end = glfw.get_time()  # seconds
            frame_dur = frame_end - frame_start
            wait_dur = max_frame_dur - frame_dur
            if wait_dur > 0:
                sleep(wait_dur)

            if m_request in ('reload',
                             'shutdown') or glfw.window_should_close(window):
                break  # stop the render loop

        # end render loop

        # if control flow got to this point, it means that
        # the render loop finished. possible reasons:
        #	- the app requested a reload
        #	- the app requested a shutdown
        #	- glfw.window_should_close(window) is true

        if glfw.window_should_close(window) or m_request == 'shutdown':
            break  # end the reload loop, run user shutdown, close
        elif m_request == 'reload':
            rlu.recursive_reload(app_module,
                                 dir=rlu.module_dirpath(app_module),
                                 excluded=no_reload)
            setattr(app_module, '__was_reloaded__', True)
            continue

    # end reload loop

    # =========================
    if hasattr(app_module, '__app_shutdown__'):
        app_module.__app_shutdown__()
    # =========================

    renderer.shutdown()
    glfw.terminate()
Ejemplo n.º 26
0
def run_imgui_glfw_app(
    app_init=None,
    pre_frame=None,
    draw=DEFAULT_DRAW,
    post_frame=None,
    app_shutdown=None,
    # should_update,
    window_title: str = DEFAULT_WINDOW_TITLE,
    window_size=DEFAULT_WINDOW_SIZE,
    # pause_on_no_input: bool = DEFAULT_PAUSE_ON_NO_INPUT,
    target_framerate: float = DEFAULT_TARGET_FRAMERATE
) -> None:

    user_app_init = app_init
    user_pre_frame = pre_frame
    user_post_frame = post_frame
    user_app_shutdown = app_shutdown

    window = impl_glfw_init(window_title=window_title, window_size=window_size)
    renderer = GlfwRenderer(window)
    io = imgui.get_io()

    max_frame_dur = 1 / target_framerate

    frame_start = 0.
    frame_end = 0.
    frame_dur = 0.
    wait_dur = 0.

    prev_mouse_pos = (0, 0)
    mouse_pos = (0, 0)
    prev_mouse_down_0 = False
    prev_frame_click_0_finished = False

    def got_input() -> bool:
        """
		Checks if the user sent any left-mouse mouse inputs, like moving/clicking the mouse
		"""
        nonlocal mouse_pos
        nonlocal prev_mouse_pos
        nonlocal prev_mouse_down_0
        nonlocal prev_frame_click_0_finished

        mouse_pos = io.mouse_pos
        mouse_moved = (mouse_pos != prev_mouse_pos)
        mouse_changed = io.mouse_down[0] != prev_mouse_down_0
        click_0_finished = prev_mouse_down_0 and (
            not io.mouse_down[0])  # mouse was down previous frame, now it's up
        # key_clicked = any(io.keys_down)
        result = mouse_moved or mouse_changed or io.mouse_down[
            0] or prev_frame_click_0_finished  # or key_clicked

        prev_mouse_pos = mouse_pos
        prev_mouse_down_0 = io.mouse_down[0]
        prev_frame_click_0_finished = click_0_finished
        return result

    # ========================
    if user_app_init != None:
        user_app_init()
    # ========================

    while not glfw.window_should_close(window):

        frame_start = glfw.get_time()  # seconds
        # debug_log("frame_start_ms", frame_start*1000) # miliseconds

        glfw.poll_events()
        renderer.process_inputs()

        got_inp = got_input()
        if got_inp:

            imgui.new_frame()

            # =========================
            if user_pre_frame != None:  # TODO: should this run before imgui.new_frame(?)
                user_pre_frame()

            draw()

            if user_post_frame != None:  # TODO: should this run before imgui.end_frame(?)
                user_post_frame()
            # =========================

            gl.glClearColor(1., 1., 1., 1)
            gl.glClear(gl.GL_COLOR_BUFFER_BIT)

            imgui.render()

            glfw.swap_buffers(window)

        frame_end = glfw.get_time()  # seconds
        frame_dur = frame_end - frame_start
        wait_dur = max_frame_dur - frame_dur
        if wait_dur > 0:
            sleep(wait_dur)

    # =========================
    if user_app_shutdown != None:
        user_app_shutdown()
    # =========================

    renderer.shutdown()
    imgui.shutdown()
    glfw.terminate()
Ejemplo n.º 27
0
class App:
    def __init__(self, width=640, height=480, title="Hello world"):
        imgui.create_context()

        if not glfw.init():
            return

        self.window = glfw.create_window(width, height, title, None, None)
        if not self.window:
            glfw.terminate()
            return

        glfw.make_context_current(self.window)
        self.ctx = moderngl.create_context(require=460)

        self.impl = ImguiRenderer(self.window, attach_callbacks=False)

        glfw.set_key_callback(self.window, self._on_key)
        glfw.set_cursor_pos_callback(self.window, self._on_mouse_move)
        glfw.set_mouse_button_callback(self.window, self._on_mouse_button)
        glfw.set_window_size_callback(self.window, self._on_resize)
        glfw.set_char_callback(self.window, self._on_char)
        glfw.set_scroll_callback(self.window, self._on_scroll)

        self.init()

    def main_loop(self):
        previous_time = glfw.get_time()

        # Loop until the user closes the window
        while not glfw.window_should_close(self.window):
            glfw.poll_events()
            self.impl.process_inputs()

            current_time = glfw.get_time()
            delta_time = current_time - previous_time
            previous_time = current_time
            self.update(current_time, delta_time)
            self.render()

            imgui.new_frame()
            self.ui()
            imgui.render()
            self.impl.render(imgui.get_draw_data())

            glfw.swap_buffers(self.window)

        self.impl.shutdown()
        glfw.terminate()

    def should_close(self):
        glfw.set_window_should_close(self.window, True)

    def mouse_pos(self):
        return glfw.get_cursor_pos(self.window)

    def size(self):
        return glfw.get_window_size(self.window)

    def init(self):
        pass

    def update(self, time):
        pass

    def render(self):
        pass

    def ui(self):
        pass

    def _on_key(self, window, key, scancode, action, mods):
        self.impl.keyboard_callback(window, key, scancode, action, mods)
        self.on_key(key, scancode, action, mods)

    def on_key(self, key, scancode, action, mods):
        pass

    def _on_char(self, window, codepoint):
        self.impl.char_callback(window, codepoint)
        self.on_char(codepoint)

    def on_char(self, codepoint):
        pass

    def _on_mouse_move(self, window, x, y):
        self.impl.mouse_callback(window, x, y)
        self.on_mouse_move(x, y)

    def on_mouse_move(self, x, y):
        pass

    def _on_mouse_button(self, window, button, action, mods):
        if not imgui.get_io().want_capture_mouse:
            self.on_mouse_button(button, action, mods)

    def on_mouse_button(self, button, action, mods):
        pass

    def _on_scroll(self, window, xoffset, yoffset):
        self.impl.scroll_callback(window, xoffset, yoffset)
        self.on_scroll(xoffset, yoffset)

    def on_scroll(self, xoffset, yoffset):
        pass

    def _on_resize(self, window, width, height):
        self.impl.resize_callback(window, width, height)
        self.on_resize(width, height)

    def on_resize(self, width, height):
        pass
Ejemplo n.º 28
0
def main():
    if len(sys.argv) < 2:
        print('I need a path to the project\'s root')
        return 1

    project_path = Path(sys.argv[1])
    if not os.path.isdir(project_path):
        print('Invalid path')
        return 1

    project_file = project_path / 'project.plik'
    if os.path.isfile(project_file):
        printf(HTML(f'<gray>Found project file at {project_file}</gray>'))

    # Init graphics
    imgui.create_context()
    window = _glfw_init(500, 1000)
    renderer = GlfwRenderer(window)

    __main_locals_marker = None

    def on_glfw_key(window, key, scancode, action, mods):
        renderer.keyboard_callback(window, key, scancode, action, mods)

        if action == glfw.RELEASE:
            if key in (glfw.KEY_PAUSE, glfw.KEY_SCROLL_LOCK):
                # Pretty slow I assume, but reliable
                frame = inspect.currentframe()
                while frame:
                    if '__main_locals_marker' in frame.f_locals:
                        break
                    frame = frame.f_back

                ipshell(local_ns=frame.f_locals)

    # Need to set this after creating the renderer because by default it does its own hooks
    glfw.set_key_callback(window, on_glfw_key)

    #  TODO
    state = State()
    state.project_path = project_path
    state.project_file = project_file

    app.prompt.start(state)

    running = True
    while not glfw.window_should_close(window) and running:

        glfw.poll_events()
        renderer.process_inputs()

        # TODO Render only when any events are detected to lower CPU usage
        imgui.new_frame()

        imgui.show_test_window()

        # state.window_width, state.window_height = glfw.get_window_size(window)
        # TODO Just set the font at the beginning!
        # with imgui.font(font):
        running = app.prompt.process_next_entry(state)

        gl.glClearColor(.1, .1, .1, .1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        renderer.render(imgui.get_draw_data())
        glfw.swap_buffers(window)

    renderer.shutdown()
    glfw.terminate()
Ejemplo n.º 29
0
        glClear(GL_COLOR_BUFFER_BIT)

        # imgui function
        impl.process_inputs()

        locationX, locationY, angle, color = \
            transformGuiOverlay(locationX, locationY, angle, color)

        # Setting uniforms and drawing the Quad
        glUniformMatrix4fv(
            glGetUniformLocation(pipeline.shaderProgram, "transform"), 1,
            GL_TRUE,
            np.matmul(tr.translate(locationX, locationY, 0.0),
                      tr.rotationZ(angle)))
        glUniform3f(
            glGetUniformLocation(pipeline.shaderProgram, "modulationColor"),
            color[0], color[1], color[2])
        pipeline.drawCall(gpuQuad)

        # Drawing the imgui texture over our drawing
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
        impl.render(imgui.get_draw_data())

        # Once the render is done, buffers are swapped, showing only the complete scene.
        glfw.swap_buffers(window)

    # freeing GPU memory
    gpuQuad.clear()

    impl.shutdown()
    glfw.terminate()
Ejemplo n.º 30
0
def main():
    width, height = Settings.WindowWidth, Settings.WindowHeight

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

    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    glfw.window_hint(glfw.SAMPLES, 4)
    glfw.window_hint(glfw.DEPTH_BITS, 32)

    window = glfw.create_window(width, height, "OpenGL Window", None, None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    glfw.set_framebuffer_size_callback(window, framebuffer_size_callback)
    # glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED)

    # imgui stuff
    imgui.create_context()
    impl = GlfwRenderer(window)

    # Check OpenGL version
    print(glGetString(GL_VERSION))

    glfw.swap_interval(0)

    load = GLTFLoader("resources/gltf/trailer/scene.gltf")

    scene = load.get_scene()

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

    Global.ProjMat = glm.perspective(glm.radians(35), width / height, 1.0,
                                     100000.0)

    scene.setup_scene()

    grid = GUI.Grid(10, 50)

    renderer = Renderer()

    translation = glm.vec3(0.0, 0.0, 0.0)

    grid = GUI.Grid(10, 50)
    rotation = 0.0
    increment = 2.0

    view = glm.mat4(1.0)

    # Camera
    cam = GUI.Flycam(glm.vec3(0.0, 150.0, 1000))

    # Time & FPS counter
    tt = GUI.TimeTracker()

    # Input poll
    inpt = GUI.Input()

    # glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED)
    glfw.set_mouse_button_callback(window, mouse_button_callback)
    glfw.set_drop_callback(window, drop_callback)

    scene.nodelist[0].transformation = glm.rotate(
        scene.nodelist[0].transformation, glm.radians(90), vec3(1.0, 0.0, 0.0))

    scene.nodelist[0].transformation = glm.rotate(
        scene.nodelist[0].transformation, glm.radians(180),
        vec3(0.0, 1.0, 0.0))

    while not glfw.window_should_close(window):
        # Time & FPS counter
        tt.update()

        # Input
        process_input(window)
        inpt.poll_mouse_pos(window)
        glfw.poll_events()

        # Camera
        cam.update(window)

        renderer.clear()
        glClear(GL_DEPTH_BUFFER_BIT)

        # --------Imgui----------
        impl.process_inputs()
        imgui.new_frame()
        GUI.draw_imgui(scene)

        imgui.show_demo_window()

        # Camera Stuff
        Global.ViewMat = cam.get_view()

        grid.draw_grid(Global.ProjMat, Global.ViewMat)

        scene.draw_scene()

        imgui.render()
        impl.render(imgui.get_draw_data())
        glfw.swap_buffers(window)

    impl.shutdown()
    glfw.terminate()