def update(self):
        bitmap = self._renderer.bitmap
        if bitmap is None:
            return

        imgui.begin("Tiny Renderer")

        imgui.image(bitmap.get_texture_id(), bitmap.get_width(),
                    bitmap.get_height())
        imgui.end()

        imgui.begin("Rendering")
        _, self._render_mode = imgui.combo("Rendering Mode", self._render_mode,
                                           self._render_mode_captions)
        _, self._light_mode = imgui.combo("Lighting Mode", self._light_mode,
                                          self._light_mode_captions)

        imgui.separator()
        if imgui.button("Render"):
            t = time.time()
            self.on_click_render()
            self._time_to_render = time.time() - t

        imgui.label_text("", f"Time to render: {self._time_to_render: .2f}s")
        imgui.separator()

        imgui.end()
Example #2
0
    def configurationInterface(self):
        super().configurationInterface()

        changed, current = imgui.combo("Network Adapter", self.curAdapter,
                                       self.adapters)

        if changed:
            self.curAdapter = current
            self.rx_bytes = []
            self.rx_bytes.append(0)
            self.tx_bytes = []
            self.tx_bytes.append(0)
            log.logNorm("Network watch interface changed: " +
                        self.adapters[current])

        percent_changed, percent_val = imgui.input_int("Trigger Percent",
                                                       self.triggerPercent, 5)

        if percent_changed:
            self.triggerPercent = percent_val

        floor_changed, floor_val = imgui.input_float("Alert Floor",
                                                     self.alertFloor, 0.005)

        if floor_changed:
            self.alertFloor = floor_val
Example #3
0
    def onDrawGuiCallback(self, args):
        if self.visible:
            if imgui.begin("Combat Assist##combatassist_mainwindo", (450,300)):
                player = BigWorld.player()

                imgui.text("Combat script : ")
                selectedChanged, self.combatSelectedIndex = imgui.combo("##combatassist_combatcombo", self.combatSelectedIndex, combats.LOADED_COMBATS.keys())
                if selectedChanged:
                    combats.LOADED_COMBATS.keys()[self.combatSelectedIndex]
                    self.combatRotationName = combats.LOADED_COMBATS.keys()[self.combatSelectedIndex]
                    roplus.log("Using combat script : " + self.combatRotationName)
                imgui.sameLine()
                if imgui.button("Reload##grinder_reload_scripts", (imgui.getContentRegionAvail()[0], 24)):
                    combats.reloadCombatModules()
                imgui.separator()
                if self.combatSelectedIndex == -1:
                    imgui.text("Select a combat script first ...")
                else:
                    if imgui.checkbox("Enable combat", self.rotationEnabled):
                        self.rotationEnabled = not self.rotationEnabled
                    if imgui.checkbox("Only attack in combat targets", self.combatCheck):
                        self.combatCheck = not self.combatCheck
                    if imgui.checkbox("Allow combat script to use movements", self.handleMovements):
                        self.handleMovements = not self.handleMovements
                    if imgui.checkbox("Automatically target attackers (Not implemented)", self.autoTargetEnemies):
                        self.autoTargetEnemies = not self.autoTargetEnemies
            imgui.end()
Example #4
0
    def on_draw(self):
        imgui.create_context()

        imgui.new_frame()

        imgui.begin("FrameBuffer", True)
        fbs = [
            o for o in gc.get_referrers(FrameBuffer)
            if isinstance(o, FrameBuffer)
        ]
        gl.glClearColor(0, 0, 0, 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        clicked, self.current_framebuffer = imgui.combo(
            "FrameBuffer", self.current_framebuffer, [str(fb) for fb in fbs])

        fb = fbs[self.current_framebuffer]
        w, h = fb.size
        for name, tex in fb.textures.items():
            imgui.text(name)
            imgui.image(tex.name, 200, 200 * h / w)
        imgui.end()

        imgui.render()
        imgui.end_frame()

        data = imgui.get_draw_data()
        if data:
            self.imgui_renderer.render(imgui.get_draw_data())
Example #5
0
    def do_gui(self):
        imgui.new_frame()

        imgui.set_next_window_position(self.width, 0, pivot_x=1.0)
        imgui.begin("win",
                    closable=False,
                    flags=imgui.WINDOW_NO_TITLE_BAR | imgui.WINDOW_NO_MOVE
                    | imgui.WINDOW_NO_RESIZE)

        changed, self.time_per_div_selected = imgui.combo(
            "TIME/DIV", self.time_per_div_selected,
            [str(option) for option in TIME_PER_DIV_OPTIONS])
        if changed:
            self.time_per_div = TIME_PER_DIV_OPTIONS[
                self.time_per_div_selected]

        changed, self.y_per_div_selected = imgui.combo(
            "Y/DIV", self.y_per_div_selected,
            [str(option) for option in Y_PER_DIV_OPTIONS])
        if changed:
            self.y_per_div = Y_PER_DIV_OPTIONS[self.y_per_div_selected]

        imgui.text("Values")
        for addr in self.addresses:
            color_changed = False
            if addr in self.lines:
                # Change text color to indicate the color of plot
                r, g, b = self.line_colors[addr]
                imgui.push_style_color(imgui.COLOR_TEXT, r, g, b)
                color_changed = True

            changed, selected = imgui.selectable(addr, addr in self.lines)
            if changed and selected:
                self.lines[addr] = collections.deque(maxlen=MAX_POINTS)
            elif changed and not selected:
                del self.lines[addr]

            if color_changed:
                imgui.pop_style_color()

        self.gui_width = imgui.get_window_width()

        imgui.end()

        # imgui.render() in on_draw caused a "newFrame is not called" error on Windows,
        # therefore we invoke it here
        imgui.render()
Example #6
0
    def draw(self):
        imgui.begin("Example: combo widget")

        clicked, self.current = imgui.combo(
            "combo", self.current, ["first", "second", "third"]
        )

        imgui.end()
Example #7
0
    def onDrawGuiCallback(self, args):
        if self.visible:
            if imgui.begin("Grinder##grinder_mainwindow", (300,350)):
                player = BigWorld.player()
                imgui.columns(2)
                imgui.separator()
                imgui.text("State")
                imgui.nextColumn()
                if self.bot.running and self.bot.engine.currentState:
                    imgui.text(self.bot.engine.currentState.name)
                else:
                    imgui.text("N/A")
                imgui.nextColumn()
                imgui.text("Name")
                imgui.nextColumn()
                if player:
                    imgui.text(player.playerName)
                else:
                    imgui.text("Not ingame")
                imgui.nextColumn()
                imgui.text("Experience")
                imgui.nextColumn()
                if player:
                    exp_label = '{0} / {1}'.format(player.exp, data.avatar_lv_data.data.get(player.realLv, {}).get('upExp', '?'))
                    imgui.text(exp_label)
                else:
                    imgui.text("Not ingame")
                imgui.columns(1)
                imgui.separator()
                if not self.bot.running:
                    if imgui.button("Start##grinder_start_bot", (imgui.getContentRegionAvail()[0] / 2, 25)):
                        try:
                            combat_inst = combats.LOADED_COMBATS[combats.LOADED_COMBATS.keys()[self.combatSelectedIndex]]
                            self.bot.start(combat_inst)
                            self.profileEditor.hide()
                        except IndexError:
                            roplus.log("Please select a combat script first !")
                    imgui.sameLine()
                    if imgui.button("Profile editor##grinder_profile_editor", (imgui.getContentRegionAvail()[0], 25)):
                        self.profileEditor.show()
                else:
                    if imgui.button("Stop##grinder_stop_bot", (imgui.getContentRegionAvail()[0], 25)):
                        self.bot.stop()

                imgui.separator()
                if imgui.button("Save settings##grinder_save_settings", (imgui.getContentRegionAvail()[0], 25)):
                    settings.saveSettings(self.bot.settings, "grinder")
                if imgui.collapsingHeader("Combats##grinder_combats_settings", 0x20):
                    selectedChanged, self.combatSelectedIndex = imgui.combo("##grinder_combatcombo", self.combatSelectedIndex, combats.LOADED_COMBATS.keys())
                    if selectedChanged:
                        self.bot.settings["lastUsedCombat"] = combats.LOADED_COMBATS.keys()[self.combatSelectedIndex]
                        self.bot.saveSettings()
                    imgui.sameLine()
                    if imgui.button("Reload##grinder_reload_scripts", (imgui.getContentRegionAvail()[0], 24)):
                        combats.reloadCombatModules()
                        
        
            imgui.end()
Example #8
0
    def draw(self):
        imgui.new_frame()

        imgui.set_next_window_position(16, 32, imgui.ONCE)
        imgui.set_next_window_size(512, 512, imgui.ONCE)

        imgui.begin("Example: combo widget")

        clicked, self.current = imgui.combo(
            "combo", self.current, ["first", "second", "third"]
        )

        imgui.end()

        imgui.end_frame()

        imgui.render()

        self.renderer.render(imgui.get_draw_data())
Example #9
0
def FileWindow():
    '''
    string wdir, path to project folder
    '''
    global WDIR
    global LoadedFile
    global InstIndex
    global PersonIndex
    global ReloadPDF
      
    if not WDIR:
        imgui.dummy(50, 0)
        imgui.same_line()
        if imgui.button("選擇推甄資料目錄"):
            WDIR = TkFileDialog()
            
    else:
        imgui.text("現行推甄資料目錄:")
        imgui.push_text_wrap_position(150)
        imgui.text(WDIR)
        imgui.dummy(80,0)
        imgui.same_line()
        if imgui.button("變更"):
            WDIR = TkFileDialog()
        imgui.separator()
        if GF.CheckWDIR(WDIR):
            imgui.text('目前系所:')
            IList = os.listdir(WDIR)
            _, InstIndex = imgui.combo("", InstIndex, IList)
            imgui.text('學生編號:')
            PersonList = os.listdir(WDIR+'/'+IList[InstIndex])
            _, PersonIndex = imgui.listbox("", PersonIndex, PersonList, 15)
            imgui.text(f"目前檔案: {PersonList[PersonIndex]}")
            if imgui.button("查看檔案"):
                os.startfile(f'{WDIR}/{IList[InstIndex]}/{PersonList[PersonIndex]}/{PersonList[PersonIndex]}.pdf')                
                    
        else:
            with imgui.font(largefont):
                imgui.text('目錄錯誤,請重選!')
Example #10
0
def draw(imgui) -> None:
    global show_sendable_debug
    global show_demo
    global active_widgets

    if imgui.begin_main_menu_bar():
        if imgui.begin_menu("Help"):
            clicked, _ = imgui.menu_item(
                "Hide Demo" if show_demo else "Show Demo")
            if clicked:
                show_demo = not show_demo
            imgui.end_menu()
        imgui.end_main_menu_bar()

    if show_demo:
        imgui.show_test_window()

    if imgui.begin('All Entries'):
        if imgui.begin_popup_context_window():
            clicked, do_debug = imgui.checkbox('Show Chooser Debug Info',
                                               show_sendable_debug)
            if clicked:
                show_sendable_debug = do_debug
            imgui.end_popup()

        def table_tree(table: EntryGroup):
            for key, entry in table.items():
                if isinstance(entry, NetworkTableEntry):
                    imgui.text(entry_name(key) + ': ' + str(entry.value))

                    imgui.same_line()
                    imgui.push_id(key)
                    if imgui.button('Add'):
                        active_widgets[key] = Widget(entry)
                    imgui.pop_id()
                else:
                    t = NetworkTables.getTable(key)
                    if '.type' in t.getKeys():
                        name = t.getString('.name', '')

                        imgui.text(name)

                        imgui.same_line()
                        imgui.push_id(key)
                        if imgui.button('Add'):
                            active_widgets[key] = Widget(t, EntryType.Chooser)
                        imgui.pop_id()

                        if show_sendable_debug:
                            if imgui.tree_node('Chooser Debug (' + key + ')'):
                                table_tree(entry)
                                imgui.tree_pop()
                    elif imgui.tree_node(entry_name(key),
                                         imgui.TREE_NODE_DEFAULT_OPEN):
                        # nothing fancy, just a subtable
                        table_tree(entry)
                        imgui.tree_pop()

        entries = buildList(
            sorted(NetworkTables.getEntries('', 0), key=lambda e: e.getName()))
        table_tree(entries)
    imgui.end()

    to_close: List[str] = []
    for key, widget in active_widgets.items():
        expanded, opened = imgui.begin(entry_name(key), True)
        if not opened:
            to_close.append(key)

        if ((widget.tipe.is_entry() and widget.entry is None)
                or (not widget.tipe.is_entry() and widget.table is None)):
            imgui.text_colored('WARNING! Disconnected!', 1, 0, 0)
            imgui.end()
            continue

        if widget.tipe == EntryType.Boolean:
            assert widget.entry is not None

            if widget.show_indicator:
                imgui.push_item_width(-1)
                r, g, b = (0, 1, 0) if widget.entry.value else (1, 0, 0)
                imgui.color_button(key + '/indicator',
                                   r,
                                   g,
                                   b,
                                   width=imgui.get_window_width(),
                                   height=100)

            clicked, new_val = imgui.checkbox('on', widget.entry.value)
            if clicked:
                widget.entry.setValue(new_val)
        elif widget.tipe == EntryType.Double:
            assert widget.entry is not None

            val = str(widget.entry.getDouble(0))
            changed, new_val = imgui.input_text('', val, 64,
                                                imgui.INPUT_TEXT_CHARS_DECIMAL)
            if changed:
                try:
                    widget.entry.setDouble(float(new_val))
                except ValueError:
                    pass
        elif widget.tipe == EntryType.String:
            assert widget.entry is not None

            changed, new_val = imgui.input_text('', widget.entry.getString(''),
                                                256)
            if changed:
                widget.entry.setString(new_val)
        elif widget.tipe == EntryType.Chooser:
            assert widget.table is not None

            values = widget.table.getStringArray('options', [])
            try:
                selected = values.index(widget.table.getString('active', ''))
            except ValueError:
                selected = 0

            changed, current = imgui.combo('', selected, values)
            if changed:
                widget.table.putString('active', values[current])
        else:
            try:
                assert widget.entry is not None
                imgui.text(str(widget.entry.value))
            except AttributeError:
                imgui.text('Could not view contents.')

        if imgui.begin_popup_context_window():
            if widget.tipe == EntryType.Boolean:
                clicked, new_val = imgui.checkbox('Show Indicator',
                                                  widget.show_indicator)
                if clicked:
                    widget.show_indicator = new_val
            imgui.end_popup()

        # imgui.button('Options')

        imgui.end()

    for key in to_close:
        active_widgets.pop(key)
Example #11
0
def itemListCombo(currentItem, items, name):
    ind = items.index(currentItem)
    _, ind = imgui.combo(name, ind, items)
    return items[ind]
Example #12
0
    def onDrawGuiCallback(self, args):
        p = BigWorld.player()
        if self.visible:
            if imgui.begin("Quester##Quester_mainwindow", (300,350)):
                imgui.columns(2)
                imgui.separator()
                imgui.text("Name")
                imgui.nextColumn()
                if p:
                    imgui.text(p.playerName)
                else:
                    imgui.text("Not ingame")
                imgui.nextColumn()
                imgui.text("Map ID")
                imgui.nextColumn()
                if p:
                    imgui.text(str(p.mapID))
                else:
                    imgui.text("Not ingame")
                imgui.nextColumn()
                imgui.text("Experience")
                imgui.nextColumn()
                if p:
                    exp_label = '{0} / {1}'.format(p.exp, data.avatar_lv_data.data.get(p.realLv, {}).get('upExp', '?'))
                    imgui.text(exp_label)
                    imgui.nextColumn()
                else:
                    imgui.text("Not ingame")
                    imgui.nextColumn()
                imgui.text("State")
                imgui.nextColumn()
                if self.bot.running and self.bot.engine.currentState:
                    imgui.text(self.bot.engine.currentState.name)
                else:
                    imgui.text("N/A")
                imgui.nextColumn()
                imgui.text("Active quest")
                imgui.nextColumn()
                if self.bot.running and self.bot.currentQuestCompletor:
                    imgui.text(str(self.bot.currentQuestCompletor.questId))
                else:
                    imgui.text("N/A")
                imgui.nextColumn()
                imgui.text("Quest state")
                imgui.nextColumn()
                if self.bot.running and self.bot.currentQuestCompletor:
                    imgui.text(self.bot.currentQuestCompletor.state)
                else:
                    imgui.text("N/A")
                imgui.nextColumn()
                imgui.columns(1)
                imgui.separator()

                if not self.bot.running:
                    if imgui.button("Start##Quester_start_bot", (imgui.getContentRegionAvail()[0], 25)):
                        try:
                            combat_inst = combats.LOADED_COMBATS[combats.LOADED_COMBATS.keys()[self.combatSelectedIndex]]
                            self.bot.start(combat_inst)
                        except IndexError:
                            roplus.log("Please select a combat script first !")
                else:
                    if imgui.button("Stop##Quester_stop_bot", (imgui.getContentRegionAvail()[0], 25)):
                        self.bot.stop()

                imgui.separator()
                if imgui.button("Save settings##Quester_save_settings", (imgui.getContentRegionAvail()[0], 25)):
                    settings.saveSettings(self.bot.settings, "Quester")

                #
                # Combats
                #
                if imgui.collapsingHeader("Combats##Quester_combats_settings", 0x20):
                    selectedChanged, self.combatSelectedIndex = imgui.combo("##Quester_combatcombo", self.combatSelectedIndex, combats.LOADED_COMBATS.keys())
                    if selectedChanged:
                        self.bot.settings["lastUsedCombat"] = combats.LOADED_COMBATS.keys()[self.combatSelectedIndex]
                        self.bot.saveSettings()
                    imgui.sameLine()
                    if imgui.button("Reload##Quester_reload_scripts", (imgui.getContentRegionAvail()[0], 24)):
                        combats.reloadCombatModules()

                #
                # Quest Logs
                #
                if imgui.collapsingHeader("[Debug] Quests Info##Quester_questslog"):
                    if p and p.questInfoCache:
                        for category, questIds in p.questInfoCache.items():
                            if imgui.treeNode("[{}] {}".format(str(len(questIds)), category)):
                                for questId in questIds:
                                    questDetails = p.genQuestDetail(questId, -1)
                                    questData = QuestData.data.get(questId, {})
                                    if questData and imgui.treeNode("[{}] {}".format(str(questId), questData.get("name", ""))):
                                        if questDetails and questDetails.get("taskGoal", {}) and imgui.treeNode("Quest goals ({})##questid_{}".format(str(len(questDetails["taskGoal"])), str(questId))):
                                            for i, taskGoal in enumerate(questDetails["taskGoal"]):
                                                questGoal = QuestGoal(taskGoal)
                                                if imgui.treeNode("[{0}] {1}##quest_goal_{2}_{0}".format(str(i+1), questGoal.description, str(questId))):
                                                    imgui.text("State : {}".format(str(questGoal.state)))
                                                    imgui.text("Type : {}".format(str(questGoal.type)))
                                                    imgui.text("Track Seek ID : {}".format(str(questGoal.trackSeekId)))
                                                    imgui.text("Track Task Type : {}".format(str(questGoal.trackTaskType)))
                                                    imgui.text("Order : {}".format(str(questGoal.order)))
                                                    if questGoal.trackSeekData and imgui.treeNode("Track Task data##questid_{}_{}".format(str(questId), str(i))):
                                                        for k,v in questGoal.trackSeekData.items():
                                                            imgui.text("{} -> {}".format(str(k), str(v)))
                                                        imgui.treePop()
                                                    imgui.treePop()
                                            imgui.treePop()
                                        if questData and imgui.treeNode("Quest data##questid_{}".format(str(questId))):
                                            for k,v in questData.items():
                                                imgui.text("{} -> {}".format(str(k), str(v)))
                                            imgui.treePop()
                                        if questDetails and imgui.treeNode("Quest details##questid_{}".format(str(questId))):
                                            for k,v in questDetails.items():
                                                imgui.text("{} -> {}".format(str(k), str(v)))
                                            imgui.treePop()
                                        imgui.treePop()
                                imgui.treePop()
                            #for questInfo in roplus.helpers.questing.getQuestInfosFromCache(questCategory):
                            #    if imgui.treeNode("["+questCategory+"] "+questInfo.getName()+"##" + str(questInfo.questId)):
                            #        if imgui.treeNode("-> Quest Data##" + str(questInfo.questId)):
                            #            for k,v in questInfo.questData.items():
                            #                imgui.text(str(k) + " -> " + str(v))
                            #            imgui.treePop()
                            #        if imgui.treeNode("-> Quest Details##" + str(questInfo.questId)):
                            #            for k,v in player.genQuestDetail(questInfo.questId, -1).items():
                            #                imgui.text(str(k) + " -> " + str(v))
                            #            imgui.treePop()
                            #        imgui.treePop()
        
            imgui.end()
Example #13
0
        curY = -touch['cur_y'] + h // 2
        press = touch['is_holded'] | touch['is_moved']
    impl.process_inputs()

    core.update()

    camera.shoot(showcase)
    if _particle is not None:
        _particle.shoot(camera.projectionMatrix,
                        vmath.inverse(camera.viewInverseMatrix),
                        core.getElapsedTime())

    imgui.new_frame()
    imgui.begin("Effekseer", True, imgui.WINDOW_ALWAYS_AUTO_RESIZE)

    changed, effect_current = imgui.combo("Effects", effect_current,
                                          effect_list)
    if changed is True:
        _particle.stop_all_effects()
        _handle = _particle.add(effect_list[effect_current],
                                loop=_loop_enabled)
        _particle.set_dynamic_input(_handle, _dynamic)
        _particle.set_location(_handle, _position[0], _position[1],
                               _position[2])
        _particle.set_scale(_handle, _scale[0], _scale[1], _scale[2])

    changed, _show_enabled = imgui.checkbox("Show", _show_enabled)
    if changed is True:
        _particle.set_shown(_handle, _show_enabled, True)
    imgui.same_line()
    changed, _loop_enabled = imgui.checkbox("Loop", _loop_enabled)
    if changed is True:
Example #14
0
 def __call__(self, *args, **kwargs):
     clicked, value = imgui.combo(self.label, self.enum_map[self.value],
                                  self.enum_values)
     if clicked:
         self.value = self.enum_map_invert[value]
Example #15
0
def userInterface(graphicItem, app):
    """ Control graphicItem parameters interactively
    """
    imgui.new_frame()
    expanded, opened = imgui.begin('Controls', closable=True,
            flags=imgui.WINDOW_ALWAYS_AUTO_RESIZE)
    if opened:
        # Field to show
        current = app.ifield
        changed, current = imgui.combo('Field', current, list(CHOICES))
        if changed:
            app.setField(current)

        # Speed Rate
        changed, speed = imgui.drag_float('Speed',
            graphicItem.speedFactor, 0.01, 0.0, 10.0)
        if changed:
            graphicItem.speedFactor = speed

        # Decay
        changed, decay = imgui.drag_float('Decay',
            graphicItem.decay, 0.001, 0.001, 1.0)
        if changed:
            graphicItem.decay = decay

        # Drop Rate Bump
        changed, decayBoost = imgui.drag_float('Decay boost',
            graphicItem.decayBoost, 0.01, 0.001, 1.0)
        if changed:
            graphicItem.decayBoost = decayBoost

        # Unknown const
        changed, opacity = imgui.drag_float('Opacity',
            graphicItem.fadeOpacity, 0.001, 0.900, 0.999, '%.4f')
        if changed:
            graphicItem.fadeOpacity = opacity

        # Palette
        changed, color = imgui.color_edit3('Color', *graphicItem.color)
        if changed:
            graphicItem.color = color
        imgui.same_line()
        changed, palette = imgui.checkbox("Palette", graphicItem.palette)
        if changed:
            graphicItem.palette = palette

        changed, bg_color = imgui.color_edit4('Background color',
                *app.bg_color)
        if changed:
            app.bg_color = bg_color

        # Point size
        changed, pointSize = imgui.input_int("Point size",
            graphicItem.pointSize, 1, 1, 1)
        if changed:
            if pointSize > 5:
                pointSize = 5
            elif pointSize < 1:
                pointSize = 1
            graphicItem.pointSize = pointSize

        # Number of Points
        changed, tracersCount = imgui.drag_int("Number of "
            "Tracers", graphicItem.tracersCount, 1000.0, 4000, 10000000)
        if changed:
            graphicItem.tracersCount = tracersCount

        # Periodic border
        changed, periodic = imgui.checkbox("Periodic", graphicItem.periodic)
        if changed:
            graphicItem.periodic = periodic

        # Draw field
        changed, drawfield = imgui.checkbox("Draw Field",
                graphicItem.drawField)
        if changed:
            graphicItem.drawField = drawfield
    imgui.end()
    imgui.render()
    return opened
def main():

    useLiveCamera = True

    #gc.disable()

    # # transform to convert the image to tensor
    # transform = transforms.Compose([
    #     transforms.ToTensor()
    # ])
    # # initialize the model
    # model = torchvision.models.detection.keypointrcnn_resnet50_fpn(pretrained=True,
    #                                                             num_keypoints=17)
    # # set the computation device
    # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    # # load the modle on to the computation device and set to eval mode
    # model.to(device).eval()

    # initialize glfw
    if not glfw.init():
        return
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    #creating the window
    window = glfw.create_window(1600, 900, "PyGLFusion", None, None)
    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)

    imgui.create_context()
    impl = GlfwRenderer(window)

    # rendering
    glClearColor(0.2, 0.3, 0.2, 1.0)

    #           positions        texture coords
    quad = [
        -1.0, -1.0, 0.0, 0.0, 0.0, 1.0, -1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0,
        1.0, 1.0, -1.0, 1.0, 0.0, 0.0, 1.0
    ]

    quad = np.array(quad, dtype=np.float32)

    indices = [0, 1, 2, 2, 3, 0]

    indices = np.array(indices, dtype=np.uint32)

    screenVertex_shader = (Path(__file__).parent /
                           'shaders/ScreenQuad.vert').read_text()

    screenFragment_shader = (Path(__file__).parent /
                             'shaders/ScreenQuad.frag').read_text()

    renderShader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(screenVertex_shader, GL_VERTEX_SHADER),
        OpenGL.GL.shaders.compileShader(screenFragment_shader,
                                        GL_FRAGMENT_SHADER))

    # set up VAO and VBO for full screen quad drawing calls
    VAO = glGenVertexArrays(1)
    glBindVertexArray(VAO)

    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, 80, quad, GL_STATIC_DRAW)

    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, 24, indices, GL_STATIC_DRAW)

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(12))
    glEnableVertexAttribArray(1)

    # shaders

    bilateralFilter_shader = (Path(__file__).parent /
                              'shaders/bilateralFilter.comp').read_text()
    bilateralFilterShader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(bilateralFilter_shader,
                                        GL_COMPUTE_SHADER))

    alignDepthColor_shader = (Path(__file__).parent /
                              'shaders/alignDepthColor.comp').read_text()
    alignDepthColorShader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(alignDepthColor_shader,
                                        GL_COMPUTE_SHADER))

    depthToVertex_shader = (Path(__file__).parent /
                            'shaders/depthToVertex.comp').read_text()
    depthToVertexShader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(depthToVertex_shader,
                                        GL_COMPUTE_SHADER))

    vertexToNormal_shader = (Path(__file__).parent /
                             'shaders/vertexToNormal.comp').read_text()
    vertexToNormalShader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(vertexToNormal_shader,
                                        GL_COMPUTE_SHADER))

    raycast_shader = (Path(__file__).parent /
                      'shaders/raycast.comp').read_text()
    raycastShader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(raycast_shader, GL_COMPUTE_SHADER))

    integrate_shader = (Path(__file__).parent /
                        'shaders/integrate.comp').read_text()
    integrateShader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(integrate_shader, GL_COMPUTE_SHADER))

    trackP2P_shader = (Path(__file__).parent /
                       'shaders/p2pTrack.comp').read_text()
    trackP2PShader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(trackP2P_shader, GL_COMPUTE_SHADER))

    reduceP2P_shader = (Path(__file__).parent /
                        'shaders/p2pReduce.comp').read_text()
    reduceP2PShader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(reduceP2P_shader, GL_COMPUTE_SHADER))

    trackP2V_shader = (Path(__file__).parent /
                       'shaders/p2vTrack.comp').read_text()
    trackP2VShader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(trackP2V_shader, GL_COMPUTE_SHADER))

    reduceP2V_shader = (Path(__file__).parent /
                        'shaders/p2vReduce.comp').read_text()
    reduceP2VShader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(reduceP2V_shader, GL_COMPUTE_SHADER))

    LDLT_shader = (Path(__file__).parent / 'shaders/LDLT.comp').read_text()
    LDLTShader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(LDLT_shader, GL_COMPUTE_SHADER))

    # Splatter
    globalMapUpdate_shader = (Path(__file__).parent /
                              'shaders/GlobalMapUpdate.comp').read_text()
    globalMapUpdateShader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(globalMapUpdate_shader,
                                        GL_COMPUTE_SHADER))

    indexMapGenVert_shader = (Path(__file__).parent /
                              'shaders/IndexMapGeneration.vert').read_text()

    indexMapGenFrag_shader = (Path(__file__).parent /
                              'shaders/IndexMapGeneration.frag').read_text()

    IndexMapGenerationShader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(indexMapGenVert_shader,
                                        GL_VERTEX_SHADER),
        OpenGL.GL.shaders.compileShader(indexMapGenFrag_shader,
                                        GL_FRAGMENT_SHADER))

    SurfaceSplattingVert_shader = (
        Path(__file__).parent / 'shaders/SurfaceSplatting.vert').read_text()

    SurfaceSplattingFrag_shader = (
        Path(__file__).parent / 'shaders/SurfaceSplatting.frag').read_text()

    SurfaceSplattingShader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(SurfaceSplattingVert_shader,
                                        GL_VERTEX_SHADER),
        OpenGL.GL.shaders.compileShader(SurfaceSplattingFrag_shader,
                                        GL_FRAGMENT_SHADER))

    UnnecessaryPointRemoval_shader = (
        Path(__file__).parent /
        'shaders/UnnecessaryPointRemoval.comp').read_text()
    UnnecessaryPointRemovalShader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(UnnecessaryPointRemoval_shader,
                                        GL_COMPUTE_SHADER))

    # P2V
    expm_shader = (Path(__file__).parent / 'shaders/expm.comp').read_text()
    expmShader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(expm_shader, GL_COMPUTE_SHADER))

    d2c, c2d, K, invK, colK = camera.start(useLiveCamera)

    shaderDict = {
        'renderShader': renderShader,
        'bilateralFilterShader': bilateralFilterShader,
        'alignDepthColorShader': alignDepthColorShader,
        'depthToVertexShader': depthToVertexShader,
        'vertexToNormalShader': vertexToNormalShader,
        'raycastVolumeShader': raycastShader,
        'integrateVolumeShader': integrateShader,
        'trackP2PShader': trackP2PShader,
        'reduceP2PShader': reduceP2PShader,
        'trackP2VShader': trackP2VShader,
        'reduceP2VShader': reduceP2VShader,
        'LDLTShader': LDLTShader,
        'globalMapUpdate': globalMapUpdateShader,
        'indexMapGeneration': IndexMapGenerationShader,
        'surfaceSplatting': SurfaceSplattingShader,
        'unnecessaryPointRemoval': UnnecessaryPointRemovalShader,
        'expm': expmShader
    }

    bufferDict = {
        'p2pReduction': -1,
        'p2pRedOut': -1,
        'p2vReduction': -1,
        'p2vRedOut': -1,
        'test': -1,
        'outBuf': -1,
        'poseBuffer': -1,
        'globalMap0': -1,
        'globalMap1': -1,
        'atomic0': -1,
        'atomic1': -1
    }

    textureDict = {
        'rawColor': -1,
        'lastColor': -1,
        'nextColor': -1,
        'rawDepth': -1,
        'filteredDepth': -1,
        'lastDepth': -1,
        'nextDepth': -1,
        'refVertex': -1,
        'refNormal': -1,
        'virtualVertex': -1,
        'virtualNormal': -1,
        'virtualDepth': -1,
        'virtualColor': -1,
        'mappingC2D': -1,
        'mappingD2C': -1,
        'xyLUT': -1,
        'tracking': -1,
        'volume': -1,
        'indexMap': -1
    }

    fboDict = {'indexMap': -1, 'virtualFrame': -1}
    #        'iters' : (2, 5, 10),

    fusionConfig = {
        'volSize': (128, 128, 128),
        'volDim': (1.0, 1.0, 1.0),
        'iters': (2, 2, 2),
        'initOffset': (0, 0, 0),
        'maxWeight': 100.0,
        'distThresh': 0.05,
        'normThresh': 0.9,
        'nearPlane': 0.1,
        'farPlane': 4.0,
        'maxMapSize': 5000000,
        'c_stable': 10.0,
        'sigma': 0.6
    }

    cameraConfig = {
        'depthWidth': 640,
        'depthHeight': 576,
        'colorWidth': 1920,
        'colorHeight': 1080,
        'd2c': d2c,
        'c2d': c2d,
        'depthScale': 0.001,
        'K': K,
        'invK': invK,
        'colK': colK
    }

    textureDict = frame.generateTextures(textureDict, cameraConfig,
                                         fusionConfig)
    bufferDict = frame.generateBuffers(bufferDict, cameraConfig, fusionConfig)

    colorMat = np.zeros(
        (cameraConfig['colorHeight'], cameraConfig['colorWidth'], 3),
        dtype="uint8")
    useColorMat = False
    integrateFlag = True
    resetFlag = True
    initPose = glm.mat4()
    initPose[3, 0] = fusionConfig['volDim'][0] / 2.0
    initPose[3, 1] = fusionConfig['volDim'][1] / 2.0
    initPose[3, 2] = 0

    blankResult = np.array([0, 0, 0, 0, 0, 0], dtype='float32')

    glBindBuffer(GL_SHADER_STORAGE_BUFFER, bufferDict['poseBuffer'])
    glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, 16 * 4,
                    glm.value_ptr(initPose))
    glBufferSubData(GL_SHADER_STORAGE_BUFFER, 16 * 4, 16 * 4,
                    glm.value_ptr(glm.inverse(initPose)))
    glBufferSubData(GL_SHADER_STORAGE_BUFFER, 16 * 4 * 2, 16 * 4,
                    glm.value_ptr(glm.mat4(1.0)))
    glBufferSubData(GL_SHADER_STORAGE_BUFFER, 16 * 4 * 3, 16 * 4,
                    glm.value_ptr(glm.mat4(1.0)))
    glBufferSubData(GL_SHADER_STORAGE_BUFFER, 16 * 4 * 4, 6 * 4, blankResult)
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0)

    mouseX, mouseY = 0, 0
    clickedPoint3D = glm.vec4(fusionConfig['volDim'][0] / 2.0,
                              fusionConfig['volDim'][1] / 2.0, 0, 0)
    sliderDim = fusionConfig['volDim'][0]

    #[32 64 128 256 512]
    currentSize = math.log2(fusionConfig['volSize'][0]) - 5
    volumeStatsChanged = False

    currPose = initPose

    # splatter stuff
    frameCount = 0
    fboDict = frame.generateFrameBuffers(fboDict, textureDict, cameraConfig)

    initAtomicCount = np.array([0], dtype='uint32')
    mapSize = np.array([0], dtype='uint32')

    glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, bufferDict['atomic0'])
    glBufferSubData(GL_ATOMIC_COUNTER_BUFFER, 0, 4, initAtomicCount)
    glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, 0)

    glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, bufferDict['atomic1'])
    glBufferSubData(GL_ATOMIC_COUNTER_BUFFER, 0, 4, initAtomicCount)
    glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, 0)

    # aa = torch.tensor([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0], dtype=torch.float32, device=torch.device('cuda'))
    # bb = torch.tensor([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], dtype=torch.float32, device=torch.device('cuda'))

    # #setup pycuda gl interop needs to be after openGL is init
    # import pycuda.gl.autoinit
    # import pycuda.gl
    # cuda_gl = pycuda.gl
    # cuda_driver = pycuda.driver
    # from pycuda.compiler import SourceModule
    # import pycuda

    # pycuda_source_ssbo = cuda_gl.RegisteredBuffer(int(bufferDict['test']), cuda_gl.graphics_map_flags.NONE)

    # sm = SourceModule("""
    #     __global__ void simpleCopy(float *inputArray, float *outputArray) {
    #             unsigned int x = blockIdx.x*blockDim.x + threadIdx.x;

    #             outputArray[x] = inputArray[x];
    #             inputArray[x] = 8008.135f;
    #     }
    # """)

    # cuda_function = sm.get_function("simpleCopy")

    # mappingObj = pycuda_source_ssbo.map()
    # data, size = mappingObj.device_ptr_and_size()

    # cuda_function(np.intp(aa.data_ptr()), np.intp(data), block=(8, 1, 1))

    # mappingObj.unmap()

    # glBindBuffer(GL_SHADER_STORAGE_BUFFER, bufferDict['test'])
    # tee = glGetBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, 32)
    # glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0)
    # teeData = np.frombuffer(tee, dtype=np.float32)
    # print(teeData)

    # modTensor = aa.cpu().data.numpy()
    # print(modTensor)

    #fusionConfig['initOffset'] = (initPose[3,0], initPose[3,1], initPose[3,2])

    # LUTs
    #createXYLUT(k4a, textureDict, cameraConfig) <-- bug in this

    person.init()

    while not glfw.window_should_close(window):

        glfw.poll_events()
        impl.process_inputs()
        imgui.new_frame()

        sTime = time.perf_counter()

        try:
            capture = camera.getFrames(useLiveCamera)

            if capture.color is not None:
                #if useLiveCamera == False:
                #if k4a.configuration["color_format"] == ImageFormat.COLOR_MJPG:
                #    colorMat = cv2.imdecode(capture.color, cv2.IMREAD_COLOR)
                #    useColorMat = True
                glActiveTexture(GL_TEXTURE0)
                glBindTexture(GL_TEXTURE_2D, textureDict['rawColor'])
                glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0,
                                int(cameraConfig['colorWidth']),
                                int(cameraConfig['colorHeight']),
                                (GL_RGB, GL_RGBA)[useLiveCamera],
                                GL_UNSIGNED_BYTE,
                                (capture.color, colorMat)[useColorMat])

            if capture.depth is not None:
                glActiveTexture(GL_TEXTURE1)
                glBindTexture(GL_TEXTURE_2D, textureDict['rawDepth'])
                glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0,
                                int(cameraConfig['depthWidth']),
                                int(cameraConfig['depthHeight']), GL_RED,
                                GL_UNSIGNED_SHORT, capture.depth)

        except EOFError:
            break

        # #smallMat = cv2.pyrDown(colorMat)
        # start_time = time.time()
        # rotMat = cv2.flip(colorMat, 0)

        # pil_image = Image.fromarray(rotMat).convert('RGB')
        # image = transform(pil_image)

        # image = image.unsqueeze(0).to(device)
        # end_time = time.time()
        # print((end_time - start_time) * 1000.0)

        # with torch.no_grad():
        #     outputs = model(image)

        # output_image = utils.draw_keypoints(outputs, rotMat)
        # cv2.imshow('Face detection frame', output_image)
        # if cv2.waitKey(1) & 0xFF == ord('q'):
        #     break

        person.getPose(textureDict, cameraConfig, capture.color)

        frame.bilateralFilter(shaderDict, textureDict, cameraConfig)
        frame.depthToVertex(shaderDict, textureDict, cameraConfig,
                            fusionConfig)
        frame.alignDepthColor(shaderDict, textureDict, cameraConfig,
                              fusionConfig)
        frame.vertexToNormal(shaderDict, textureDict, cameraConfig)

        frame.mipmapTextures(textureDict)

        #currPose = track.runP2P(shaderDict, textureDict, bufferDict, cameraConfig, fusionConfig, currPose, integrateFlag, resetFlag)
        currPose = track.runP2V(shaderDict, textureDict, bufferDict,
                                cameraConfig, fusionConfig, currPose,
                                integrateFlag, resetFlag)

        #mapSize = track.runSplatter(shaderDict, textureDict, bufferDict, fboDict, cameraConfig, fusionConfig, mapSize, frameCount, integrateFlag, resetFlag)
        frameCount += 1

        if resetFlag == True:
            resetFlag = False
            integrateFlag = True

        imgui.begin("Menu", True)
        if imgui.button("Reset"):
            fusionConfig['volSize'] = (1 << (currentSize + 5), 1 <<
                                       (currentSize + 5), 1 <<
                                       (currentSize + 5))
            fusionConfig['volDim'] = (sliderDim, sliderDim, sliderDim)
            currPose, integrateFlag, resetFlag = track.reset(
                textureDict, bufferDict, cameraConfig, fusionConfig,
                clickedPoint3D)
            volumeStatsChanged = False

        if imgui.button("Integrate"):
            integrateFlag = not integrateFlag
        imgui.same_line()
        imgui.checkbox("", integrateFlag)

        changedDim, sliderDim = imgui.slider_float("dim",
                                                   sliderDim,
                                                   min_value=0.01,
                                                   max_value=5.0)

        clickedSize, currentSize = imgui.combo(
            "size", currentSize, ["32", "64", "128", "256", "512"])

        if imgui.is_mouse_clicked():
            if not imgui.is_any_item_active():
                mouseX, mouseY = imgui.get_mouse_pos()
                w, h = glfw.get_framebuffer_size(window)
                xPos = ((mouseX % int(w / 3)) / (w / 3) *
                        cameraConfig['depthWidth'])
                yPos = (mouseY / (h)) * cameraConfig['depthHeight']
                clickedDepth = capture.depth[
                    int(yPos + 0.5),
                    int(xPos + 0.5)] * cameraConfig['depthScale']
                clickedPoint3D = clickedDepth * (
                    cameraConfig['invK'] * glm.vec4(xPos, yPos, 1.0, 0.0))
                volumeStatsChanged = True

        if changedDim or clickedSize:
            volumeStatsChanged = True

        imgui.end()

        graphics.render(VAO, window, shaderDict, textureDict)

        imgui.render()

        impl.render(imgui.get_draw_data())

        eTime = time.perf_counter()

        #print((eTime-sTime) * 1000, mapSize[0])

        glfw.swap_buffers(window)

    glfw.terminate()
    if useLiveCamera == True:
        camera.stop()
Example #17
0
    def draw_scene_gui(self):
        imgui.begin("Scene", True)

        imgui.text('test:')

        changed0, self.solver_index = imgui.combo('solver', self.solver_index, 
                                                 self.solver_list)
        
        changed1, self.case_index = imgui.combo('case', self.case_index, 
                                                 self.case_list)

        if changed0 or changed1:
            self.load_scene = True
            new_scene = self.case_list[self.case_index]
            if 'box-case' in new_scene:
                self.build_mode_case(lambda: box_case(int(new_scene[-1])))
            if new_scene == 'peg-in-hole-4':
                self.build_mode_case(lambda: peg_in_hole(4))
            if new_scene == 'peg-in-hole-8':
                self.build_mode_case(lambda: peg_in_hole(8))
            if 'box-box' in new_scene:
                self.build_mode_case(lambda: box_box_case(int(new_scene[-1])))
            if new_scene == 'hand-football':
                self.build_mode_case(lambda: hand_football(False))
            if new_scene == 'hand-football-fixed':
                self.build_mode_case(lambda: hand_football(True))

        imgui.text('control:')
        changed, self.lattice_height = imgui.slider_float('height', self.lattice_height, 0, 500)
        changed, self.plot_gui = imgui.checkbox('plot', self.plot_gui)
        changed, self.max_steps = imgui.drag_float('max steps', self.max_steps,
                                                    1, 0, 200)
        changed, self.h = imgui.drag_float('h', self.h, 0.0001, 0, 0.05)

        imgui.text('render:')
        changed, self.alpha = imgui.slider_float('alpha', self.alpha, 0.0, 1.0)
        if changed or self.load_scene:
            self.renderer.opacity = self.alpha

        changed, self.peel_depth = imgui.slider_int(
            'peel', self.peel_depth, 0, self.renderer.max_peel_depth)
        if changed or self.load_scene:
            self.renderer.peel_depth = self.peel_depth

        changed, new_color = imgui.color_edit4('object', *self.object_color)
        if changed or self.load_scene:
            [body.set_color(np.array(new_color)) for body in self.system.bodies]
            self.object_color = new_color
        
        changed, new_scale = imgui.drag_float3('frame', 
                                               *self.frame_scale,
                                               0.005, 0.0, 5.0)
        if changed or self.load_scene:
            self.frame.set_radius(new_scale[0])
            self.frame.set_length(new_scale[1])
            self.frame.set_alpha(new_scale[2])
            self.frame_scale = new_scale

        changed, new_color = imgui.color_edit4('contact', *self.contact_color)
        if changed or self.load_scene:
            self.contact_spheres[0].set_color(np.array(new_color))
            self.contact_arrows[0].set_color(np.array(new_color))
            self.contact_color = new_color

        changed, new_color = imgui.color_edit4('separate', *self.separating_color)
        if changed or self.load_scene:
            self.contact_spheres[1].set_color(np.array(new_color))
            self.contact_arrows[1].set_color(np.array(new_color))
            self.separating_color = new_color

        changed, new_scale = imgui.drag_float('sphere r',
                                              self.contact_scale,
                                              0.005, 0.0, 1.0)
        if changed or self.load_scene:
            for sphere in self.contact_spheres:
                sphere.set_radius(self.contact_scale)
            self.contact_scale = new_scale
        
        changed, new_scale = imgui.drag_float4('vel', 
                                               *self.velocity_scale,
                                               0.005, 0.0, 100.0)
        if changed or self.load_scene:
            for arrow in self.contact_arrows:
                arrow.set_shaft_length(new_scale[0])
                arrow.set_shaft_radius(new_scale[1])
                arrow.set_head_length(new_scale[2])
                arrow.set_head_radius(new_scale[3])
            self.velocity_scale = new_scale

        changed, new_color = imgui.color_edit4('obs', *self.obstacle_color)
        if changed or self.load_scene:
            [o.set_color(np.array(new_color)) for o in self.system.obstacles]
            self.obstacle_color = new_color

        changed, new_pos = imgui.slider_float3('light', *self.light_pos, -10.0, 10.0)
        if changed or self.load_scene:
            self.light_pos = new_pos
        
        # changed, new_pos = imgui.slider_float3('cam', *self.cam_focus, -10.0, 10.0)
        # if changed or self.load_scene:
        #     self.cam_focus = new_pos

        changed, self.show_grid = imgui.checkbox('grid', self.show_grid)

        changed, self.big_lattice = imgui.checkbox('big lattice', self.big_lattice)

        changed, self.show_contact_frames = imgui.checkbox('frames', self.show_contact_frames)

        changed, self.show_contacts = imgui.checkbox('contacts', self.show_contacts)

        changed, self.show_velocities = imgui.checkbox('velocities', self.show_velocities)
        
        self.load_scene = False
        imgui.end()
Example #18
0
    def displayInterface(self):

        imgui.begin_child("left_bottom", width=606, height=370)

        if (self.activeInterface == "main"):

            imgui.text("Main Interface (SSH)")
            imgui.begin_child("left_bottom",
                              width=606,
                              height=290,
                              border=True)

            imgui.begin_child("connections", width=606)

            imgui.columns(4, 'ssh_connections')
            imgui.text("ID")
            imgui.next_column()
            imgui.text("USER")
            imgui.next_column()
            imgui.text("IP")
            imgui.next_column()
            imgui.text("Time Connected")
            imgui.separator()

            imgui.set_column_width(0, 70)

            for conn in list(self.activeConnections.keys()):
                now = datetime.now()
                elapsed = now - self.activeConnections[conn]["connected_time"]
                imgui.next_column()
                imgui.text(self.activeConnections[conn]["ssh_proc"])
                imgui.next_column()
                imgui.text(self.activeConnections[conn]["user"])
                imgui.next_column()
                imgui.text(self.activeConnections[conn]["ip"])
                imgui.next_column()
                imgui.text(str(elapsed))

            imgui.columns(1)

            imgui.end_child()
            imgui.end_child()

            imgui.text("Select a SSH Session")

            clicked, current = imgui.combo("##Path input", self.sshSelected,
                                           self.sshSelectionOptions)

            if (clicked):
                self.sshSelected = current

            if (imgui.button("Kick")):
                ssh_proc = self.sshSelectionOptions[
                    self.sshSelected].split()[0][1:-1]
                log.logNorm("Kicked SSH Session (" + ssh_proc + ") " +
                            self.activeConnections[ssh_proc]["user"])
                self.disconnectSSHConnection(ssh_proc)

            imgui.same_line()
            if (imgui.button("Ban Both")):
                self.handleBanningUser()
                self.handleBanningIPAddr()
                self.handleDisconnectingCurrentSelection()

            imgui.same_line()
            if (imgui.button("Ban User")):
                self.handleBanningUser()
                self.handleDisconnectingCurrentSelection()

            imgui.same_line()
            if (imgui.button("Ban IP")):
                self.handleBanningIPAddr()
                self.handleDisconnectingCurrentSelection()

        elif (self.activeInterface == "ban"):
            imgui.text("Ban List (SSH)")
            imgui.begin_child("left_bottom",
                              width=299,
                              height=310,
                              border=True)

            imgui.columns(2, 'ssh_connections')
            imgui.text("USERNAME")
            imgui.next_column()
            imgui.next_column()
            imgui.separator()

            for user in self.banList["users"]:
                imgui.text(user)
                imgui.next_column()

            imgui.columns(1)
            imgui.end_child()

            imgui.same_line()

            imgui.begin_child("right_bottom",
                              width=299,
                              height=310,
                              border=True)
            imgui.text("IP Address")
            imgui.next_column()
            imgui.next_column()
            imgui.separator()

            for user in self.banList["ip_addresses"]:
                imgui.text(user)
                imgui.next_column()

            imgui.columns(1)
            imgui.end_child()

            imgui.begin_child("left_selection", width=299)

            clicked, current = imgui.combo("##Path input",
                                           self.banUserSelected,
                                           self.banList["users"])

            imgui.same_line()

            if (imgui.button("Unban")):
                self.alert("Unbanning User (" +
                           self.banList["users"][self.banUserSelected] + ")")
                del self.banList["users"][self.banUserSelected]
                self.saveBanList()

            imgui.end_child()

            imgui.same_line()

            imgui.begin_child("right_selection", width=299)

            clicked, current = imgui.combo("##Path input", self.banIPSelected,
                                           self.banList["ip_addresses"])

            imgui.same_line()

            if (imgui.button("Unban")):
                self.alert("Unbanning IP (" +
                           self.banList["ip_addresses"][self.banIPSelected] +
                           ")")
                del self.banList["ip_addresses"][self.banIPSelected]
                self.saveBanList()

            imgui.end_child()

        imgui.end_child()

        imgui.same_line()

        imgui.begin_child("ssh_alerts")
        imgui.text("SSH Connections Alerts")

        imgui.begin_child("ssh_alerts_logger", border=True)

        for message in self.alerts:
            imgui.text_wrapped(message)

        imgui.end_child()
        imgui.end_child()
Example #19
0
    def update(self):
        # return done, value
        do_return = False
        recipe = ''
        if self.extra_font:
            imgui.push_font(self.extra_font)
        width = 750
        height = 250
        imgui.set_next_window_size(width, height)
        imgui.set_next_window_position(self.center_x - width // 2,
                                       self.center_y - height // 2)
        imgui.push_style_var(imgui.STYLE_ALPHA, self.alpha)
        imgui.begin('Drop', False, flags=self.flags)
        self.left_label('ID:')
        xx, self.id = imgui.input_text('\n', self.id, 128)
        self.tooltip_help('Participant ID/Name')

        self.add_space(3)
        self.left_label('Español:')
        _, self.spanish = imgui.checkbox('', self.spanish)
        self.tooltip_help('Spanish text for subsequent instructions')
        self.add_space(3)

        self.left_label('Recipe:')
        # current filenames
        recipe_names = []
        recipe_short = []
        for file in glob.glob('recipes/**/*.toml', recursive=True):
            if (os.path.sep + 'defaults' + os.path.sep) not in file:
                recipe_names.append(file)
                recipe_short.append(os.path.relpath(file, 'recipes'))
        changed, self.current_recipe = imgui.combo(' ', self.current_recipe,
                                                   recipe_short)
        self.tooltip_help(
            'Available recipes (TOML files) in the recipe directory')
        imgui.same_line()
        imgui.button('Preview')
        if imgui.is_item_hovered() and recipe_names:
            with open(recipe_names[self.current_recipe], 'r') as f:
                prev = f.read()
            # width in characters, height in number of newlines
            if prev:
                wid = len(
                    max(open(recipe_names[self.current_recipe], 'r'), key=len))
                # TODO: need to be careful of newline char??
                hei = prev.count('\n') + 1
            else:
                wid = 10
                hei = 1
            fac = 0.6
            font_size = imgui.get_font_size() * fac
            wid = int(wid * font_size / 2)  # get something like pix
            hei = int(hei * font_size)
            # if height is >= half the window height, turn to scroll
            val = hei
            if hei >= self.center_y:
                val = self.center_y
            imgui.begin_tooltip()
            imgui.begin_child('region', wid, val)
            imgui.set_scroll_y(imgui.get_scroll_y() -
                               imgui.get_io().mouse_wheel * 30)
            imgui.set_window_font_scale(fac)
            imgui.text(prev)
            imgui.end_child()
            imgui.end_tooltip()
            imgui.set_item_default_focus()

            # imgui.set_tooltip(prev)
        self.add_space(3)

        if imgui.button('Ok'):
            do_return = True
        if imgui.get_io().keys_down[imgui.KEY_ENTER]:
            do_return = True

        imgui.pop_style_var(1)
        imgui.end()
        if self.extra_font:
            imgui.pop_font()

        # disallow depending on current state
        if not self.id:
            do_return = False
        try:
            recipe = recipe_names[self.current_recipe]
        except IndexError:
            do_return = False
        if not os.path.isdir(self.recipe_dir):
            do_return = False
        # no need to validate data dir, we'll create it
        data = {
            'id': self.id,
            'recipe': recipe,
            'spanish': 'es' if self.spanish else 'en'
        }
        return do_return, data
Example #20
0
    def gui_newFrame(self):
        imgui.new_frame()
        imgui.begin("Properties", True)

        changed, self.pause = imgui.checkbox("Paused", self.pause)
        imgui.new_line()

        changed, self.map_type = imgui.combo(
            "Map Type", self.map_type, ["CubeT", "Cube", "Sphere", "SphereT"])

        changed, self.map_size = imgui.drag_int(
            label="Map Size",
            value=self.map_size,
            change_speed=0.1,
            min_value=10,
            max_value=100,
        )

        changed, new_boid_count = imgui.drag_int(label="Boid Count",
                                                 value=self.boid_count,
                                                 change_speed=100,
                                                 min_value=1,
                                                 max_value=self.max_boids)
        if changed:
            self.resize_boids_buffer(new_boid_count)

        imgui.new_line()

        changed, self.speed = imgui.drag_float(label="Speed",
                                               value=self.speed,
                                               change_speed=0.0005,
                                               min_value=0.001,
                                               max_value=0.5,
                                               format="%.3f")

        changed, self.view_distance = imgui.drag_float(
            label="View Distance",
            value=self.view_distance,
            change_speed=0.001,
            min_value=0.0,
            max_value=10.0,
            format="%.2f")

        changed, self.view_angle = imgui.drag_float(label="View Angle",
                                                    value=self.view_angle,
                                                    change_speed=0.001,
                                                    min_value=0.0,
                                                    max_value=pi,
                                                    format="%.2f")

        changed, self.separation_force = imgui.drag_float(
            label="Separation Force",
            value=self.separation_force,
            change_speed=0.002,
            min_value=0.0,
            max_value=10.0,
            format="%.2f")

        changed, self.alignment_force = imgui.drag_float(
            label="Aligment Force",
            value=self.alignment_force,
            change_speed=0.002,
            min_value=0.0,
            max_value=10.0,
            format="%.2f")

        changed, self.cohesion_force = imgui.drag_float(
            label="Cohesion Force",
            value=self.cohesion_force,
            change_speed=0.002,
            min_value=0.0,
            max_value=10.0,
            format="%.2f")

        imgui.new_line()
        imgui.begin_group()
        imgui.text("Custom profiles:")
        if (imgui.button("Profile 1")):
            self.set_custom_profile_1()
        if (imgui.button("Profile 2")):
            self.set_custom_profile_2()
        imgui.end_group()

        imgui.end()
Example #21
0
    def onDrawGuiCallback(self, args):
        if self.visible:
            if imgui.begin("Grinder - Profile Editor##grinder_profileeditor",
                           (400, 400)):
                textChanged, self.bot.currentProfile["name"] = imgui.inputText(
                    "##profilesavename", self.bot.currentProfile["name"])
                imgui.sameLine()
                if imgui.button("Save##profileeditor_save_profile"):
                    self.saveProfile()
                selectedChanged, self.profilesSelectedIndex = imgui.combo(
                    "##qfsdsfs", self.profilesSelectedIndex,
                    self.availableProfiles)
                imgui.sameLine()
                if imgui.button("Load##profileeditor_load_profile"):
                    profileName = self.availableProfiles[
                        self.profilesSelectedIndex]
                    self.loadProfile(profileName)
                if imgui.button("Clear profile##profileeditor_clear_profile",
                                (imgui.getContentRegionAvail()[0], 25)):
                    self.bot.currentProfile = profile.defaultProfile()
                imgui.separator()
                if imgui.collapsingHeader("Hotspots##profileeditor_hotspots",
                                          0x20):
                    if imgui.button("Add hotspot"):
                        player = BigWorld.player()
                        if player:
                            position = player.position
                            self.bot.currentProfile["hotspots"].append(
                                (position.x, position.y, position.z,
                                 player.mapID))
                    imgui.sameLine()
                    if imgui.checkbox(
                            "Randomize hotspots",
                            self.bot.currentProfile["randomizeHotspots"]):
                        self.bot.currentProfile[
                            "randomizeHotspots"] = not self.bot.currentProfile[
                                "randomizeHotspots"]

                    if len(self.bot.currentProfile["hotspots"]) > 0:
                        imgui.columns(3)
                        imgui.text("MapID")
                        imgui.nextColumn()
                        imgui.text("Position")
                        imgui.nextColumn()
                        imgui.text("Action")
                        imgui.nextColumn()
                        hotspotToRemove = None
                        for index, hotspot in enumerate(
                                self.bot.currentProfile["hotspots"]):
                            imgui.text(str(hotspot[3]))
                            imgui.nextColumn()
                            imgui.text(
                                str(math.trunc(hotspot[0])) + ", " +
                                str(math.trunc(hotspot[1])) + ", " +
                                str(math.trunc(hotspot[2])))
                            imgui.nextColumn()
                            if imgui.button("Remove##rem_hotspot" +
                                            str(index)):
                                hotspotToRemove = hotspot
                            imgui.nextColumn()
                        if hotspotToRemove:
                            self.bot.currentProfile["hotspots"].remove(
                                hotspotToRemove)
                        imgui.columns(1)
            imgui.end()
Example #22
0
 def _show(self, value, read_only):
     imgui.push_item_width(self.width)
     changed, v = imgui.combo("", value.value, self.choices)
     if changed and not read_only:
         value.value = v