Пример #1
0
    def __init__(self):

        # Init mounts
        self._mount_mgr = MountManager(None)
        self._mount_mgr.mount()

        self._plugin_mgr = PluginManager(None)
        self._plugin_mgr.load()

        QtGui.QMainWindow.__init__(self)
        self.setupUi()
        self._tree_widgets = []
        self._cmd_queue = set()

        self._update_settings_list()

        self._selected_setting_handle = None
        self._selected_setting = None
        self._selected_plugin = None
        self._current_time = 0.5
        self._on_time_changed(self.time_slider.value())
        self.set_settings_visible(False)

        self._bg_thread = Thread(target=self.updateThread)
        self._bg_thread.start()
Пример #2
0
    def __init__(self):

        # Init mounts
        self._mount_mgr = MountManager(None)
        self._mount_mgr.mount()

        self._plugin_mgr = PluginManager(None)
        self._plugin_mgr.requires_daytime_settings = False

        QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)

        self._current_plugin = None
        self._current_plugin_instance = None
        self.lbl_restart_pipeline.hide()
        self._set_settings_visible(False)
        self._update_queue = list()

        qt_connect(self.lst_plugins, "itemSelectionChanged()",
                   self.on_plugin_selected)
        qt_connect(self.lst_plugins, "itemChanged(QListWidgetItem*)",
                   self.on_plugin_state_changed)
        qt_connect(self.btn_reset_plugin_settings, "clicked()",
                   self.on_reset_plugin_settings)

        self._load_plugin_list()

        # Adjust column widths
        self.table_plugin_settings.setColumnWidth(0, 140)
        self.table_plugin_settings.setColumnWidth(1, 105)
        self.table_plugin_settings.setColumnWidth(2, 160)

        update_thread = Thread(target=self.update_thread, args=())
        update_thread.start()
Пример #3
0
    def _create_managers(self):
        """ Internal method to create all managers and instances"""
        self.task_scheduler = TaskScheduler(self)
        self.tag_mgr = TagStateManager(Globals.base.cam)
        self.plugin_mgr = PluginManager(self)
        self.stage_mgr = StageManager(self)
        self.light_mgr = LightManager(self)
        self.daytime_mgr = DayTimeManager(self)
        self.ies_loader = IESProfileLoader(self)

        # Load commonly used resources
        self._com_resources = CommonResources(self)
        self._init_common_stages()
Пример #4
0
 def _create_managers(self):
     """ Internal method to create all managers and instances. This also
     initializes the commonly used render stages, which are always required,
     independently of which plugins are enabled. """
     self.task_scheduler = TaskScheduler(self)
     self.tag_mgr = TagStateManager(Globals.base.cam)
     self.plugin_mgr = PluginManager(self)
     self.stage_mgr = StageManager(self)
     self.light_mgr = LightManager(self)
     self.daytime_mgr = DayTimeManager(self)
     self.ies_loader = IESProfileLoader(self)
     self.common_resources = CommonResources(self)
     self._init_common_stages()
Пример #5
0
    def __init__(self):

        # Init mounts
        self._mount_mgr = MountManager(None)
        self._mount_mgr.mount()

        self._plugin_mgr = PluginManager(None)
        self._plugin_mgr.load()

        QtGui.QMainWindow.__init__(self)
        self.setupUi()
        self._tree_widgets = []
        self._cmd_queue = set()

        self._update_settings_list()

        self._selected_setting_handle = None
        self._selected_setting = None
        self._selected_plugin = None
        self._current_time = 0.5
        self._on_time_changed(self.time_slider.value())
        self.set_settings_visible(False)

        self._bg_thread = Thread(target=self.updateThread)
        self._bg_thread.start()
Пример #6
0
    def __init__(self):
        # Init mounts
        self._mount_mgr = MountManager(None)
        self._mount_mgr.mount()

        self._plugin_mgr = PluginManager(None)
        self._plugin_mgr.requires_daytime_settings = False

        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)

        self._current_plugin = None
        self._current_plugin_instance = None
        self.lbl_restart_pipeline.hide()
        self._set_settings_visible(False)
        self._update_queue = list()

        connect(self.lst_plugins, QtCore.SIGNAL("itemSelectionChanged()"),
                self.on_plugin_selected)
        connect(self.lst_plugins, QtCore.SIGNAL("itemChanged(QListWidgetItem*)"),
                self.on_plugin_state_changed)
        connect(self.btn_reset_plugin_settings, QtCore.SIGNAL("clicked()"),
                self.on_reset_plugin_settings)

        self._load_plugin_list()

        # Adjust column widths
        self.table_plugin_settings.setColumnWidth(0, 110)
        self.table_plugin_settings.setColumnWidth(1, 80)
        self.table_plugin_settings.setColumnWidth(2, 120)

        update_thread = Thread(target=self.update_thread, args=())
        update_thread.start()
Пример #7
0
    def _create_managers(self):
        """ Internal method to create all managers and instances"""
        self.task_scheduler = TaskScheduler(self)
        self.tag_mgr = TagStateManager(Globals.base.cam)
        self.plugin_mgr = PluginManager(self)
        self.stage_mgr = StageManager(self)
        self.light_mgr = LightManager(self)
        self.daytime_mgr = DayTimeManager(self)
        self.ies_loader = IESProfileLoader(self)

        # Load commonly used resources
        self._com_resources = CommonResources(self)
        self._init_common_stages()
Пример #8
0
 def _create_managers(self):
     """ Internal method to create all managers and instances. This also
     initializes the commonly used render stages, which are always required,
     independently of which plugins are enabled. """
     self.task_scheduler = TaskScheduler(self)
     self.tag_mgr = TagStateManager(Globals.base.cam)
     self.plugin_mgr = PluginManager(self)
     self.stage_mgr = StageManager(self)
     self.light_mgr = LightManager(self)
     self.daytime_mgr = DayTimeManager(self)
     self.ies_loader = IESProfileLoader(self)
     self.common_resources = CommonResources(self)
     self._init_common_stages()
Пример #9
0
class DayTimeEditor(QtGui.QMainWindow, Ui_MainWindow):

    """ This is the main editor class which handles the user interface """

    def __init__(self):

        # Init mounts
        self._mount_mgr = MountManager(None)
        self._mount_mgr.mount()

        self._plugin_mgr = PluginManager(None)
        self._plugin_mgr.load()

        QtGui.QMainWindow.__init__(self)
        self.setupUi()
        self._tree_widgets = []
        self._cmd_queue = set()

        self._update_settings_list()

        self._selected_setting_handle = None
        self._selected_setting = None
        self._selected_plugin = None
        self._current_time = 0.5
        self._on_time_changed(self.time_slider.value())
        self.set_settings_visible(False)

        self._bg_thread = Thread(target=self.updateThread)
        self._bg_thread.start()

    def set_settings_visible(self, visibility):
        if not visibility:
            self.frame_current_setting.hide()
            self.lbl_select_setting.show()
        else:
            self.frame_current_setting.show()
            self.lbl_select_setting.hide()

    def closeEvent(self, event):  # noqa
        event.accept()
        import os
        os._exit(1)

    def updateThread(self):  # noqa
        """ Seperate update thread """

        while True:
            if self._cmd_queue:
                cmd = self._cmd_queue.pop()
                if cmd == "settime":
                    NetworkCommunication.send_async(
                        NetworkCommunication.DAYTIME_PORT, "settime " + str(self._current_time))
                    continue
                elif cmd == "write_settings":
                    self._plugin_mgr.save_daytime_overrides("/$$rpconfig/daytime.yaml")
                    NetworkCommunication.send_async(
                        NetworkCommunication.DAYTIME_PORT, "loadconf")
                else:
                    print("Unkown cmd:", cmd)

            time.sleep(0.1)

    def setupUi(self):  # noqa
        """ Setups the UI Components """
        Ui_MainWindow.setupUi(self, self)
        self.settings_tree.setColumnWidth(0, 160)
        self.settings_tree.expandAll()

        self.edit_widget = CurveWidget(self)
        self.edit_widget.set_change_handler(self._on_curve_edited)
        self.prefab_edit_widget.addWidget(self.edit_widget)

        connect(self.time_slider, QtCore.SIGNAL("valueChanged(int)"), self._on_time_changed)
        connect(self.settings_tree,
                QtCore.SIGNAL("itemSelectionChanged()"), self._on_setting_selected)
        connect(self.btn_insert_point, QtCore.SIGNAL("clicked()"), self._insert_point)
        connect(self.btn_reset, QtCore.SIGNAL("clicked()"), self._reset_settings)

    def _reset_settings(self):
        """ Resets the current plugins settings """
        # QtGui.QMessageBox.warning(self, "Houston, we have a problem!",
        #     "This functionality is not yet implemented! Blame tobspr if you need it.\n\n"
        #     "On a more serious note, you can still hand-edit config/daytime.yaml.",
        #     QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)

        # Ask the user if he's really sure about it
        msg = "Are you sure you want to reset the control points of '" +\
              self._selected_setting_handle.label + "'?\n"
        msg += "!! This cannot be undone !! They will be lost forever (a long time!)."
        reply = QtGui.QMessageBox.question(
            self, "Warning", msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
        if reply == QtGui.QMessageBox.Yes:

            QtGui.QMessageBox.information(self, "Success", "Control points have been reset!")
            default = self._selected_setting_handle.default
            self._selected_setting_handle.curves[0].set_single_value(default)
            self._update_settings_list()
            self._cmd_queue.add("write_settings")

    def _insert_point(self):
        """ Asks the user to insert a new point """
        dialog = PointDialog(self)
        if dialog.exec_():
            time, val = dialog.get_value()
            minutes = (time.hour() * 60 + time.minute()) / (24 * 60)

            if (val < self._selected_setting_handle.minvalue or
               val > self._selected_setting_handle.maxvalue):
                QtGui.QMessageBox.information(
                    self, "Invalid Value", "Value is out of setting range!", QtGui.QMessageBox.Ok)
                return

            val_linear = self._selected_setting_handle.get_linear_value(val)
            self._selected_setting_handle.curves[0].append_cv(minutes, val_linear)
            self._cmd_queue.add("write_settings")

    def _update_tree_widgets(self):
        """ Updates the tree widgets """
        for setting_handle, widget in self._tree_widgets:
            value = setting_handle.get_scaled_value_at(self._current_time)
            formatted = setting_handle.format(value)
            widget.setText(1, formatted)

            if setting_handle.type == "color":
                widget.setBackground(1, QtGui.QBrush(QtGui.QColor(*value)))

    def _on_curve_edited(self):
        """ Called when the curve got edited in the curve widget """
        self._cmd_queue.add("write_settings")
        self._update_tree_widgets()

    def _on_setting_selected(self):
        """ Called when a setting got selected in the settings tree """
        selected = self.settings_tree.selectedItems()
        if len(selected) != 1:
            self._selected_setting = None
            self._selected_plugin = None
            self._selected_setting_handle = None
            self.edit_widget.set_curves([])
            self.set_settings_visible(False)
        else:
            selected = selected[0]

            self._selected_plugin = selected._plugin_id
            self._selected_setting = selected._setting_id
            self._selected_setting_handle = selected._setting_handle

            self.lbl_current_setting.setText(self._selected_setting_handle.label)
            self.lbl_setting_desc.setText(self._selected_setting_handle.description)

            self.edit_widget.set_curves(self._selected_setting_handle.curves)

            if self._selected_setting_handle.type == "color":
                self.edit_widget.set_unit_processor(lambda x: str(int(x * 255)))
                self.btn_insert_point.hide()
            else:
                self.edit_widget.set_unit_processor(
                    lambda x: self._selected_setting_handle.format(
                        self._selected_setting_handle.get_scaled_value(x)))
                self.btn_insert_point.show()

            self.set_settings_visible(True)
            self._update_tree_widgets()

    def _on_time_changed(self, val):
        """ Handler when the time slider got moved """
        hour = val // (60 * 60 * 60)
        minute = (val // (60 * 60)) % 60
        ftime = float(val) / (24 * 60 * 60 * 60)

        self.time_label.setText(str(hour).zfill(2) + ":" + str(minute).zfill(2))
        self.time_float_label.setText("{:1.4f}".format(ftime))
        self.edit_widget.set_current_time(ftime)
        self._current_time = ftime
        self._update_tree_widgets()
        self._cmd_queue.add("settime")

    def _update_settings_list(self):
        """ Updates the list of visible settings """

        self.settings_tree.clear()
        self._tree_widgets = []

        for plugin_id, plugin in iteritems(self._plugin_mgr.instances):

            daytime_settings = self._plugin_mgr.day_settings[plugin_id]

            if not daytime_settings:
                # Skip plugins with empty settings
                continue

            plugin_head = QtGui.QTreeWidgetItem(self.settings_tree)
            plugin_head.setText(0, plugin.name)
            plugin_head.setFlags(QtCore.Qt.ItemIsEnabled)
            font = QtGui.QFont()
            font.setBold(True)
            if not self._plugin_mgr.is_plugin_enabled(plugin_id):
                plugin_head.setText(0, plugin.name)
            plugin_head.setFont(0, font)

            # Display all settings
            for setting, setting_handle in iteritems(daytime_settings):
                setting_item = QtGui.QTreeWidgetItem(plugin_head)
                setting_item.setText(0, setting_handle.label)
                setting_item.setTextColor(0, QtGui.QColor(150, 150, 150))
                setting_item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
                setting_item._setting_id = setting
                setting_item._setting_handle = setting_handle
                setting_item._plugin_id = plugin_id
                setting_item.setToolTip(0, setting_handle.description)
                setting_item.setToolTip(1, setting_handle.description)
                self._tree_widgets.append((setting_handle, setting_item))

        self.settings_tree.expandAll()
Пример #10
0
class RenderPipeline(RPObject):

    """ This is the main pipeline logic, it combines all components of the
    pipeline to form a working system. It does not do much work itself, but
    instead setups all the managers and systems to be able to do their work.

    It also derives from RPExtensions to provide some useful functions like
    creating a default skybox or loading effect files. """

    def __init__(self, outdated_parameter=None):
        """ Creates a new pipeline with a given showbase instance. This should
        be done before intializing the ShowBase, the pipeline will take care of
        that. """
        RPObject.__init__(self)
        if outdated_parameter is not None:
            self.fatal("The render pipeline no longer takes the ShowBase argument "
                       "as constructor parameter. Please have a look at the "
                       "00-Loading the pipeline sample to see how to initialize "
                       "the pipeline properly.")
        self.debug("Using Python {}.{} with architecture {}".format(
            sys.version_info.major, sys.version_info.minor, PandaSystem.get_platform()))
        self.debug("Using Panda3D {} built on {}".format(
            PandaSystem.get_version_string(), PandaSystem.get_build_date()))
        if PandaSystem.get_git_commit():
            self.debug("Using git commit {}".format(PandaSystem.get_git_commit()))
        else:
            self.debug("Using custom Panda3D build")
        self.mount_mgr = MountManager(self)
        self.settings = {}
        self._pre_showbase_initialized = False
        self._first_frame = None
        self.set_default_loading_screen()

        # Check for the right Panda3D version
        if not self._check_version():
            self.fatal("Your Panda3D version is outdated! Please update to the newest \n"
                       "git version! Checkout https://github.com/panda3d/panda3d to "
                       "compile panda from source, or get a recent buildbot build.")

    def load_settings(self, path):
        """ Loads the pipeline configuration from a given filename. Usually
        this is the 'config/pipeline.ini' file. If you call this more than once,
        only the settings of the last file will be used. """
        self.settings = load_yaml_file_flat(path)

    def reload_shaders(self):
        """ Reloads all shaders """
        if self.settings["pipeline.display_debugger"]:
            self.debug("Reloading shaders ..")
            self._debugger.get_error_msg_handler().clear_messages()
            self._debugger.set_reload_hint_visible(True)
            self._showbase.graphicsEngine.render_frame()
            self._showbase.graphicsEngine.render_frame()

        self.tag_mgr.cleanup_states()
        self.stage_mgr.reload_shaders()
        self.light_mgr.reload_shaders()

        # Set the default effect on render and trigger the reload hook
        self._set_default_effect()
        self.plugin_mgr.trigger_hook("shader_reload")

        if self.settings["pipeline.display_debugger"]:
            self._debugger.set_reload_hint_visible(False)

    def pre_showbase_init(self):
        """ Setups all required pipeline settings and configuration which have
        to be set before the showbase is setup. This is called by create(),
        in case the showbase was not initialized, however you can (and have to)
        call it manually before you init your custom showbase instance.
        See the 00-Loading the pipeline sample for more information."""

        if not self.mount_mgr.is_mounted:
            self.debug("Mount manager was not mounted, mounting now ...")
            self.mount_mgr.mount()

        if not self.settings:
            self.debug("No settings loaded, loading from default location")
            self.load_settings("/$$rpconfig/pipeline.yaml")

        # Check if the pipeline was properly installed, before including anything else
        if not isfile("/$$rp/data/install.flag"):
            self.fatal("You didn't setup the pipeline yet! Please run setup.py.")

        # Load the default prc config
        load_prc_file("/$$rpconfig/panda3d-config.prc")

        # Set the initialization flag
        self._pre_showbase_initialized = True

    def create(self, base=None):
        """ This creates the pipeline, and setups all buffers. It also
        constructs the showbase. The settings should have been loaded before
        calling this, and also the base and write path should have been
        initialized properly (see MountManager).

        If base is None, the showbase used in the RenderPipeline constructor
        will be used and initialized. Otherwise it is assumed that base is an
        initialized ShowBase object. In this case, you should call
        pre_showbase_init() before initializing the ShowBase"""

        start_time = time.time()
        self._init_showbase(base)
        self._init_globals()

        # Create the loading screen
        self._loading_screen.create()
        self._adjust_camera_settings()
        self._create_managers()

        # Load plugins and daytime settings
        self.plugin_mgr.load()
        self.daytime_mgr.load_settings()
        self._com_resources.write_config()

        # Init the onscreen debugger
        self._init_debugger()

        # Let the plugins setup their stages
        self.plugin_mgr.trigger_hook("stage_setup")

        self._create_common_defines()
        self._setup_managers()
        self._create_default_skybox()

        self.plugin_mgr.trigger_hook("pipeline_created")

        # Hide the loading screen
        self._loading_screen.remove()

        # Start listening for updates
        self._listener = NetworkCommunication(self)
        self._set_default_effect()

        # Measure how long it took to initialize everything
        init_duration = (time.time() - start_time)
        self.debug("Finished initialization in {:3.3f} s".format(init_duration))

        self._first_frame = time.clock()

    def _create_managers(self):
        """ Internal method to create all managers and instances"""
        self.task_scheduler = TaskScheduler(self)
        self.tag_mgr = TagStateManager(Globals.base.cam)
        self.plugin_mgr = PluginManager(self)
        self.stage_mgr = StageManager(self)
        self.light_mgr = LightManager(self)
        self.daytime_mgr = DayTimeManager(self)
        self.ies_loader = IESProfileLoader(self)

        # Load commonly used resources
        self._com_resources = CommonResources(self)
        self._init_common_stages()

    def _setup_managers(self):
        """ Internal method to setup all managers """
        self.stage_mgr.setup()
        self.stage_mgr.reload_shaders()
        self.light_mgr.reload_shaders()
        self._init_bindings()
        self.light_mgr.init_shadows()

    def _init_debugger(self):
        """ Internal method to initialize the GUI-based debugger """
        if self.settings["pipeline.display_debugger"]:
            self._debugger = Debugger(self)
        else:
            # Use an empty onscreen debugger in case the debugger is not
            # enabled, which defines all member functions as empty lambdas
            class EmptyDebugger(object):
                def __getattr__(self, *args, **kwargs):
                    return lambda *args, **kwargs: None
            self._debugger = EmptyDebugger()
            del EmptyDebugger

    def _init_globals(self):
        """ Inits all global bindings """
        Globals.load(self._showbase)
        w, h = self._showbase.win.get_x_size(), self._showbase.win.get_y_size()

        scale_factor = self.settings["pipeline.resolution_scale"]
        w = int(float(w) * scale_factor)
        h = int(float(h) * scale_factor)

        # Make sure the resolution is a multiple of 4
        w = w - w % 4
        h = h - h % 4

        self.debug("Render resolution is", w, "x", h)
        Globals.resolution = LVecBase2i(w, h)

        # Connect the render target output function to the debug object
        RenderTarget.RT_OUTPUT_FUNC = lambda *args: RPObject.global_warn(
            "RenderTarget", *args[1:])

        RenderTarget.USE_R11G11B10 = self.settings["pipeline.use_r11_g11_b10"]

    def _init_showbase(self, base):
        """ Inits the the given showbase object """

        # Construct the showbase and init global variables
        if base:
            # Check if we have to init the showbase
            if not hasattr(base, "render"):
                self.pre_showbase_init()
                ShowBase.__init__(base)
            else:
                if not self._pre_showbase_initialized:
                    self.fatal("You constructed your own ShowBase object but you "
                               "did not call pre_show_base_init() on the render "
                               "pipeline object before! Checkout the 00-Loading the "
                               "pipeline sample to see how to initialize the RP.")
            self._showbase = base
        else:
            self.pre_showbase_init()
            self._showbase = ShowBase()

    def _init_bindings(self):
        """ Inits the tasks and keybindings """

        # Add a hotkey to reload the shaders, but only if the debugger is enabled
        if self.settings["pipeline.display_debugger"]:
            self._showbase.accept("r", self.reload_shaders)

        self._showbase.addTask(self._manager_update_task, "RP_UpdateManagers", sort=10)
        self._showbase.addTask(self._plugin_pre_render_update, "RP_Plugin_BeforeRender", sort=12)
        self._showbase.addTask(self._plugin_post_render_update, "RP_Plugin_AfterRender", sort=15)
        self._showbase.addTask(self._update_inputs_and_stages, "RP_UpdateInputsAndStages", sort=18)
        self._showbase.taskMgr.doMethodLater(0.5, self._clear_state_cache, "RP_ClearStateCache")

    def _clear_state_cache(self, task=None):
        """ Task which repeatedly clears the state cache to avoid storing
        unused states. """
        task.delayTime = 2.0
        TransformState.clear_cache()
        RenderState.clear_cache()
        return task.again

    def _manager_update_task(self, task):
        """ Update task which gets called before the rendering """
        self.task_scheduler.step()
        self._listener.update()
        self._debugger.update()
        self.daytime_mgr.update()
        self.light_mgr.update()
        return task.cont

    def _update_inputs_and_stages(self, task):
        """ Updates teh commonly used inputs """
        self._com_resources.update()
        self.stage_mgr.update()
        return task.cont

    def _plugin_pre_render_update(self, task):
        """ Update task which gets called before the rendering, and updates the
        plugins. This is a seperate task to split the work, and be able to do
        better performance analysis """
        self.plugin_mgr.trigger_hook("pre_render_update")
        return task.cont

    def _plugin_post_render_update(self, task):
        """ Update task which gets called after the rendering """
        self.plugin_mgr.trigger_hook("post_render_update")

        if self._first_frame is not None:
            duration = time.clock() - self._first_frame
            self.debug("Took", round(duration, 3), "s until first frame")
            self._first_frame = None

        return task.cont

    def _create_common_defines(self):
        """ Creates commonly used defines for the shader auto config """
        defines = self.stage_mgr.defines

        # 3D viewport size
        defines["WINDOW_WIDTH"] = Globals.resolution.x
        defines["WINDOW_HEIGHT"] = Globals.resolution.y

        # Actual window size - might differ for supersampling
        defines["NATIVE_WINDOW_WIDTH"] = Globals.base.win.get_x_size()
        defines["NATIVE_WINDOW_HEIGHT"] = Globals.base.win.get_y_size()

        # Pass camera near and far plane
        defines["CAMERA_NEAR"] = round(Globals.base.camLens.get_near(), 10)
        defines["CAMERA_FAR"] = round(Globals.base.camLens.get_far(), 10)

        # Work arround buggy nvidia driver, which expects arrays to be const
        if "NVIDIA 361.43" in self._showbase.win.get_gsg().get_driver_version():
            defines["CONST_ARRAY"] = "const"
        else:
            defines["CONST_ARRAY"] = ""

        # Provide driver vendor as a default
        vendor = self._showbase.win.get_gsg().get_driver_vendor().lower()
        if "nvidia" in vendor:
            defines["IS_NVIDIA"] = 1
        if "ati" in vendor:
            defines["IS_AMD"] = 1
        if "intel" in vendor:
            defines["IS_INTEL"] = 1

        defines["REFERENCE_MODE"] = self.settings["pipeline.reference_mode"]

        # Only activate this experimental feature if the patch was applied,
        # since it is a local change in my Panda3D build which is not yet
        # reviewed by rdb. Once it is in public Panda3D Dev-Builds this will
        # be the default.
        if (not isfile("/$$rp/data/panda3d_patches/prev-model-view-matrix.diff") or
                isfile("D:/__dev__")):

            # You can find the required patch in
            # data/panda3d_patches/prev-model-view-matrix.diff.
            # Delete it after you applied it, so the render pipeline knows the
            # patch is available.
            # self.warn("Experimental feature activated, no guarantee it works!")
            # defines["EXPERIMENTAL_PREV_TRANSFORM"] = 1
            pass
            
        self.light_mgr.init_defines()
        self.plugin_mgr.init_defines()

    def set_loading_screen(self, loading_screen):
        """ Sets a loading screen to be used while loading the pipeline. When
        the pipeline gets constructed (and creates the showbase), create()
        will be called on the object. During the loading progress,
        progress(msg) will be called. After the loading is finished,
        remove() will be called. If a custom loading screen is passed, those
        methods should be implemented. """
        self._loading_screen = loading_screen

    def set_default_loading_screen(self):
        """ Tells the pipeline to use the default loading screen. """
        self._loading_screen = LoadingScreen(self)

    def set_empty_loading_screen(self):
        """ Tells the pipeline to use no loading screen """
        self._loading_screen = EmptyLoadingScreen()

    @property
    def loading_screen(self):
        """ Returns the current loading screen """
        return self._loading_screen

    def add_light(self, light):
        """ Adds a new light to the rendered lights, check out the LightManager
        add_light documentation for further information. """
        self.light_mgr.add_light(light)

    def remove_light(self, light):
        """ Removes a previously attached light, check out the LightManager
        remove_light documentation for further information. """
        self.light_mgr.remove_light(light)

    def _create_default_skybox(self, size=40000):
        """ Returns the default skybox, with a scale of <size>, and all
        proper effects and shaders already applied. The skybox is already
        parented to render as well. """
        skybox = self._com_resources.load_default_skybox()
        skybox.set_scale(size)
        skybox.reparent_to(Globals.render)
        skybox.set_bin("unsorted", 10000)
        self.set_effect(skybox, "effects/skybox.yaml", {
            "render_shadows":   False,
            "render_envmap":    False,
            "render_voxel":     False,
            "alpha_testing":    False,
            "normal_mapping":   False,
            "parallax_mapping": False
        }, 1000)
        return skybox

    def load_ies_profile(self, filename):
        """ Loads an IES profile from a given filename and returns a handle which
        can be used to set an ies profile on a light """
        return self.ies_loader.load(filename)

    def set_effect(self, nodepath, effect_src, options=None, sort=30):
        """ Sets an effect to the given object, using the specified options.
        Check out the effect documentation for more information about possible
        options and configurations. The object should be a nodepath, and the
        effect will be applied to that nodepath and all nodepaths below whose
        current effect sort is less than the new effect sort (passed by the
        sort parameter). """

        effect = Effect.load(effect_src, options)
        if effect is None:
            return self.error("Could not apply effect")

        # Apply default stage shader
        if not effect.get_option("render_gbuffer"):
            nodepath.hide(self.tag_mgr.get_mask("gbuffer"))
        else:
            nodepath.set_shader(effect.get_shader_obj("gbuffer"), sort)
            nodepath.show(self.tag_mgr.get_mask("gbuffer"))

        # Apply shadow stage shader
        if not effect.get_option("render_shadows"):
            nodepath.hide(self.tag_mgr.get_mask("shadow"))
        else:
            shader = effect.get_shader_obj("shadows")
            self.tag_mgr.apply_state(
                "shadow", nodepath, shader, str(effect.effect_id), 25 + sort)
            nodepath.show(self.tag_mgr.get_mask("shadow"))

        # Apply voxelization stage shader
        if not effect.get_option("render_voxel"):
            nodepath.hide(self.tag_mgr.get_mask("voxelize"))
        else:
            shader = effect.get_shader_obj("voxelize")
            self.tag_mgr.apply_state(
                "voxelize", nodepath, shader, str(effect.effect_id), 35 + sort)
            nodepath.show(self.tag_mgr.get_mask("voxelize"))

        # Apply envmap stage shader
        if not effect.get_option("render_envmap"):
            nodepath.hide(self.tag_mgr.get_mask("envmap"))
        else:
            shader = effect.get_shader_obj("envmap")
            self.tag_mgr.apply_state(
                "envmap", nodepath, shader, str(effect.effect_id), 45 + sort)
            nodepath.show(self.tag_mgr.get_mask("envmap"))

        # Apply forward shading shader
        if not effect.get_option("render_forward"):
            nodepath.hide(self.tag_mgr.get_mask("forward"))
        else:
            shader = effect.get_shader_obj("forward")
            self.tag_mgr.apply_state(
                "forward", nodepath, shader, str(effect.effect_id), 55 + sort)
            nodepath.show_through(self.tag_mgr.get_mask("forward"))

        # Check for invalid options
        if effect.get_option("render_gbuffer") and effect.get_option("render_forward"):
            self.error("You cannot render an object forward and deferred at the same time! Either "
                       "use render_gbuffer or use render_forward, but not both.")

    def add_environment_probe(self):
        """ Constructs a new environment probe and returns the handle, so that
        the probe can be modified """

        # TODO: This method is super hacky
        if not self.plugin_mgr.is_plugin_enabled("env_probes"):
            self.warn("EnvProbe plugin is not loaded, can not add environment probe")
            class DummyEnvironmentProbe(object):
                def __getattr__(self, *args, **kwargs):
                    return lambda *args, **kwargs: None
            return DummyEnvironmentProbe()

        from rpplugins.env_probes.environment_probe import EnvironmentProbe
        probe = EnvironmentProbe()
        self.plugin_mgr.instances["env_probes"].probe_mgr.add_probe(probe)
        return probe

    def prepare_scene(self, scene):
        """ Prepares a given scene, by converting panda lights to render pipeline
        lights """

        # TODO: IES profiles
        ies_profile = self.load_ies_profile("soft_display.ies") # pylint: disable=W0612
        lights = []

        for light in scene.find_all_matches("**/+PointLight"):
            light_node = light.node()
            rp_light = PointLight()
            rp_light.pos = light.get_pos(Globals.base.render)
            rp_light.radius = light_node.max_distance
            rp_light.energy = 100.0 * light_node.color.w
            rp_light.color = light_node.color.xyz
            rp_light.casts_shadows = light_node.shadow_caster
            rp_light.shadow_map_resolution = light_node.shadow_buffer_size.x
            rp_light.inner_radius = 0.8
            self.add_light(rp_light)
            light.remove_node()
            lights.append(rp_light)

        for light in scene.find_all_matches("**/+Spotlight"):
            light_node = light.node()
            rp_light = SpotLight()
            rp_light.pos = light.get_pos(Globals.base.render)
            rp_light.radius = light_node.max_distance
            rp_light.energy = 100.0 * light_node.color.w
            rp_light.color = light_node.color.xyz
            rp_light.casts_shadows = light_node.shadow_caster
            rp_light.shadow_map_resolution = light_node.shadow_buffer_size.x
            rp_light.fov = light_node.exponent / math.pi * 180.0
            lpoint = light.get_mat(Globals.base.render).xform_vec((0, 0, -1))
            rp_light.direction = lpoint
            self.add_light(rp_light)
            light.remove_node()
            lights.append(rp_light)

        envprobes = []

        # Add environment probes
        for np in scene.find_all_matches("**/ENVPROBE*"):
            probe = self.add_environment_probe()
            probe.set_mat(np.get_mat())
            probe.border_smoothness = 0.001
            probe.parallax_correction = True
            np.remove_node()
            envprobes.append(probe)

        # Find transparent objects and set the right effect
        for geom_np in scene.find_all_matches("**/+GeomNode"):
            geom_node = geom_np.node()
            geom_count = geom_node.get_num_geoms()
            for i in range(geom_count):
                state = geom_node.get_geom_state(i)
                if not state.has_attrib(MaterialAttrib):
                    self.warn("Geom", geom_node, "has no material!")
                    continue
                material = state.get_attrib(MaterialAttrib).get_material()
                shading_model = material.emission.x

                # SHADING_MODEL_TRANSPARENT
                if shading_model == 3:
                    if geom_count > 1:
                        self.error("Transparent materials must have their own geom!")
                        continue

                    self.set_effect(
                        geom_np, "effects/default.yaml",
                        {"render_forward": True, "render_gbuffer": False}, 100)

                 # SHADING_MODEL_FOLIAGE
                elif shading_model == 5:
                    # XXX: Maybe only enable alpha testing for foliage unless
                    # specified otherwise
                    pass


        return {"lights": lights, "envprobes": envprobes}

    def _check_version(self):
        """ Internal method to check if the required Panda3D version is met. Returns
        True if the version is new enough, and False if the version is outdated. """

        from panda3d.core import PointLight as Panda3DPointLight
        if not hasattr(Panda3DPointLight(""), "shadow_caster"):
            return False

        return True

    def _init_common_stages(self):
        """ Inits the commonly used stages, which don't belong to any plugin,
        but yet are necessary and widely used. """
        add_stage = self.stage_mgr.add_stage

        self._ambient_stage = AmbientStage(self)
        add_stage(self._ambient_stage)

        self._gbuffer_stage = GBufferStage(self)
        add_stage(self._gbuffer_stage)

        self._final_stage = FinalStage(self)
        add_stage(self._final_stage)

        self._downscale_stage = DownscaleZStage(self)
        add_stage(self._downscale_stage)

        self._combine_velocity_stage = CombineVelocityStage(self)
        add_stage(self._combine_velocity_stage)

        # Add an upscale/downscale stage in case we render at a different resolution
        if abs(1 - self.settings["pipeline.resolution_scale"]) > 0.05:
            self._upscale_stage = UpscaleStage(self)
            add_stage(self._upscale_stage)

    def _set_default_effect(self):
        """ Sets the default effect used for all objects if not overridden """
        self.set_effect(Globals.render, "effects/default.yaml", {}, -10)

    def _adjust_camera_settings(self):
        """ Sets the default camera settings """
        self._showbase.camLens.set_near_far(0.1, 70000)
        self._showbase.camLens.set_fov(60)
Пример #11
0
class PluginConfigurator(QtGui.QMainWindow, Ui_MainWindow):

    """ Interface to change the plugin settings """

    def __init__(self):
        # Init mounts
        self._mount_mgr = MountManager(None)
        self._mount_mgr.mount()

        self._plugin_mgr = PluginManager(None)
        self._plugin_mgr.requires_daytime_settings = False

        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)

        self._current_plugin = None
        self._current_plugin_instance = None
        self.lbl_restart_pipeline.hide()
        self._set_settings_visible(False)
        self._update_queue = list()

        connect(self.lst_plugins, QtCore.SIGNAL("itemSelectionChanged()"),
                self.on_plugin_selected)
        connect(self.lst_plugins, QtCore.SIGNAL("itemChanged(QListWidgetItem*)"),
                self.on_plugin_state_changed)
        connect(self.btn_reset_plugin_settings, QtCore.SIGNAL("clicked()"),
                self.on_reset_plugin_settings)

        self._load_plugin_list()

        # Adjust column widths
        self.table_plugin_settings.setColumnWidth(0, 110)
        self.table_plugin_settings.setColumnWidth(1, 80)
        self.table_plugin_settings.setColumnWidth(2, 120)

        update_thread = Thread(target=self.update_thread, args=())
        update_thread.start()

    def closeEvent(self, event):  # noqa
        event.accept()
        import os
        os._exit(1)

    def on_reset_plugin_settings(self):
        """ Gets called when the user wants to reset settings of a plugin """

        # Ask the user if he's really sure about it
        msg = "Are you sure you want to reset the settings of '"
        msg += self._current_plugin_instance.name + "'?\n"
        msg += "This does not reset the Time of Day settings of this plugin.\n\n"
        msg += "!! This cannot be undone !! They will be lost forever (a long time!)."
        reply = QtGui.QMessageBox.question(
            self, "Warning", msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
        if reply == QtGui.QMessageBox.Yes:

            QtGui.QMessageBox.information(
                self, "Success",
                "Settings have been reset! You may have to restart the pipeline.")
            self._plugin_mgr.reset_plugin_settings(self._current_plugin)

            # Save config
            self._plugin_mgr.save_overrides("/$$rpconfig/plugins.yaml")

            # Always show the restart hint, even if its not always required
            self._show_restart_hint()

            # Re-render everything
            self._load_plugin_list()

    def on_plugin_state_changed(self, item):
        """ Handler when a plugin got activated/deactivated """
        plugin_id = item._plugin_id
        state = item.checkState() == QtCore.Qt.Checked
        self._plugin_mgr.set_plugin_enabled(plugin_id, state)
        self._rewrite_plugin_config()
        self._show_restart_hint()

    def on_plugin_selected(self):
        """ Gets called when a plugin got selected in the plugin list """
        selected_item = self.lst_plugins.selectedItems()
        if not selected_item:
            self._current_plugin = None
            self._current_plugin_instance = None
            self._set_settings_visible(False)
            return
        assert len(selected_item) == 1
        selected_item = selected_item[0]
        self._current_plugin = selected_item._plugin_id
        self._current_plugin_instance = self._plugin_mgr.instances[self._current_plugin]
        assert(self._current_plugin_instance is not None)
        self._render_current_plugin()
        self._set_settings_visible(True)

    def update_thread(self):
        """ Internal update thread """
        while True:
            if len(self._update_queue) > 0:
                item = self._update_queue.pop(-1)
                NetworkCommunication.send_async(NetworkCommunication.CONFIG_PORT, item)

                if item.startswith("setval "):
                    setting_id = item.split()[1]
                    for entry in list(self._update_queue):
                        if entry.split()[1] == setting_id:
                            self._update_queue.remove(entry)
            time.sleep(0.2)

    def _rewrite_plugin_config(self):
        """ Rewrites the plugin configuration """
        self._plugin_mgr.save_overrides("/$$rpconfig/plugins.yaml")

    def _render_current_plugin(self):
        """ Displays the currently selected plugin """
        self.lbl_plugin_name.setText(self._current_plugin_instance.name)

        version_str = "Version " + self._current_plugin_instance.version
        version_str += " by " + self._current_plugin_instance.author

        self.lbl_plugin_version.setText(version_str)
        self.lbl_plugin_desc.setText(self._current_plugin_instance.description)

        if "(!)" in version_str:
            self.lbl_plugin_version.setStyleSheet(
                "background: rgb(200, 50, 50); padding: 5px; color: #eee;"
                "padding-left: 3px; border-radius: 3px;")
        else:
            self.lbl_plugin_version.setStyleSheet("color: #4f8027;")

        self._render_current_settings()

    def _show_restart_hint(self):
        """ Shows a hint to restart the pipeline """
        self.lbl_restart_pipeline.show()

    def _render_current_settings(self):
        """ Renders the current plugin settings """
        settings = self._plugin_mgr.settings[self._current_plugin]

        # remove all rows
        while self.table_plugin_settings.rowCount() > 0:
            self.table_plugin_settings.removeRow(0)

        label_font = QtGui.QFont()
        label_font.setPointSize(10)
        label_font.setFamily("Segoe UI")

        desc_font = QtGui.QFont()
        desc_font.setPointSize(8)
        desc_font.setFamily("Segoe UI")

        for index, (name, handle) in enumerate(iteritems(settings)):
            if not handle.should_be_visible(settings):
                continue

            row_index = self.table_plugin_settings.rowCount()

            # Increase row count
            self.table_plugin_settings.insertRow(self.table_plugin_settings.rowCount())

            label = QtGui.QLabel()
            label.setText(handle.label)
            label.setWordWrap(True)
            label.setFont(label_font)

            if handle.shader_runtime or handle.runtime:
                # label.setBackground(QtGui.QColor(200, 255, 200, 255))
                label.setStyleSheet("background: rgba(162, 204, 128, 255);")
            else:
                label.setStyleSheet("background: rgba(230, 230, 230, 255);")

            label.setMargin(10)

            self.table_plugin_settings.setCellWidget(row_index, 0, label)

            item_default = QtGui.QTableWidgetItem()
            item_default.setText(str(handle.default))
            item_default.setTextAlignment(QtCore.Qt.AlignCenter)
            self.table_plugin_settings.setItem(row_index, 1, item_default)

            setting_widget = self._get_widget_for_setting(name, handle)
            self.table_plugin_settings.setCellWidget(row_index, 2, setting_widget)

            label_desc = QtGui.QLabel()
            label_desc.setText(handle.description)
            label_desc.setWordWrap(True)
            label_desc.setFont(desc_font)
            label_desc.setStyleSheet("color: #555;padding: 5px;")

            self.table_plugin_settings.setCellWidget(row_index, 3, label_desc)

    def _do_update_setting(self, setting_id, value):
        """ Updates a setting of the current plugin """

        # Check whether the setting is a runtime setting
        setting_handle = self._plugin_mgr.get_setting_handle(
            self._current_plugin, setting_id)

        # Skip the setting in case the value is equal
        if setting_handle.value == value:
            return

        # Otherwise set the new value
        setting_handle.set_value(value)
        self._rewrite_plugin_config()

        if not setting_handle.runtime and not setting_handle.shader_runtime:
            self._show_restart_hint()
        else:
            # In case the setting is dynamic, notice the pipeline about it:
            # print("Sending reload packet ...")
            self._update_queue.append("setval {}.{} {}".format(
                self._current_plugin, setting_id, value))

        # Update GUI, but only in case of enum and bool values, since they can trigger
        # display conditions:
        if setting_handle.type == "enum" or setting_handle.type == "bool":
            self._render_current_settings()

    def _on_setting_bool_changed(self, setting_id, value):
        self._do_update_setting(setting_id, value == QtCore.Qt.Checked)

    def _on_setting_scalar_changed(self, setting_id, value):
        self._do_update_setting(setting_id, value)

    def _on_setting_enum_changed(self, setting_id, value):
        self._do_update_setting(setting_id, value)

    def _on_setting_slider_changed(self, setting_id, setting_type, bound_objs, value):
        if setting_type == "float":
            value /= 100000.0
        self._do_update_setting(setting_id, value)

        for obj in bound_objs:
            obj.setValue(value)

    def _on_setting_spinbox_changed(self, setting_id, setting_type, bound_objs, value):
        self._do_update_setting(setting_id, value)
        # Assume objects are sliders, so we need to rescale the value
        for obj in bound_objs:
            obj.setValue(value * 100000.0 if setting_type == "float" else value)

    def _choose_path(self, setting_id, setting_handle, bound_objs):
        """ Shows a file chooser to show an path from """

        this_dir = os.path.dirname(os.path.realpath(__file__))
        plugin_dir = os.path.join(this_dir, "../../rpplugins/" + self._current_plugin, "resources")
        plugin_dir = os.path.abspath(plugin_dir)
        search_dir = os.path.join(plugin_dir, setting_handle.base_path)

        print("Plugin dir =", plugin_dir)
        print("Search dir =", search_dir)

        current_file = setting_handle.value.replace("\\", "/").split("/")[-1]
        print("Current file =", current_file)
        file_dlg = QtGui.QFileDialog(self, "Choose File ..", search_dir, setting_handle.file_type)
        file_dlg.selectFile(current_file)
        # file_dlg.setViewMode(QtGui.QFileDialog.Detail)

        if file_dlg.exec_():
            filename = file_dlg.selectedFiles()
            filename = filename[-1]
            print("QT selected files returned:", filename)

            filename = os.path.relpath(str(filename), plugin_dir)
            filename = filename.replace("\\", "/")
            print("Relative path is", filename)
            self._do_update_setting(setting_id, filename)

            display_file = filename.split("/")[-1]
            for obj in bound_objs:
                obj.setText(display_file)

    def _get_widget_for_setting(self, setting_id, setting):
        """ Returns an appropriate widget to control the given setting """

        widget = QtGui.QWidget()
        layout = QtGui.QVBoxLayout()
        layout.setAlignment(QtCore.Qt.AlignCenter)
        widget.setLayout(layout)

        if setting.type == "bool":
            box = QtGui.QCheckBox()
            box.setChecked(QtCore.Qt.Checked if setting.value else QtCore.Qt.Unchecked)
            connect(box, QtCore.SIGNAL("stateChanged(int)"),
                    partial(self._on_setting_bool_changed, setting_id))
            layout.addWidget(box)

        elif setting.type == "float" or setting.type == "int":

            if setting.type == "float":
                box = QtGui.QDoubleSpinBox()

                if setting.maxval - setting.minval <= 2.0:
                    box.setDecimals(4)
            else:
                box = QtGui.QSpinBox()
            box.setMinimum(setting.minval)
            box.setMaximum(setting.maxval)
            box.setValue(setting.value)

            box.setAlignment(QtCore.Qt.AlignCenter)

            slider = QtGui.QSlider()
            slider.setOrientation(QtCore.Qt.Horizontal)

            if setting.type == "float":
                box.setSingleStep(abs(setting.maxval - setting.minval) / 100.0)
                slider.setMinimum(setting.minval * 100000.0)
                slider.setMaximum(setting.maxval * 100000.0)
                slider.setValue(setting.value * 100000.0)
            elif setting.type == "int":
                box.setSingleStep(max(1, (setting.maxval - setting.minval) / 32))
                slider.setMinimum(setting.minval)
                slider.setMaximum(setting.maxval)
                slider.setValue(setting.value)

            layout.addWidget(box)
            layout.addWidget(slider)

            connect(slider, QtCore.SIGNAL("valueChanged(int)"),
                    partial(self._on_setting_slider_changed, setting_id, setting.type, [box]))

            value_type = "int" if setting.type == "int" else "double"

            connect(box, QtCore.SIGNAL("valueChanged(" + value_type + ")"),
                    partial(self._on_setting_spinbox_changed, setting_id, setting.type, [slider]))

        elif setting.type == "enum":
            box = QtGui.QComboBox()
            for value in setting.values:
                box.addItem(value)
            connect(box, QtCore.SIGNAL("currentIndexChanged(QString)"),
                    partial(self._on_setting_enum_changed, setting_id))
            box.setCurrentIndex(setting.values.index(setting.value))

            layout.addWidget(box)

        elif setting.type == "path":

            label = QtGui.QLabel()
            display_file = setting.value.replace("\\", "/").split("/")[-1]

            desc_font = QtGui.QFont()
            desc_font.setPointSize(7)
            desc_font.setFamily("Segoe UI")

            label.setText(display_file)
            label.setFont(desc_font)

            button = QtGui.QPushButton()
            button.setText("Choose File ...")
            connect(button, QtCore.SIGNAL("clicked()"), partial(
                self._choose_path, setting_id, setting, (label,)))

            layout.addWidget(label)
            layout.addWidget(button)

        else:
            print("ERROR: Unkown setting type:", setting.type)

        return widget

    def _set_settings_visible(self, flag):
        """ Sets whether the settings panel is visible or not """
        if flag:
            self.lbl_select_plugin.hide()
            self.frame_details.show()
        else:
            self.lbl_select_plugin.show()
            self.frame_details.hide()

    def _load_plugin_list(self):
        """ Reloads the whole plugin list """
        print("Loading plugin list")

        # Reset selection
        self._current_plugin = None
        self._current_plugin_instance = None
        self._set_settings_visible(False)

        # Plugins are all plugins in the plugins directory
        self._plugin_mgr.unload()
        self._plugin_mgr.load()

        self.lst_plugins.clear()
        plugins = sorted(iteritems(self._plugin_mgr.instances), key=lambda plg: plg[1].name)

        for plugin_id, instance in plugins:

            item = QtGui.QListWidgetItem()
            item.setText(" " + instance.name)

            if self._plugin_mgr.is_plugin_enabled(plugin_id):
                item.setCheckState(QtCore.Qt.Checked)
            else:
                item.setCheckState(QtCore.Qt.Unchecked)

            item._plugin_id = plugin_id
            self.lst_plugins.addItem(item)
Пример #12
0
class RenderPipeline(RPObject):

    """ This is the main render pipeline class, it combines all components of
    the pipeline to form a working system. It does not do much work itself, but
    instead setups all the managers and systems to be able to do their work. """

    def __init__(self):
        """ Creates a new pipeline with a given showbase instance. This should
        be done before intializing the ShowBase, the pipeline will take care of
        that. If the showbase has been initialized before, have a look at
        the alternative initialization of the render pipeline (the first sample)."""
        RPObject.__init__(self)
        self.debug("Using Python {}.{} with architecture {}".format(
            sys.version_info.major, sys.version_info.minor, PandaSystem.get_platform()))
        self.debug("Using Panda3D {} built on {}".format(
            PandaSystem.get_version_string(), PandaSystem.get_build_date()))
        if PandaSystem.get_git_commit():
            self.debug("Using git commit {}".format(PandaSystem.get_git_commit()))
        else:
            self.debug("Using custom Panda3D build")
        if not self._check_version():
            self.fatal("Your Panda3D version is outdated! Please update to the newest \n"
                       "git version! Checkout https://github.com/panda3d/panda3d to "
                       "compile panda from source, or get a recent buildbot build.")
        self.mount_mgr = MountManager(self)
        self.settings = {}
        self._pre_showbase_initialized = False
        self._first_frame = None
        self.set_loading_screen_image("/$$rp/data/gui/loading_screen_bg.txo")

    def load_settings(self, path):
        """ Loads the pipeline configuration from a given filename. Usually
        this is the 'config/pipeline.ini' file. If you call this more than once,
        only the settings of the last file will be used. """
        self.settings = load_yaml_file_flat(path)

    def reload_shaders(self):
        """ Reloads all shaders. This will reload the shaders of all plugins,
        as well as the pipelines internally used shaders. Because of the
        complexity of some shaders, this operation take might take several
        seconds. Also notice that all applied effects will be lost, and instead
        the default effect will be set on all elements again. Due to this fact,
        this method is primarly useful for fast iterations when developing new
        shaders. """
        if self.settings["pipeline.display_debugger"]:
            self.debug("Reloading shaders ..")
            self.debugger.error_msg_handler.clear_messages()
            self.debugger.set_reload_hint_visible(True)
            self._showbase.graphicsEngine.render_frame()
            self._showbase.graphicsEngine.render_frame()
        self.tag_mgr.cleanup_states()
        self.stage_mgr.reload_shaders()
        self.light_mgr.reload_shaders()
        self._set_default_effect()
        self.plugin_mgr.trigger_hook("shader_reload")
        if self.settings["pipeline.display_debugger"]:
            self.debugger.set_reload_hint_visible(False)

    def pre_showbase_init(self):
        """ Setups all required pipeline settings and configuration which have
        to be set before the showbase is setup. This is called by create(),
        in case the showbase was not initialized, however you can (and have to)
        call it manually before you init your custom showbase instance.
        See the 00-Loading the pipeline sample for more information. """
        if not self.mount_mgr.is_mounted:
            self.debug("Mount manager was not mounted, mounting now ...")
            self.mount_mgr.mount()

        if not self.settings:
            self.debug("No settings loaded, loading from default location")
            self.load_settings("/$$rpconfig/pipeline.yaml")

        if not isfile("/$$rp/data/install.flag"):
            self.fatal("You didn't setup the pipeline yet! Please run setup.py.")

        load_prc_file("/$$rpconfig/panda3d-config.prc")
        self._pre_showbase_initialized = True

    def create(self, base=None):
        """ This creates the pipeline, and setups all buffers. It also
        constructs the showbase. The settings should have been loaded before
        calling this, and also the base and write path should have been
        initialized properly (see MountManager).

        If base is None, the showbase used in the RenderPipeline constructor
        will be used and initialized. Otherwise it is assumed that base is an
        initialized ShowBase object. In this case, you should call
        pre_showbase_init() before initializing the ShowBase"""

        start_time = time.time()
        self._init_showbase(base)

        if not self._showbase.win.gsg.supports_compute_shaders:
            self.fatal(
                "Sorry, your GPU does not support compute shaders! Make sure\n"
                "you have the latest drivers. If you already have, your gpu might\n"
                "be too old, or you might be using the open source drivers on linux.")

        self._init_globals()
        self.loading_screen.create()
        self._adjust_camera_settings()
        self._create_managers()
        self.plugin_mgr.load()
        self.daytime_mgr.load_settings()
        self.common_resources.write_config()
        self._init_debugger()

        self.plugin_mgr.trigger_hook("stage_setup")

        self._create_common_defines()
        self._initialize_managers()
        self._create_default_skybox()

        self.plugin_mgr.trigger_hook("pipeline_created")

        self.loading_screen.remove()
        self._listener = NetworkCommunication(self)
        self._set_default_effect()

        # Measure how long it took to initialize everything, and also store
        # when we finished, so we can measure how long it took to render the
        # first frame (where the shaders are actually compiled)
        init_duration = (time.time() - start_time)
        self.debug("Finished initialization in {:3.3f} s".format(init_duration))
        self._first_frame = time.clock()

    def set_loading_screen_image(self, image_source):
        """ Tells the pipeline to use the default loading screen, which consists
        of a simple loading image. The image source should be a fullscreen
        16:9 image, and not too small, to avoid being blurred out. """
        self.loading_screen = LoadingScreen(self, image_source)

    def add_light(self, light):
        """ Adds a new light to the rendered lights, check out the LightManager
        add_light documentation for further information. """
        self.light_mgr.add_light(light)

    def remove_light(self, light):
        """ Removes a previously attached light, check out the LightManager
        remove_light documentation for further information. """
        self.light_mgr.remove_light(light)

    def load_ies_profile(self, filename):
        """ Loads an IES profile from a given filename and returns a handle which
        can be used to set an ies profile on a light """
        return self.ies_loader.load(filename)

    def set_effect(self, nodepath, effect_src, options=None, sort=30):
        """ Sets an effect to the given object, using the specified options.
        Check out the effect documentation for more information about possible
        options and configurations. The object should be a nodepath, and the
        effect will be applied to that nodepath and all nodepaths below whose
        current effect sort is less than the new effect sort (passed by the
        sort parameter). """
        effect = Effect.load(effect_src, options)
        if effect is None:
            return self.error("Could not apply effect")

        for i, stage in enumerate(("gbuffer", "shadow", "voxelize", "envmap", "forward")):
            if not effect.get_option("render_" + stage):
                nodepath.hide(self.tag_mgr.get_mask(stage))
            else:
                shader = effect.get_shader_obj(stage)
                if stage == "gbuffer":
                    nodepath.set_shader(shader, 25)
                else:
                    self.tag_mgr.apply_state(
                        stage, nodepath, shader, str(effect.effect_id), 25 + 10 * i + sort)
                nodepath.show_through(self.tag_mgr.get_mask(stage))

        if effect.get_option("render_gbuffer") and effect.get_option("render_forward"):
            self.error("You cannot render an object forward and deferred at the "
                       "same time! Either use render_gbuffer or use render_forward, "
                       "but not both.")

    def add_environment_probe(self):
        """ Constructs a new environment probe and returns the handle, so that
        the probe can be modified. In case the env_probes plugin is not activated,
        this returns a dummy object which can be modified but has no impact. """
        if not self.plugin_mgr.is_plugin_enabled("env_probes"):
            self.warn("env_probes plugin is not loaded - cannot add environment probe")

            class DummyEnvironmentProbe(object):  # pylint: disable=too-few-public-methods
                def __getattr__(self, *args, **kwargs):
                    return lambda *args, **kwargs: None
            return DummyEnvironmentProbe()

        # Ugh ..
        from rpplugins.env_probes.environment_probe import EnvironmentProbe
        probe = EnvironmentProbe()
        self.plugin_mgr.instances["env_probes"].probe_mgr.add_probe(probe)
        return probe

    def prepare_scene(self, scene):
        """ Prepares a given scene, by converting panda lights to render pipeline
        lights. This also converts all empties with names starting with 'ENVPROBE'
        to environment probes. Conversion of blender to render pipeline lights
        is done by scaling their intensity by 100 to match lumens.

        Additionally, this finds all materials with the 'TRANSPARENT' shading
        model, and sets the proper effects on them to ensure they are rendered
        properly.

        This method also returns a dictionary with handles to all created
        objects, that is lights, environment probes, and transparent objects.
        This can be used to store them and process them later on, or delete
        them when a newer scene is loaded."""
        lights = []
        for light in scene.find_all_matches("**/+PointLight"):
            light_node = light.node()
            rp_light = PointLight()
            rp_light.pos = light.get_pos(Globals.base.render)
            rp_light.radius = light_node.max_distance
            rp_light.energy = 20.0 * light_node.color.w
            rp_light.color = light_node.color.xyz
            rp_light.casts_shadows = light_node.shadow_caster
            rp_light.shadow_map_resolution = light_node.shadow_buffer_size.x
            rp_light.inner_radius = 0.4

            self.add_light(rp_light)
            light.remove_node()
            lights.append(rp_light)

        for light in scene.find_all_matches("**/+Spotlight"):
            light_node = light.node()
            rp_light = SpotLight()
            rp_light.pos = light.get_pos(Globals.base.render)
            rp_light.radius = light_node.max_distance
            rp_light.energy = 20.0 * light_node.color.w
            rp_light.color = light_node.color.xyz
            rp_light.casts_shadows = light_node.shadow_caster
            rp_light.shadow_map_resolution = light_node.shadow_buffer_size.x
            rp_light.fov = light_node.exponent / math.pi * 180.0
            lpoint = light.get_mat(Globals.base.render).xform_vec((0, 0, -1))
            rp_light.direction = lpoint
            self.add_light(rp_light)
            light.remove_node()
            lights.append(rp_light)

        envprobes = []
        for np in scene.find_all_matches("**/ENVPROBE*"):
            probe = self.add_environment_probe()
            probe.set_mat(np.get_mat())
            probe.border_smoothness = 0.05
            probe.parallax_correction = True
            np.remove_node()
            envprobes.append(probe)

        transparent_objects = []
        for geom_np in scene.find_all_matches("**/+GeomNode"):
            geom_node = geom_np.node()
            geom_count = geom_node.get_num_geoms()
            for i in range(geom_count):
                state = geom_node.get_geom_state(i)
                if not state.has_attrib(MaterialAttrib):
                    self.warn("Geom", geom_node, "has no material!")
                    continue
                material = state.get_attrib(MaterialAttrib).get_material()
                shading_model = material.emission.x

                # SHADING_MODEL_TRANSPARENT
                if shading_model == 3:
                    if geom_count > 1:
                        self.error("Transparent materials must be on their own geom!\n"
                                   "If you are exporting from blender, split them into\n"
                                   "seperate meshes, then re-export your scene. The\n"
                                   "problematic mesh is: " + geom_np.get_name())
                        continue
                    self.set_effect(geom_np, "effects/default.yaml",
                                    {"render_forward": True, "render_gbuffer": False}, 100)

        return {"lights": lights, "envprobes": envprobes,
                "transparent_objects": transparent_objects}

    def _create_managers(self):
        """ Internal method to create all managers and instances. This also
        initializes the commonly used render stages, which are always required,
        independently of which plugins are enabled. """
        self.task_scheduler = TaskScheduler(self)
        self.tag_mgr = TagStateManager(Globals.base.cam)
        self.plugin_mgr = PluginManager(self)
        self.stage_mgr = StageManager(self)
        self.light_mgr = LightManager(self)
        self.daytime_mgr = DayTimeManager(self)
        self.ies_loader = IESProfileLoader(self)
        self.common_resources = CommonResources(self)
        self._init_common_stages()

    def _initialize_managers(self):
        """ Internal method to initialize all managers, after they have been
        created earlier in _create_managers. The creation and initialization
        is seperated due to the fact that plugins and various other subprocesses
        have to get initialized inbetween. """
        self.stage_mgr.setup()
        self.stage_mgr.reload_shaders()
        self.light_mgr.reload_shaders()
        self._init_bindings()
        self.light_mgr.init_shadows()

    def _init_debugger(self):
        """ Internal method to initialize the GUI-based debugger. In case debugging
        is disabled, this constructs a dummy debugger, which does nothing.
        The debugger itself handles the various onscreen components. """
        if self.settings["pipeline.display_debugger"]:
            self.debugger = Debugger(self)
        else:
            # Use an empty onscreen debugger in case the debugger is not
            # enabled, which defines all member functions as empty lambdas
            class EmptyDebugger(object):  # pylint: disable=too-few-public-methods
                def __getattr__(self, *args, **kwargs):
                    return lambda *args, **kwargs: None
            self.debugger = EmptyDebugger()  # pylint: disable=redefined-variable-type
            del EmptyDebugger

    def _init_globals(self):
        """ Inits all global bindings. This includes references to the global
        ShowBase instance, as well as the render resolution, the GUI font,
        and various global logging and output methods. """
        Globals.load(self._showbase)
        native_w, native_h = self._showbase.win.get_x_size(), self._showbase.win.get_y_size()
        Globals.native_resolution = LVecBase2i(native_w, native_h)
        self._last_window_dims = LVecBase2i(Globals.native_resolution)
        self._compute_render_resolution()
        RenderTarget.RT_OUTPUT_FUNC = lambda *args: RPObject.global_warn(
            "RenderTarget", *args[1:])
        RenderTarget.USE_R11G11B10 = self.settings["pipeline.use_r11_g11_b10"]

    def _set_default_effect(self):
        """ Sets the default effect used for all objects if not overridden, this
        just calls set_effect with the default effect and options as parameters.
        This uses a very low sort, to make sure that overriding the default
        effect does not require a custom sort parameter to be passed. """
        self.set_effect(Globals.render, "effects/default.yaml", {}, -10)

    def _adjust_camera_settings(self):
        """ Sets the default camera settings, this includes the cameras
        near and far plane, as well as FoV. The reason for this is, that pandas
        default field of view is very small, and thus we increase it. """
        self._showbase.camLens.set_near_far(0.1, 70000)
        self._showbase.camLens.set_fov(40)

    def _compute_render_resolution(self):
        """ Computes the internally used render resolution. This might differ
        from the window dimensions in case a resolution scale is set. """
        scale_factor = self.settings["pipeline.resolution_scale"]
        w = int(float(Globals.native_resolution.x) * scale_factor)
        h = int(float(Globals.native_resolution.y) * scale_factor)
        # Make sure the resolution is a multiple of 4
        w, h = w - w % 4, h - h % 4
        self.debug("Render resolution is", w, "x", h)
        Globals.resolution = LVecBase2i(w, h)

    def _init_showbase(self, base):
        """ Inits the the given showbase object. This is part of an alternative
        method of initializing the showbase. In case base is None, a new
        ShowBase instance will be created and initialized. Otherwise base() is
        expected to either be an uninitialized ShowBase instance, or an
        initialized instance with pre_showbase_init() called inbefore. """
        if not base:
            self.pre_showbase_init()
            self._showbase = ShowBase()
        else:
            if not hasattr(base, "render"):
                self.pre_showbase_init()
                ShowBase.__init__(base)
            else:
                if not self._pre_showbase_initialized:
                    self.fatal("You constructed your own ShowBase object but you\n"
                               "did not call pre_show_base_init() on the render\n"
                               "pipeline object before! Checkout the 00-Loading the\n"
                               "pipeline sample to see how to initialize the RP.")
            self._showbase = base

        # Now that we have a showbase and a window, we can print out driver info
        self.debug("Driver Version =", self._showbase.win.gsg.driver_version)
        self.debug("Driver Vendor =", self._showbase.win.gsg.driver_vendor)
        self.debug("Driver Renderer =", self._showbase.win.gsg.driver_renderer)

    def _init_bindings(self):
        """ Internal method to init the tasks and keybindings. This constructs
        the tasks to be run on a per-frame basis. """
        self._showbase.addTask(self._manager_update_task, "RP_UpdateManagers", sort=10)
        self._showbase.addTask(self._plugin_pre_render_update, "RP_Plugin_BeforeRender", sort=12)
        self._showbase.addTask(self._plugin_post_render_update, "RP_Plugin_AfterRender", sort=15)
        self._showbase.addTask(self._update_inputs_and_stages, "RP_UpdateInputsAndStages", sort=18)
        self._showbase.taskMgr.doMethodLater(0.5, self._clear_state_cache, "RP_ClearStateCache")
        self._showbase.accept("window-event", self._handle_window_event)

    def _handle_window_event(self, event):
        """ Checks for window events. This mainly handles incoming resizes,
        and calls the required handlers """
        self._showbase.windowEvent(event)
        window_dims = LVecBase2i(self._showbase.win.get_x_size(), self._showbase.win.get_y_size())
        if window_dims != self._last_window_dims and window_dims != Globals.native_resolution:
            self._last_window_dims = LVecBase2i(window_dims)

            # Ensure the dimensions are a multiple of 4, and if not, correct it
            if window_dims.x % 4 != 0 or window_dims.y % 4 != 0:
                self.debug("Correcting non-multiple of 4 window size:", window_dims)
                window_dims.x = window_dims.x - window_dims.x % 4
                window_dims.y = window_dims.y - window_dims.y % 4
                props = WindowProperties.size(window_dims.x, window_dims.y)
                self._showbase.win.request_properties(props)

            self.debug("Resizing to", window_dims.x, "x", window_dims.y)
            Globals.native_resolution = window_dims
            self._compute_render_resolution()
            self.light_mgr.compute_tile_size()
            self.stage_mgr.handle_window_resize()
            self.debugger.handle_window_resize()

    def _clear_state_cache(self, task=None):
        """ Task which repeatedly clears the state cache to avoid storing
        unused states. While running once a while, this task prevents over-polluting
        the state-cache with unused states. This complements Panda3D's internal
        state garbarge collector, which does a great job, but still cannot clear
        up all states. """
        task.delayTime = 2.0
        TransformState.clear_cache()
        RenderState.clear_cache()
        return task.again

    def _manager_update_task(self, task):
        """ Update task which gets called before the rendering, and updates
        all managers."""
        self.task_scheduler.step()
        self._listener.update()
        self.debugger.update()
        self.daytime_mgr.update()
        self.light_mgr.update()
        return task.cont

    def _update_inputs_and_stages(self, task):
        """ Updates the commonly used inputs each frame. This is a seperate
        task to be able view detailed performance information in pstats, since
        a lot of matrix calculations are involved here. """
        self.common_resources.update()
        self.stage_mgr.update()
        return task.cont

    def _plugin_pre_render_update(self, task):
        """ Update task which gets called before the rendering, and updates the
        plugins. This is a seperate task to split the work, and be able to do
        better performance analysis in pstats later on. """
        self.plugin_mgr.trigger_hook("pre_render_update")
        return task.cont

    def _plugin_post_render_update(self, task):
        """ Update task which gets called after the rendering, and should cleanup
        all unused states and objects. This also triggers the plugin post-render
        update hook. """
        self.plugin_mgr.trigger_hook("post_render_update")
        if self._first_frame is not None:
            duration = time.clock() - self._first_frame
            self.debug("Took", round(duration, 3), "s until first frame")
            self._first_frame = None
        return task.cont

    def _create_common_defines(self):
        """ Creates commonly used defines for the shader configuration. """
        defines = self.stage_mgr.defines
        defines["CAMERA_NEAR"] = round(Globals.base.camLens.get_near(), 10)
        defines["CAMERA_FAR"] = round(Globals.base.camLens.get_far(), 10)

        # Work arround buggy nvidia driver, which expects arrays to be const
        if "NVIDIA 361.43" in self._showbase.win.gsg.get_driver_version():
            defines["CONST_ARRAY"] = "const"
        else:
            defines["CONST_ARRAY"] = ""

        # Provide driver vendor as a define
        vendor = self._showbase.win.gsg.get_driver_vendor().lower()
        defines["IS_NVIDIA"] = "nvidia" in vendor
        defines["IS_AMD"] = "ati" in vendor
        defines["IS_INTEL"] = "intel" in vendor

        defines["REFERENCE_MODE"] = self.settings["pipeline.reference_mode"]
        self.light_mgr.init_defines()
        self.plugin_mgr.init_defines()

    def _create_default_skybox(self, size=40000):
        """ Returns the default skybox, with a scale of <size>, and all
        proper effects and shaders already applied. The skybox is already
        parented to render as well. """
        skybox = self.common_resources.load_default_skybox()
        skybox.set_scale(size)
        skybox.reparent_to(Globals.render)
        skybox.set_bin("unsorted", 10000)
        self.set_effect(skybox, "effects/skybox.yaml", {
            "render_shadow": False,
            "render_envmap": False,
            "render_voxelize": False,
            "alpha_testing": False,
            "normal_mapping": False,
            "parallax_mapping": False
        }, 1000)
        return skybox

    def _check_version(self):
        """ Internal method to check if the required Panda3D version is met. Returns
        True if the version is new enough, and False if the version is outdated. """
        from panda3d.core import Texture
        if not hasattr(Texture, "F_r16i"):
            return False
        return True

    def _init_common_stages(self):
        """ Inits the commonly used stages, which don't belong to any plugin,
        but yet are necessary and widely used. """
        add_stage = self.stage_mgr.add_stage
        self._ambient_stage = AmbientStage(self)
        add_stage(self._ambient_stage)
        self._gbuffer_stage = GBufferStage(self)
        add_stage(self._gbuffer_stage)
        self._final_stage = FinalStage(self)
        add_stage(self._final_stage)
        self._downscale_stage = DownscaleZStage(self)
        add_stage(self._downscale_stage)
        self._combine_velocity_stage = CombineVelocityStage(self)
        add_stage(self._combine_velocity_stage)

        # Add an upscale/downscale stage in case we render at a different resolution
        if abs(1 - self.settings["pipeline.resolution_scale"]) > 0.005:
            self._upscale_stage = UpscaleStage(self)
            add_stage(self._upscale_stage)
Пример #13
0
class PluginConfigurator(QMainWindow, Ui_MainWindow):
    """ Interface to change the plugin settings """
    def __init__(self):

        # Init mounts
        self._mount_mgr = MountManager(None)
        self._mount_mgr.mount()

        self._plugin_mgr = PluginManager(None)
        self._plugin_mgr.requires_daytime_settings = False

        QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)

        self._current_plugin = None
        self._current_plugin_instance = None
        self.lbl_restart_pipeline.hide()
        self._set_settings_visible(False)
        self._update_queue = list()

        qt_connect(self.lst_plugins, "itemSelectionChanged()",
                   self.on_plugin_selected)
        qt_connect(self.lst_plugins, "itemChanged(QListWidgetItem*)",
                   self.on_plugin_state_changed)
        qt_connect(self.btn_reset_plugin_settings, "clicked()",
                   self.on_reset_plugin_settings)

        self._load_plugin_list()

        # Adjust column widths
        self.table_plugin_settings.setColumnWidth(0, 140)
        self.table_plugin_settings.setColumnWidth(1, 105)
        self.table_plugin_settings.setColumnWidth(2, 160)

        update_thread = Thread(target=self.update_thread, args=())
        update_thread.start()

    def closeEvent(self, event):  # noqa
        event.accept()
        import os
        os._exit(1)

    def on_reset_plugin_settings(self):
        """ Gets called when the user wants to reset settings of a plugin """

        # Ask the user if he's really sure about it
        msg = "Are you sure you want to reset the settings of '"
        msg += self._current_plugin_instance.name + "'?\n"
        msg += "This does not reset the Time of Day settings of this plugin.\n\n"
        msg += "!! This cannot be undone !! They will be lost forever (a long time!)."
        reply = QMessageBox.question(self, "Warning", msg, QMessageBox.Yes,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:

            QMessageBox.information(
                self, "Success",
                "Settings have been reset! You may have to restart the pipeline."
            )
            self._plugin_mgr.reset_plugin_settings(self._current_plugin)

            # Save config
            self._plugin_mgr.save_overrides("/$$rp/config/plugins.yaml")

            # Always show the restart hint, even if its not always required
            self._show_restart_hint()

            # Re-render everything
            self._load_plugin_list()

    def on_plugin_state_changed(self, item):
        """ Handler when a plugin got activated/deactivated """
        plugin_id = item._plugin_id
        state = item.checkState() == Qt.Checked
        self._plugin_mgr.set_plugin_enabled(plugin_id, state)
        self._rewrite_plugin_config()
        self._show_restart_hint()

    def on_plugin_selected(self):
        """ Gets called when a plugin got selected in the plugin list """
        selected_item = self.lst_plugins.selectedItems()
        if not selected_item:
            self._current_plugin = None
            self._current_plugin_instance = None
            self._set_settings_visible(False)
            return
        assert len(selected_item) == 1
        selected_item = selected_item[0]
        self._current_plugin = selected_item._plugin_id
        self._current_plugin_instance = self._plugin_mgr.instances[
            self._current_plugin]
        assert (self._current_plugin_instance is not None)
        self._render_current_plugin()
        self._set_settings_visible(True)

    def update_thread(self):
        """ Internal update thread """
        while True:
            if len(self._update_queue) > 0:
                item = self._update_queue.pop(-1)
                NetworkCommunication.send_async(
                    NetworkCommunication.CONFIG_PORT, item)

                if item.startswith("setval "):
                    setting_id = item.split()[1]
                    for entry in list(self._update_queue):
                        if entry.split()[1] == setting_id:
                            self._update_queue.remove(entry)
            time.sleep(0.2)

    def _rewrite_plugin_config(self):
        """ Rewrites the plugin configuration """
        self._plugin_mgr.save_overrides("/$$rp/config/plugins.yaml")

    def _render_current_plugin(self):
        """ Displays the currently selected plugin """
        self.lbl_plugin_name.setText(
            self._current_plugin_instance.name.upper() +
            " <span style='color: #999; margin-left: 5px;'>[" +
            self._current_plugin_instance.plugin_id + "]</span>")

        version_str = "Version " + self._current_plugin_instance.version
        version_str += " by " + self._current_plugin_instance.author

        self.lbl_plugin_version.setText(version_str)
        self.lbl_plugin_desc.setText(self._current_plugin_instance.description)

        self._render_current_settings()

    def _show_restart_hint(self):
        """ Shows a hint to restart the pipeline """
        self.lbl_restart_pipeline.show()

    def _render_current_settings(self):
        """ Renders the current plugin settings """
        settings = self._plugin_mgr.settings[self._current_plugin]

        # remove all rows
        while self.table_plugin_settings.rowCount() > 0:
            self.table_plugin_settings.removeRow(0)

        label_font = QFont()
        label_font.setPointSize(10)
        label_font.setFamily("Roboto")

        desc_font = QFont()
        desc_font.setPointSize(8)
        desc_font.setFamily("Roboto")

        for index, (name, handle) in enumerate(iteritems(settings)):
            if not handle.should_be_visible(settings):
                continue

            row_index = self.table_plugin_settings.rowCount()

            # Increase row count
            self.table_plugin_settings.insertRow(
                self.table_plugin_settings.rowCount())

            label = QLabel()
            label.setText(handle.label)
            label.setWordWrap(True)
            label.setFont(label_font)

            if not (handle.shader_runtime or handle.runtime):
                label.setStyleSheet("color: #999;")

            if handle.display_conditions:
                label.setStyleSheet(label.styleSheet() + "padding-left: 10px;")

            label.setMargin(10)

            self.table_plugin_settings.setCellWidget(row_index, 0, label)

            item_default = QTableWidgetItem()
            item_default.setText(str(handle.default))
            item_default.setTextAlignment(Qt.AlignCenter)
            self.table_plugin_settings.setItem(row_index, 1, item_default)

            setting_widget = self._get_widget_for_setting(name, handle)
            self.table_plugin_settings.setCellWidget(row_index, 2,
                                                     setting_widget)

            label_desc = QLabel()
            label_desc.setText(handle.description)
            label_desc.setWordWrap(True)
            label_desc.setFont(desc_font)
            label_desc.setStyleSheet("color: #555;padding: 5px;")

            self.table_plugin_settings.setCellWidget(row_index, 3, label_desc)

    def _do_update_setting(self, setting_id, value):
        """ Updates a setting of the current plugin """

        # Check whether the setting is a runtime setting
        setting_handle = self._plugin_mgr.get_setting_handle(
            self._current_plugin, setting_id)

        # Skip the setting in case the value is equal
        if setting_handle.value == value:
            return

        # Otherwise set the new value
        setting_handle.set_value(value)
        self._rewrite_plugin_config()

        if not setting_handle.runtime and not setting_handle.shader_runtime:
            self._show_restart_hint()
        else:
            # In case the setting is dynamic, notice the pipeline about it:
            # print("Sending reload packet ...")
            self._update_queue.append("setval {}.{} {}".format(
                self._current_plugin, setting_id, value))

        # Update GUI, but only in case of enum and bool values, since they can trigger
        # display conditions:
        if setting_handle.type == "enum" or setting_handle.type == "bool":
            self._render_current_settings()

    def _on_setting_bool_changed(self, setting_id, value):
        self._do_update_setting(setting_id, value == Qt.Checked)

    def _on_setting_scalar_changed(self, setting_id, value):
        self._do_update_setting(setting_id, value)

    def _on_setting_enum_changed(self, setting_id, value):
        self._do_update_setting(setting_id, value)

    def _on_setting_power_of_two_changed(self, setting_id, value):
        self._do_update_setting(setting_id, value)

    def _on_setting_slider_changed(self, setting_id, setting_type, bound_objs,
                                   value):
        if setting_type == "float":
            value /= 100000.0
        self._do_update_setting(setting_id, value)

        for obj in bound_objs:
            obj.setValue(value)

    def _on_setting_spinbox_changed(self, setting_id, setting_type, bound_objs,
                                    value):
        self._do_update_setting(setting_id, value)
        # Assume objects are sliders, so we need to rescale the value
        for obj in bound_objs:
            obj.setValue(value *
                         100000.0 if setting_type == "float" else value)

    def _choose_path(self, setting_id, setting_handle, bound_objs):
        """ Shows a file chooser to show an path from """

        this_dir = os.path.dirname(os.path.realpath(__file__))
        plugin_dir = os.path.join(this_dir,
                                  "../../rpplugins/" + self._current_plugin,
                                  "resources")
        plugin_dir = os.path.abspath(plugin_dir)
        search_dir = os.path.join(plugin_dir, setting_handle.base_path)

        print("Plugin dir =", plugin_dir)
        print("Search dir =", search_dir)

        current_file = setting_handle.value.replace("\\", "/").split("/")[-1]
        print("Current file =", current_file)
        file_dlg = QFileDialog(self, "Choose File ..", search_dir,
                               setting_handle.file_type)
        file_dlg.selectFile(current_file)
        # file_dlg.setViewMode(QFileDialog.Detail)

        if file_dlg.exec_():
            filename = file_dlg.selectedFiles()
            filename = filename[-1]
            print("QT selected files returned:", filename)

            filename = os.path.relpath(str(filename), plugin_dir)
            filename = filename.replace("\\", "/")
            print("Relative path is", filename)
            self._do_update_setting(setting_id, filename)

            display_file = filename.split("/")[-1]
            for obj in bound_objs:
                obj.setText(display_file)

    def _get_widget_for_setting(self, setting_id, setting):
        """ Returns an appropriate widget to control the given setting """

        widget = QWidget()
        layout = QHBoxLayout()
        layout.setAlignment(Qt.AlignCenter)
        widget.setLayout(layout)

        if setting.type == "bool":
            box = QCheckBox()
            box.setChecked(Qt.Checked if setting.value else Qt.Unchecked)
            qt_connect(box, "stateChanged(int)",
                       partial(self._on_setting_bool_changed, setting_id))
            layout.addWidget(box)

        elif setting.type == "float" or setting.type == "int":

            if setting.type == "float":
                box = QDoubleSpinBox()

                if setting.maxval - setting.minval <= 2.0:
                    box.setDecimals(4)
            else:
                box = QSpinBox()
            box.setMinimum(setting.minval)
            box.setMaximum(setting.maxval)
            box.setValue(setting.value)

            box.setAlignment(Qt.AlignCenter)

            slider = QSlider()
            slider.setOrientation(Qt.Horizontal)

            if setting.type == "float":
                box.setSingleStep(abs(setting.maxval - setting.minval) / 100.0)
                slider.setMinimum(setting.minval * 100000.0)
                slider.setMaximum(setting.maxval * 100000.0)
                slider.setValue(setting.value * 100000.0)
            elif setting.type == "int":
                box.setSingleStep(
                    max(1, (setting.maxval - setting.minval) / 32))
                slider.setMinimum(setting.minval)
                slider.setMaximum(setting.maxval)
                slider.setValue(setting.value)

            layout.addWidget(box)
            layout.addWidget(slider)

            qt_connect(
                slider, "valueChanged(int)",
                partial(self._on_setting_slider_changed, setting_id,
                        setting.type, [box]))

            value_type = "int" if setting.type == "int" else "double"

            qt_connect(
                box, "valueChanged(" + value_type + ")",
                partial(self._on_setting_spinbox_changed, setting_id,
                        setting.type, [slider]))

        elif setting.type == "enum":
            box = QComboBox()
            for value in setting.values:
                box.addItem(value)
            qt_connect(box, "currentIndexChanged(QString)",
                       partial(self._on_setting_enum_changed, setting_id))
            box.setCurrentIndex(setting.values.index(setting.value))
            box.setMinimumWidth(145)

            layout.addWidget(box)

        elif setting.type == "power_of_two":

            box = QComboBox()
            resolutions = [
                str(2**i) for i in range(1, 32)
                if 2**i >= setting.minval and 2**i <= setting.maxval
            ]
            for value in resolutions:
                box.addItem(value)
            qt_connect(
                box, "currentIndexChanged(QString)",
                partial(self._on_setting_power_of_two_changed, setting_id))
            box.setCurrentIndex(resolutions.index(str(setting.value)))
            box.setMinimumWidth(145)
            layout.addWidget(box)

        elif setting.type == "sample_sequence":

            box = QComboBox()
            for value in setting.sequences:
                box.addItem(value)
            qt_connect(box, "currentIndexChanged(QString)",
                       partial(self._on_setting_enum_changed, setting_id))
            box.setCurrentIndex(setting.sequences.index(str(setting.value)))
            box.setMinimumWidth(145)
            layout.addWidget(box)

        elif setting.type == "path":

            label = QLabel()
            display_file = setting.value.replace("\\", "/").split("/")[-1]

            desc_font = QFont()
            desc_font.setPointSize(7)
            desc_font.setFamily("Roboto")

            label.setText(display_file)
            label.setFont(desc_font)

            button = QPushButton()
            button.setText("Choose File ...")
            qt_connect(
                button, "clicked()",
                partial(self._choose_path, setting_id, setting, (label, )))

            layout.addWidget(label)
            layout.addWidget(button)

        else:
            print("ERROR: Unkown setting type:", setting.type)

        return widget

    def _set_settings_visible(self, flag):
        """ Sets whether the settings panel is visible or not """
        if flag:
            self.frame_details.show()
        else:
            self.frame_details.hide()

    def _load_plugin_list(self):
        """ Reloads the whole plugin list """
        print("Loading plugin list")

        # Reset selection
        self._current_plugin = None
        self._current_plugin_instance = None
        self._set_settings_visible(False)

        # Plugins are all plugins in the plugins directory
        self._plugin_mgr.unload()
        self._plugin_mgr.load()

        self.lst_plugins.clear()
        plugins = sorted(iteritems(self._plugin_mgr.instances),
                         key=lambda plg: plg[1].name)

        item_font = QFont()
        item_font.setBold(False)
        item_font.setPointSize(10)

        for plugin_id, instance in plugins:

            item = QListWidgetItem()
            item.setText(" " + instance.name)
            item.setFont(item_font)

            if self._plugin_mgr.is_plugin_enabled(plugin_id):
                item.setCheckState(Qt.Checked)
            else:
                item.setCheckState(Qt.Unchecked)

            item._plugin_id = plugin_id
            self.lst_plugins.addItem(item)

        self.lst_plugins.setCurrentRow(0)
Пример #14
0
class DayTimeEditor(QMainWindow, Ui_MainWindow):

    """ This is the main editor class which handles the user interface """

    def __init__(self):

        # Init mounts
        self._mount_mgr = MountManager(None)
        self._mount_mgr.mount()

        self._plugin_mgr = PluginManager(None)
        self._plugin_mgr.load()

        QMainWindow.__init__(self)
        self.setupUi()
        self._tree_widgets = []
        self._cmd_queue = set()

        self._selected_setting_handle = None
        self._selected_setting = None
        self._selected_plugin = None
        self._current_time = 0.5

        self._update_settings_list()
        self._on_time_changed(self.time_slider.value())

        self._bg_thread = Thread(target=self.updateThread)
        self._bg_thread.start()

    def set_settings_visible(self, visibility):
        if not visibility:
            self.frame_current_setting.hide()
        else:
            self.frame_current_setting.show()

    def closeEvent(self, event):  # noqa
        event.accept()
        import os
        os._exit(1)

    def updateThread(self):  # noqa
        """ Seperate update thread """

        while True:
            if self._cmd_queue:
                cmd = self._cmd_queue.pop()
                if cmd == "settime":
                    NetworkCommunication.send_async(
                        NetworkCommunication.DAYTIME_PORT, "settime " + str(self._current_time))
                    continue
                elif cmd == "write_settings":
                    self._plugin_mgr.save_daytime_overrides("/$$rp/config/daytime.yaml")
                    NetworkCommunication.send_async(
                        NetworkCommunication.DAYTIME_PORT, "loadconf")
                else:
                    print("Unkown cmd:", cmd)

            time.sleep(0.1)

    def setupUi(self):  # noqa
        """ Setups the UI Components """
        Ui_MainWindow.setupUi(self, self)
        self.settings_tree.setColumnWidth(0, 160)
        self.settings_tree.expandAll()

        self.edit_widget = CurveWidget(self)
        self.edit_widget.set_change_handler(self._on_curve_edited)
        self.prefab_edit_widget.addWidget(self.edit_widget)

        qt_connect(self.time_slider, "valueChanged(int)", self._on_time_changed)
        qt_connect(self.settings_tree, "itemSelectionChanged()", self._on_setting_selected)
        qt_connect(self.btn_insert_point, "clicked()", self._insert_point)
        qt_connect(self.btn_reset, "clicked()", self._reset_settings)

    def _reset_settings(self):
        """ Resets the current plugins settings """
        # QMessageBox.warning(self, "Houston, we have a problem!",
        #     "This functionality is not yet implemented! Blame tobspr if you need it.\n\n"
        #     "On a more serious note, you can still hand-edit config/daytime.yaml.",
        #     QMessageBox.Ok, QMessageBox.Ok)

        # Ask the user if he's really sure about it
        msg = "Are you sure you want to reset the control points of '" +\
              self._selected_setting_handle.label + "'?\n"
        msg += "!! This cannot be undone !! They will be lost forever (a long time!)."
        reply = QMessageBox.question(
            self, "Warning", msg, QMessageBox.Yes, QMessageBox.No)
        if reply == QMessageBox.Yes:

            QMessageBox.information(self, "Success", "Control points have been reset!")
            default = self._selected_setting_handle.default
            if type(default) not in (tuple, list):
                default = [default]
            for i, val, in enumerate(default):
                self._selected_setting_handle.curves[i].set_single_value(val)
            self._update_settings_list()
            self._cmd_queue.add("write_settings")

    def _insert_point(self):
        """ Asks the user to insert a new point """
        dialog = PointDialog(self)
        if dialog.exec_():
            time, val = dialog.get_value()
            minutes = (time.hour() * 60 + time.minute()) / (24 * 60)

            if (val < self._selected_setting_handle.minvalue or
               val > self._selected_setting_handle.maxvalue):
                QMessageBox.information(
                    self, "Invalid Value", "Value is out of setting range!", QMessageBox.Ok)
                return

            val_linear = self._selected_setting_handle.get_linear_value(val)
            self._selected_setting_handle.curves[0].append_cv(minutes, val_linear)
            self._cmd_queue.add("write_settings")

    def _update_tree_widgets(self):
        """ Updates the tree widgets """
        for setting_handle, widget in self._tree_widgets:
            value = setting_handle.get_scaled_value_at(self._current_time)
            formatted = setting_handle.format(value)
            widget.setText(1, formatted)

            if setting_handle.type == "color":
                widget.setBackground(1, QBrush(QColor(*value)))

    def _on_curve_edited(self):
        """ Called when the curve got edited in the curve widget """
        self._cmd_queue.add("write_settings")
        self._update_tree_widgets()

    def _on_setting_selected(self):
        """ Called when a setting got selected in the settings tree """
        selected = self.settings_tree.selectedItems()
        if len(selected) != 1:
            self._selected_setting = None
            self._selected_plugin = None
            self._selected_setting_handle = None
            self.edit_widget.set_curves([])
            self.set_settings_visible(False)
        else:
            selected = selected[0]

            self._selected_plugin = selected._plugin_id
            self._selected_setting = selected._setting_id
            self._selected_setting_handle = selected._setting_handle

            self.lbl_current_setting.setText(self._selected_setting_handle.label)
            self.lbl_setting_desc.setText(self._selected_setting_handle.description)

            self.edit_widget.set_curves(self._selected_setting_handle.curves)

            if self._selected_setting_handle.type == "color":
                self.edit_widget.set_unit_processor(lambda x: str(int(x * 255)))
                self.btn_insert_point.hide()
            else:
                self.edit_widget.set_unit_processor(
                    lambda x: self._selected_setting_handle.format(
                        self._selected_setting_handle.get_scaled_value(x)))
                self.btn_insert_point.show()

            self.set_settings_visible(True)
            self._update_tree_widgets()

    def _on_time_changed(self, val):
        """ Handler when the time slider got moved """
        hour = val // (60 * 60 * 60)
        minute = (val // (60 * 60)) % 60
        ftime = float(val) / (24 * 60 * 60 * 60)

        self.time_label.setText(str(hour).zfill(2) + ":" + str(minute).zfill(2))
        self.time_float_label.setText("{:1.4f}".format(ftime))
        self.edit_widget.set_current_time(ftime)
        self._current_time = ftime
        self._update_tree_widgets()
        self._cmd_queue.add("settime")

    def _update_settings_list(self):
        """ Updates the list of visible settings """

        self.settings_tree.clear()
        self._tree_widgets = []

        first_item = None

        for plugin_id, plugin in iteritems(self._plugin_mgr.instances):

            daytime_settings = self._plugin_mgr.day_settings[plugin_id]

            if not daytime_settings:
                # Skip plugins with empty settings
                continue

            plugin_head = QTreeWidgetItem(self.settings_tree)
            plugin_head.setText(0, plugin.name)
            plugin_head.setFlags(Qt.ItemIsEnabled)
            font = QFont()
            font.setBold(True)
            if not self._plugin_mgr.is_plugin_enabled(plugin_id):
                plugin_head.setText(0, plugin.name)
            plugin_head.setFont(0, font)

            # Display all settings
            for setting, setting_handle in iteritems(daytime_settings):
                setting_item = QTreeWidgetItem(plugin_head)
                setting_item.setText(0, setting_handle.label)
                if PYQT_VERSION == 4:
                    setting_item.setTextColor(0, QColor(150, 150, 150))
                else:
                    setting_item.setForeground(0, QColor(150, 150, 150))
                setting_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                setting_item._setting_id = setting
                setting_item._setting_handle = setting_handle
                setting_item._plugin_id = plugin_id
                setting_item.setToolTip(0, setting_handle.description)
                setting_item.setToolTip(1, setting_handle.description)
                self._tree_widgets.append((setting_handle, setting_item))
                if not first_item:
                    first_item = setting_item

        self.settings_tree.expandAll()
        if first_item:
            self.settings_tree.setCurrentItem(first_item)
Пример #15
0
    handle.close()

    # Extract data
    print("Extracting data ..")
    lines = data.replace("\r", "").split("\n")[1:]

    # Load render pipeline api
    print("Loading plugin api ..")
    sys.path.insert(0, "../../")
    from rpcore.pluginbase.manager import PluginManager
    from rpcore.mount_manager import MountManager

    mount_mgr = MountManager(None)
    mount_mgr.mount()

    plugin_mgr = PluginManager(None)
    plugin_mgr.load()

    convert_to_linear = plugin_mgr.day_settings["scattering"][
        "sun_intensity"].get_linear_value

    hour, minutes = 0, 0

    data_points_azimuth = []
    data_points_altitude = []
    data_points_intensity = []

    for line in lines:
        if not line:
            break
        date, time, azim_angle, declination, ascension, elevation = line.split(
Пример #16
0
class RenderPipeline(RPObject):
    """ This is the main pipeline logic, it combines all components of the
    pipeline to form a working system. It does not do much work itself, but
    instead setups all the managers and systems to be able to do their work.

    It also derives from RPExtensions to provide some useful functions like
    creating a default skybox or loading effect files. """
    def __init__(self, outdated_parameter=None):
        """ Creates a new pipeline with a given showbase instance. This should
        be done before intializing the ShowBase, the pipeline will take care of
        that. """
        RPObject.__init__(self)
        if outdated_parameter is not None:
            self.fatal(
                "The render pipeline no longer takes the ShowBase argument "
                "as constructor parameter. Please have a look at the "
                "00-Loading the pipeline sample to see how to initialize "
                "the pipeline properly.")
        self.debug("Using Python {}.{} with architecture {}".format(
            sys.version_info.major, sys.version_info.minor,
            PandaSystem.get_platform()))
        self.debug("Using Panda3D {} built on {}".format(
            PandaSystem.get_version_string(), PandaSystem.get_build_date()))
        if PandaSystem.get_git_commit():
            self.debug("Using git commit {}".format(
                PandaSystem.get_git_commit()))
        else:
            self.debug("Using custom Panda3D build")
        self.mount_mgr = MountManager(self)
        self.settings = {}
        self._pre_showbase_initialized = False
        self._first_frame = None
        self.set_default_loading_screen()

        # Check for the right Panda3D version
        if not self._check_version():
            self.fatal(
                "Your Panda3D version is outdated! Please update to the newest \n"
                "git version! Checkout https://github.com/panda3d/panda3d to "
                "compile panda from source, or get a recent buildbot build.")

    def load_settings(self, path):
        """ Loads the pipeline configuration from a given filename. Usually
        this is the 'config/pipeline.ini' file. If you call this more than once,
        only the settings of the last file will be used. """
        self.settings = load_yaml_file_flat(path)

    def reload_shaders(self):
        """ Reloads all shaders """
        if self.settings["pipeline.display_debugger"]:
            self.debug("Reloading shaders ..")
            self._debugger.get_error_msg_handler().clear_messages()
            self._debugger.set_reload_hint_visible(True)
            self._showbase.graphicsEngine.render_frame()
            self._showbase.graphicsEngine.render_frame()

        self.tag_mgr.cleanup_states()
        self.stage_mgr.reload_shaders()
        self.light_mgr.reload_shaders()

        # Set the default effect on render and trigger the reload hook
        self._set_default_effect()
        self.plugin_mgr.trigger_hook("shader_reload")

        if self.settings["pipeline.display_debugger"]:
            self._debugger.set_reload_hint_visible(False)

    def pre_showbase_init(self):
        """ Setups all required pipeline settings and configuration which have
        to be set before the showbase is setup. This is called by create(),
        in case the showbase was not initialized, however you can (and have to)
        call it manually before you init your custom showbase instance.
        See the 00-Loading the pipeline sample for more information."""

        if not self.mount_mgr.is_mounted:
            self.debug("Mount manager was not mounted, mounting now ...")
            self.mount_mgr.mount()

        if not self.settings:
            self.debug("No settings loaded, loading from default location")
            self.load_settings("/$$rpconfig/pipeline.yaml")

        # Check if the pipeline was properly installed, before including anything else
        if not isfile("/$$rp/data/install.flag"):
            self.fatal(
                "You didn't setup the pipeline yet! Please run setup.py.")

        # Load the default prc config
        load_prc_file("/$$rpconfig/panda3d-config.prc")

        # Set the initialization flag
        self._pre_showbase_initialized = True

    def create(self, base=None):
        """ This creates the pipeline, and setups all buffers. It also
        constructs the showbase. The settings should have been loaded before
        calling this, and also the base and write path should have been
        initialized properly (see MountManager).

        If base is None, the showbase used in the RenderPipeline constructor
        will be used and initialized. Otherwise it is assumed that base is an
        initialized ShowBase object. In this case, you should call
        pre_showbase_init() before initializing the ShowBase"""

        start_time = time.time()
        self._init_showbase(base)
        self._init_globals()

        # Create the loading screen
        self._loading_screen.create()
        self._adjust_camera_settings()
        self._create_managers()

        # Load plugins and daytime settings
        self.plugin_mgr.load()
        self.daytime_mgr.load_settings()
        self._com_resources.write_config()

        # Init the onscreen debugger
        self._init_debugger()

        # Let the plugins setup their stages
        self.plugin_mgr.trigger_hook("stage_setup")

        self._create_common_defines()
        self._setup_managers()
        self._create_default_skybox()

        self.plugin_mgr.trigger_hook("pipeline_created")

        # Hide the loading screen
        self._loading_screen.remove()

        # Start listening for updates
        self._listener = NetworkCommunication(self)
        self._set_default_effect()

        # Measure how long it took to initialize everything
        init_duration = (time.time() - start_time)
        self.debug(
            "Finished initialization in {:3.3f} s".format(init_duration))

        self._first_frame = time.clock()

    def _create_managers(self):
        """ Internal method to create all managers and instances"""
        self.task_scheduler = TaskScheduler(self)
        self.tag_mgr = TagStateManager(Globals.base.cam)
        self.plugin_mgr = PluginManager(self)
        self.stage_mgr = StageManager(self)
        self.light_mgr = LightManager(self)
        self.daytime_mgr = DayTimeManager(self)
        self.ies_loader = IESProfileLoader(self)

        # Load commonly used resources
        self._com_resources = CommonResources(self)
        self._init_common_stages()

    def _setup_managers(self):
        """ Internal method to setup all managers """
        self.stage_mgr.setup()
        self.stage_mgr.reload_shaders()
        self.light_mgr.reload_shaders()
        self._init_bindings()
        self.light_mgr.init_shadows()

    def _init_debugger(self):
        """ Internal method to initialize the GUI-based debugger """
        if self.settings["pipeline.display_debugger"]:
            self._debugger = Debugger(self)
        else:
            # Use an empty onscreen debugger in case the debugger is not
            # enabled, which defines all member functions as empty lambdas
            class EmptyDebugger(object):
                def __getattr__(self, *args, **kwargs):
                    return lambda *args, **kwargs: None

            self._debugger = EmptyDebugger()
            del EmptyDebugger

    def _init_globals(self):
        """ Inits all global bindings """
        Globals.load(self._showbase)
        w, h = self._showbase.win.get_x_size(), self._showbase.win.get_y_size()

        scale_factor = self.settings["pipeline.resolution_scale"]
        w = int(float(w) * scale_factor)
        h = int(float(h) * scale_factor)

        # Make sure the resolution is a multiple of 4
        w = w - w % 4
        h = h - h % 4

        self.debug("Render resolution is", w, "x", h)
        Globals.resolution = LVecBase2i(w, h)

        # Connect the render target output function to the debug object
        RenderTarget.RT_OUTPUT_FUNC = lambda *args: RPObject.global_warn(
            "RenderTarget", *args[1:])

        RenderTarget.USE_R11G11B10 = self.settings["pipeline.use_r11_g11_b10"]

    def _init_showbase(self, base):
        """ Inits the the given showbase object """

        # Construct the showbase and init global variables
        if base:
            # Check if we have to init the showbase
            if not hasattr(base, "render"):
                self.pre_showbase_init()
                ShowBase.__init__(base)
            else:
                if not self._pre_showbase_initialized:
                    self.fatal(
                        "You constructed your own ShowBase object but you "
                        "did not call pre_show_base_init() on the render "
                        "pipeline object before! Checkout the 00-Loading the "
                        "pipeline sample to see how to initialize the RP.")
            self._showbase = base
        else:
            self.pre_showbase_init()
            self._showbase = ShowBase()

    def _init_bindings(self):
        """ Inits the tasks and keybindings """

        # Add a hotkey to reload the shaders, but only if the debugger is enabled
        if self.settings["pipeline.display_debugger"]:
            self._showbase.accept("r", self.reload_shaders)

        self._showbase.addTask(self._manager_update_task,
                               "RP_UpdateManagers",
                               sort=10)
        self._showbase.addTask(self._plugin_pre_render_update,
                               "RP_Plugin_BeforeRender",
                               sort=12)
        self._showbase.addTask(self._plugin_post_render_update,
                               "RP_Plugin_AfterRender",
                               sort=15)
        self._showbase.addTask(self._update_inputs_and_stages,
                               "RP_UpdateInputsAndStages",
                               sort=18)
        self._showbase.taskMgr.doMethodLater(0.5, self._clear_state_cache,
                                             "RP_ClearStateCache")

    def _clear_state_cache(self, task=None):
        """ Task which repeatedly clears the state cache to avoid storing
        unused states. """
        task.delayTime = 2.0
        TransformState.clear_cache()
        RenderState.clear_cache()
        return task.again

    def _manager_update_task(self, task):
        """ Update task which gets called before the rendering """
        self.task_scheduler.step()
        self._listener.update()
        self._debugger.update()
        self.daytime_mgr.update()
        self.light_mgr.update()
        return task.cont

    def _update_inputs_and_stages(self, task):
        """ Updates teh commonly used inputs """
        self._com_resources.update()
        self.stage_mgr.update()
        return task.cont

    def _plugin_pre_render_update(self, task):
        """ Update task which gets called before the rendering, and updates the
        plugins. This is a seperate task to split the work, and be able to do
        better performance analysis """
        self.plugin_mgr.trigger_hook("pre_render_update")
        return task.cont

    def _plugin_post_render_update(self, task):
        """ Update task which gets called after the rendering """
        self.plugin_mgr.trigger_hook("post_render_update")

        if self._first_frame is not None:
            duration = time.clock() - self._first_frame
            self.debug("Took", round(duration, 3), "s until first frame")
            self._first_frame = None

        return task.cont

    def _create_common_defines(self):
        """ Creates commonly used defines for the shader auto config """
        defines = self.stage_mgr.defines

        # 3D viewport size
        defines["WINDOW_WIDTH"] = Globals.resolution.x
        defines["WINDOW_HEIGHT"] = Globals.resolution.y

        # Actual window size - might differ for supersampling
        defines["NATIVE_WINDOW_WIDTH"] = Globals.base.win.get_x_size()
        defines["NATIVE_WINDOW_HEIGHT"] = Globals.base.win.get_y_size()

        # Pass camera near and far plane
        defines["CAMERA_NEAR"] = round(Globals.base.camLens.get_near(), 10)
        defines["CAMERA_FAR"] = round(Globals.base.camLens.get_far(), 10)

        # Work arround buggy nvidia driver, which expects arrays to be const
        if "NVIDIA 361.43" in self._showbase.win.get_gsg().get_driver_version(
        ):
            defines["CONST_ARRAY"] = "const"
        else:
            defines["CONST_ARRAY"] = ""

        # Provide driver vendor as a default
        vendor = self._showbase.win.get_gsg().get_driver_vendor().lower()
        if "nvidia" in vendor:
            defines["IS_NVIDIA"] = 1
        if "ati" in vendor:
            defines["IS_AMD"] = 1
        if "intel" in vendor:
            defines["IS_INTEL"] = 1

        defines["REFERENCE_MODE"] = self.settings["pipeline.reference_mode"]

        # Only activate this experimental feature if the patch was applied,
        # since it is a local change in my Panda3D build which is not yet
        # reviewed by rdb. Once it is in public Panda3D Dev-Builds this will
        # be the default.
        if (not isfile(
                "/$$rp/data/panda3d_patches/prev-model-view-matrix.diff")
                or isfile("D:/__dev__")):

            # You can find the required patch in
            # data/panda3d_patches/prev-model-view-matrix.diff.
            # Delete it after you applied it, so the render pipeline knows the
            # patch is available.
            # self.warn("Experimental feature activated, no guarantee it works!")
            # defines["EXPERIMENTAL_PREV_TRANSFORM"] = 1
            pass

        self.light_mgr.init_defines()
        self.plugin_mgr.init_defines()

    def set_loading_screen(self, loading_screen):
        """ Sets a loading screen to be used while loading the pipeline. When
        the pipeline gets constructed (and creates the showbase), create()
        will be called on the object. During the loading progress,
        progress(msg) will be called. After the loading is finished,
        remove() will be called. If a custom loading screen is passed, those
        methods should be implemented. """
        self._loading_screen = loading_screen

    def set_default_loading_screen(self):
        """ Tells the pipeline to use the default loading screen. """
        self._loading_screen = LoadingScreen(self)

    def set_empty_loading_screen(self):
        """ Tells the pipeline to use no loading screen """
        self._loading_screen = EmptyLoadingScreen()

    @property
    def loading_screen(self):
        """ Returns the current loading screen """
        return self._loading_screen

    def add_light(self, light):
        """ Adds a new light to the rendered lights, check out the LightManager
        add_light documentation for further information. """
        self.light_mgr.add_light(light)

    def remove_light(self, light):
        """ Removes a previously attached light, check out the LightManager
        remove_light documentation for further information. """
        self.light_mgr.remove_light(light)

    def _create_default_skybox(self, size=40000):
        """ Returns the default skybox, with a scale of <size>, and all
        proper effects and shaders already applied. The skybox is already
        parented to render as well. """
        skybox = self._com_resources.load_default_skybox()
        skybox.set_scale(size)
        skybox.reparent_to(Globals.render)
        skybox.set_bin("unsorted", 10000)
        self.set_effect(
            skybox, "effects/skybox.yaml", {
                "render_shadows": False,
                "render_envmap": False,
                "render_voxel": False,
                "alpha_testing": False,
                "normal_mapping": False,
                "parallax_mapping": False
            }, 1000)
        return skybox

    def load_ies_profile(self, filename):
        """ Loads an IES profile from a given filename and returns a handle which
        can be used to set an ies profile on a light """
        return self.ies_loader.load(filename)

    def set_effect(self, nodepath, effect_src, options=None, sort=30):
        """ Sets an effect to the given object, using the specified options.
        Check out the effect documentation for more information about possible
        options and configurations. The object should be a nodepath, and the
        effect will be applied to that nodepath and all nodepaths below whose
        current effect sort is less than the new effect sort (passed by the
        sort parameter). """

        effect = Effect.load(effect_src, options)
        if effect is None:
            return self.error("Could not apply effect")

        # Apply default stage shader
        if not effect.get_option("render_gbuffer"):
            nodepath.hide(self.tag_mgr.get_mask("gbuffer"))
        else:
            nodepath.set_shader(effect.get_shader_obj("gbuffer"), sort)
            nodepath.show(self.tag_mgr.get_mask("gbuffer"))

        # Apply shadow stage shader
        if not effect.get_option("render_shadows"):
            nodepath.hide(self.tag_mgr.get_mask("shadow"))
        else:
            shader = effect.get_shader_obj("shadows")
            self.tag_mgr.apply_state("shadow", nodepath, shader,
                                     str(effect.effect_id), 25 + sort)
            nodepath.show(self.tag_mgr.get_mask("shadow"))

        # Apply voxelization stage shader
        if not effect.get_option("render_voxel"):
            nodepath.hide(self.tag_mgr.get_mask("voxelize"))
        else:
            shader = effect.get_shader_obj("voxelize")
            self.tag_mgr.apply_state("voxelize", nodepath, shader,
                                     str(effect.effect_id), 35 + sort)
            nodepath.show(self.tag_mgr.get_mask("voxelize"))

        # Apply envmap stage shader
        if not effect.get_option("render_envmap"):
            nodepath.hide(self.tag_mgr.get_mask("envmap"))
        else:
            shader = effect.get_shader_obj("envmap")
            self.tag_mgr.apply_state("envmap", nodepath, shader,
                                     str(effect.effect_id), 45 + sort)
            nodepath.show(self.tag_mgr.get_mask("envmap"))

        # Apply forward shading shader
        if not effect.get_option("render_forward"):
            nodepath.hide(self.tag_mgr.get_mask("forward"))
        else:
            shader = effect.get_shader_obj("forward")
            self.tag_mgr.apply_state("forward", nodepath, shader,
                                     str(effect.effect_id), 55 + sort)
            nodepath.show_through(self.tag_mgr.get_mask("forward"))

        # Check for invalid options
        if effect.get_option("render_gbuffer") and effect.get_option(
                "render_forward"):
            self.error(
                "You cannot render an object forward and deferred at the same time! Either "
                "use render_gbuffer or use render_forward, but not both.")

    def add_environment_probe(self):
        """ Constructs a new environment probe and returns the handle, so that
        the probe can be modified """

        # TODO: This method is super hacky
        if not self.plugin_mgr.is_plugin_enabled("env_probes"):
            self.warn(
                "EnvProbe plugin is not loaded, can not add environment probe")

            class DummyEnvironmentProbe(object):
                def __getattr__(self, *args, **kwargs):
                    return lambda *args, **kwargs: None

            return DummyEnvironmentProbe()

        from rpplugins.env_probes.environment_probe import EnvironmentProbe
        probe = EnvironmentProbe()
        self.plugin_mgr.instances["env_probes"].probe_mgr.add_probe(probe)
        return probe

    def prepare_scene(self, scene):
        """ Prepares a given scene, by converting panda lights to render pipeline
        lights """

        # TODO: IES profiles
        ies_profile = self.load_ies_profile("soft_display.ies")  # pylint: disable=W0612
        lights = []

        for light in scene.find_all_matches("**/+PointLight"):
            light_node = light.node()
            rp_light = PointLight()
            rp_light.pos = light.get_pos(Globals.base.render)
            rp_light.radius = light_node.max_distance
            rp_light.energy = 100.0 * light_node.color.w
            rp_light.color = light_node.color.xyz
            rp_light.casts_shadows = light_node.shadow_caster
            rp_light.shadow_map_resolution = light_node.shadow_buffer_size.x
            rp_light.inner_radius = 0.8
            self.add_light(rp_light)
            light.remove_node()
            lights.append(rp_light)

        for light in scene.find_all_matches("**/+Spotlight"):
            light_node = light.node()
            rp_light = SpotLight()
            rp_light.pos = light.get_pos(Globals.base.render)
            rp_light.radius = light_node.max_distance
            rp_light.energy = 100.0 * light_node.color.w
            rp_light.color = light_node.color.xyz
            rp_light.casts_shadows = light_node.shadow_caster
            rp_light.shadow_map_resolution = light_node.shadow_buffer_size.x
            rp_light.fov = light_node.exponent / math.pi * 180.0
            lpoint = light.get_mat(Globals.base.render).xform_vec((0, 0, -1))
            rp_light.direction = lpoint
            self.add_light(rp_light)
            light.remove_node()
            lights.append(rp_light)

        envprobes = []

        # Add environment probes
        for np in scene.find_all_matches("**/ENVPROBE*"):
            probe = self.add_environment_probe()
            probe.set_mat(np.get_mat())
            probe.border_smoothness = 0.001
            probe.parallax_correction = True
            np.remove_node()
            envprobes.append(probe)

        # Find transparent objects and set the right effect
        for geom_np in scene.find_all_matches("**/+GeomNode"):
            geom_node = geom_np.node()
            geom_count = geom_node.get_num_geoms()
            for i in range(geom_count):
                state = geom_node.get_geom_state(i)
                if not state.has_attrib(MaterialAttrib):
                    self.warn("Geom", geom_node, "has no material!")
                    continue
                material = state.get_attrib(MaterialAttrib).get_material()
                shading_model = material.emission.x

                # SHADING_MODEL_TRANSPARENT
                if shading_model == 3:
                    if geom_count > 1:
                        self.error(
                            "Transparent materials must have their own geom!")
                        continue

                    self.set_effect(geom_np, "effects/default.yaml", {
                        "render_forward": True,
                        "render_gbuffer": False
                    }, 100)

                # SHADING_MODEL_FOLIAGE
                elif shading_model == 5:
                    # XXX: Maybe only enable alpha testing for foliage unless
                    # specified otherwise
                    pass

        return {"lights": lights, "envprobes": envprobes}

    def _check_version(self):
        """ Internal method to check if the required Panda3D version is met. Returns
        True if the version is new enough, and False if the version is outdated. """

        from panda3d.core import PointLight as Panda3DPointLight
        if not hasattr(Panda3DPointLight(""), "shadow_caster"):
            return False

        return True

    def _init_common_stages(self):
        """ Inits the commonly used stages, which don't belong to any plugin,
        but yet are necessary and widely used. """
        add_stage = self.stage_mgr.add_stage

        self._ambient_stage = AmbientStage(self)
        add_stage(self._ambient_stage)

        self._gbuffer_stage = GBufferStage(self)
        add_stage(self._gbuffer_stage)

        self._final_stage = FinalStage(self)
        add_stage(self._final_stage)

        self._downscale_stage = DownscaleZStage(self)
        add_stage(self._downscale_stage)

        self._combine_velocity_stage = CombineVelocityStage(self)
        add_stage(self._combine_velocity_stage)

        # Add an upscale/downscale stage in case we render at a different resolution
        if abs(1 - self.settings["pipeline.resolution_scale"]) > 0.05:
            self._upscale_stage = UpscaleStage(self)
            add_stage(self._upscale_stage)

    def _set_default_effect(self):
        """ Sets the default effect used for all objects if not overridden """
        self.set_effect(Globals.render, "effects/default.yaml", {}, -10)

    def _adjust_camera_settings(self):
        """ Sets the default camera settings """
        self._showbase.camLens.set_near_far(0.1, 70000)
        self._showbase.camLens.set_fov(60)
Пример #17
0
class RenderPipeline(RPObject):
    """ This is the main render pipeline class, it combines all components of
    the pipeline to form a working system. It does not do much work itself, but
    instead setups all the managers and systems to be able to do their work. """

    effect_class = Effect

    def __init__(self):
        """ Creates a new pipeline with a given showbase instance. This should
        be done before intializing the ShowBase, the pipeline will take care of
        that. If the showbase has been initialized before, have a look at
        the alternative initialization of the render pipeline (the first sample)."""
        RPObject.__init__(self)
        self._analyze_system()
        self.mount_mgr = MountManager(self)
        self.settings = {}
        self._applied_effects = []
        self._pre_showbase_initialized = False
        self._first_frame = None
        self.set_loading_screen_image(
            "/$$rp/rpcore/data/gui/loading_screen_bg.txo.pz")

    def load_settings(self, path):
        """ Loads the pipeline configuration from a given filename. Usually
        this is the 'config/pipeline.ini' file. If you call this more than once,
        only the settings of the last file will be used. """
        self.settings = load_yaml_file_flat(path)

    def reload_shaders(self):
        """ Reloads all shaders. This will reload the shaders of all plugins,
        as well as the pipelines internally used shaders. Because of the
        complexity of some shaders, this operation take might take several
        seconds. Also notice that all applied effects will be lost, and instead
        the default effect will be set on all elements again. Due to this fact,
        this method is primarly useful for fast iterations when developing new
        shaders. """
        if self.settings["pipeline.display_debugger"]:
            self.debug("Reloading shaders ..")
            self.debugger.error_msg_handler.clear_messages()
            self.debugger.set_reload_hint_visible(True)
            self._showbase.graphicsEngine.render_frame()
            self._showbase.graphicsEngine.render_frame()
        self.tag_mgr.cleanup_states()
        self.stage_mgr.reload_shaders()
        self.light_mgr.reload_shaders()
        self._set_default_effect()
        self.plugin_mgr.trigger_hook("shader_reload")
        if self.settings["pipeline.display_debugger"]:
            self.debugger.set_reload_hint_visible(False)
        self._apply_custom_shaders()

    def _apply_custom_shaders(self):
        """ Re-applies all custom shaders the user applied, to avoid them getting
        removed when the shaders are reloaded """
        self.debug("Re-applying", len(self._applied_effects), "custom shaders")
        for args in self._applied_effects:
            self._internal_set_effect(*args)

    def pre_showbase_init(self):
        """ Setups all required pipeline settings and configuration which have
        to be set before the showbase is setup. This is called by create(),
        in case the showbase was not initialized, however you can (and have to)
        call it manually before you init your custom showbase instance.
        See the 00-Loading the pipeline sample for more information. """
        if not self.mount_mgr.is_mounted:
            self.debug("Mount manager was not mounted, mounting now ...")
            self.mount_mgr.mount()

        if not self.settings:
            self.debug("No settings loaded, loading from default location")
            self.load_settings("/$$rp/config/pipeline.yaml")

        load_prc_file("/$$rp/config/panda3d-config.prc")
        self._pre_showbase_initialized = True

    def create(self, base=None):
        """ This creates the pipeline, and setups all buffers. It also
        constructs the showbase. The settings should have been loaded before
        calling this, and also the base and write path should have been
        initialized properly (see MountManager).

        If base is None, the showbase used in the RenderPipeline constructor
        will be used and initialized. Otherwise it is assumed that base is an
        initialized ShowBase object. In this case, you should call
        pre_showbase_init() before initializing the ShowBase"""

        start_time = time.time()
        self._init_showbase(base)

        if not self._showbase.win.gsg.supports_compute_shaders:
            self.fatal(
                "Sorry, your GPU does not support compute shaders! Make sure\n"
                "you have the latest drivers. If you already have, your gpu might\n"
                "be too old, or you might be using the open source drivers on linux."
            )

        self._init_globals()
        self.loading_screen.create()
        self._adjust_camera_settings()
        self._create_managers()
        self.plugin_mgr.load()
        self.daytime_mgr.load_settings()
        self.common_resources.write_config()
        self._init_debugger()

        self.plugin_mgr.trigger_hook("stage_setup")
        self.plugin_mgr.trigger_hook("post_stage_setup")

        self._create_common_defines()
        self._initialize_managers()
        self._create_default_skybox()

        self.plugin_mgr.trigger_hook("pipeline_created")

        self._listener = NetworkCommunication(self)
        self._set_default_effect()

        # Measure how long it took to initialize everything, and also store
        # when we finished, so we can measure how long it took to render the
        # first frame (where the shaders are actually compiled)
        init_duration = (time.time() - start_time)
        self._first_frame = time.process_time()
        self.debug(
            "Finished initialization in {:3.3f} s, first frame: {}".format(
                init_duration, Globals.clock.get_frame_count()))

    def set_loading_screen_image(self, image_source):
        """ Tells the pipeline to use the default loading screen, which consists
        of a simple loading image. The image source should be a fullscreen
        16:9 image, and not too small, to avoid being blurred out. """
        self.loading_screen = LoadingScreen(self, image_source)

    def add_light(self, light):
        """ Adds a new light to the rendered lights, check out the LightManager
        add_light documentation for further information. """
        self.light_mgr.add_light(light)

    def remove_light(self, light):
        """ Removes a previously attached light, check out the LightManager
        remove_light documentation for further information. """
        self.light_mgr.remove_light(light)

    def load_ies_profile(self, filename):
        """ Loads an IES profile from a given filename and returns a handle which
        can be used to set an ies profile on a light """
        return self.ies_loader.load(filename)

    def _internal_set_effect(self,
                             nodepath,
                             effect_src,
                             options=None,
                             sort=30):
        """ Sets an effect to the given object, using the specified options.
        Check out the effect documentation for more information about possible
        options and configurations. The object should be a nodepath, and the
        effect will be applied to that nodepath and all nodepaths below whose
        current effect sort is less than the new effect sort (passed by the
        sort parameter). """
        effect = self.effect_class.load(effect_src, options)
        if effect is None:
            return self.error("Could not apply effect")

        for i, stage in enumerate(self.effect_class._PASSES):
            if not effect.get_option("render_" + stage):
                nodepath.hide(self.tag_mgr.get_mask(stage))
            else:
                shader = effect.get_shader_obj(stage)
                if stage == "gbuffer":
                    nodepath.set_shader(shader, 25)
                else:
                    self.tag_mgr.apply_state(stage, nodepath, shader,
                                             str(effect.effect_id),
                                             25 + 10 * i + sort)
                nodepath.show_through(self.tag_mgr.get_mask(stage))

        if effect.get_option("render_gbuffer") and effect.get_option(
                "render_forward"):
            self.error(
                "You cannot render an object forward and deferred at the "
                "same time! Either use render_gbuffer or use render_forward, "
                "but not both.")

    def set_effect(self, nodepath, effect_src, options=None, sort=30):
        """ See _internal_set_effect. """
        args = (nodepath, effect_src, options, sort)
        self._applied_effects.append(args)
        self._internal_set_effect(*args)

    def add_environment_probe(self):
        """ Constructs a new environment probe and returns the handle, so that
        the probe can be modified. In case the env_probes plugin is not activated,
        this returns a dummy object which can be modified but has no impact. """
        if not self.plugin_mgr.is_plugin_enabled("env_probes"):
            self.warn(
                "env_probes plugin is not loaded - cannot add environment probe"
            )

            class DummyEnvironmentProbe(object):  # pylint: disable=too-few-public-methods
                def __getattr__(self, *args, **kwargs):
                    return lambda *args, **kwargs: None

            return DummyEnvironmentProbe()

        # Ugh ..
        from rpplugins.env_probes.environment_probe import EnvironmentProbe
        probe = EnvironmentProbe()
        self.plugin_mgr.instances["env_probes"].probe_mgr.add_probe(probe)
        return probe

    def prepare_scene(self, scene):
        """ Prepares a given scene, by converting panda lights to render pipeline
        lights. This also converts all empties with names starting with 'ENVPROBE'
        to environment probes. Conversion of blender to render pipeline lights
        is done by scaling their intensity by 100 to match lumens.

        Additionally, this finds all materials with the 'TRANSPARENT' shading
        model, and sets the proper effects on them to ensure they are rendered
        properly.

        This method also returns a dictionary with handles to all created
        objects, that is lights, environment probes, and transparent objects.
        This can be used to store them and process them later on, or delete
        them when a newer scene is loaded."""
        lights = []
        for light in scene.find_all_matches("**/+PointLight"):
            light_node = light.node()
            rp_light = PointLight()
            rp_light.pos = light.get_pos(Globals.base.render)
            rp_light.radius = light_node.max_distance
            rp_light.energy = 20.0 * light_node.color.w
            rp_light.color = light_node.color.xyz
            rp_light.casts_shadows = light_node.shadow_caster
            rp_light.shadow_map_resolution = light_node.shadow_buffer_size.x
            rp_light.inner_radius = 0.4

            self.add_light(rp_light)
            light.remove_node()
            lights.append(rp_light)

        for light in scene.find_all_matches("**/+Spotlight"):
            light_node = light.node()
            rp_light = SpotLight()
            rp_light.pos = light.get_pos(Globals.base.render)
            rp_light.radius = light_node.max_distance
            rp_light.energy = 20.0 * light_node.color.w
            rp_light.color = light_node.color.xyz
            rp_light.casts_shadows = light_node.shadow_caster
            rp_light.shadow_map_resolution = light_node.shadow_buffer_size.x
            rp_light.fov = light_node.exponent / math.pi * 180.0
            lpoint = light.get_mat(Globals.base.render).xform_vec((0, 0, -1))
            rp_light.direction = lpoint
            self.add_light(rp_light)
            light.remove_node()
            lights.append(rp_light)

        envprobes = []
        for np in scene.find_all_matches("**/ENVPROBE*"):
            probe = self.add_environment_probe()
            probe.set_mat(np.get_mat())
            probe.border_smoothness = 0.0001
            probe.parallax_correction = True
            np.remove_node()
            envprobes.append(probe)

        tristrips_warning_emitted = False
        transparent_objects = []
        for geom_np in scene.find_all_matches("**/+GeomNode"):
            geom_node = geom_np.node()
            geom_count = geom_node.get_num_geoms()
            for i in range(geom_count):
                state = geom_node.get_geom_state(i)
                geom = geom_node.get_geom(i)

                needs_conversion = False
                for prim in geom.get_primitives():
                    if isinstance(prim, GeomTristrips):
                        needs_conversion = True
                        if not tristrips_warning_emitted:
                            self.warn(
                                "At least one GeomNode (",
                                geom_node.get_name(),
                                "and possible more..) contains tristrips.")
                            self.warn(
                                "Due to a NVIDIA Driver bug, we have to convert them to triangles now."
                            )
                            self.warn(
                                "Consider exporting your models with the Bam Exporter to avoid this."
                            )
                            tristrips_warning_emitted = True
                            break

                if needs_conversion:
                    geom_node.modify_geom(i).decompose_in_place()

                if not state.has_attrib(MaterialAttrib):
                    self.warn("Geom", geom_node,
                              "has no material! Please fix this.")
                    continue

                material = state.get_attrib(MaterialAttrib).get_material()
                shading_model = material.emission.x

                # SHADING_MODEL_TRANSPARENT
                if shading_model == 3:
                    if geom_count > 1:
                        self.error(
                            "Transparent materials must be on their own geom!\n"
                            "If you are exporting from blender, split them into\n"
                            "seperate meshes, then re-export your scene. The\n"
                            "problematic mesh is: " + geom_np.get_name())
                        continue
                    self.set_effect(geom_np, "/$$rp/effects/default.yaml", {
                        "render_forward": True,
                        "render_gbuffer": False
                    }, 100)

        return {
            "lights": lights,
            "envprobes": envprobes,
            "transparent_objects": transparent_objects
        }

    def _create_managers(self):
        """ Internal method to create all managers and instances. This also
        initializes the commonly used render stages, which are always required,
        independently of which plugins are enabled. """
        self.task_scheduler = TaskScheduler(self)
        self.tag_mgr = TagStateManager(Globals.base.cam)
        self.plugin_mgr = PluginManager(self)
        self.stage_mgr = StageManager(self)
        self.light_mgr = LightManager(self)
        self.daytime_mgr = DayTimeManager(self)
        self.ies_loader = IESProfileLoader(self)
        self.common_resources = CommonResources(self)
        self._init_common_stages()

    def _analyze_system(self):
        """ Prints information about the system used, including information
        about the used Panda3D build. Also checks if the Panda3D build is out
        of date. """
        self.debug("Using Python {}.{} with architecture {}".format(
            sys.version_info.major, sys.version_info.minor,
            PandaSystem.get_platform()))
        self.debug("Using Panda3D {} built on {}".format(
            PandaSystem.get_version_string(), PandaSystem.get_build_date()))
        if PandaSystem.get_git_commit():
            self.debug("Using git commit {}".format(
                PandaSystem.get_git_commit()))
        else:
            self.debug("Using custom Panda3D build")
        if not self._check_version():
            self.fatal(
                "Your Panda3D version is outdated! Please update to the newest \n"
                "git version! Checkout https://github.com/panda3d/panda3d to "
                "compile panda from source, or get a recent buildbot build.")

    def _initialize_managers(self):
        """ Internal method to initialize all managers, after they have been
        created earlier in _create_managers. The creation and initialization
        is seperated due to the fact that plugins and various other subprocesses
        have to get initialized inbetween. """
        self.stage_mgr.setup()
        self.stage_mgr.reload_shaders()
        self.light_mgr.reload_shaders()
        self._init_bindings()
        self.light_mgr.init_shadows()

    def _init_debugger(self):
        """ Internal method to initialize the GUI-based debugger. In case debugging
        is disabled, this constructs a dummy debugger, which does nothing.
        The debugger itself handles the various onscreen components. """
        if self.settings["pipeline.display_debugger"]:
            self.debugger = Debugger(self)
        else:
            # Use an empty onscreen debugger in case the debugger is not
            # enabled, which defines all member functions as empty lambdas
            class EmptyDebugger(object):  # pylint: disable=too-few-public-methods
                def __getattr__(self, *args, **kwargs):
                    return lambda *args, **kwargs: None

            self.debugger = EmptyDebugger()  # pylint: disable=redefined-variable-type
            del EmptyDebugger

    def _init_globals(self):
        """ Inits all global bindings. This includes references to the global
        ShowBase instance, as well as the render resolution, the GUI font,
        and various global logging and output methods. """
        Globals.load(self._showbase)
        native_w, native_h = self._showbase.win.get_x_size(
        ), self._showbase.win.get_y_size()
        Globals.native_resolution = LVecBase2i(native_w, native_h)
        self._last_window_dims = LVecBase2i(Globals.native_resolution)
        self._compute_render_resolution()
        RenderTarget.RT_OUTPUT_FUNC = lambda *args: RPObject.global_warn(
            "RenderTarget", *args[1:])
        RenderTarget.USE_R11G11B10 = self.settings["pipeline.use_r11_g11_b10"]

    def _set_default_effect(self):
        """ Sets the default effect used for all objects if not overridden, this
        just calls set_effect with the default effect and options as parameters.
        This uses a very low sort, to make sure that overriding the default
        effect does not require a custom sort parameter to be passed. """
        self.set_effect(Globals.render, "/$$rp/effects/default.yaml", {}, -10)

    def _adjust_camera_settings(self):
        """ Sets the default camera settings, this includes the cameras
        near and far plane, as well as FoV. The reason for this is, that pandas
        default field of view is very small, and thus we increase it. """
        self._showbase.camLens.set_near_far(0.1, 70000)
        self._showbase.camLens.set_fov(40)

    def _compute_render_resolution(self):
        """ Computes the internally used render resolution. This might differ
        from the window dimensions in case a resolution scale is set. """
        scale_factor = self.settings["pipeline.resolution_scale"]
        w = int(float(Globals.native_resolution.x) * scale_factor)
        h = int(float(Globals.native_resolution.y) * scale_factor)
        # Make sure the resolution is a multiple of 4
        w, h = w - w % 4, h - h % 4
        self.debug("Render resolution is", w, "x", h)
        Globals.resolution = LVecBase2i(w, h)

    def _init_showbase(self, base):
        """ Inits the the given showbase object. This is part of an alternative
        method of initializing the showbase. In case base is None, a new
        ShowBase instance will be created and initialized. Otherwise base() is
        expected to either be an uninitialized ShowBase instance, or an
        initialized instance with pre_showbase_init() called inbefore. """
        if not base:
            self.pre_showbase_init()
            self._showbase = ShowBase()
        else:
            if not hasattr(base, "render"):
                self.pre_showbase_init()
                ShowBase.__init__(base)
            else:
                if not self._pre_showbase_initialized:
                    self.fatal(
                        "You constructed your own ShowBase object but you\n"
                        "did not call pre_show_base_init() on the render\n"
                        "pipeline object before! Checkout the 00-Loading the\n"
                        "pipeline sample to see how to initialize the RP.")
            self._showbase = base

        # Now that we have a showbase and a window, we can print out driver info
        self.debug("Driver Version =", self._showbase.win.gsg.driver_version)
        self.debug("Driver Vendor =", self._showbase.win.gsg.driver_vendor)
        self.debug("Driver Renderer =", self._showbase.win.gsg.driver_renderer)

    def _init_bindings(self):
        """ Internal method to init the tasks and keybindings. This constructs
        the tasks to be run on a per-frame basis. """
        self._showbase.addTask(self._manager_update_task,
                               "RP_UpdateManagers",
                               sort=10)
        self._showbase.addTask(self._plugin_pre_render_update,
                               "RP_Plugin_BeforeRender",
                               sort=12)
        self._showbase.addTask(self._plugin_post_render_update,
                               "RP_Plugin_AfterRender",
                               sort=15)
        self._showbase.addTask(self._update_inputs_and_stages,
                               "RP_UpdateInputsAndStages",
                               sort=18)
        self._showbase.taskMgr.doMethodLater(0.5, self._clear_state_cache,
                                             "RP_ClearStateCache")
        self._showbase.accept("window-event", self._handle_window_event)

    def _handle_window_event(self, event):
        """ Checks for window events. This mainly handles incoming resizes,
        and calls the required handlers """
        self._showbase.windowEvent(event)
        window_dims = LVecBase2i(self._showbase.win.get_x_size(),
                                 self._showbase.win.get_y_size())
        if window_dims != self._last_window_dims and window_dims != Globals.native_resolution:
            self._last_window_dims = LVecBase2i(window_dims)

            # Ensure the dimensions are a multiple of 4, and if not, correct it
            if window_dims.x % 4 != 0 or window_dims.y % 4 != 0:
                self.debug("Correcting non-multiple of 4 window size:",
                           window_dims)
                window_dims.x = window_dims.x - window_dims.x % 4
                window_dims.y = window_dims.y - window_dims.y % 4
                props = WindowProperties.size(window_dims.x, window_dims.y)
                self._showbase.win.request_properties(props)

            self.debug("Resizing to", window_dims.x, "x", window_dims.y)
            Globals.native_resolution = window_dims
            self._compute_render_resolution()
            self.light_mgr.compute_tile_size()
            self.stage_mgr.handle_window_resize()
            self.debugger.handle_window_resize()
            self.plugin_mgr.trigger_hook("window_resized")

    def _clear_state_cache(self, task=None):
        """ Task which repeatedly clears the state cache to avoid storing
        unused states. While running once a while, this task prevents over-polluting
        the state-cache with unused states. This complements Panda3D's internal
        state garbarge collector, which does a great job, but still cannot clear
        up all states. """
        task.delayTime = 2.0
        TransformState.clear_cache()
        RenderState.clear_cache()
        return task.again

    def _manager_update_task(self, task):
        """ Update task which gets called before the rendering, and updates
        all managers."""
        self.task_scheduler.step()
        self._listener.update()
        self.debugger.update()
        self.daytime_mgr.update()
        self.light_mgr.update()

        if Globals.clock.get_frame_count() == 10:
            self.debug("Hiding loading screen after 10 pre-rendered frames.")
            self.loading_screen.remove()

        return task.cont

    def _update_inputs_and_stages(self, task):
        """ Updates the commonly used inputs each frame. This is a seperate
        task to be able view detailed performance information in pstats, since
        a lot of matrix calculations are involved here. """
        self.common_resources.update()
        self.stage_mgr.update()
        return task.cont

    def _plugin_pre_render_update(self, task):
        """ Update task which gets called before the rendering, and updates the
        plugins. This is a seperate task to split the work, and be able to do
        better performance analysis in pstats later on. """
        self.plugin_mgr.trigger_hook("pre_render_update")
        return task.cont

    def _plugin_post_render_update(self, task):
        """ Update task which gets called after the rendering, and should cleanup
        all unused states and objects. This also triggers the plugin post-render
        update hook. """
        self.plugin_mgr.trigger_hook("post_render_update")
        if self._first_frame is not None:
            duration = time.process_time() - self._first_frame
            self.debug("Took", round(duration, 3), "s until first frame")
            self._first_frame = None
        return task.cont

    def _create_common_defines(self):
        """ Creates commonly used defines for the shader configuration. """
        defines = self.stage_mgr.defines
        defines["CAMERA_NEAR"] = round(Globals.base.camLens.get_near(), 10)
        defines["CAMERA_FAR"] = round(Globals.base.camLens.get_far(), 10)

        # Work arround buggy nvidia driver, which expects arrays to be const
        if "NVIDIA 361.43" in self._showbase.win.gsg.get_driver_version():
            defines["CONST_ARRAY"] = "const"
        else:
            defines["CONST_ARRAY"] = ""

        # Provide driver vendor as a define
        vendor = self._showbase.win.gsg.get_driver_vendor().lower()
        defines["IS_NVIDIA"] = "nvidia" in vendor
        defines["IS_AMD"] = vendor.startswith("ati")
        defines["IS_INTEL"] = "intel" in vendor

        defines["REFERENCE_MODE"] = self.settings["pipeline.reference_mode"]
        self.light_mgr.init_defines()
        self.plugin_mgr.init_defines()

    def _create_default_skybox(self, size=40000):
        """ Returns the default skybox, with a scale of <size>, and all
        proper effects and shaders already applied. The skybox is already
        parented to render as well. """
        skybox = self.common_resources.load_default_skybox()
        skybox.set_scale(size)
        skybox.reparent_to(Globals.render)
        skybox.set_bin("unsorted", 10000)
        self.set_effect(
            skybox, "/$$rp/effects/skybox.yaml", {
                "render_shadow": False,
                "render_envmap": False,
                "render_voxelize": False,
                "alpha_testing": False,
                "normal_mapping": False,
                "parallax_mapping": False
            }, 1000)
        return skybox

    def _check_version(self):
        """ Internal method to check if the required Panda3D version is met. Returns
        True if the version is new enough, and False if the version is outdated. """
        from panda3d.core import Texture
        if not hasattr(Texture, "F_r16i"):
            return False
        return True

    def _init_common_stages(self):
        """ Inits the commonly used stages, which don't belong to any plugin,
        but yet are necessary and widely used. """
        add_stage = self.stage_mgr.add_stage
        self._ambient_stage = AmbientStage(self)
        add_stage(self._ambient_stage)
        self._gbuffer_stage = GBufferStage(self)
        add_stage(self._gbuffer_stage)
        self._final_stage = FinalStage(self)
        add_stage(self._final_stage)
        self._downscale_stage = DownscaleZStage(self)
        add_stage(self._downscale_stage)
        self._combine_velocity_stage = CombineVelocityStage(self)
        add_stage(self._combine_velocity_stage)

        # Add an upscale/downscale stage in case we render at a different resolution
        if abs(1 - self.settings["pipeline.resolution_scale"]) > 0.005:
            self._upscale_stage = UpscaleStage(self)
            add_stage(self._upscale_stage)

    def _get_serialized_material_name(self, material, index=0):
        """ Returns a serializable material name """
        return str(index) + "-" + (material.get_name().replace(
            " ", "").strip() or "unnamed")

    def export_materials(self, pth):
        """ Exports a list of all materials found in the current scene in a
        serialized format to the given path """

        with open(pth, "w") as handle:
            for i, material in enumerate(Globals.render.find_all_materials()):
                if not material.has_base_color() or not material.has_roughness(
                ) or not material.has_refractive_index():
                    print("Skipping non-pbr material:", material.name)
                    continue

                handle.write(("{} " * 11).format(
                    self._get_serialized_material_name(material, i),
                    material.base_color.x,
                    material.base_color.y,
                    material.base_color.z,
                    material.roughness,
                    material.refractive_index,
                    material.metallic,
                    material.emission.x,  # shading model
                    material.emission.y,  # normal strength
                    material.emission.z,  # arbitrary 0
                    material.emission.w,  # arbitrary 1
                ) + "\n")

    def update_serialized_material(self, data):
        """ Internal method to update a material from a given serialized material """
        name = data[0]

        for i, material in enumerate(Globals.render.find_all_materials()):
            if self._get_serialized_material_name(material, i) == name:
                material.set_base_color(
                    Vec4(float(data[1]), float(data[2]), float(data[3]), 1.0))
                material.set_roughness(float(data[4]))
                material.set_refractive_index(float(data[5]))
                material.set_metallic(float(data[6]))
                material.set_emission(
                    Vec4(
                        float(data[7]),
                        float(data[8]),
                        float(data[9]),
                        float(data[10]),
                    ))

        RenderState.clear_cache()
Пример #18
0
    # Extract data
    print("Extracting data ..")
    lines = data.replace("\r", "").split("\n")[1:]

    # Load render pipeline api
    print("Loading plugin api ..")
    sys.path.insert(0, "../../")
    from rpcore.pluginbase.manager import PluginManager
    from rpcore.mount_manager import MountManager


    mount_mgr = MountManager(None)
    mount_mgr.mount()

    plugin_mgr = PluginManager(None)
    plugin_mgr.load()

    convert_to_linear = plugin_mgr.day_settings["scattering"]["sun_intensity"].get_linear_value

    hour, minutes = 0, 0

    data_points_azimuth = []
    data_points_altitude = []
    data_points_intensity = []

    for line in lines:
        if not line:
            break
        date, time, azim_angle, declination, ascension, elevation = line.split(",")