Esempio n. 1
0
def init(base):
    config = pman.get_config()
    if not pman.is_frozen() and base.appRunner is None and config.getboolean('run', 'auto_build'):
        pman.build(config)

    # Add export directory to model path
    exportdir = pman.get_abs_path(config, config.get('build', 'export_dir'))
    exportdir = p3d.Filename.from_os_specific(exportdir)
    p3d.get_model_path().prepend_directory(exportdir)

    base._bpbase = BPBase(base, config)
Esempio n. 2
0
def init(base):
    config = pman.get_config()
    if base.appRunner is None and config.getboolean('run', 'auto_build'):
        pman.build(config)

    # Add export directory to model path
    exportdir = pman.get_abs_path(config, config.get('build', 'export_dir'))
    exportdir = p3d.Filename.from_os_specific(exportdir)
    p3d.get_model_path().prepend_directory(exportdir)

    base._bpbase = BPBase(base, config)
Esempio n. 3
0
    def __init__(self):
        super().__init__()
        # we are running from a sub directory
        # but we still want to load the models/textures without the extra '../'
        # so we put the up directory on the model path
        p3d.get_model_path().append_directory('..')

        self.disable_mouse()
        self.set_background_color(0.0, 0.0, 0.0)
        self.render.set_shader_auto()
        self.render.set_antialias(M_MSAA)
Esempio n. 4
0
def init(base):
    config = pman.get_config()
    if not pman.is_frozen(
    ) and base.appRunner is None and config['run']['auto_build']:
        pman.build(config)

    # Add export directory to model path
    exportdir = pman.get_abs_path(config, config['build']['export_dir'])
    maindir = os.path.dirname(
        pman.get_abs_path(config, config['run']['main_file']))
    if pman.is_frozen():
        exportdir = os.path.relpath(exportdir, maindir)
    exportdir = p3d.Filename.from_os_specific(exportdir)
    p3d.get_model_path().prepend_directory(exportdir)
Esempio n. 5
0
def init(base):
    config = pman.get_config()
    if not pman.is_frozen() and base.appRunner is None and config.getboolean('run', 'auto_build'):
        pman.build(config)

    # Add export directory to model path
    exportdir = pman.get_abs_path(config, config.get('build', 'export_dir'))
    maindir = os.path.dirname(pman.get_abs_path(config, config.get('run', 'main_file')))
    if pman.is_frozen():
        exportdir = os.path.relpath(exportdir, maindir)
    exportdir = p3d.Filename.from_os_specific(exportdir)
    p3d.get_model_path().prepend_directory(exportdir)

    base._bpbase = BPBase(base, config)
Esempio n. 6
0
def init(_base):
    assetdir_rel = p3d.Filename('assets')
    config = None

    if not pman.is_frozen():
        config = pman.get_config()
        if config['run']['auto_build']:
            pman.build(config)
        assetdir_rel = p3d.Filename.from_os_specific(
            config['build']['export_dir'])

    # Add assets directory to model path
    assetdir = p3d.Filename(p3d.Filename.expand_from('$MAIN_DIR'),
                            assetdir_rel)
    p3d.get_model_path().prepend_directory(assetdir)
Esempio n. 7
0
def main():
    args = parse_args()

    if args.frames:
        animations_frames = map(int, args.frames.split(','))
    else:
        animations_frames = [len(args.input)]

    kwargs = {}
    if args.fps:
        kwargs['fps'] = args.fps
    if args.scale:
        kwargs['scale'] = args.scale
    if args.type:
        kwargs['type'] = args.type
    if args.empty:
        kwargs['empty'] = args.empty
    if args.prefix:
        kwargs['prefix'] = args.prefix

    if args.prefix:
        vfs = VirtualFileSystem.get_global_ptr()
        vfs.mount(
            Filename.from_os_specific('.').get_fullpath(),
            args.prefix.rstrip('/'), 0)
        mp = get_model_path()
        mp.prepend_directory(args.prefix.rstrip('/'))

    cm = CardMaker(animations_frames, args.input, **kwargs)
    cm.make(args.output)
Esempio n. 8
0
    def __resolve_vfs_relative_path(self,
                                    file_path,
                                    okMissing=False,
                                    file_type=''):
        """
        Resolves a file path to a VFS relative Filename object
        for use in resource loading
        """

        if not isinstance(file_path, core.Filename):
            file_name = core.Filename(file_path)
        else:
            file_name = file_path

        vfs = core.VirtualFileSystem.get_global_ptr()
        search_path = core.get_model_path().get_value()

        # Verify the file exists
        found = vfs.resolve_filename(file_name, search_path)
        if not found:
            # Notify the user
            message = 'Failed to load %s file: %s' % (file_type,
                                                      file_name.c_str())
            sprite_notify.warning('Search Path: %s' %
                                  str(search_path.get_directories()))

            if not okMissing:
                sprite_notify.error(message)
            else:
                sprite_notify.warning(message)

            return None

        return file_name
Esempio n. 9
0
    def load(self, filename):
        """ Loads a profile from a given filename """

        # Make filename unique

        fname = Filename.from_os_specific(filename)
        if not VirtualFileSystem.get_global_ptr().resolve_filename(fname, get_model_path().get_value(), "ies"):
            self.error("Could not resolve", filename)
            return -1
        fname = fname.get_fullpath()

        # Check for cache entries
        if fname in self._entries:
            return self._entries.index(fname)

        # Check for out of bounds
        if len(self._entries) >= self._max_entries:
            # TODO: Could remove unused profiles here or regenerate texture
            self.warn("Cannot load IES Profile, too many loaded! (Maximum: 32)")

        # Try loading the dataset, and see what happes
        try:
            dataset = self._loader.load(fname)
        except IESLoaderException as msg:
            self.warn("Failed to load profile from", filename, ":", msg)
            return -1

        if not dataset:
            return -1

        # Dataset was loaded successfully, now copy it
        dataset.generate_dataset_texture_into(self._storage_tex, len(self._entries))
        self._entries.append(fname)

        return len(self._entries) - 1
Esempio n. 10
0
def append_subdirectories_to_search(root_dir: str,
                                    mount_root: bool = True) -> None:
    """
    Walks through a root directory and mounts all subdirectorys
    to the search path. Generally used for development
    source version of an application or servers.
    """

    model_path = get_model_path()
    folders = [
        os.path.join(root_dir, o) for o in os.listdir(root_dir)
        if os.path.isdir(os.path.join(root_dir, o))
    ]
    if mount_root:
        if not root_dir.endswith('/'):
            root_dir += '/'
        folders.append(root_dir)

    for folder in folders:

        # Ignore invalid folders
        base_name = os.path.basename(folder)
        if base_name.startswith('.'):
            continue

        folder = Filename.from_os_specific(os.path.abspath(folder))
        __file_notify.debug('Mounting (%s) to search path' % (folder))
        model_path.append_directory(folder)
Esempio n. 11
0
def vfs_mount_directory(mount_point: str, directory: str) -> bool:
    """
    Mounts the directory to the requested mount point.
    Returning the result of the mounting operation
    """

    result = _vfs.mount(Filename(directory), Filename(mount_point),
                        VirtualFileSystem.MF_read_only)

    if not result:
        __file_notify.warning('Failed to mount directory (%s) to (%s)!' %
                              (directory, mount_point))

    get_model_path().append_directory(directory)
    switch_file_functions_to_vfs()
    return result
Esempio n. 12
0
def vfs_mount_url(mount_point: str, url: str) -> bool:
    """
    Mounts a http directory to the requested mount point.
    Returning the result of the mounting operation. Best used with
    CDN or download like servers
    """

    m = VirtualFileMountHTTP('%s%s' % (url, mount_point))
    __file_notify.info('Mounting remote directory (%s) to (%s)' %
                       (url, mount_point))
    result = _vfs.mount(m, mount_point, VirtualFileSystem.MFReadOnly)
    if not result:
        __file_notify.warning('Failed to mount url (%s) to (%s)!' %
                              (url, mount_point))

    get_model_path().append_directory(mount_point)
    switch_file_functions_to_vfs()
    return result
Esempio n. 13
0
    def __init__(self, scene_root_np, render_np):
        # Setup model path so shaders can be loaded
        fafnir_dir = os.path.dirname(os.path.realpath(__file__))
        p3d.get_model_path().prepend_directory(fafnir_dir)

        self.data = DataManager(scene_root_np, render_np)

        # Setup stages
        self.stages = [
            StageGather(self.data),
            StageDraw(self.data),
        ]
        self.enable_stages(2)
        self.enable_debug_bindings()

        # Hook into task manager
        def task_update(task):
            self.update()
            return task.cont
        taskMgr.add(task_update, 'Fafnir update')
Esempio n. 14
0
def get_search_path() -> DSearchPath:
    """
    Returns the configured panda3d model search path
    """

    search_path = get_model_path().value
    search_path.append_directory('.')

    return search_path


#----------------------------------------------------------------------------------------------------------------------------------#
Esempio n. 15
0
    def execute(self, context):
        import panda3d.core as p3d

        blender_converter = BTFConverter()
        panda_converter = converter.Converter()

        # Setup model path to find textures
        p3d.get_model_path().clear()
        p3d.get_model_path().prepend_directory(os.path.dirname(bpy.data.filepath))

        def convert_cb(data):
            panda_converter.update(data, writing_bam=True)
            #panda_converter.active_scene.ls()

            # Copy images
            for img in data.get('images', {}).values():
                src = os.path.join(os.path.dirname(bpy.data.filepath), img['uri'])
                dst = os.path.dirname(self.filepath)
                print('Copying image from "{}" to "{}"'.format(src, dst))
                shutil.copy(src, dst)

        blender_converter.convert(*self._collect_deltas(), callback=convert_cb)

        panda_converter.active_scene.write_bam_file(self.filepath)

        # Clean up the model path
        p3d.get_model_path().clear()
        return {'FINISHED'}
Esempio n. 16
0
def vfs_mount_multifile(mount_point: str, multifile: str) -> bool:
    """
    Mounts the multifile to the requested mount point
    if it exists. Returning the result of the mounting
    operation
    """

    if not os_path_exists(multifile):
        return False

    m = Multifile()
    m.openReadWrite(multifile)

    __file_notify.info('Mounting MF "%s" at "%s"' % (multifile, mount_point))
    result = _vfs.mount(m, mount_point, VirtualFileSystem.MFReadOnly)
    if not result:
        __file_notify.warning('Failed to mount multifile (%s) to (%s)!' %
                              (multifile, mount_point))

    get_model_path().append_directory(mount_point)
    switch_file_functions_to_vfs()
    return result
Esempio n. 17
0
def main():
    try:
        options = parameters.get_parameters()
        core.load_prc_file_data("", "sync-video #f")
        core.load_prc_file_data("", "show-frame-rate-meter #t")
        core.load_prc_file_data("", "disable-message-loop #t")
        core.load_prc_file_data("", "audio-library-name p3openal_audio")
        core.load_prc_file_data("", "tk-frame-rate 1000")
        if options.performance_stats:
            core.load_prc_file_data("", "want-pstats 1")
        if options.direct_tools:
            raise NotImplementedError()
            # core.load_prc_file_data('', 'want-tk #t')
            # core.load_prc_file_data('', 'want-directtools #t')

        working_directory = pathlib.Path.cwd()
        drive_letter = None
        if working_directory.drive:
            drive_letter = working_directory.drive[0].lower()
            working_directory = pathlib.Path(f"/{drive_letter}",
                                             *working_directory.parts[1:])
        working_directory = working_directory.as_posix()
        core.get_model_path().append_directory(working_directory)

        if constants.DEBUG:
            log_level = logging.DEBUG
        else:
            log_level = logging.INFO

        logging.basicConfig(
            level=log_level,
            format="%(asctime)s [%(levelname)s] %(message)s",
            handlers=[logging.StreamHandler()],
        )

        app = bloom_app.Bloom(options.map_path)
        app.run()
    except Exception as error:
        print(f"Error running application: {error}")
Esempio n. 18
0
    def __init__(self):
        if len(sys.argv) < 2:
            print("Missing input file")
            sys.exit(1)

        super().__init__()

        simplepbr.init()

        gltf.patch_loader(self.loader)

        infile = p3d.Filename.from_os_specific(os.path.abspath(sys.argv[1]))
        p3d.get_model_path().prepend_directory(infile.get_dirname())

        self.model_root = self.loader.load_model(infile, noCache=True)

        self.accept('escape', sys.exit)
        self.accept('q', sys.exit)
        self.accept('w', self.toggle_wireframe)
        self.accept('t', self.toggle_texture)
        self.accept('shift-l', self.model_root.ls)
        self.accept('shift-a', self.model_root.analyze)

        if not self.model_root.find('**/+Light'):
            self.light = self.render.attach_new_node(p3d.PointLight('light'))
            self.light.set_pos(-5, 5, 5)
            self.render.set_light(self.light)

        self.cam.set_pos(-6, 6, 6)
        self.cam.look_at(self.model_root)

        self.model_root.reparent_to(self.render)

        if self.model_root.find('**/+Character'):
            self.anims = p3d.AnimControlCollection()
            p3d.autoBind(self.model_root.node(), self.anims, ~0)
            if self.anims.get_num_anims() > 0:
                self.anims.get_anim(0).loop(True)
Esempio n. 19
0
    def reset(self, workingdir):
        self.bg = p3d.LVector4(0.0, 0.0, 0.0, 1.0)

        p3d.get_model_path().clear()
        pman_conf = None

        if workingdir:
            p3d.get_model_path().prepend_directory(workingdir)
            try:
                pman_conf = pman.get_config(workingdir)
            except pman.NoConfigError:
                pass

        if self.converter is not None:

            self.converter.active_scene.remove_node()
        self.converter = converter.Converter()

        if self.render is not None:
            self.render.remove_node
        self.render = p3d.NodePath('render')

        self.render_manager = rendermanager.create_render_manager(self, pman_conf)
Esempio n. 20
0
    def __init__(self):
        if len(sys.argv) < 2:
            print("Missing input file")
            sys.exit(1)

        super().__init__()

        self.setup_shaders(self.render)

        gltf.patch_loader(self.loader)

        infile = p3d.Filename.from_os_specific(os.path.abspath(sys.argv[1]))
        p3d.get_model_path().prepend_directory(infile.get_dirname())

        self.model_root = self.loader.load_model(infile)

        self.accept('escape', sys.exit)
        self.accept('q', sys.exit)


        self.light = self.render.attach_new_node(p3d.PointLight('light'))
        self.light.set_pos(-5, 5, 5)
        self.render.set_light(self.light)

        self.cam.set_pos(-10, 10, 10)

        if self.model_root.find('**/+Character'):
            self.actor = Actor(self.model_root)
            self.actor.reparent_to(self.render)
            anims = self.actor.get_anim_names()
            if anims:
                self.actor.loop(anims[0])
            self.cam.look_at(self.actor)
        else:
            self.model_root.reparent_to(self.render)
            self.cam.look_at(self.model_root)
Esempio n. 21
0
 def __init__(self, mdt, model_path, antialiasing):
     Gfx.__init__(self, mdt)
     get_model_path().append_directory(model_path)
     if base.appRunner:
         root_dir = base.appRunner.p3dFilename.get_dirname()
         get_model_path().append_directory(root_dir + '/' + model_path)
         get_model_path().append_directory(root_dir)
     mdt.base.enableParticles()
     render.set_shader_auto()
     render.set_two_sided(True)
     if antialiasing:
         render.set_antialias(AntialiasAttrib.MAuto)
     self.root = None
Esempio n. 22
0
    def load(self, filename):
        """ Loads a profile from a given filename and returns the internal
        used index which can be assigned to a light."""

        # Make sure the user can load profiles directly from the ies profile folder
        data_path = join("/$$rp/rpcore/data/ies_profiles/", filename)
        if isfile(data_path):
            filename = data_path

        # Make filename unique
        fname = Filename.from_os_specific(filename)
        if not VirtualFileSystem.get_global_ptr().resolve_filename(
                fname,
                get_model_path().get_value(), "ies"):
            self.error("Could not resolve", filename)
            return -1
        fname = fname.get_fullpath()

        # Check for cache entries
        if fname in self._entries:
            return self._entries.index(fname)

        # Check for out of bounds
        if len(self._entries) >= self._max_entries:
            # TODO: Could remove unused profiles here or regenerate texture
            self.warn(
                "Cannot load IES Profile, too many loaded! (Maximum: 32)")

        # Try loading the dataset, and see what happes
        try:
            dataset = self._load_and_parse_file(fname)
        except InvalidIESProfileException as msg:
            self.warn("Failed to load profile from", filename, ":", msg)
            return -1

        if not dataset:
            return -1

        # Dataset was loaded successfully, now copy it
        dataset.generate_dataset_texture_into(self._storage_tex,
                                              len(self._entries))
        self._entries.append(fname)

        return len(self._entries) - 1
    def load(self, filename):
        """ Loads a profile from a given filename and returns the internal
        used index which can be assigned to a light."""

        # Make sure the user can load profiles directly from the ies profile folder
        data_path = join("/$$rp/data/ies_profiles/", filename)
        if isfile(data_path):
            filename = data_path

        # Make filename unique
        fname = Filename.from_os_specific(filename)
        if not VirtualFileSystem.get_global_ptr().resolve_filename(
                fname, get_model_path().get_value(), "ies"):
            self.error("Could not resolve", filename)
            return -1
        fname = fname.get_fullpath()

        # Check for cache entries
        if fname in self._entries:
            return self._entries.index(fname)

        # Check for out of bounds
        if len(self._entries) >= self._max_entries:
            # TODO: Could remove unused profiles here or regenerate texture
            self.warn("Cannot load IES Profile, too many loaded! (Maximum: 32)")

        # Try loading the dataset, and see what happes
        try:
            dataset = self._load_and_parse_file(fname)
        except InvalidIESProfileException as msg:
            self.warn("Failed to load profile from", filename, ":", msg)
            return -1

        if not dataset:
            return -1

        # Dataset was loaded successfully, now copy it
        dataset.generate_dataset_texture_into(self._storage_tex, len(self._entries))
        self._entries.append(fname)

        return len(self._entries) - 1
    def mount(self):
        """ Inits the VFS Mounts. This creates the following virtual directory
        structure, from which all files can be located:

        /$$rp/  (Mounted from the render pipeline base directory)
           + config/
           + data/
           + rpcore/
           + shader/
           + ...

        /$$rptemp/ (Either ramdisk or user specified)
            + day_time_config
            + shader_auto_config
            + ...

         """
        self.debug("Setting up virtual filesystem")
        self._mounted = True

        def convert_path(pth):
            return Filename.from_os_specific(pth).get_fullpath()

        vfs = VirtualFileSystem.get_global_ptr()

        # Mount the pipeline temp path:
        # If no write path is specified, use a virtual ramdisk
        if self._write_path is None:
            self.debug("Mounting ramdisk as /$$rptemp")
            vfs.mount(VirtualFileMountRamdisk(), "/$$rptemp", 0)
        else:
            # In case an actual write path is specified:
            # Ensure the pipeline write path exists, and if not, create it
            if not isdir(self._write_path):
                self.debug(
                    "Creating temporary path, since it does not exist yet")
                try:
                    os.makedirs(self._write_path)
                except IOError as msg:
                    self.fatal("Failed to create temporary path:", msg)
            self.debug("Mounting", self._write_path, "as /$$rptemp")
            vfs.mount(convert_path(self._write_path), '/$$rptemp', 0)

        get_model_path().prepend_directory("/$$rp")
        get_model_path().prepend_directory("/$$rp/shader")
        get_model_path().prepend_directory("/$$rptemp")
Esempio n. 25
0
    def mount(self):
        """ Inits the VFS Mounts. This creates the following virtual directory
        structure, from which all files can be located:

        /$$rp/  (Mounted from the render pipeline base directory)
           + rpcore/
           + shader/
           + ...

        /$rpconfig/ (Mounted from config/, may be set by user)
           + pipeline.yaml
           + ...

        /$$rptemp/ (Either ramdisk or user specified)
            + day_time_config
            + shader_auto_config
            + ...

        /$$rpshader/ (Link to /$$rp/rpcore/shader)

         """
        self.debug("Setting up virtual filesystem")
        self._mounted = True

        def convert_path(pth):
            return Filename.from_os_specific(pth).get_fullpath()
        vfs = VirtualFileSystem.get_global_ptr()

        # Mount config dir as $$rpconf
        if self._config_dir is None:
            config_dir = convert_path(join(self._base_path, "config/"))
            self.debug("Mounting auto-detected config dir:", config_dir)
            vfs.mount(config_dir, "/$$rpconfig", 0)
        else:
            self.debug("Mounting custom config dir:", self._config_dir)
            vfs.mount(convert_path(self._config_dir), "/$$rpconfig", 0)

        # Mount directory structure
        vfs.mount(convert_path(self._base_path), "/$$rp", 0)
        vfs.mount(convert_path(join(self._base_path, "rpcore/shader")), "/$$rp/shader", 0)
        vfs.mount(convert_path(join(self._base_path, "effects")), "effects", 0)

        # Mount the pipeline temp path:
        # If no write path is specified, use a virtual ramdisk
        if self._write_path is None:
            self.debug("Mounting ramdisk as /$$rptemp")
            vfs.mount(VirtualFileMountRamdisk(), "/$$rptemp", 0)
        else:
            # In case an actual write path is specified:
            # Ensure the pipeline write path exists, and if not, create it
            if not isdir(self._write_path):
                self.debug("Creating temporary path, since it does not exist yet")
                try:
                    os.makedirs(self._write_path)
                except IOError as msg:
                    self.fatal("Failed to create temporary path:", msg)
            self.debug("Mounting", self._write_path, "as /$$rptemp")
            vfs.mount(convert_path(self._write_path), '/$$rptemp', 0)

        get_model_path().prepend_directory("/$$rp")
        get_model_path().prepend_directory("/$$rp/shader")
        get_model_path().prepend_directory("/$$rptemp")
Esempio n. 26
0
    def mount(self):
        """ Inits the VFS Mounts. This creates the following virtual directory
        structure, from which all files can be located:

        /$$rp/  (Mounted from the render pipeline base directory)
           + rpcore/
           + shader/
           + ...

        /$rpconfig/ (Mounted from config/, may be set by user)
           + pipeline.yaml
           + ...

        /$$rptemp/ (Either ramdisk or user specified)
            + day_time_config
            + shader_auto_config
            + ...

        /$$rpshader/ (Link to /$$rp/rpcore/shader)

         """
        self.debug("Setting up virtual filesystem")
        self._mounted = True

        convert_path = lambda pth: Filename.from_os_specific(pth).get_fullpath(
        )
        vfs = VirtualFileSystem.get_global_ptr()

        # Mount config dir as $$rpconf
        if self._config_dir is None:
            config_dir = convert_path(join(self._base_path, "config/"))
            self.debug("Mounting auto-detected config dir:", config_dir)
            vfs.mount(config_dir, "/$$rpconfig", 0)
        else:
            self.debug("Mounting custom config dir:", self._config_dir)
            vfs.mount(convert_path(self._config_dir), "/$$rpconfig", 0)

        # Mount directory structure
        vfs.mount(convert_path(self._base_path), "/$$rp", 0)
        vfs.mount(convert_path(join(self._base_path, "rpcore/shader")),
                  "/$$rp/shader", 0)
        vfs.mount(convert_path(join(self._base_path, "effects")), "effects", 0)

        # Mount the pipeline temp path:
        # If no write path is specified, use a virtual ramdisk
        if self._write_path is None:
            self.debug("Mounting ramdisk as /$$rptemp")
            vfs.mount(VirtualFileMountRamdisk(), "/$$rptemp", 0)
        else:
            # In case an actual write path is specified:
            # Ensure the pipeline write path exists, and if not, create it
            if not isdir(self._write_path):
                self.debug(
                    "Creating temporary path, since it does not exist yet")
                try:
                    os.makedirs(self._write_path)
                except IOError as msg:
                    self.fatal("Failed to create temporary path:", msg)
            self.debug("Mounting", self._write_path, "as /$$rptemp")
            vfs.mount(convert_path(self._write_path), '/$$rptemp', 0)

        get_model_path().prepend_directory("/$$rp")
        get_model_path().prepend_directory("/$$rp/shader")
        get_model_path().prepend_directory("/$$rptemp")
Esempio n. 27
0
    def __init__(self, workingdir, conn_addr):
        ShowBase.__init__(self)
        self.view_lens = p3d.MatrixLens()
        self.cam = p3d.NodePath(p3d.Camera('view'))
        self.cam.node().set_lens(self.view_lens)
        self.cam.node().set_active(True)
        self.cam.reparent_to(self.render)

        self.pipe = p3d.GraphicsPipeSelection.get_global_ptr().make_module_pipe('pandagl')

        self.bg_color = p3d.LVecBase4(0.0, 0.0, 0.0, 1.0)

        p3d.get_model_path().prepend_directory(workingdir)
        self.workingdir = workingdir

        self.texture = p3d.Texture()
        self.win = None
        self.renderer = None
        self.make_offscreen(1, 1)

        self.disableMouse()
        self.setFrameRateMeter(True)

        self.image_width = 1
        self.image_height = 1
        self.image_data = struct.pack('=BBB', 0, 0, 0)

        self.scene = self.render.attach_new_node(p3d.PandaNode("Empty Scene"))

        self.connection = BlenderConnection(conn_addr)

        def set_bg_clear_color(task):
            # Keep bg color working even if DisplayRegions get switched around
            # (e.g., from FilterManager)
            for win in self.graphicsEngine.windows:
                for dispregion in win.display_regions:
                    if dispregion.get_camera() == self.cam:
                        dispregion.set_clear_color_active(True)
                        dispregion.set_clear_color(self.bg_color)
            return task.cont
        self.taskMgr.add(set_bg_clear_color, 'Set BG Clear Color')

        def do_updates(task):
            if not self.connection.running:
                sys.exit()

            latest_scene_update = None
            for update in self.connection.get_updates():
                # print('update: {}'.format(update))
                update_type = update['type']
                if update_type == 'view':
                    self.update_view(
                        update['width'],
                        update['height'],
                        self.load_matrix(update['projection_matrix']),
                        self.load_matrix(update['view_matrix']),
                    )
                elif update_type == 'scene':
                    latest_scene_update = update
                elif update_type == 'background_color':
                    self.bg_color = p3d.LVector4(*update['color'])
                else:
                    raise RuntimeError('Unknown update type: {}'.format(update_type))

            if latest_scene_update is not None:
                self.update_scene(latest_scene_update['path'])

            return task.cont
        self.taskMgr.add(do_updates, 'Updates')

        def image_updates(task):
            if self.texture.has_ram_image():
                #start = time.perf_counter()
                self.connection.send_image(
                    self.texture.get_x_size(),
                    self.texture.get_y_size(),
                    memoryview(self.texture.get_ram_image_as('BGR'))
                )
                #print('Extern: Updated image data in {}ms'.format((time.perf_counter() - start) * 1000))
            return task.cont
        self.taskMgr.add(image_updates, 'Upload Images')
Esempio n. 28
0
    def __init__(self, workingdir, conn_addr):
        ShowBase.__init__(self)
        self.view_lens = p3d.MatrixLens()
        self.cam = p3d.NodePath(p3d.Camera('view'))
        self.cam.node().set_lens(self.view_lens)
        self.cam.node().set_active(True)
        self.cam.reparent_to(self.render)

        self.pipe = p3d.GraphicsPipeSelection.get_global_ptr().make_module_pipe('pandagl')

        self.bg_color = p3d.LVecBase4(0.0, 0.0, 0.0, 1.0)

        p3d.get_model_path().prepend_directory(workingdir)
        self.workingdir = workingdir

        self.texture = p3d.Texture()
        self.win = None
        self.renderer = None
        self.make_offscreen(1, 1)

        self.disableMouse()
        self.setFrameRateMeter(True)

        self.image_width = 1
        self.image_height = 1
        self.image_data = struct.pack('=BBB', 0, 0, 0)

        self.scene = self.render.attach_new_node(p3d.PandaNode("Empty Scene"))

        self.connection = BlenderConnection(conn_addr)

        def set_bg_clear_color(task):
            # Keep bg color working even if DisplayRegions get switched around
            # (e.g., from FilterManager)
            for win in self.graphicsEngine.windows:
                for dispregion in win.display_regions:
                    if dispregion.get_camera() == self.cam:
                        dispregion.set_clear_color_active(True)
                        dispregion.set_clear_color(self.bg_color)
            return task.cont
        self.taskMgr.add(set_bg_clear_color, 'Set BG Clear Color')

        def do_updates(task):
            if not self.connection.running:
                sys.exit()

            latest_scene_update = None
            for update in self.connection.get_updates():
                # print('update: {}'.format(update))
                update_type = update['type']
                if update_type == 'view':
                    self.update_view(
                        update['width'],
                        update['height'],
                        self.load_matrix(update['projection_matrix']),
                        self.load_matrix(update['view_matrix']),
                    )
                elif update_type == 'scene':
                    latest_scene_update = update
                elif update_type == 'background_color':
                    self.bg_color = p3d.LVector4(*update['color'])
                else:
                    raise RuntimeError('Unknown update type: {}'.format(update_type))

            if latest_scene_update is not None:
                self.update_scene(latest_scene_update['path'])

            return task.cont
        self.taskMgr.add(do_updates, 'Updates')

        def image_updates(task):
            if self.texture.has_ram_image():
                #start = time.perf_counter()
                self.connection.send_image(
                    self.texture.get_x_size(),
                    self.texture.get_y_size(),
                    memoryview(self.texture.get_ram_image_as('BGR'))
                )
                #print('Extern: Updated image data in {}ms'.format((time.perf_counter() - start) * 1000))
            return task.cont
        self.taskMgr.add(image_updates, 'Upload Images')
Esempio n. 29
0
    def __init__(self, workingdir):
        ShowBase.__init__(self)
        self.view_lens = p3d.MatrixLens()
        self.cam = p3d.NodePath(p3d.Camera('view'))
        self.cam.node().set_lens(self.view_lens)
        self.cam.node().set_active(True)
        self.cam.reparent_to(self.render)

        self.pipe = p3d.GraphicsPipeSelection.get_global_ptr(
        ).make_module_pipe('pandagl')

        self.bg_color = p3d.LVecBase4(0.0, 0.0, 0.0, 1.0)

        p3d.get_model_path().prepend_directory(workingdir)
        self.workingdir = workingdir

        self.texture = p3d.Texture()
        self.win = None
        self.rendermanager = None
        self.make_offscreen(1, 1)

        self.disableMouse()
        self.setFrameRateMeter(True)

        self.image_width = 1
        self.image_height = 1
        self.image_data = struct.pack('=BBB', 0, 0, 0)

        # Setup conversion logic
        self.converter = Converter()
        self.conversion_queue = queue.Queue()

        def conversion(task):
            while not self.conversion_queue.empty():
                data = self.conversion_queue.get()
                #print(data)
                if 'extras' in data and 'view' in data['extras']:
                    viewd = data['extras']['view']
                    if 'width' in viewd:
                        width = viewd['width']
                        height = viewd['height']
                        self.make_offscreen(width, height)
                    if 'projection_matrix' in viewd:
                        proj_mat = self.converter.load_matrix(
                            viewd['projection_matrix'])
                        self.view_lens.set_user_mat(proj_mat)
                    if 'view_matrix' in viewd:
                        view_mat = self.converter.load_matrix(
                            viewd['view_matrix'])

                        # Panda wants an OpenGL model matrix instead of an OpenGL view matrix
                        view_mat.invert_in_place()
                        self.view_lens.set_view_mat(view_mat)

                self.converter.update(data)
                bg_color = self.converter.background_color
                self.bg_color = p3d.LVector4(bg_color[0], bg_color[1],
                                             bg_color[2], 1)
                self.view_region.set_clear_color(self.bg_color)
                self.converter.active_scene.reparent_to(self.render)
                #self.render.ls()

            if self.texture.has_ram_image():
                #start = time.perf_counter()
                self.server.image_lock.acquire()
                self.image_width = self.texture.get_x_size()
                self.image_height = self.texture.get_y_size()
                self.image_data = memoryview(
                    self.texture.get_ram_image_as("BGR"))
                self.server.image_lock.release()
                #print('Extern: Updated image data in {}ms'.format((time.perf_counter() - start) * 1000))
                #self.texture.write('tex.png')
            return task.cont

        self.taskMgr.add(conversion, 'Conversion')

        # Setup communication with Blender
        self.server = Server(self.handle_data, self.get_img)
        if USE_THREAD:
            self.server.start()

            def server_mon(task):
                if not self.server.is_alive():
                    print('Server thread has terminated, closing program')
                    sys.exit()
                return task.cont

            self.taskMgr.add(server_mon, 'Server Monitor')
        else:

            def server_task(task):
                self.server.run()
                return task.cont

            self.taskMgr.add(server_task, 'Server Communication')
Esempio n. 30
0
    def __init__(self, workingdir):
        ShowBase.__init__(self)
        self.view_lens = p3d.MatrixLens()
        self.cam = p3d.NodePath(p3d.Camera('view'))
        self.cam.node().set_lens(self.view_lens)
        self.cam.node().set_active(True)
        self.cam.reparent_to(self.render)

        self.pipe = p3d.GraphicsPipeSelection.get_global_ptr().make_module_pipe('pandagl')

        self.bg = p3d.LVecBase4(0.0, 0.0, 0.0, 1.0)

        p3d.get_model_path().prepend_directory(workingdir)

        self.texture = p3d.Texture()
        self.win = None
        self.make_offscreen(1, 1)

        self.disableMouse()
        self.setFrameRateMeter(True)

        self.image_width = 1
        self.image_height = 1
        self.image_data = struct.pack('=BBB', 0, 0, 0)

        # Setup conversion logic
        self.converter = Converter()
        self.conversion_queue = queue.Queue()
        def conversion(task):
            while not self.conversion_queue.empty():
                data = self.conversion_queue.get()
                #print(data)
                if 'extras' in data and 'view' in data['extras']:
                    viewd = data['extras']['view']
                    if 'width' in viewd:
                        width = viewd['width']
                        height = viewd['height']
                        self.make_offscreen(width, height)
                    if 'projection_matrix' in viewd:
                        proj_mat = self.converter.load_matrix(viewd['projection_matrix'])
                        self.view_lens.set_user_mat(proj_mat)
                    if 'view_matrix' in viewd:
                        view_mat = self.converter.load_matrix(viewd['view_matrix'])

                        # Panda wants an OpenGL model matrix instead of an OpenGL view matrix
                        view_mat.invert_in_place()
                        self.view_lens.set_view_mat(view_mat)

                self.converter.update(data)
                bg = self.converter.background_color
                self.bg = p3d.LVector4(bg[0], bg[1], bg[2], 1)
                self.view_region.set_clear_color(self.bg)
                self.converter.active_scene.reparent_to(self.render)
                #self.render.ls()

            if self.texture.has_ram_image():
                #start = time.perf_counter()
                self.server.image_lock.acquire()
                self.image_width = self.texture.get_x_size()
                self.image_height = self.texture.get_y_size()
                self.image_data = memoryview(self.texture.get_ram_image_as("BGR"))
                self.server.image_lock.release()
                #print('Extern: Updated image data in {}ms'.format((time.perf_counter() - start) * 1000))
                #self.texture.write('tex.png')
            return task.cont

        self.taskMgr.add(conversion, 'Conversion')

        # Setup communication with Blender
        self.server = Server(self.handle_data, self.get_img)
        if USE_THREAD:
            self.server.start()
            def server_mon(task):
                if not self.server.is_alive():
                    print('Server thread has terminated, closing program')
                    self.server.destroy()
                    time.sleep(0.1)
                    sys.exit()
                return task.cont
            self.taskMgr.add(server_mon, 'Server Monitor')
        else:
            def server_task(task):
                self.server.run()
                return task.cont
            self.taskMgr.add(server_task, 'Server Communication')


        try:
            pman_conf = pman.get_config(workingdir)
        except pman.NoConfigError:
            pman_conf = None

        self.rendermanager = rendermanager.create_render_manager(self, pman_conf)
Esempio n. 31
0
    def __init__(self):
        if len(sys.argv) < 2:
            print("Missing input file")
            sys.exit(1)

        super().__init__()

        self.pipeline = simplepbr.init()

        gltf.patch_loader(self.loader)

        infile = p3d.Filename.from_os_specific(os.path.abspath(sys.argv[1]))
        p3d.get_model_path().prepend_directory(infile.get_dirname())

        self.model_root = self.loader.load_model(infile, noCache=True)

        self.accept('escape', sys.exit)
        self.accept('q', sys.exit)
        self.accept('w', self.toggle_wireframe)
        self.accept('t', self.toggle_texture)
        self.accept('n', self.toggle_normal_maps)
        self.accept('e', self.toggle_emission_maps)
        self.accept('o', self.toggle_occlusion_maps)
        self.accept('a', self.toggle_ambient_light)
        self.accept('shift-l', self.model_root.ls)
        self.accept('shift-a', self.model_root.analyze)

        self.model_root.reparent_to(self.render)

        bounds = self.model_root.getBounds()
        center = bounds.get_center()
        if bounds.is_empty():
            radius = 1
        else:
            radius = bounds.get_radius()

        fov = self.camLens.get_fov()
        distance = radius / math.tan(math.radians(min(fov[0], fov[1]) / 2.0))
        self.camLens.set_near(min(self.camLens.get_default_near(), radius / 2))
        self.camLens.set_far(max(self.camLens.get_default_far(), distance + radius * 2))
        trackball = self.trackball.node()
        trackball.set_origin(center)
        trackball.set_pos(0, distance, 0)
        trackball.setForwardScale(distance * 0.006)

        # Create a light if the model does not have one
        if not self.model_root.find('**/+Light'):
            self.light = self.render.attach_new_node(p3d.PointLight('light'))
            self.light.set_pos(0, -distance, distance)
            self.render.set_light(self.light)

        # Move lights to render
        self.model_root.clear_light()
        for light in self.model_root.find_all_matches('**/+Light'):
            light.parent.wrt_reparent_to(self.render)
            self.render.set_light(light)

        # Add some ambient light
        self.ambient = self.render.attach_new_node(p3d.AmbientLight('ambient'))
        self.ambient.node().set_color((.2, .2, .2, 1))
        self.render.set_light(self.ambient)

        if self.model_root.find('**/+Character'):
            self.anims = p3d.AnimControlCollection()
            p3d.autoBind(self.model_root.node(), self.anims, ~0)
            if self.anims.get_num_anims() > 0:
                self.anims.get_anim(0).loop(True)
Esempio n. 32
0
    def mount(self):
        """ Inits the VFS Mounts """

        self.debug("Setting up virtual filesystem.")
        self._mounted = True
        vfs = VirtualFileSystem.get_global_ptr()

        # Mount data and models
        dirs_to_mount = ["Data", "Effects", "Plugins", "Shader"]
        for directory in dirs_to_mount:
            vfs.mount_loop(join(self._base_path, directory), directory, 0)

        if isdir(join(self._base_path, "Models")):
            vfs.mount_loop(join(self._base_path, 'Models'), 'Models', 0)

        # Mount config dir
        if self._config_dir is None:
            config_dir = join(self._base_path, "Config/")
            vfs.mount_loop(config_dir, "$$Config/", 0)
            self.debug("Auto-Detected config dir:", config_dir)
        else:
            vfs.mount_loop(self._config_dir, "$$Config/", 0)
            self.debug("Config dir:", self._config_dir)


        # Convert the base path to something the os can work with
        sys_base_path = Filename(self._base_path).to_os_specific()

        # Add plugin folder to the include path
        sys.path.insert(0, join(sys_base_path, 'Plugins'))

        # Add current folder to the include path
        sys.path.insert(0, sys_base_path)

        # Mount the pipeline temp path:
        # If no write path is specified, use a virtual ramdisk
        if self._write_path is None:
            self.debug("Mounting ramdisk as $$PipelineTemp/")
            vfs.mount(VirtualFileMountRamdisk(), "$$PipelineTemp/", 0)
        else:
            # In case an actual write path is specified:
            # Ensure the pipeline write path exists, and if not, create it
            if not isdir(self._write_path):
                self.debug("Creating temp path, it does not exist yet")
                try:
                    os.makedirs(self._write_path)
                except IOError as msg:
                    self.fatal("Failed to create temp path:", msg)
            self.debug("Mounting", self._write_path, "as $$PipelineTemp/")
            vfs.mount_loop(self._write_path, '$$PipelineTemp/', 0)

        # #pragma include "something" searches in current directory first,
        # and then on the model-path. Append the Shader directory to the
        # modelpath to ensure the shader includes can be found.
        self._model_paths.append(join(self._base_path, "Shader"))

        # Add the pipeline root directory to the model path as well
        self._model_paths.append(self._base_path)
        self._model_paths.append(".")

        # Append the write path to the model directory to make pragma include
        # find the ShaderAutoConfig.include
        self._model_paths.append("$$PipelineTemp")

        # Add the plugins dir to the model path so plugins can include their
        # own resources more easily
        self._model_paths.append(join(self._base_path, "Plugins"))

        # Write the model paths to the global model path
        for pth in self._model_paths:
            get_model_path().append_directory(pth)