Пример #1
0
 def __init__(self):
     base = ShowBase()
     self.text = TextNode("node name")
     textfile = open("Dedicatory.txt")
     self.text.setText(textfile.read())
     textNodePath = aspect2d.attachNewNode(self.text)
     textNodePath.setScale(0.5)
     textNodePath.setPos(0, 30, 0)
     textNodePath.reparentTo(render)
     self.text.setTextColor(0, 0, 0, 1)
     base.setBackgroundColor(1, 1, 1)
     #font = loader.loadFont("tnr.bam")
     #font.setPixelsPerUnit(25)
     self.text.setWordwrap(35)
     #self.text.setFont(font)
     base.accept("escape", sys.exit)
     base.useTrackball()
     self.output = "Psalms.txt"
     base.trackball.node().setPos(-7.55, 0, 6)
     menu = DirectOptionMenu(
         text="New",
         scale=0.04,
         items=[
             "Matthew", "Mark", "Luke", "John", "Acts", "Romans",
             "1 Corinthians", "2 Corinthians", "Galatians", "Ephesians",
             "Philippians", "Colossians", "1 Thessalonians",
             "2 Thessalonians", "1 Timothy", "2 Timothy", "Titus",
             "Philemon", "Hebrews", "James", "1 Peter", "2 Peter", "1 John",
             "2 John", "3 John", "Jude", "Revelation"
         ],
         highlightColor=(0.65, 0.65, 0.65, 1),
         command=self.itemSel)
     menuold = DirectOptionMenu(
         text="Old",
         scale=0.04,
         items=[
             "Genesis", "Exodus", "Leviticus", "Numbers", "Deuteronomy",
             "Joshua", "Judges", "Ruth", "1 Samuel", "2 Samuel", "1 Kings",
             "2 Kings", "1 Chronicles", "2 Chronicles", "Ezra", "Nehemiah",
             "Esther", "Job", "Psalms", "Proverbs", "Ecclesiastes",
             "SongofSolomon", "Isaiah", "Jeremiah", "Lamentations",
             "Ezekiel", "Daniel", "Hosea", "Joel", "Amos", "Obadiah",
             "Jonah", "Micah", "Nahum", "Habakkuk", "Zephaniah", "Haggai",
             "Zechariah", "Malachi"
         ],
         highlightColor=(0.65, 0.65, 0.65, 1),
         command=self.itemSel)
     menu.setPos(-1.31, 0, 0.8)
     menuold.setPos(-1.31, 0, 0.9)
     onebutton = DirectButton(text=("NextSection"),
                              scale=.04,
                              command=self.one)
     onebutton.setPos(-1.2, 0, 0.7)
     self.sectnum = 1
     taskMgr.add(self.exampleTask, "MyTaskName")
Пример #2
0
	'/c/Users/Brian/Documents/panda3d/build_test/phase_7/audio/bgm/tt_elevator.ogg',
	'/c/Users/Brian/Documents/panda3d/build_test/phase_7/audio/bgm/encntr_general_bg_indoor.ogg',
	'/c/Users/Brian/Documents/panda3d/build_test/phase_7/audio/bgm/encntr_toon_winning_indoor.ogg']
currentSong = -1
#music = loader.loadMusic(array[currentSong])
#music.setLoop(False)
#music.play()

music = None

def stopCurrentMusic():
	music.stop()
	
def playNextSong():
	global music
	global currentSong
	if music:
		music.stop()
	currentSong += 1
	music = loader.loadMusic(array[currentSong])
	music.setLoop(True)
	music.play()

base.accept("s", stopCurrentMusic)
base.accept("p", playNextSong)

#base.accept("PandaPaused", base.enableMusic, [False])
#base.accept("PandaRestarted", base.enableMusic, [True])

base.run()
Пример #3
0
# all imports needed by the engine itself
from direct.showbase.ShowBase import ShowBase

# initialize the engine
base = ShowBase()

# initialize the client

from direct.distributed.ClientRepository import ClientRepository
from panda3d.core import URLSpec, ConfigVariableInt, ConfigVariableString
from direct.gui.OnscreenText import OnscreenText
from panda3d.core import TextNode


base.accept("escape", exit)

# Function to put instructions on the screen.
def addInstructions(pos, msg):
    return OnscreenText(text=msg, style=1, fg=(0, 0, 0, 1), shadow=(1, 1, 1, 1),
                        parent=base.a2dTopLeft, align=TextNode.ALeft,
                        pos=(0.08, -pos - 0.04), scale=.06)

# Function to put title on the screen.
def addTitle(text):
    return OnscreenText(text=text, style=1, pos=(-0.1, 0.09), scale=.08,
                        parent=base.a2dBottomRight, align=TextNode.ARight,
                        fg=(1, 1, 1, 1), shadow=(0, 0, 0, 1))

title = addTitle("Panda3D: Tutorial - Distributed Network (NOT CONNECTED)")
inst1 = addInstructions(0.06, "esc: Close the client")
inst2 = addInstructions(0.12, "See console output")
from direct.showbase.ShowBase import ShowBase

from panda3d.core import VBase3
from panda3d.core import Vec3
from panda3d.core import Quat
from panda3d.core import invert
from panda3d.bullet import BulletWorld
from panda3d.bullet import BulletRigidBodyNode
from panda3d.bullet import BulletSphereShape
from panda3d.bullet import BulletDebugNode


# Basic setup
s = ShowBase()
s.disable_mouse()
s.accept('escape', sys.exit)
s.cam.set_pos(0, -10, 0)


# Physics
bullet_world = BulletWorld()
def run_physics(task):
    bullet_world.do_physics(globalClock.getDt())
    return task.cont
s.task_mgr.add(run_physics, sort=1)


# Debug visualization
debug_node = BulletDebugNode('Debug')
debug_node.showWireframe(True)
debug_node.showConstraints(True)
Пример #5
0
from direct.showbase.ShowBase import ShowBase

from panda3d.core import VBase3
from panda3d.core import Vec3
from panda3d.core import Quat
from panda3d.core import invert
from panda3d.bullet import BulletWorld
from panda3d.bullet import BulletRigidBodyNode
from panda3d.bullet import BulletSphereShape
from panda3d.bullet import BulletDebugNode

# Basic setup
s = ShowBase()
s.disable_mouse()
s.accept('escape', sys.exit)
s.cam.set_pos(0, -10, 0)

# Physics
bullet_world = BulletWorld()


def run_physics(task):
    bullet_world.do_physics(globalClock.getDt())
    return task.cont


s.task_mgr.add(run_physics, sort=1)

# Debug visualization
debug_node = BulletDebugNode('Debug')
Пример #6
0
def handlePick():
    if not editMode:
        return

    if base.mouseWatcherNode.hasMouse():
        mpos = base.mouseWatcherNode.getMouse()
        pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())

        traverser.traverse(render)
        if handler.getNumEntries() > 0:
            handler.sortEntries()
            pickedObj = handler.getEntry(0).getIntoNodePath()
            pickedObj = pickedObj.findNetTag('cell')
            if not pickedObj.isEmpty():
                cell = grid[int(pickedObj.getX())][int(pickedObj.getY())]
                cell.alive = not cell.alive
                cell.draw()


def clearGrid():
    for row in grid:
        for cell in row:
            cell.alive = False
    draw()


base.accept('mouse1', handlePick)

initialize()
base.run()
    agentNP = app.loader.load_model("eve.egg")
    agentNP.set_scale(0.40)

    # create the crowd agent and set the position
    crowdAgentNP = navMesMgr.create_crowd_agent("crowdAgent")
    crowdAgentNP.hide()
    crowdAgent = crowdAgentNP.node()

    # attach the agent model to crowdAgent
    agentNP.reparent_to(crowdAgentNP)

    # start the path finding default update task
    navMesMgr.start_default_update()

    # toggle setup (true) and cleanup (false)
    app.accept("s", toggleSetupCleanup)

    # toggle debug draw
    app.accept("d", toggleDebugDraw)

    # place crowd agent
    app.accept("p", placeCrowdAgent)

    # handle move target on scene surface
    app.accept("t", setMoveTarget)

    # add areas
    app.accept("a", addArea, [True])
    app.accept("shift-a", addArea, [False])
    # remove areas
    app.accept("r", removeArea)
Пример #8
0
class MyApp:
    """The main class."""
    def __init__(self):
        """Start the app."""
        self.base = ShowBase()
        self.base.disableMouse()

        filters = CommonFilters(self.base.win, self.base.cam)
        filters.setBloom(blend=(0, 0, 0, 1))
        self.base.render.setShaderAuto(
            BitMask32.allOn() & ~BitMask32.bit(Shader.BitAutoShaderGlow))
        ts = TextureStage('ts')
        ts.setMode(TextureStage.MGlow)
        tex = self.base.loader.loadTexture('models/black.png')
        self.base.render.setTexture(ts, tex)

        self.terrain = Terrain(self.base.render, self.base.loader)

        minimap_size = 200
        self.minimap = Minimap(
            self.base.win.makeDisplayRegion(
                1 - minimap_size / self.base.win.getProperties().getXSize(), 1,
                1 - minimap_size / self.base.win.getProperties().getYSize(),
                1))
        self.minimap.node_path.reparentTo(self.base.render)

        # self.light_nodes =
        self.set_lights()
        self.set_fog()

        self.key_state = dict.fromkeys(Object.values(config.key_map.character),
                                       False)
        self.set_key_state_handler()

        self.game_state = "pause"
        self.toggle_pause()

        self.selection = Selection(self.base.loader, self.terrain.geom_node)
        self.selection_text = OnscreenText(
            mayChange=True,
            scale=0.07,
            align=TextNode.ALeft,
            pos=(0.02 - self.base.getAspectRatio(), 1 - 0.07))
        self.timer_text = OnscreenText(mayChange=True,
                                       scale=0.07,
                                       align=TextNode.ALeft,
                                       pos=(0.02 - self.base.getAspectRatio(),
                                            -1 + 0.02 + 0.07))

        self.enemies = set()

        self.base.accept(config.key_map.utility.pause, self.toggle_pause)
        self.base.accept(
            "q", lambda: self.selection.advance_tower(self.base.loader))
        self.base.accept("mouse1", self.player_click)
        self.base.cam.node().setCameraMask(BitMask32.bit(0))
        self.base.setBackgroundColor(*config.map_params.colors.sky)

        self.player = Player()
        self.base.taskMgr.add(lambda task: self.terrain.start_up(), "start up")
        self.mouse_pos = (0.0, 0.0)
        self.base.taskMgr.add(self.move_player_task, "move_player_task")
        self.base.taskMgr.add(self.move_enemies_task, "move_enemies_task")
        self.base.taskMgr.add(self.player_select_task, "player_select_task")
        self.base.taskMgr.add(self.tower_task, "tower_task")
        self.base.taskMgr.add(self.check_end_game, "check_end_game_task")
        rand = Random()
        rand.seed(config.map_params.seed)
        self.base.taskMgr.doMethodLater(1,
                                        self.clock_task,
                                        'clock_task',
                                        extraArgs=[rand])
        self.rounds = 0
        self.coin = 40
        # self.base.setFrameRateMeter(True)

    def set_fog(self):
        """Set render distance of camera."""
        fog = Fog("Scene fog")
        fog.setColor(0.7, 0.7, 0.7)
        fog.setExpDensity(0.01)
        # self.terrain.geom_node.setFog(fog)
        self.base.camLens.setFar(4000.0)
        return fog

    def set_lights(self):
        """Set up the lights."""
        light_nodes = [None] * 9
        for i, dirs in zip(range(9), [0] + Object.values(directions) * 2):
            dlight = DirectionalLight(f"directional light {i}")
            if i <= 4:
                dlight.setColor((0.5, 0.5, 0.5, 0.8))
            else:
                dlight.setColor((2, 2, 2, 2))
            light_nodes[i] = self.base.render.attachNewNode(dlight)
            if i == 0:
                light_nodes[i].setPos(0, 0, 1)
            else:
                light_nodes[i].setPos(*dirs, 0)
            light_nodes[i].lookAt(0, 0, 0)
            if i <= 4:
                self.base.render.setLight(light_nodes[i])
                self.terrain.terrain_node.clearLight(light_nodes[i])
            else:
                # self.terrain.terrain_node.setLight(light_nodes[i])
                pass

        alight = AmbientLight('ambient light')
        alight.setColor((0.3, 0.3, 0.3, 1))
        ambient_light_node = self.base.render.attachNewNode(alight)
        self.base.render.setLight(ambient_light_node)
        return light_nodes, ambient_light_node

    def set_key_state_handler(self):
        """Accept key and records to key_state."""
        def set_key_state(key, state):
            self.key_state[key] = state

        for key in self.key_state:
            self.base.accept(key, set_key_state, [key, True])
            self.base.accept(key + "-up", set_key_state, [key, False])

    def toggle_pause(self):
        """Toggle pause."""
        if self.game_state == "ended":
            return
        if self.game_state == "pause":
            self.game_state = "active"
            props = WindowProperties()
            props.setCursorHidden(True)
            props.setMouseMode(WindowProperties.M_confined)
            self.base.win.requestProperties(props)
        else:
            self.game_state = "pause"
            props = WindowProperties()
            props.setCursorHidden(False)
            props.setMouseMode(WindowProperties.M_absolute)
            self.base.win.requestProperties(props)
        print("toggled pause")

    def move_player_task(self, task):  # pylint: disable=unused-argument
        """The task that handles player movement."""
        if self.game_state != "active":
            return Task.cont
        if not self.base.mouseWatcherNode.hasMouse():
            self.toggle_pause()
            return Task.cont
        self.player.update_pos(self.key_state,
                               ClockObject.getGlobalClock().getDt(),
                               lambda pos: self.terrain.get_tile(pos).walkable)
        self.mouse_pos = (
            self.mouse_pos[0] + self.base.mouseWatcherNode.getMouseX(),
            self.mouse_pos[1] + self.base.mouseWatcherNode.getMouseY(),
        )
        self.player.update_hpr(self.mouse_pos)
        self.base.win.movePointer(0,
                                  self.base.win.getXSize() // 2,
                                  self.base.win.getYSize() // 2)
        self.base.camera.setPos(self.player.pos)
        self.minimap.set_pos(self.player.pos, self.player.hpr)
        self.base.camera.setHpr(self.player.hpr)
        self.terrain.update_player_pos(tuple(self.player.pos))
        return Task.cont

    def move_enemies_task(self, task):  # pylint: disable=unused-argument
        """The task that handles enemy movement."""
        if self.game_state != "active":
            return Task.cont
        for enemy in set(self.enemies):
            if not enemy.generated:
                enemy.generate(self.terrain.path_finder, self.base.loader,
                               self.terrain.geom_node, self.terrain.get_tile)
            if not enemy.check_active():
                self.enemies.remove(enemy)
                continue
            # enemy.model.setPos(self.player.pos)
            enemy.move(ClockObject.getGlobalClock().getDt())
        return Task.cont

    def tower_task(self, task):
        if self.game_state != "active":
            return Task.cont
        for tower in set(self.terrain.towers):
            if not tower.generated:
                tower.generate(self.base.loader, self.terrain.geom_node,
                               self.terrain.get_tile)
            if not tower.check_active():
                self.terrain.towers.remove(tower)
                self.terrain[tower.grid_pos] = Floor()
                continue
            tower.move(ClockObject.getGlobalClock().getDt(), self.enemies)
            tower.generate_bullet(self.base.loader, self.terrain.geom_node,
                                  self.terrain.get_tile)
        return Task.cont

    def player_select_task(self, task):
        self.selection.set_selection(
            self.player.view(self.terrain.get_tile, self.enemies))
        self.selection_text.setText(self.selection.get_text())
        if self.selection.tower_class != Empty:
            self.selection.set_disable(
                self.coin < self.selection.tower_class.cost)
        return Task.cont

    def player_click(self):
        if isinstance(self.selection.select, Floor) and \
                issubclass(self.selection.tower_class, Tower) and \
                self.selection.tower_class.cost <= self.coin:
            self.coin -= self.selection.tower_class.cost
            pos = self.selection.model.getPos()
            coord_pos = (int(pos[0] // config.map_params.unit_size),
                         int(pos[1] // config.map_params.unit_size))
            self.terrain[coord_pos] = self.selection.tower_class(coord_pos)

    def spawn_enemies(self, rand):
        if self.game_state != "active":
            return Task.cont
        dsts = [tower.model.getPos().length() for tower in self.terrain.towers]
        radius = max(dsts + [0]) + 100
        num = (self.rounds + config.game.sep // 2) // config.game.sep
        for _ in range(num):
            theta = rand.uniform(0, 2 * pi)
            enemy = Kikiboss if _ % 5 or num % 5 else Dabi
            self.enemies.add(enemy(Vec3(cos(theta), sin(theta), 0) * radius))
        return Task.again

    def clock_task(self, rand):
        if self.game_state != "active":
            return Task.cont
        self.rounds += 1
        self.coin += 1
        ending = "y" if self.coin <= 1 else "ies"
        self.timer_text.setText(
            f"You have {self.coin} cherr{ending}\n" +
            f"{config.game.sep - self.rounds % config.game.sep}s " +
            f"until wave {self.rounds // config.game.sep + 1}.")
        if self.rounds % config.game.sep == 0:
            return self.spawn_enemies(rand)
        return Task.again

    def check_end_game(self, task):
        if self.terrain[(0, 0)].hp <= 0:
            if self.game_state == "active":
                self.toggle_pause()
            self.game_state = "ended"
            self.terrain.geom_node.setColorScale(0.2, 0.2, 0.2, 1)
            OnscreenText(text="GAME OVER",
                         scale=0.2,
                         fg=(1, 0, 0, 1),
                         align=TextNode.ACenter,
                         pos=(0, 0))
            OnscreenText(text=f"score: {self.rounds}",
                         scale=0.07,
                         align=TextNode.ACenter,
                         pos=(0, -.15))
            return task.done
        return task.cont

    def run(self):
        """Run."""
        self.base.run()
Пример #9
0
import sys

from direct.showbase.ShowBase import ShowBase
from direct.actor.Actor import Actor

from panda3d.core import DirectionalLight, KeyboardButton

s = ShowBase()
s.accept('escape', sys.exit)
s.cam.setPos(0, -5, 5)
s.cam.lookAt(0, 0, 0)

a = Actor('assets/cars/Ricardeaut_Magnesium.bam')
a.reparentTo(s.render)
puppet = s.loader.loadModel('assets/cars/Ricardeaut_Magnesium.bam')
puppet.find("armature").hide()
puppet.reparentTo(a)

repulsors = a.findAllMatches('**/fz_repulsor*')
print(repulsors)
for r, repulsor in enumerate(repulsors):
    repulsor.setPos(0, 0, 0)
    repulsor.setP(-90)
    joint = a.exposeJoint(None, "modelRoot", "repulsor_bone:" + str(r))
    repulsor.reparentTo(joint)

#a.enableBlend()
animations = ["gems", "accelerate", "turn", "strafe", "hover"]
for animation in animations:
    a.setControlEffect(animation, 1)
    a.play(animation)
Пример #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 Panda3dInstance(object):
    """This class normally is instantiated in a subprocess, where it spawns
    Panda3D.

    If you aren't 100% sure what you're doing, use the Panda3dManager instead.
    """
    def __init__(self, pipe, name):
        """Arguments:
        pipe -- Multiprocessing pipe for communication. See messagecenter
                module for more info.
        name -- Name of this instance.
        """

        #self.gameobjects = []

        self.messageclient = MessageClient(pipe)
        self.name = name
        self.windows = {}

        # set a few default settings
        loadPrcFileData("", "window-type none")
        loadPrcFileData("", "audio-library-name null")

        # initiate Panda3D
        self.base = ShowBase()
        
        # start processing incoming requests
        self.messageclient.addListener(self.UImessageProcessor, req_type=UI)

        # The request processing task should never stop as long as the
        # subprocess exists. This is a wrapper that ensures that and saves
        # us from confusion about "hey, why has this message processing
        # stopped?!"
        def messageProcessor(task):
            self.messageclient.process()
            return task.cont
        self.base.addTask(messageProcessor, "message processor")

        # As soon as the user clicks the window, it should get focus, like any other widget.
        self.base.accept("mouse1", self.focus)

        # TODO: Wrap this around a try..except block and notify the main
        # process on errors.
        self.base.run()

    def getWindowUnderPointer(self):
        """Returns the key from self.windows of the window the primary poiter
        currently hovers over.
        """
        for win_id, win in self.windows.iteritems():
            props = win.getProperties()
            pointer = win.getPointer(0)
            if pointer.getInWindow():
                return win_id

    def addWindow(self, handle=None, width=500, height=500):
        """Create a new window showing the scene. Add it to the windows list
        and return it.
        If handle is not None, it is used as parent window.
        """
        wp = WindowProperties()
        wp.setOrigin(0, 0)
        wp.setSize(width, height)
        if handle is not None:
            wp.setParentWindow(handle)
        self.base.openDefaultWindow(props=wp,
                                    type="onscreen",
                                    requireWindow=True)
        return self.base.winList[-1]

    def UImessageProcessor(self, message):
        p = message.payload
        # TODO: look up the req_spec attribute, not class instance
        if p.req_spec == OPEN_WINDOW:
            assert not self.windows.has_key(p.window_id)
            win = self.addWindow(p.handle, p.width, p.height)
            self.windows[p.window_id] = win
        elif p.req_spec == RESIZE_WINDOW:
            self.resizeWindow(p.window_id, p.width, p.height)

    def focus(self, window_id=None):
        """Bring Panda3d to foreground, so that it gets keyboard focus.
        Also send a message to wx, so that it doesn't render a widget focused.
        We also need to say wx that Panda now has focus, so that it can notice when
        to take focus back.

        If window_id is given, that window will be focused, otherwise the one
        the pointer hovers upon. If the pointer doesn't hover over a window,
        a random window is taken. If there is no window, this function does nothing.
        """
        if window_id is None:
            window_id = self.getWindowUnderPointer()
        if window_id is None:
            for win in self.windows.values():
                window_id = win
                break
        if window_id is None:
            return
        wp = WindowProperties()
        wp.setForeground(True)
        self.windows[window_id].requestProperties(wp)
        # We request focus (and probably already have keyboard focus), so make wx
        # set it officially. This prevents other widgets from being rendered focused.
        self.messageclient.unicast(self.name+" gui", FocusWindowRequest(window_id))

    def resizeWindow(self, window_id, width, height):
        """window_id is an index of a window from base.winList."""
        window = self.windows[window_id]
        old_wp = window.getProperties()
        if old_wp.getXSize() == width and old_wp.getYSize() == height:
            return
        wp = WindowProperties()
        wp.setOrigin(0, 0)
        wp.setSize(width, height)
        window.requestProperties(wp)

    def close(self):
        # Everything should be garbage collected this way, except maybe the
        # messaging connection to the server, which will keep sending messages
        # to us.
        # TODO: fix that.
        sys.exit()

    def addGameObject(self, name=None):
        """Add a new game object to the scene."""
        # TODO: we should send a real id instead of name or None
        
        self.messageclient.others(AddGameObjectRequest(name))
        self.addRequestedGameObject(name)

    def addRequestedGameObject(self, name=None):
        """Add a game object to the local scene (only this P3D instance)."""
        go = GameObject(name)
        go.transform.parent = Root(render)
        self.gameobjects.append(go)
Пример #12
0
    ruler.setPos(-(R0+.25),0,1) # z = .5 *2scale
    ruler.setScale(.05,1,2) #2 unit tall board
    ruler.setTwoSided(1)
    ruler.reparentTo(base.render)
    
    def rotateTree(task):
        phi = 10*task.time
        tree.setH(phi)
        return task.cont
    base.taskMgr.add(rotateTree,"merrygoround")

    base.cam.setPos(0,-4*L0, L0/2)    
    base.render.setShaderAuto()
    base.setFrameRateMeter(1)    
#    base.toggleWireframe()
    base.accept('escape',sys.exit)
    base.accept('z',base.toggleWireframe)
#    pycallgraph.make_dot_graph('treeXpcg.png')
    base.setBackgroundColor((.0,.5,.9))
    base.render.analyze()
    base.run()

#TODO
#2013.04.24: Rework. 
                    # each "branch" will grow ~f(generation). 
                    # buds will spawn at semi random locations along the length of a branch
                    # every 'generation' (season) will produce 0 - N new buds/ child-branches
#            The .addbud method will be split into a .grow and .addbuds methods to accomplish above
                
                         
##### OLD COMMENTS PRE SPLIT ON 2013.04.24    
Пример #13
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)
base.loader = CogInvasionLoader.CogInvasionLoader(base)
base.graphicsEngine.setDefaultLoader(base.loader.loader)
__builtin__.loader = base.loader
from lib.coginvasion.globals import CIGlobals
cbm = CullBinManager.getGlobalPtr()
cbm.addBin('ground', CullBinManager.BTUnsorted, 18)
cbm.addBin('shadow', CullBinManager.BTBackToFront, 19)
cbm.addBin('gui-popup', CullBinManager.BTUnsorted, 60)
base.setBackgroundColor(CIGlobals.DefaultBackgroundColor)
base.disableMouse()
base.enableParticles()
base.camLens.setNearFar(CIGlobals.DefaultCameraNear, CIGlobals.DefaultCameraFar)
base.transitions.IrisModelName = "phase_3/models/misc/iris.bam"
base.transitions.FadeModelName = "phase_3/models/misc/fade.bam"
base.accept('f9', ScreenshotHandler.__takeScreenshot)

print "CIStart: Setting display preferences..."
sm.applySettings(jsonfile)
if base.win == None:
    print "CIStart: Unable to open window; aborting."
    sys.exit()
else:
    print "CIStart: Successfully opened window."
ConfigVariableDouble('decompressor-step-time').setValue(0.01)
ConfigVariableDouble('extractor-step-time').setValue(0.01)

DirectGuiGlobals.setDefaultFontFunc(CIGlobals.getToonFont)
DirectGuiGlobals.setDefaultFont(CIGlobals.getToonFont())
DirectGuiGlobals.setDefaultRolloverSound(loader.loadSfx("phase_3/audio/sfx/GUI_rollover.ogg"))
DirectGuiGlobals.setDefaultClickSound(loader.loadSfx("phase_3/audio/sfx/GUI_create_toon_fwd.ogg"))
Пример #15
0
        else:
            model = loader.loadModel("camera")
            model.reparent_to(device_anchor)
            model.set_scale(0.1)


# Set up the window, camera, etc.

base = ShowBase()
base.setFrameRateMeter(True)

# Create and configure the VR environment

ovr = P3DOpenVR()
ovr.init()

model = loader.loadModel("panda")
model.reparentTo(render)
min_bounds, max_bounds = model.get_tight_bounds()
height = max_bounds.get_z() - min_bounds.get_z()
model.set_scale(1.5 / height)
model.set_pos(0, 1, -min_bounds.get_z() / height * 1.5)

demo = MinimalDemo(ovr)

base.accept('escape', base.userExit)
base.accept('d', ovr.list_devices)
base.accept('b', base.bufferViewer.toggleEnable)

base.run()
Пример #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
                    overflow=False)
entry["state"] = DGG.DISABLED


def updateEntry(arg):
    if arg == "=":
        entry.set(str(eval(entry.get())))
    elif arg == "c":
        entry.set(entry.get()[:-1])
    elif arg == "CE":
        entry.set("")
    else:
        entry.set(entry.get() + arg)


app.accept("updateEntry", updateEntry)

leftBox.addItem(entry)
leftBox.addItem(gridSizer)
leftBox.setX(-DGH.getRealWidth(leftBox) / 2)
leftBox.setZ(DGH.getRealHeight(leftBox) / 2)

# SPINNER
spinBox = DirectSpinBox(pos=(0.8, 0, 0.25),
                        value=0,
                        minValue=-10,
                        maxValue=10,
                        repeatdelay=0.125,
                        buttonOrientation=DGG.HORIZONTAL,
                        valueEntry_text_align=TextNode.ACenter,
                        borderWidth=(.1, .1))
Пример #18
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()
Пример #19
0
from direct.showbase.ShowBase import ShowBase

from panda3d.core import VBase3
from panda3d.core import Vec3
from panda3d.core import Quat
from panda3d.core import invert
from panda3d.bullet import BulletWorld
from panda3d.bullet import BulletRigidBodyNode
from panda3d.bullet import BulletSphereShape
from panda3d.bullet import BulletDebugNode


# Basic setup
s = ShowBase()
s.disable_mouse()
s.accept('escape', sys.exit)
s.cam.set_pos(0, -10, 0)


# Physics
bullet_world = BulletWorld()
def run_physics(task):
    bullet_world.do_physics(globalClock.getDt())
    return task.cont
s.task_mgr.add(run_physics, sort=1)
# Debug visualization
debug_node = BulletDebugNode('Debug')
debug_node.showWireframe(True)
debug_node.showConstraints(True)
debug_node.showBoundingBoxes(False)
debug_node.showNormals(False)
Пример #20
0
# all imports needed by the engine itself
from direct.showbase.ShowBase import ShowBase

# import our own repositories
from ClientRepository import GameClientRepository

# initialize the engine
base = ShowBase()

# initialize the client
client = GameClientRepository()

base.accept("escape", exit)

from direct.gui.OnscreenText import OnscreenText
from panda3d.core import TextNode


# Function to put instructions on the screen.
def addInstructions(pos, msg):
    return OnscreenText(text=msg,
                        style=1,
                        fg=(0, 0, 0, 1),
                        shadow=(1, 1, 1, 1),
                        parent=base.a2dTopLeft,
                        align=TextNode.ALeft,
                        pos=(0.08, -pos - 0.04),
                        scale=.06)


# Function to put title on the screen.
Пример #21
0
class Fountain(object):

    def __init__(self):
        self.base = ShowBase()
        self.thrust = 0.5
        self.wind = 0.2

        self.UP = Vec3(0, 0, 1)  # might as well just make this a variable
        # set up camera
        self.base.disableMouse()
        self.base.camera.setPos(20, -20, 5)
        self.base.camera.lookAt(0, 0, 5)

        # Set up the collision traverser.  If we bind it to base.cTrav, then Panda will handle
        # management of this traverser (for example, by calling traverse() automatically for us once per frame)
        self.base.cTrav = CollisionTraverser()

        # Now let's set up some collision bits for our masks
        self.ground_bit = 1
        self.ball_bit = 2

        self.base.setBackgroundColor(0.64, 0, 0)
        # First, we build a card to represent the ground
        cm = CardMaker('ground-card')
        cm.setFrame(-60, 60, -60, 60)
        card = self.base.render.attachNewNode(cm.generate())
        card.lookAt(0, 0, -1)  # align upright
        #tex = loader.loadTexture('maps/envir-ground.jpg')
        tex = loader.loadTexture('models/textures/rock12.bmp')
        card.setTexture(tex)

        # Then we build a collisionNode which has a plane solid which will be the ground's collision
        # representation
        groundColNode = card.attachNewNode(CollisionNode('ground-cnode'))
        groundColPlane = CollisionPlane(Plane(Vec3(0, -1, 0), Point3(0, 0, 0)))
        groundColNode.node().addSolid(groundColPlane)

        # Now, set the ground to the ground mask
        groundColNode.setCollideMask(BitMask32().bit(self.ground_bit))

        # Why aren't we adding a collider?  There is no need to tell the collision traverser about this
        # collisionNode, as it will automatically be an Into object during traversal.

        # enable forces
        self.base.enableParticles()
        node = NodePath("PhysicsNode")
        node.reparentTo(self.base.render)

        # may want to have force dependent on mass eventually,
        # but at the moment assume all balls same weight
        self.force_mag = 200

        # gravity
        gravity_fn = ForceNode('world-forces')
        gravity_fnp = self.base.render.attachNewNode(gravity_fn)
        gravity_force = LinearVectorForce(0.0, 0.0, -9.81)
        gravity_fn.addForce(gravity_force)
        self.base.physicsMgr.addLinearForce(gravity_force)

        # wind
        wind_fn = ForceNode('world-forces')
        wind_fnp = self.base.render.attachNewNode(wind_fn)
        wind_force = LinearVectorForce(1.0, 0.5, 0.0)
        wind_fn.addForce(wind_force)
        self.base.physicsMgr.addLinearForce(wind_force)

        # spurt out of fountain, bounce
        self.spurt = ForceNode("spurt")
        spurt_np = self.base.render.attachNewNode(self.spurt)

        # create a list for our ball actors, not sure if I need this, but seems likely
        self.ball_actors = []

        # make a teapot
        teapot = loader.loadModel('teapot.egg')
        tex = loader.loadTexture('maps/color-grid.rgb')
        #teapot.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition)
        teapot.setTexture(tex)
        teapot.reparentTo(self.base.render)
        teapot.setPos(-5, 10, 10)
        # create the first ball:
        #ball = self.create_a_ball()
        #self.enliven_ball(ball)

        smiley = loader.loadModel('smiley.egg')
        lerper = NodePath('lerper')
        smiley.setTexProjector(TextureStage.getDefault(), NodePath(), lerper)
        smiley.reparentTo(self.base.render)
        smiley.setPos(5, 10, 10)
        i = lerper.posInterval(5, VBase3(0, 1, 0))
        i.loop()

        # Tell the messenger system we're listening for smiley-into-ground messages and invoke our callback
        self.base.accept('ball_cnode-into-ground-cnode', self.ground_callback)

        ball_fountain = taskMgr.doMethodLater(.5, self.spurt_balls, 'tickTask')

        # tasks
        #self.frameTask = self.base.taskMgr.add(self.frame_loop, "frame_loop")
        #self.frameTask.last = 0

    def frame_loop(self, task):
        # Make more balls!
        dt = task.time - task.last
        task.last = task.time
        # self.move_ball(dt)
        return task.cont

    # This task increments itself so that the delay between task executions
    # gradually increases over time. If you do not change task.delayTime
    # the task will simply repeat itself every 2 seconds
    def spurt_balls(self, task):
        print "Delay:", task.delayTime
        print "Frame:", task.frame
        # task.delayTime += 1
        # for i in range(5):
        ball = self.create_a_ball()
        self.enliven_ball(ball)
        return task.again

    def move_ball(self, dt):
        pass
        #x, y, z = self.ball.getPos()
        #print x, y, z
        #print self.actor_node.getPhysicsObject().getPosition()
        # rotate ball
        #prevRot = LRotationf(self.ball.getQuat())
        #axis = self.UP.cross(self.ballV)
        #newRot = LRotationf(axis, 45, 5 * dt)
        #self.ball.setQuat(prevRot + newRot)
        #print x, y, z
        #z += dt * self.thrust
        #x += dt * self.wind
        #y += dt * self.wind
        #self.ball.setPos(x, y, z)

    def remove_force(self, actor, force, task):
        print('remove force', force)
        actor.getPhysical(0).removeLinearForce(force)
        self.spurt.removeForce(force)
        return task.done

    def apply_spurt(self, actor_node, force=None):
        print 'spurt'
        print('force', force)
        #print actor_node
        # really want this to remember its previous state with that
        # particular ball, and reduce the force from then by some amount.
        if force is None:
            # force = LinearVectorForce(0.0, 0.0, self.force_mag)
            force = LinearVectorForce(0.0, 0.0, self.force_mag)
            self.spurt.addForce(force)
            print('new', force)
            #self.force_mag -= 15
        else:
            force.getAmplitude()
        # apply the spurt
        actor_node.getPhysical(0).addLinearForce(force)
        print('added force', self.spurt.getForce(0).getVector(actor_node.getPhysicsObject())[2])
        #print force, actor_node
        #for child in self.base.render.getChildren():
        #    print child
        # set a task that will clear this force a short moment later
        self.base.taskMgr.doMethodLater(0.01, self.remove_force, 'removeForceTask',
                                        extraArgs=[actor_node, force],
                                        appendTask=True)
        print 'set do method later'

    def ground_callback(self, entry):
        '''This is our ground collision message handler.  It is called whenever a collision message is
        triggered'''
        print 'callback'
        # Get our parent actor_node
        ball_actor_node = entry.getFromNodePath().getParent().node()
        # Why do we call getParent?  Because we are passed the CollisionNode during the event and the
        # ActorNode is one level up from there.  Our node graph looks like so:
        # - ActorNode
        #   + ModelNode
        #   + CollisionNode
        # add bounce!
        self.apply_spurt(ball_actor_node)

    def create_a_ball(self):
        print 'new ball'
        ball = self.base.loader.loadModel('smiley')
        texture = self.base.loader.loadTexture('models/textures/rock12.bmp')
        #ball.setTexture(texture)
        #tex = loader.loadTexture('maps/noise.rgb')
        ball.setPos(0, 0, 0)
        ball.reparentTo(self.base.render)
        ball.setTexture(texture, 1)
        return ball

    def enliven_ball(self, ball):
        # create an actor node for the balls
        ball_actor = self.base.render.attachNewNode(ActorNode("ball_actor_node"))
        # choose a random color
        #ball_actor.setColor(random.random(), random.random(), random.random(), random.random())
        self.create_ball_coll(ball_actor)
        # apply forces to it
        self.base.physicsMgr.attachPhysicalNode(ball_actor.node())
        #spurt_force = LinearVectorForce(0.0, 0.0, self.force_mag)
        #spurt_force.setMassDependent(True)
        #self.spurt.addForce(spurt_force)
        #self.spurt.addForce()
        self.apply_spurt(ball_actor.node())
        ball.reparentTo(ball_actor)
        self.ball_actors.append(ball_actor)

    def create_ball_coll(self, ball_actor):
        # Build a collisionNode for this smiley which is a sphere of the same diameter as the model
        ball_coll_node = ball_actor.attachNewNode(CollisionNode('ball_cnode'))
        ball_coll_sphere = CollisionSphere(0, 0, 0, 1)
        ball_coll_node.node().addSolid(ball_coll_sphere)
        # Watch for collisions with our brothers, so we'll push out of each other
        ball_coll_node.node().setIntoCollideMask(BitMask32().bit(self.ball_bit))
        # we're only interested in colliding with the ground and other smileys
        cMask = BitMask32()
        cMask.setBit(self.ground_bit)
        cMask.setBit(self.ball_bit)
        ball_coll_node.node().setFromCollideMask(cMask)

        # Now, to keep the spheres out of the ground plane and each other, let's attach a physics handler to them
        ball_handler = PhysicsCollisionHandler()

        # Set the physics handler to manipulate the smiley actor's transform.
        ball_handler.addCollider(ball_coll_node, ball_actor)

        # This call adds the physics handler to the traverser list
        # (not related to last call to addCollider!)
        self.base.cTrav.addCollider(ball_coll_node, ball_handler)

        # Now, let's set the collision handler so that it will also do a CollisionHandlerEvent callback
        # But...wait?  Aren't we using a PhysicsCollisionHandler?
        # The reason why we can get away with this is that all CollisionHandlerXs are inherited from
        # CollisionHandlerEvent,
        # so all the pattern-matching event handling works, too
        ball_handler.addInPattern('%fn-into-%in')

        return ball_coll_node
Пример #22
0
        right_pose = self.get_action_pose(self.action_pose_right)
        if right_pose.pose.bPoseIsValid:
            right_matrix = self.get_pose_modelview(right_pose.pose)
            if self.right_hand is None:
                self.right_hand = self.tracking_space.attach_new_node(
                    'right-hand')
                model = loader.loadModel("box")
                model.reparent_to(self.right_hand)
                model.set_scale(0.1)
            self.right_hand.show()
            self.right_hand.set_mat(right_matrix)
        else:
            if self.right_hand is not None:
                self.right_hand.hide()


base = ShowBase()
base.setFrameRateMeter(True)

myvr = MinimalOpenVR()
myvr.init()

model = loader.loadModel("panda")
model.reparentTo(render)
model.setPos(0, 10, -5)

base.accept('d', myvr.list_devices)
base.accept('b', base.bufferViewer.toggleEnable)

base.run()
Пример #23
0
    def avance(self):
        # On modifie la coordonnées x
        self.x = self.x + 1
        # On l'applique au personnage
        self.perso.setX(self.x)


# le corps du programme principal
if __name__ == "__main__":
    monJeu = ShowBase()
    ######## MISE EN PLACE DU DECOR
    monJeu.cam.setPos(40, -80, 80)
    # Orientation de la caméra
    monJeu.cam.setHpr(20, -30, 0)
    # Dessin du decor
    decor = monJeu.loader.loadModel("mes_objets3D/environment")
    # On attache le décor à la cène
    decor.reparentTo(monJeu.render)
    ######## AJOUT DU PERSONNAGE
    # On charge le modèle 3D
    modeleJoueur = Actor("mes_objets3D/panda")
    # On l'attache à la scène
    modeleJoueur.reparentTo(monJeu.render)
    # On règle les paramètres du joueur
    joueur = Perso(modeleJoueur, 0, 42, 0, 45)
    ######## GESTION DES EVENEMENTS
    monJeu.accept("arrow_left", joueur.avance)

    monJeu.run()
Пример #24
0
# # second option: start a path finding custom update task
    app.taskMgr.add(updateNavMesh,
                    "updateNavMesh",
                    extraArgs=[navMesh],
                    appendTask=True)

    # DEBUG DRAWING
    # make the debug reference node path sibling of the reference node
    navMesMgr.get_reference_node_path_debug().reparent_to(app.render)
    # enable debug drawing
    navMesh.enable_debug_drawing(app.camera)

    # # set events' callbacks
    # toggle debug draw
    toggleDebugFlag = False
    app.accept("d", toggleDebugDraw)

    # toggle setup (true) and cleanup (false)
    setupCleanupFlag = False
    app.accept("s", toggleSetupCleanup)

    # handle CrowdAgents' events
    app.accept("move-event", handleCrowdAgentEvent)

    # place crowd agents randomly
    app.accept("p", placeCrowdAgents)

    # handle move targets on scene surface
    app.accept("t", setMoveTarget, [crowdAgent[0]])
    app.accept("y", setMoveTarget, [crowdAgent[1]])
Пример #25
0
    Used to demonstrate the disconnect event
    """

    connection.disconnect()

base.userExit = shutdown

def on_discord_ready(connected_user):
    """
    Called when the Discord connection is established. connected_user
    represents the currently logged in Discord user.
    """

    print('Hello %s!' % connected_user.discord_tag)

base.accept('discord-ready', on_discord_ready)

def on_discord_disconnect():
    """
    Called when the connection is closed
    """

    print('Disconnected from Discord client')

base.accept('discord-disconnect', on_discord_disconnect)

def on_discord_disconnected(error_code, message):
    """
    Called when the connection is forcefully closed by the Discord
    client.
    """
Пример #26
0
#!/usr/bin/env python

import sys
from direct.showbase.ShowBase import ShowBase
from direct.gui.DirectGui import DirectButton

s = ShowBase()

b = DirectButton(text       = ("OK", "click!", "rolling over", "disabled"),
                 text_scale = 0.1,
                 frameColor = (0.6, 0.6, 0.6, 1.0),
                 frameSize  = (-0.3, 0.3, -0.3, 0.3),
                 pos        = (0.0, 0.0, -0.7))

s.accept("escape", sys.exit)

s.run()
Пример #27
0
        # Tourner l'objet
        self.perso.setH(self.direction)

    def tourne(self):
        self.direction = self.direction + 10
        self.perso.setH(self.direction)


# le corps du programme principal
if __name__ == "__main__":
    monJeu = ShowBase()
    ######## MISE EN PLACE DU DECOR
    monJeu.cam.setPos(40, -80, 80)
    # Orientation de la caméra
    monJeu.cam.setHpr(20, -30, 0)
    # Dessin du decor
    decor = monJeu.loader.loadModel("mes_objets3D/environment")
    # On attache le décor à la cène
    decor.reparentTo(monJeu.render)
    ######## AJOUT DU PERSONNAGE
    # On charge le modèle 3D
    modeleJoueur = Actor("mes_objets3D/panda")
    # On l'attache à la scène
    modeleJoueur.reparentTo(monJeu.render)
    # On règle les paramètres du joueur
    joueur = Perso(modeleJoueur, 0, 42, 0, 45)
    ######## GESTION DES EVENEMENTS
    monJeu.accept("mouse1", joueur.tourne)

    monJeu.run()
Пример #28
0
    mesh.set_textures(database["textures"])
    mesh.set_scale(6371)
    pos = 6371 + 9000
    mesh.set_pos(Point3(0, pos, 0))
    render_pipeline.setEffect(mesh.node_path, "Effects/Earth.effect")
    mesh.reparent_to(base.render)

    sun_light = DirectionalLight()
    sun_pos = Vec3(10000, pos, 0)
    sun_light.setSunDistance(20000)
    sun_light.setPos(sun_pos)
    sun_light.setPssmTarget(base.cam, base.camLens)
    sun_light.setColor(Vec3(1.0))
    sun_light.setShadowMapResolution(2048)
    sun_light.setCastsShadows(True)
    render_pipeline.addLight(sun_light)

    scattering = render_pipeline.getScattering()
    scattering.adjustSetting("atmosphereOffset", Vec3(0, pos, 0))
    scattering.adjustSetting("atmosphereScale", Vec3(1.0))
    render_pipeline.setScatteringSource(sun_light)

    controller = MovementController(base)
    controller.setup()

    base.accept("f3", toggleSceneWireframe)
    render_pipeline.reloadShaders()
    render_pipeline.onSceneInitialized()

    base.run()
Пример #29
0
import sys

from direct.showbase.ShowBase import ShowBase
from direct.actor.Actor import Actor

from panda3d.core import DirectionalLight
from panda3d.core import KeyboardButton
from panda3d.core import VBase3

s = ShowBase()
s.disable_mouse()
s.accept('escape', sys.exit)

s.cam.set_pos(0, -5, 5)
s.cam.look_at(0, 0, 0)

a = s.loader.loadModel('assets/cars/Ricardeaut_Magnesium.bam')
a.reparent_to(s.render)

repulsors = a.findAllMatches("**/fz_repulsor*")
ACCELERATE = 'accelerate'
TURN_LEFT = 'turn_left'
TURN_RIGHT = 'turn_right'
STRAFE = 'strafe'
HOVER = 'hover'
tags = [ACCELERATE, TURN_LEFT, TURN_RIGHT, STRAFE, HOVER]
X = '_x'
Y = '_y'
for repulsor in repulsors:
    for tag in tags:
        tag_x = repulsor.get_tag(tag + X)
Пример #30
0
    pos = (-0.8,0,0.5),
    scale = 0.1,
    width = 14,
    numLines = 10,
    state = DGG.DISABLED,
    parent = frameMain)

# Function which will write the given text in the
# textbox, where we store all send and recieved messages.
# This Function will only write the last 10 messages and
# cut of the erlier messages
def setText(messageText):
    # get all messages from the textbox
    parts = txt_messages.get().split('\n')
    if len(parts) >= 10:
        cutParts = ''
        # as the textbox can only hold 10 lines cut out the first entry
        for i in range(1,len(parts)):
            cutParts += parts[i] + '\n'
        txt_messages.enterText(cutParts + messageText)
    else:
        txt_messages.enterText(txt_messages.get() + '\n' + messageText)

# create a DirectObject instance, which will then catch the events and
# handle them with the given functions
base.accept('setText', setText)
base.accept('escape', exit)

# start the application
base.run()
Пример #31
0
traverser.addCollider(pickerNP, handler)

def handlePick():
    if not editMode:
        return

    if base.mouseWatcherNode.hasMouse():
        mpos = base.mouseWatcherNode.getMouse()
        pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())

        traverser.traverse(render)
        if handler.getNumEntries() > 0:
            handler.sortEntries()
            pickedObj = handler.getEntry(0).getIntoNodePath()
            pickedObj = pickedObj.findNetTag('cell')
            if not pickedObj.isEmpty():
                cell = grid[int(pickedObj.getX())][int(pickedObj.getY())]
                cell.alive = not cell.alive
                cell.draw()

def clearGrid():
    for row in grid:
        for cell in row:
            cell.alive = False
    draw()

base.accept('mouse1', handlePick)

initialize()
base.run()
Пример #32
0
    ruler.setScale(.05, 1, 2)  #2 unit tall board
    ruler.setTwoSided(1)
    ruler.reparentTo(base.render)

    def rotateTree(task):
        phi = 10 * task.time
        tree.setH(phi)
        return task.cont

    base.taskMgr.add(rotateTree, "merrygoround")

    base.cam.setPos(0, -4 * L0, L0 / 2)
    base.render.setShaderAuto()
    base.setFrameRateMeter(1)
    #    base.toggleWireframe()
    base.accept('escape', sys.exit)
    base.accept('z', base.toggleWireframe)
    #    pycallgraph.make_dot_graph('treeXpcg.png')
    base.setBackgroundColor((.0, .5, .9))
    base.render.analyze()
    base.run()

#TODO
#2013.04.24: Rework.
# each "branch" will grow ~f(generation).
# buds will spawn at semi random locations along the length of a branch
# every 'generation' (season) will produce 0 - N new buds/ child-branches
#            The .addbud method will be split into a .grow and .addbuds methods to accomplish above

##### OLD COMMENTS PRE SPLIT ON 2013.04.24
#   - clean up: move branch Hpr out of bud and into child branch property
Пример #33
0
        camvec.normalize()
        if camdist > 10.0:
            base.camera.setPos(base.camera.getPos() + camvec * (camdist - 10))
            camdist = 10.0
        if camdist < 5.0:
            base.camera.setPos(base.camera.getPos() - camvec * (5 - camdist))
            camdist = 5.0

        # The camera should look in ralph's direction,
        # but it should also try to stay horizontal, so look at
        # a floater which hovers above ralph's head.
        base.camera.lookAt(self.floater)

        return task.cont

base.accept("escape", exit)

# initialize the client
client = GameClientRepository()


from direct.gui.OnscreenText import OnscreenText
from panda3d.core import TextNode

# Function to put instructions on the screen.
def addInstructions(pos, msg):
    return OnscreenText(text=msg, style=1, fg=(0, 0, 0, 1), shadow=(1, 1, 1, 1),
                        parent=base.a2dTopLeft, align=TextNode.ALeft,
                        pos=(0.08, -pos - 0.04), scale=.06)

# Function to put title on the screen.
#!/usr/bin/env python

import sys

from direct.showbase.ShowBase import ShowBase
from panda3d.core import Vec3, Point3
from panda3d.bullet import BulletWorld, BulletRigidBodyNode, BulletSphereShape

s = ShowBase()
s.disable_mouse()
s.accept('escape', sys.exit)

# The physics simulation itself
physics = BulletWorld()
physics.setGravity(Vec3(0, 0, 0))
def step_physics(task):
  dt = globalClock.getDt()
  physics.doPhysics(dt)
  return task.cont
s.taskMgr.add(step_physics, 'physics simulation')

# A physical object in the simulation
node = BulletRigidBodyNode('Box')
node.setMass(1.0)
node.addShape(BulletSphereShape(1))
# Attaching the physical object in the scene graph and adding
# a visible model to it
np = s.render.attachNewNode(node)
np.set_pos(0, 0, 0)
np.set_hpr(45, 0, 45)
m = loader.loadModel("models/smiley")
Пример #35
0
 def accept(self, event, method, extraArgs=[], direct=False):
     if len(event) == 1 and not direct:
         self.keystrokes[event] = [method, extraArgs]
     else:
         ShowBase.accept(self, event, method, extraArgs=extraArgs)
Пример #36
0
class Panda3dInstance(object):
    """This class normally is instantiated in a subprocess, where it spawns
    Panda3D.

    If you aren't 100% sure what you're doing, use the Panda3dManager instead.
    """
    def __init__(self, pipe, name):
        """Arguments:
        pipe -- Multiprocessing pipe for communication. See messagecenter
                module for more info.
        name -- Name of this instance.
        """

        #self.gameobjects = []

        self.messageclient = MessageClient(pipe)
        self.name = name
        self.windows = {}

        # set a few default settings
        loadPrcFileData("", "window-type none")
        loadPrcFileData("", "audio-library-name null")

        # initiate Panda3D
        self.base = ShowBase()

        # start processing incoming requests
        self.messageclient.addListener(self.UImessageProcessor, req_type=UI)

        # The request processing task should never stop as long as the
        # subprocess exists. This is a wrapper that ensures that and saves
        # us from confusion about "hey, why has this message processing
        # stopped?!"
        def messageProcessor(task):
            self.messageclient.process()
            return task.cont

        self.base.addTask(messageProcessor, "message processor")

        # As soon as the user clicks the window, it should get focus, like any other widget.
        self.base.accept("mouse1", self.focus)

        # TODO: Wrap this around a try..except block and notify the main
        # process on errors.
        self.base.run()

    def getWindowUnderPointer(self):
        """Returns the key from self.windows of the window the primary poiter
        currently hovers over.
        """
        for win_id, win in self.windows.iteritems():
            props = win.getProperties()
            pointer = win.getPointer(0)
            if pointer.getInWindow():
                return win_id

    def addWindow(self, handle=None, width=500, height=500):
        """Create a new window showing the scene. Add it to the windows list
        and return it.
        If handle is not None, it is used as parent window.
        """
        wp = WindowProperties()
        wp.setOrigin(0, 0)
        wp.setSize(width, height)
        if handle is not None:
            wp.setParentWindow(handle)
        self.base.openDefaultWindow(props=wp,
                                    type="onscreen",
                                    requireWindow=True)
        return self.base.winList[-1]

    def UImessageProcessor(self, message):
        p = message.payload
        # TODO: look up the req_spec attribute, not class instance
        if p.req_spec == OPEN_WINDOW:
            assert not self.windows.has_key(p.window_id)
            win = self.addWindow(p.handle, p.width, p.height)
            self.windows[p.window_id] = win
        elif p.req_spec == RESIZE_WINDOW:
            self.resizeWindow(p.window_id, p.width, p.height)

    def focus(self, window_id=None):
        """Bring Panda3d to foreground, so that it gets keyboard focus.
        Also send a message to wx, so that it doesn't render a widget focused.
        We also need to say wx that Panda now has focus, so that it can notice when
        to take focus back.

        If window_id is given, that window will be focused, otherwise the one
        the pointer hovers upon. If the pointer doesn't hover over a window,
        a random window is taken. If there is no window, this function does nothing.
        """
        if window_id is None:
            window_id = self.getWindowUnderPointer()
        if window_id is None:
            for win in self.windows.values():
                window_id = win
                break
        if window_id is None:
            return
        wp = WindowProperties()
        wp.setForeground(True)
        self.windows[window_id].requestProperties(wp)
        # We request focus (and probably already have keyboard focus), so make wx
        # set it officially. This prevents other widgets from being rendered focused.
        self.messageclient.unicast(self.name + " gui",
                                   FocusWindowRequest(window_id))

    def resizeWindow(self, window_id, width, height):
        """window_id is an index of a window from base.winList."""
        window = self.windows[window_id]
        old_wp = window.getProperties()
        if old_wp.getXSize() == width and old_wp.getYSize() == height:
            return
        wp = WindowProperties()
        wp.setOrigin(0, 0)
        wp.setSize(width, height)
        window.requestProperties(wp)

    def close(self):
        # Everything should be garbage collected this way, except maybe the
        # messaging connection to the server, which will keep sending messages
        # to us.
        # TODO: fix that.
        sys.exit()

    def addGameObject(self, name=None):
        """Add a new game object to the scene."""
        # TODO: we should send a real id instead of name or None

        self.messageclient.others(AddGameObjectRequest(name))
        self.addRequestedGameObject(name)

    def addRequestedGameObject(self, name=None):
        """Add a game object to the local scene (only this P3D instance)."""
        go = GameObject(name)
        go.transform.parent = Root(render)
        self.gameobjects.append(go)
Пример #37
0
#!/usr/bin/env python

import sys

from panda3d.core import Point3

from direct.showbase.ShowBase import ShowBase

s = ShowBase()
base.disable_mouse()
s.accept("escape", sys.exit)

model = base.loader.load_model("models/smiley")
model.reparent_to(base.render)
base.cam.set_pos(0, -20, 0)
base.cam.look_at(0, 0, 0)


def adjust_pos(task):
    if base.mouseWatcherNode.has_mouse():
        model_pos = model.get_pos(base.cam)
        frustum_pos = Point3()
        base.cam.node().get_lens().project(model_pos, frustum_pos)
        mouse_x = base.mouseWatcherNode.get_mouse_x()
        mouse_y = base.mouseWatcherNode.get_mouse_y()
        model_depth = frustum_pos[2]
        new_frustum_pos = Point3(mouse_x, mouse_y, model_depth)
        new_model_pos = Point3()
        base.cam.node().get_lens().extrude_depth(new_frustum_pos,
                                                 new_model_pos)
        model.set_pos(base.cam, new_model_pos)
Пример #38
0
base = ShowBase()


def set_dirty_name():
    wp = WindowProperties()
    wp.setTitle("*Node Editor")
    base.win.requestProperties(wp)


def set_clean_name():
    wp = WindowProperties()
    wp.setTitle("Node Editor")
    base.win.requestProperties(wp)


base.accept("request_dirty_name", set_dirty_name)
base.accept("request_clean_name", set_clean_name)

# Disable the default camera movements
base.disableMouse()

#
# VIEW SETTINGS
#
base.win.setClearColor((0.16, 0.16, 0.16, 1))
render.setAntialias(AntialiasAttrib.MAuto)
render2d.setAntialias(AntialiasAttrib.MAuto)

NodeEditor(base.pixel2d)

base.run()
Пример #39
0
                        handler.getEntry(0).getIntoNodePath().findNetTag(
                            'botTag').isEmpty())
                else:
                    handlePickedObject(pickedObj)


def hotbarSelect(slot):
    global currentBlock
    currentBlock = inventory[slot - 1]
    currentBlockText["text"] = blockNames[currentBlock]
    if verboseLogging:
        print "Selected hotbar slot %d" % slot
        print "Current block: %s" % blockNames[currentBlock]


base.accept('mouse1', handlePick)
base.accept('mouse3', handlePick, extraArgs=[True])
base.accept('escape', pause)
base.accept('1', hotbarSelect, extraArgs=[1])
base.accept('2', hotbarSelect, extraArgs=[2])
base.accept('3', hotbarSelect, extraArgs=[3])
base.accept('4', hotbarSelect, extraArgs=[4])
base.accept('5', hotbarSelect, extraArgs=[5])
base.accept('6', hotbarSelect, extraArgs=[6])
base.accept('7', hotbarSelect, extraArgs=[7])
base.accept('8', hotbarSelect, extraArgs=[8])
base.accept('9', hotbarSelect, extraArgs=[9])


def handlePickedObject(obj):
    if verboseLogging:
Пример #40
0
                    handleRightPickedObject(pickedObj, handler.getEntry(0).getIntoNodePath().findNetTag('westTag').isEmpty(),
                        handler.getEntry(0).getIntoNodePath().findNetTag('northTag').isEmpty(), handler.getEntry(0).getIntoNodePath().findNetTag('eastTag').isEmpty(),
                        handler.getEntry(0).getIntoNodePath().findNetTag('southTag').isEmpty(), handler.getEntry(0).getIntoNodePath().findNetTag('topTag').isEmpty(),
                        handler.getEntry(0).getIntoNodePath().findNetTag('botTag').isEmpty())
                else:
                    handlePickedObject(pickedObj)

def hotbarSelect(slot):
    global currentBlock
    currentBlock = inventory[slot-1]
    currentBlockText["text"] = blockNames[currentBlock]
    if verboseLogging:
        print "Selected hotbar slot %d" % slot
        print "Current block: %s" % blockNames[currentBlock]

base.accept('mouse1', handlePick)
base.accept('mouse3', handlePick, extraArgs=[True])
base.accept('escape', pause)
base.accept('1', hotbarSelect, extraArgs=[1])
base.accept('2', hotbarSelect, extraArgs=[2])
base.accept('3', hotbarSelect, extraArgs=[3])
base.accept('4', hotbarSelect, extraArgs=[4])
base.accept('5', hotbarSelect, extraArgs=[5])
base.accept('6', hotbarSelect, extraArgs=[6])
base.accept('7', hotbarSelect, extraArgs=[7])
base.accept('8', hotbarSelect, extraArgs=[8])
base.accept('9', hotbarSelect, extraArgs=[9])

def handlePickedObject(obj):
    if verboseLogging:
        print "Left clicked a block at %d, %d, %d" % (obj.getX(), obj.getY(), obj.getZ())
Пример #41
0
app = ShowBase()
app.setBackgroundColor(0.6, 0.65, 1.0)

# render-to-texture stuff
altBuffer = app.win.makeTextureBuffer("spritebuf", 256, 256)
#altBuffer.setInverted(True)
altRender = NodePath("alt render")
altCam = app.makeCamera(altBuffer)
altCam.reparentTo(altRender)
#altCam.setPos(0.25, -12, 0)
teapot = loader.loadModel('model/banana.egg')
teapot.reparentTo(altRender)
teapot.setPos(0, 5, -0.1)
teapot.setH(270)  # lazy way to compensate for the inverted buffer
teapot.setP(180)
app.accept("v", app.bufferViewer.toggleEnable)
app.bufferViewer.setPosition("llcorner")
app.bufferViewer.setCardSize(1.0, 0.0)

# lighting
dlight = DirectionalLight('dlight')
alight = AmbientLight('alight')
dlnp = altRender.attachNewNode(dlight)
alnp = altRender.attachNewNode(alight)
dlight.setColor(Vec4(0.8, 0.8, 0.5, 1))
alight.setColor(Vec4(0.2, 0.2, 0.2, 1))
dlnp.setHpr(0, -60, 0)
#altRender.setLight(dlnp)
#altRender.setLight(alnp)

# vertex writer