コード例 #1
0
def fill(filler, frame, BGColor, lineThick, bevel=None, arrowhead=None):
    h = frame[3] - frame[2]
    incr = 10 / float(base.win.getProperties().getYSize())
    bg = LineSegs()
    bg.setColor(BGColor)
    bg.setThickness(lineThick)
    for i in range(1, int(h * 33)):
        if bevel and arrowhead:
            filler(bg, [
                frame[0] + incr * i, frame[1] - incr * i, frame[2] + incr * i,
                frame[3] - incr * i
            ], bevel, arrowhead)
        elif bevel:
            filler(bg, [
                frame[0] + incr * i, frame[1] - incr * i, frame[2] + incr * i,
                frame[3] - incr * i
            ], bevel)
        elif arrowhead:
            filler(bg, [
                frame[0] + incr * i, frame[1] - incr * i, frame[2] + incr * i,
                frame[3] - incr * i
            ], arrowhead)
        else:
            filler(bg, [
                frame[0] + incr * i, frame[1] - incr * i, frame[2] + incr * i,
                frame[3] - incr * i
            ])
    fnp = NodePath(bg.create())
    fnp.setBin("fixed", 10)
    return fnp
コード例 #2
0
class RepairSawingLine:
    def __init__(self, parent, thickness, color, lineSpawnDist=0.01):
        self.points = []
        self.parent = parent
        self.thickness = thickness
        self.color = color
        self.lineNode = None
        self.lineDrawer = LineSegs()
        self.lineDrawer.setThickness(thickness)
        self.lineSpawnDist = lineSpawnDist
        self.currentPoint = None
        self.startPoint = None
        self.redraw()

    def redraw(self):
        self.clearLine()
        self.lineDrawer.reset()
        self.lineDrawer.setThickness(self.thickness)
        self.lineDrawer.setColor(self.color)
        if len(self.points) > 0:
            self.lineDrawer.moveTo(self.points[0])
            for i in range(1, len(self.points)):
                p = self.points[i]
                self.lineDrawer.drawTo(p)
                self.currentPoint = p

        self.lineNode = NodePath(self.lineDrawer.create())
        self.lineNode.reparentTo(self.parent)
        self.lineNode.setBin('fixed', 37)
        self.lineNode.setTransparency(True)

    def update(self, point):
        if self.currentPoint == None or (
                point - self.currentPoint).length() >= self.lineSpawnDist:
            self.addPoint(point)
            self.redraw()

    def addPoint(self, p):
        if len(self.points) == 0:
            self.startPoint = p

        self.points.append(p)

    def clearLine(self):
        if self.lineNode != None:
            self.lineNode.removeNode()

    def reset(self):
        self.clearLine()
        self.points = []
        self.redraw()
        self.currentPoint = None
        self.startPoint = None

    def show(self):
        self.lineNode.unstash()

    def hide(self):
        self.lineNode.stash()
コード例 #3
0
 def addToon(self, toon):
     marker = NodePath('toon_marker-%i' % toon.doId)
     marker.reparentTo(self)
     self._getToonMarker(toon).copyTo(marker)
     marker.setColor(toon.style.getHeadColor())
     if toon.isLocal():
         marker.setScale(Globals.Gui.LocalMarkerScale)
         marker.setBin('fixed', 10)
     else:
         marker.setScale(Globals.Gui.MarkerScale)
         marker.setBin('fixed', 5)
     marker.flattenStrong()
     self._toonMarkers[toon] = marker
コード例 #4
0
 def addToon(self, toon):
     marker = NodePath('toon_marker-%i' % toon.doId)
     marker.reparentTo(self)
     self._getToonMarker(toon).copyTo(marker)
     marker.setColor(toon.style.getHeadColor())
     if toon.isLocal():
         marker.setScale(Globals.Gui.LocalMarkerScale)
         marker.setBin('fixed', 10)
     else:
         marker.setScale(Globals.Gui.MarkerScale)
         marker.setBin('fixed', 5)
     marker.flattenStrong()
     self._toonMarkers[toon] = marker
コード例 #5
0
ファイル: sprites.py プロジェクト: vardis/pano
    def createSprite(self, sprite):
        '''
        Creates a new sprite and returns a SpriteRenderInterface for controlling this sprite instance.
        The newly created sprite is located at (0,0) in screen coordinates its dimensions are specified
        by the given Sprite argument.
        @param sprite: A Sprite resource that describes the properties of the sprite to created.
        @return: A SpriteRenderInterface instance or None if it failed to create the sprite.
        '''
        if sprite.eggFile is not None:
            spriteNP = self.resources.loadModel(sprite.eggFile)
            tex = None
        else:
            if sprite.video is not None:
                card = self.cardMaker.generate()
                tex = VideoPlayer.renderToTexture(self.resources,
                                                  video=sprite.video,
                                                  audio=sprite.audio)
            elif sprite.image is not None:
                card = self.cardMaker.generate()
                tex = self.resources.loadTexture(sprite.image)
                sprite.width = tex.getXSize()
                sprite.height = tex.getYSize()
            else:
                self.log.error('Could not determine type for sprite: %s' %
                               sprite.name)
                return None

            spriteNP = NodePath(card)
            spriteNP.setTexture(tex)

        nodeName = self.getSpriteNodeName(sprite.name)
        spriteNP.setName(nodeName)
        spriteNP.setPos(0, 1, 0)
        spriteNP.setScale(sprite.width, 1.0, sprite.height)
        spriteNP.setTransparency(1)

        spriteNP.reparentTo(self.sprite2d)

        spriteNP.setDepthTest(False)
        spriteNP.setDepthWrite(False)
        spriteNP.setBin("fixed", PanoConstants.RENDER_ORDER_SPRITES)
        spriteNP.setPythonTag('sprite', sprite)

        if sprite.video is not None:
            spriteNP.setPythonTag('video', tex)
            tex.setLoop(True)
            tex.play()

        return SpriteRenderInterface(spriteNP)
コード例 #6
0
def setSky(directory, ext=".jpg"):
    """Sets up a skybox. 'directory' is the directory whitch contains 6
    pictures with the names right.ext, left.ext and so on (see template).
    ext is the extension the pictures have (with dot).
    """
    #TODO: accept all supported image file extensions without the need for an
    #      extra argument

    # remove the old sky first when loading a new one
    # TODO: get this working...
    #oldsky = render.find("*sky*")
    #print oldsky
    #for child in render.getChildren():
    #    child.remove()

    sky = NodePath().attachNewNode("sky")
    sides = {
        "right":  ( 1,  0,  0, -90,   0,  0),
        "left":   (-1,  0,  0,  90,   0,  0),
        "top":    ( 0,  0,  1,   0,  90,  0),
        "bottom": ( 0,  0, -1,  180,  -90,  0),
        "front":  ( 0,  1,  0,   0,   0,  0),
        "back":   ( 0, -1,  0, 180,   0,  0)
        }
    for name, poshpr in sides.iteritems():

        c = CardMaker(name)
        c.setFrame(-1, 1, -1, 1)
        card = c.generate()
        cardnode = sky.attachNewNode(card)
        cardnode.setPosHpr(*poshpr)
        tex = loader.loadTexture("skyboxes/" + directory + "/" + name + ext)
        tex.setWrapV(tex.WMClamp)
        tex.setMagfilter(tex.FTNearestMipmapNearest)
        tex.setMinfilter(tex.FTNearestMipmapNearest)
        cardnode.setTexture(tex)

    sky.flattenStrong()
    sky.setScale(10, 10, 10)
    sky.setCompass()
    sky.setBin('background', 0)
    sky.setDepthTest(False)
    sky.setDepthWrite(False)
    sky.setLightOff()
    sky.reparentTo(camera)

    geom = sky.getChild(0).node()
    geom.setName("cube")
コード例 #7
0
ファイル: buttonjoe.py プロジェクト: rll/labeling_tool
def fill(filler, frame, BGColor, lineThick, bevel = None, arrowhead = None):
	h = frame[3]-frame[2]
	incr = 10/float(base.win.getProperties().getYSize())
	bg = LineSegs()
	bg.setColor(BGColor)
	bg.setThickness(lineThick)
	for i in range(1,int(h*33)):
		if bevel and arrowhead:
			filler(bg, [frame[0]+incr*i,frame[1]-incr*i,frame[2]+incr*i,frame[3]-incr*i], bevel, arrowhead)
		elif bevel:
			filler(bg, [frame[0]+incr*i,frame[1]-incr*i,frame[2]+incr*i,frame[3]-incr*i], bevel)
		elif arrowhead:
			filler(bg, [frame[0]+incr*i,frame[1]-incr*i,frame[2]+incr*i,frame[3]-incr*i], arrowhead)
		else:
			filler(bg, [frame[0]+incr*i,frame[1]-incr*i,frame[2]+incr*i,frame[3]-incr*i])
	fnp = NodePath(bg.create())
	fnp.setBin("fixed", 10) 
	return fnp
コード例 #8
0
ファイル: Node2DRenderer.py プロジェクト: vardis/pano
class Node2DRenderer:
    def __init__(self, resources, spriteEngine):

        self.log = logging.getLogger('pano.render2D')

        self.resources = resources

        # the Node that is being rendered
        self.node = None

        # the scene's root node
        self.sceneRoot = None

        # scene node for the full screen quad that renders the background texture of 2D nodes
        self.bgCard = None

        # bounds in XZ plane, by default we assume the node is parented to render2d
        # the order is left, right, top, bottom
        self.bounds = (-1.0, 1.0, -1.0, 1.0)

        self.spritesByHotspot = {}
        self.debugSprites = {}

        # used for detecting the hotspot under a window coordinate
        self.raycaster = None

        # this caches the node's hotspot map, if any
        self.hotspotsMap = None

        self.spritesEngine = spriteEngine

    def initialize(self):

        asp = base.getAspectRatio()
        lens = OrthographicLens()
        lens.setFilmSize(2.0, 2.0)
        lens.setNearFar(-1000, 1000)
        self.getCamera().node().setLens(lens)

        # creates the root node
        if self.sceneRoot is None:
            self.sceneRoot = render2d.attachNewNode(
                PanoConstants.NODE2D_ROOT_NODE)

        self.raycaster = NodeRaycaster(self)
        self.raycaster.initialize()

    def dispose(self):
        '''
        Disposes any rendering resources, it assumes that this instance won't be used again.
        '''
        if self.raycaster is not None:
            self.raycaster.dispose()

        self.clearScene()

        if self.sceneRoot is not None:
            self.sceneRoot.removeNode()
            self.sceneRoot = None

    def clearScene(self):
        '''
        Clears the scenegraph effectively removing all nodes from rendering.
        '''
        if self.bgCard is not None and not self.bgCard.empty():
            self.bgCard.removeNode()

        for spr in self.spritesByHotspot.values():
            spr.remove()

        for dbgSpr in self.debugSprites.values():
            dbgSpr.remove()

        self.spritesByHotspot = {}
        self.debugSprites = {}
        self.hotspotsMap = None

    def displayNode(self, node):
        """
        Displays the given node.
        """
        if self.node is not None and self.node.getName() == node.getName():
            return
        else:
            self.clearScene()
            self.node = node

        if self.node.parent2d is None or self.node.parent2d == Node.PT_Render2D:
            # when the parent is not explicitly defined, then assume render2d
            self.bounds = (-1.0, 1.0, -1.0, 1.0)
            self.sceneRoot.setScale(1.0, 1.0, 1.0)
            self.sceneRoot.reparentTo(render2d)
        else:
            #            asp = self.getCamera().node().getLens().getAspectRatio()
            asp = base.getAspectRatio()
            self.bounds = (-asp, asp, -1.0, 1.0)
            #            aspectRatio = base.getAspectRatio()
            #            self.sceneRoot.setScale(1.0 / asp, 1.0, 1.0)
            self.sceneRoot.reparentTo(aspect2d)

        if self.node.image is not None:
            self._setBackgroundTexture()

        if self.node.hotspotsMapFilename:
            if self.hotspotsMap is None:
                self.hotspotsMap = self.resources.loadHotspotsMap(
                    self.node.hotspotsMapFilename)

        self._createHotspotsGeoms()

    def render(self, millis):
        pass

    def getNode(self):
        """
        Returns the Node object that we are currently rendering.
        """
        return self.node

    def getSceneRoot(self):
        '''
        Returns the Nodepath that acts as the scene root.
        '''
        return self.sceneRoot

    def getCamera(self):
        return base.cam2d

    def _setBackgroundTexture(self):
        '''
        Sets the background texture for 2D nodes.
        It creates a full screen quad that has the corresponding texture applied to it.
        Note: The field node.parent2d specifies if the quad will be parented to render2d or aspect2d.
        '''
        bgTex = self.resources.loadTexture(self.node.image)
        if bgTex is not None:
            cm = CardMaker('node_bg')
            cm.setFrame(self.bounds[0], self.bounds[1], self.bounds[2],
                        self.bounds[3])
            cm.setHasUvs(True)
            self.bgCard = NodePath(cm.generate())
            self.bgCard.setName('2dnode_image')
            self.bgCard.setTexture(bgTex)
            bgTex.setMinfilter(Texture.FTNearest)
            bgTex.setMagfilter(Texture.FTNearest)
            self.bgCard.reparentTo(self.sceneRoot)
            self.bgCard.setBin("fixed",
                               PanoConstants.RENDER_ORDER_BACKGROUND_IMAGE)
        else:
            self.log.error('Failed to set background texture for node %s.' %
                           self.node.name)

    def _createHotspotsGeoms(self):
        """
        Creates nodes for the pickable geometry (a box) of hotspots and their sprite visuals.
        """
        for hp in self.node.getHotspots():
            self.renderHotspot(hp)
            self.renderHotspotDebugGeom(hp)

    def renderHotspot(self, hp, spriteOverride=None):
        '''
        Renders the given hotspot using its associated sprite.
        @param hp: The hotspot to render. 
        @param sprite: If not None it is used for overriding the hotspot's sprite.
        '''
        spriteName = hp.sprite if spriteOverride is None else spriteOverride
        if spriteName is not None:
            sprite = self.resources.loadSprite(spriteName)
            if sprite is None:
                self.log.error('Failed to render sprite %s' % sprite.name)
                return

            sri = self.spritesEngine.createSprite(sprite)
            sri.setPos(hp.xo + hp.width / 2, 1.0, hp.yo + hp.height / 2)
            if not hp.active:
                sri.hide()

            self.spritesByHotspot[hp.name] = sri

    def renderHotspotDebugGeom(self, hp):
        '''
        Renders a debug geometry for the given hotspot. 
        @param hp: The hotspot for which to render debug geometry.
        '''
#        dbgSprite = Sprite('debug_' + hp.name)
#        dbgSprite.eggFile = 'debug_box.egg'
#        dbgSprite.width = hp.width
#        dbgSprite.height = hp.height
#
#        sri = self.spritesEngine.createSprite(dbgSprite)
#        sri.setPos(hp.xo, 1.0, hp.yo)
#        self.debugSprites[hp.name] = sri

    def getHotspotSprite(self, hotspot):
        """
        Returns a SpriteRenderInterface which can be used to control the hotspot's sprite.
        
        @param hotspot: The hotspot instance
        @return: A SpriteRenderInterface instance or None.
        """
        return self.spritesByHotspot.get(hotspot.name)

    def removeHotspot(self, hotspot):
        '''
        Removes a hotspot from the render list. The debug geometry and sprite associated with the hotspot
        won't be visible anymore.
        @param hotspot: A pano.model.Hotspot instance for the hotspot to be removed.
        '''
        if self.log.isEnabledFor(logging.DEBUG):
            self.log.debug('Removing hotspot %s' % hotspot.name)

        spr = self.getHotspotSprite(hotspot)
        if spr is not None:
            spr.remove()
            del self.spritesByHotspot[hotspot.name]

        # remove the hotspot's debug geometry
        spr = self.debugSprites.get(hotspot.name)
        if spr is not None:
            spr.remove()
            del self.debugSprites[hotspot.name]

    def hideHotspot(self, hp):
        '''
        Hides the scene node that parents the hotspots sprite in the scene.
        @param hp: The hotspot that will be hidden. 
        '''
        if self.log.isEnabledFor(logging.DEBUG):
            self.log.debug('Hiding hotspot %s' % hp.name)

        sri = self.getHotspotSprite(hp)
        if sri is not None:
            sri.hide()

    def showHotspot(self, hp):
        '''
        Shows the scene node that parents the hotspots sprite in the scene.
        @param hp: The hotspot that will be shown. 
        '''
        if self.log.isEnabledFor(logging.DEBUG):
            self.log.debug('Showing hotspot %s' % hp.name)

        sri = self.getHotspotSprite(hp)
        if sri is not None:
            sri.show()

    def replaceHotspotSprite(self, hotspot, newSprite):
        '''
        Changes the visual appearance of a hotspot by replacing its sprite with a new one.
        @param hp: The hotspot that will have its sprite replaced.
        @param newSprite: The name of the new sprite to use for rendering.  
        '''
        if self.log.isEnabledFor(logging.DEBUG):
            self.log.debug("Replacing hotspot's %s sprite with %s" %
                           (hotspot.name, newSprite))
        self.removeHotspot(hotspot)
        self.renderHotspot(hotspot, newSprite)
        self.renderHotspotDebugGeom(hotspot)

    def pauseAnimations(self):
        """
        Stops all node animations.
        """
        for sri in self.spritesByHotspot.values():
            sri.pause()

    def resumeAnimations(self):
        """
        Resumes node animations.
        """
        for sri in self.spritesByHotspot.values():
            sri.play()

    def drawDebugHotspots(self, flag):
        self.drawHotspots = flag
        for spr in self.debugSprites.values():
            spr.show()
        else:
            spr.hide()

    def raycastHotspots(self, x, y):
        '''
        Returns the hotspot(s) under the given window coordinates.
        @param x: The x window coordinate of the mouse in render space.
        @param y: The y window coordinate of the mouse in render space.
        @return: A list of Hotspot instances or None. 
        '''
        screenPoint = sprite2d.getRelativePoint(render, Vec3(x, 1.0, y))
        hotspots = []
        sx = int(screenPoint.getX())
        sy = int(screenPoint.getZ())

        # use the node's hotspots map if exists, otherwise check if the click point
        # lies inside a hotspot's bounds
        if self.node.hotspotsMapFilename:
            # convert the coordinates from -1..1 to 0..1 range
            x = (x + 1) / 2.0
            y = (y + 1) / 2.0
            hpName = self.hotspotsMap.getHotspot(x, 1.0 - y)
            hp = self.node.getHotspot(hpName)
            if hp:
                hotspots.append(hp)
        else:
            # check through bounds
            for hp in self.node.getHotspots():
                if sx >= hp.xo and sx <= hp.xe and sy >= hp.yo and sy <= hp.ye:
                    maskImg = self.hotspotsImageMasks.get(hp.name)
                    if maskImg is not None:
                        imgX = int(maskImg.getXSize() * sx / (hp.xe - hp.xo))
                        imgY = int(maskImg.getYSize() * sy / (hp.ye - hp.yo))
                        col = maskImg.getXel(imgX, imgY)
                        if col[0] == 0.0 and col[1] == 0.0 and col[2] == 0.0:
                            continue

                    hotspots.append(hp)
        return hotspots

    def _getImageDimensions(self):
        tex = self.bgCard.getTexture()
        return (tex.getXSize(), tex.getYSize())
コード例 #9
0
def generateHullCache(modelClass):
    geom = loader.loadModel('models/shipparts/pir_m_shp_%s' %
                            HullDict[modelClass])
    stripPrefix(geom, 'model:')
    for node in geom.findAllMatches('**/omit'):
        parent = node.getParent()
        omit = parent.attachNewNode(ModelNode('omit'))
        node.reparentTo(omit)
        node.setName('geom')

    preFlatten(geom)
    logic = loader.loadModel('models/shipparts/pir_m_shp_%s_logic' %
                             HullDict[modelClass])
    locators = logic.find('**/locators')
    for side in ['left', 'right']:
        bad = locators.find('**/location_ropeLadder_0_%s' % side)
        if bad:
            bad.setName('location_ropeLadder_%s_0' % side)

        bad = locators.find('**/location_ropeLadder_1_%s' % side)
        if bad:
            bad.setName('location_ropeLadder_%s_1' % side)

        bad = locators.find('**/location_ropeLadder_1_%s1' % side)
        if bad:
            bad.setName('location_ropeLadder_%s_2' % side)

    collisions = logic.find('**/collisions')
    badPanel = collisions.find('**/collision_panel_3')
    if badPanel:
        badPanel.setName('collision_panel_2')
    collisions.find('**/collision_panel_0').setTag('Hull Code', '0')
    collisions.find('**/collision_panel_1').setTag('Hull Code', '1')
    collisions.find('**/collision_panel_2').setTag('Hull Code', '2')
    walls = collisions.find('**/collision_walls')
    if walls:
        walls.setTag('Hull Code', '255')
    else:
        collisions.attachNewNode('collision_walls')

    shipToShipCollide = collisions.find('**/collision_shiptoship')
    shipToShipCollide.setCollideMask(PiratesGlobals.ShipCollideBitmask)
    deck = collisions.find('**/collision_deck')
    if not deck:
        deck = collisions.attachNewNode('deck')

    mask = deck.getCollideMask()
    mask ^= PiratesGlobals.FloorBitmask
    mask |= PiratesGlobals.ShipFloorBitmask
    deck.setCollideMask(mask)
    floors = collisions.find('**/collision_floors')
    if not floors:
        floors = collisions.find('**/collision_floor')

    mask = floors.getCollideMask()
    mask ^= PiratesGlobals.FloorBitmask
    mask |= PiratesGlobals.ShipFloorBitmask
    floors.setCollideMask(mask)
    floors.setTag('Hull Code', str(255))
    geomHigh = geom.find('**/lod_high')
    geomMed = geom.find('**/lod_medium')
    if not geomMed:
        geomMed = geom.find('**/low_medium')
    if not geomMed:
        geomMed = geomHigh.copyTo(NodePath())
    geomLow = geom.find('**/lod_low')
    if not geomLow:
        geomLow = geomMed.copyTo(NodePath())
    geomSuperLow = geom.find('**/lod_superlow')
    if not geomSuperLow:
        geomSuperLow = geomLow.copyTo(NodePath())
    geomHigh.setName('high')
    geomMed.setName('med')
    geomLow.setName('low')
    geomSuperLow.setName('superlow')
    if modelClass in [21, 22, 23]:
        spike = loader.loadModel('models/shipparts/pir_m_shp_ram_spike')
        spikeTrans = locators.find('**/location_ram').getTransform(locators)
        spike.setTransform(spikeTrans)
        spike.flattenLight()
        spikeHi = spike.find('**/lod_high')
        spikeMed = spike.find('**/lod_medium')
        spikeLow = spike.find('**/lod_low')
        spikeHi.copyTo(geomHigh)
        spikeMed.copyTo(geomMed)
        spikeLow.copyTo(geomLow)
        spikeLow.copyTo(geomSuperLow)

    flipRoot = NodePath('root')
    collisions.reparentTo(flipRoot)
    locators.reparentTo(flipRoot)
    geomHigh.reparentTo(flipRoot)
    geomMed.reparentTo(flipRoot)
    geomLow.reparentTo(flipRoot)
    geomSuperLow.reparentTo(flipRoot)
    flipRoot.setH(180)
    flipRoot.flattenLight()
    omits = flipRoot.findAllMatches('**/omit')
    for node in omits:
        node.flattenStrong()

    for group in [
            'static', 'transparent', 'ropeLadder_*', 'stripeA', 'stripeB',
            'pattern'
    ]:
        for node in flipRoot.findAllMatches('**/%s' % group):
            name = node.getName()
            for subNode in node.findAllMatches('**/*'):
                subNode.setName(name)

            node.flattenStrong()
            node.setName(name)

    geomHigh.detachNode()
    geomMed.detachNode()
    geomLow.detachNode()
    geomSuperLow.detachNode()
    locators.detachNode()
    collisions.detachNode()
    genericGeoms = [geomHigh, geomMed, geomLow, geomSuperLow]

    customGeoms = [x.copyTo(NodePath()) for x in genericGeoms]
    for np in genericGeoms:
        trans = np.find('**/transparent')
        if trans:
            trans.stash()
        np.flattenLight()
        sails = np.findAllMatches('**/sails')
        sails.stash()
        omits = np.findAllMatches('**/omit')
        omits.stash()
        for node in omits:
            node.node().setPreserveTransform(node.node().PTDropNode)

        generic = NodePath('generic')
        np.findAllMatches('**/+GeomNode').wrtReparentTo(generic)
        np.findAllMatches('*').detach()
        generic.flattenStrong()
        generic.reparentTo(np)
        stripAttribs(generic, TextureAttrib)
        stripAttribs(generic, TransparencyAttrib)
        stripAttribs(generic, CullBinAttrib)
        generic.setBin('ground', 1)
        collapse(generic)
        sails.unstash()
        sails.reparentTo(np)
        for node in sails:
            node.node().setPreserveTransform(node.node().PTDropNode)

        if trans:
            trans.unstash()
            trans.flattenStrong()
            if trans.node().isOfType(ModelNode.getClassType()):
                trans.node().setPreserveTransform(ModelNode.PTDropNode)
        deck = np.find('**/=cam=shground')
        if deck:
            deck.setName('deck')
        omits.unstash()

    for np in customGeoms:
        collapse(np.find('**/static'))

    data = HullCache()
    data.root = NodePath('hull')
    data.genericGeoms = genericGeoms
    data.customGeoms = customGeoms
    data.collisions = collisions
    data.locators = locators
    return data
コード例 #10
0
ファイル: terrain.py プロジェクト: asceth/devsyn
  def make_layer(self, i, a, b):
    # get data
    data = self.subdata[a][b]

    # set color + alpha of vertex texture
    def ap(n):
      alpha = 0
      if i == n:
        alpha = 1.0
      return alpha
    def tp(n):
      list = [0, 0, 0, 0]
      if i == n:
        list = [1, 1, 1, 0.75]
      return list

    # set vertex data
    vdata = GeomVertexData('plane', GeomVertexFormat.getV3n3c4t2(), Geom.UHStatic)
    vertex = GeomVertexWriter(vdata, 'vertex')
    normal = GeomVertexWriter(vdata, 'normal')
    color = GeomVertexWriter(vdata, 'color')
    uv = GeomVertexWriter(vdata, 'texcoord')

    # set vertices
    number = 0
    for x in range(0, len(data) - 1):
      for y in range(0, len(data[x]) - 1):
        # get vertex data
        v1 = Vec3(x, y, data[x][y]['h'])
        c1 = data[x][y]['c']
        t1 = data[x][y]['texnum']
        v2 = Vec3(x+1, y, data[x+1][y]['h'])
        c2 = data[x+1][y]['c']
        t2 = data[x+1][y]['texnum']
        v3 = Vec3(x+1, y+1, data[x+1][y+1]['h'])
        c3 = data[x+1][y+1]['c']
        t3 = data[x+1][y+1]['texnum']
        v4 = Vec3(x, y+1, data[x][y+1]['h'])
        c4 = data[x][y+1]['c']
        t4 = data[x][y+1]['texnum']
        n=(0, 0, 1) # normal

        # assign vertex colors + alpha
        a1, a2, a3, a4 = ap(t1), ap(t2), ap(t3), ap(t4)
        t1, t2, t3, t4 = tp(t1), tp(t2), tp(t3), tp(t4)

        if v1[2]==0:
          t1 = [data[x][y]['c'][0], data[x][y]['c'][1], data[x][y]['c'][2],
                a1]
        if v2[2]==0:
          t2 = [data[x+1][y]['c'][0], data[x+1][y]['c'][1],
                data[x+1][y]['c'][2], a2]
        if v3[2]==0:
          t3 = [data[x+1][y+1]['c'][0], data[x+1][y+1]['c'][1],
                data[x+1][y+1]['c'][2], a3]
        if v4[2]==0:
          t4 = [data[x][y+1]['c'][0], data[x][y+1]['c'][1],
                data[x][y+1]['c'][2], a4]

        if a1 == 0 and a2 == 0 and a3 == 0 and a4 == 0:
          continue

        # add vertices
        vertex.addData3f(v1)
        normal.addData3f(*n)
        color.addData4f(*t1)
        uv.addData2f(0,0)

        vertex.addData3f(v2)
        normal.addData3f(*n)
        color.addData4f(*t2)
        uv.addData2f(1,0)

        vertex.addData3f(v3)
        normal.addData3f(*n)
        color.addData4f(*t3)
        uv.addData2f(1,1)

        vertex.addData3f(v1)
        normal.addData3f(*n)
        color.addData4f(*t1)
        uv.addData2f(0,0)

        vertex.addData3f(v3)
        normal.addData3f(*n)
        color.addData4f(*t3)
        uv.addData2f(1,1)

        vertex.addData3f(v4)
        normal.addData3f(*n)
        color.addData4f(*t4)
        uv.addData2f(0,1)

        number = number + 2

    # add triangles
    prim = GeomTriangles(Geom.UHStatic)
    for n in range(number):
      prim.addVertices((n * 3) + 2, (n * 3) + 0, (n * 3) + 1)
    prim.closePrimitive()

    # make geom
    geom = Geom(vdata)
    geom.addPrimitive(prim)

    # make geom node
    node = GeomNode("layer" + str(i) + "_" + str(a) + "_" + str(b))
    node.addGeom(geom)

    # make mesh nodePath
    mesh = NodePath(node)

    # load and assign texture
    txfile = self.tiles[i]['tex']
    tx = base.loader.loadTexture(txfile)
    tx.setMinfilter(Texture.FTLinearMipmapLinear)
    mesh.setDepthTest(DepthTestAttrib.MLessEqual)
    mesh.setDepthWrite(False)
    mesh.setTransparency(True)
    mesh.setTexture(tx)

    # set render order
    mesh.setBin("", 1)

    # locate mesh
    mesh.setPos(self.divsep * (a * int(len(self.data[a]) / self.div)),
                self.divsep * (b * int(len(self.data[b]) / self.div)), 0.001)

    # reparent mesh
    mesh.reparentTo(self.root)

    # return mesh
    return mesh
コード例 #11
0
ファイル: terrain.py プロジェクト: asceth/devsyn
  def make_base(self, a, b):
    # get data
    data = self.subdata[a][b]
    # set vertex data
    vdata = GeomVertexData('plane', GeomVertexFormat.getV3n3c4t2(), Geom.UHStatic)
    vertex = GeomVertexWriter(vdata, 'vertex')
    normal = GeomVertexWriter(vdata, 'normal')
    color = GeomVertexWriter(vdata, 'color')
    uv = GeomVertexWriter(vdata, 'texcoord')

    # set vertices
    number = 0
    for x in range(0, len(data) - 1):
      for y in range(0, len(data[x]) - 1):
        # get vertex data
        v1 = Vec3(x, y, data[x][y]['h'])
        v2 = Vec3(x + 1, y, data[x+1][y]['h'])
        v3 = Vec3(x + 1, y + 1, data[x+1][y+1]['h'])
        v4 = Vec3(x, y + 1, data[x][y+1]['h'])
        n = (0, 0, 1) # normal

        # assign vertex colors + alpha
        option = 1 # black
        if option == 1:
          c = 0
          c1 = [c, c, c, 1]
          c2 = [c, c, c, 1]
          c3 = [c, c, c, 1]
          c4 = [c, c, c, 1]
        # option2: color vertices
        if option == 2:
          alpha = 1.0
          c1 = [data[x][y]['c'][0], data[x][y]['c'][1],
                data[x][y]['c'][2], alpha]
          c2 = [data[x+1][y]['c'][0], data[x+1][y]['c'][1],
                data[x+1][y]['c'][2], alpha]
          c3 = [data[x+1][y+1]['c'][0], data[x+1][y+1]['c'][1],
                data[x+1][y+1]['c'][2], alpha]
          c4 = [data[x][y+1]['c'][0], data[x][y+1]['c'][1],
                data[x][y+1]['c'][2], alpha]

        if option == 3:
          c1 = self.color_vertex(v1)
          c2 = self.color_vertex(v2)
          c3 = self.color_vertex(v3)
          c4 = self.color_vertex(v4)

        vertex.addData3f(v1)
        normal.addData3f(*n)
        color.addData4f(*c1)
        uv.addData2f(0,0)

        vertex.addData3f(v2)
        normal.addData3f(*n)
        color.addData4f(*c2)
        uv.addData2f(1,0)

        vertex.addData3f(v3)
        normal.addData3f(*n)
        color.addData4f(*c3)
        uv.addData2f(1,1)

        vertex.addData3f(v1)
        normal.addData3f(*n)
        color.addData4f(*c1)
        uv.addData2f(0,0)

        vertex.addData3f(v3)
        normal.addData3f(*n)
        color.addData4f(*c3)
        uv.addData2f(1,1)

        vertex.addData3f(v4)
        normal.addData3f(*n)
        color.addData4f(*c4)
        uv.addData2f(0,1)

#         # add vertex h
#         vertex.addData3f(v1)
#         # normal.addData3f(*n)
#         vertex.addData3f(v2)
#         # normal.addData3f(*n)
#         vertex.addData3f(v3)
#         # normal.addData3f(*n)
#         vertex.addData3f(v1)
#         # normal.addData3f(*n)
#         vertex.addData3f(v3)
#         # normal.addData3f(*n)
#         vertex.addData3f(v4)
#         # normal.addData3f(*n)
#         # add vertex color
#         color.addData4f(*c1)
#         color.addData4f(*c2)
#         color.addData4f(*c3)
#         color.addData4f(*c1)
#         color.addData4f(*c3)
#         color.addData4f(*c4)

        # iterate
        number = number + 2

    # add triangles
    prim = GeomTriangles(Geom.UHStatic)
    for n in range(number):
      prim.addVertices((n * 3) + 2, (n * 3) + 0, (n * 3) + 1)
    prim.closePrimitive()

    # make geom
    geom = Geom(vdata)
    geom.addPrimitive(prim)

    # make geom node
    node = GeomNode("base" + "_" + str(a) + "_" + str(b))
    node.addGeom(geom)

    # make mesh nodePath
    mesh = NodePath(node)
    # set render order
    mesh.setBin("", 1)

    # locate mesh
    mesh.setPos(self.divsep * (a * int(len(self.data[a]) / self.div)),
                self.divsep * (b * int(len(self.data[b]) / self.div)), 0)

    # reparent mesh
    mesh.reparentTo(self.root)

    # return mesh
    return mesh
コード例 #12
0
class CogdoFlyingCameraManager:
    def __init__(self, cam, parent, player, level):
        self._toon = player.toon
        self._camera = cam
        self._parent = parent
        self._player = player
        self._level = level
        self._enabled = False

    def enable(self):
        if self._enabled:
            return
        self._toon.detachCamera()
        self._prevToonY = 0.0
        levelBounds = self._level.getBounds()
        l = Globals.Camera.LevelBoundsFactor
        self._bounds = ((levelBounds[0][0] * l[0], levelBounds[0][1] * l[0]),
                        (levelBounds[1][0] * l[1], levelBounds[1][1] * l[1]),
                        (levelBounds[2][0] * l[2], levelBounds[2][1] * l[2]))
        self._lookAtZ = self._toon.getHeight(
        ) + Globals.Camera.LookAtToonHeightOffset
        self._camParent = NodePath('CamParent')
        self._camParent.reparentTo(self._parent)
        self._camParent.setPos(self._toon, 0, 0, 0)
        self._camParent.setHpr(180, Globals.Camera.Angle, 0)
        self._camera.reparentTo(self._camParent)
        self._camera.setPos(0, Globals.Camera.Distance, 0)
        self._camera.lookAt(self._toon, 0, 0, self._lookAtZ)
        self._cameraLookAtNP = NodePath('CameraLookAt')
        self._cameraLookAtNP.reparentTo(self._camera.getParent())
        self._cameraLookAtNP.setPosHpr(self._camera.getPos(),
                                       self._camera.getHpr())
        self._levelBounds = self._level.getBounds()
        self._enabled = True
        self._frozen = False
        self._initCollisions()

    def _initCollisions(self):
        self._camCollRay = CollisionRay()
        camCollNode = CollisionNode('CameraToonRay')
        camCollNode.addSolid(self._camCollRay)
        camCollNode.setFromCollideMask(OTPGlobals.WallBitmask
                                       | OTPGlobals.CameraBitmask
                                       | ToontownGlobals.FloorEventBitmask
                                       | ToontownGlobals.CeilingBitmask)
        camCollNode.setIntoCollideMask(0)
        self._camCollNP = self._camera.attachNewNode(camCollNode)
        self._camCollNP.show()
        self._collOffset = Vec3(0, 0, 0.5)
        self._collHandler = CollisionHandlerQueue()
        self._collTrav = CollisionTraverser()
        self._collTrav.addCollider(self._camCollNP, self._collHandler)
        self._betweenCamAndToon = {}
        self._transNP = NodePath('trans')
        self._transNP.reparentTo(render)
        self._transNP.setTransparency(True)
        self._transNP.setAlphaScale(Globals.Camera.AlphaBetweenToon)
        self._transNP.setBin('fixed', 10000)

    def _destroyCollisions(self):
        self._collTrav.removeCollider(self._camCollNP)
        self._camCollNP.removeNode()
        del self._camCollNP
        del self._camCollRay
        del self._collHandler
        del self._collOffset
        del self._betweenCamAndToon
        self._transNP.removeNode()
        del self._transNP

    def freeze(self):
        self._frozen = True

    def unfreeze(self):
        self._frozen = False

    def disable(self):
        if not self._enabled:
            return
        self._destroyCollisions()
        self._camera.wrtReparentTo(render)
        self._cameraLookAtNP.removeNode()
        del self._cameraLookAtNP
        self._camParent.removeNode()
        del self._camParent
        del self._prevToonY
        del self._lookAtZ
        del self._bounds
        del self._frozen
        self._enabled = False

    def update(self, dt=0.0):
        self._updateCam(dt)
        self._updateCollisions()

    def _updateCam(self, dt):
        toonPos = self._toon.getPos()
        camPos = self._camParent.getPos()
        x = camPos[0]
        z = camPos[2]
        toonWorldX = self._toon.getX(render)
        maxX = Globals.Camera.MaxSpinX
        toonWorldX = clamp(toonWorldX, -1.0 * maxX, maxX)
        spinAngle = Globals.Camera.MaxSpinAngle * toonWorldX * toonWorldX / (
            maxX * maxX)
        newH = 180.0 + spinAngle
        self._camParent.setH(newH)
        spinAngle = spinAngle * (pi / 180.0)
        distBehindToon = Globals.Camera.SpinRadius * cos(spinAngle)
        distToRightOfToon = Globals.Camera.SpinRadius * sin(spinAngle)
        d = self._camParent.getX() - clamp(toonPos[0], *self._bounds[0])
        if abs(d) > Globals.Camera.LeewayX:
            if d > Globals.Camera.LeewayX:
                x = toonPos[0] + Globals.Camera.LeewayX
            else:
                x = toonPos[0] - Globals.Camera.LeewayX
        x = self._toon.getX(render) + distToRightOfToon
        boundToonZ = min(toonPos[2], self._bounds[2][1])
        d = z - boundToonZ
        if d > Globals.Camera.MinLeewayZ:
            if self._player.velocity[2] >= 0 and toonPos[
                    1] != self._prevToonY or self._player.velocity[2] > 0:
                z = boundToonZ + d * INVERSE_E**(dt *
                                                 Globals.Camera.CatchUpRateZ)
            elif d > Globals.Camera.MaxLeewayZ:
                z = boundToonZ + Globals.Camera.MaxLeewayZ
        elif d < -Globals.Camera.MinLeewayZ:
            z = boundToonZ - Globals.Camera.MinLeewayZ
        if self._frozen:
            y = camPos[1]
        else:
            y = self._toon.getY(render) - distBehindToon
        self._camParent.setPos(x, smooth(camPos[1], y), smooth(camPos[2], z))
        if toonPos[2] < self._bounds[2][1]:
            h = self._cameraLookAtNP.getH()
            if d >= Globals.Camera.MinLeewayZ:
                self._cameraLookAtNP.lookAt(self._toon, 0, 0, self._lookAtZ)
            elif d <= -Globals.Camera.MinLeewayZ:
                self._cameraLookAtNP.lookAt(self._camParent, 0, 0,
                                            self._lookAtZ)
            self._cameraLookAtNP.setHpr(h, self._cameraLookAtNP.getP(), 0)
            self._camera.setHpr(
                smooth(self._camera.getHpr(), self._cameraLookAtNP.getHpr()))
        self._prevToonY = toonPos[1]

    def _updateCollisions(self):
        pos = self._toon.getPos(self._camera) + self._collOffset
        self._camCollRay.setOrigin(pos)
        direction = -Vec3(pos)
        direction.normalize()
        self._camCollRay.setDirection(direction)
        self._collTrav.traverse(render)
        nodesInBetween = {}
        if self._collHandler.getNumEntries() > 0:
            self._collHandler.sortEntries()
            for entry in self._collHandler.getEntries():
                name = entry.getIntoNode().getName()
                if name.find('col_') >= 0:
                    np = entry.getIntoNodePath().getParent()
                    if not np in nodesInBetween:
                        nodesInBetween[np] = np.getParent()

        for np in nodesInBetween.keys():
            if np in self._betweenCamAndToon:
                del self._betweenCamAndToon[np]
            else:
                np.setTransparency(True)
                np.wrtReparentTo(self._transNP)
                if np.getName().find('lightFixture') >= 0:
                    if not np.find('**/*floor_mesh').isEmpty():
                        np.find('**/*floor_mesh').hide()
                elif np.getName().find('platform') >= 0:
                    if not np.find('**/*Floor').isEmpty():
                        np.find('**/*Floor').hide()

        for np, parent in self._betweenCamAndToon.items():
            np.wrtReparentTo(parent)
            np.setTransparency(False)
            if np.getName().find('lightFixture') >= 0:
                if not np.find('**/*floor_mesh').isEmpty():
                    np.find('**/*floor_mesh').show()
            elif np.getName().find('platform') >= 0:
                if not np.find('**/*Floor').isEmpty():
                    np.find('**/*Floor').show()

        self._betweenCamAndToon = nodesInBetween
コード例 #13
0
class RepairSawingLine:
    
    def __init__(self, parent, thickness, color, lineSpawnDist = 0.01):
        self.points = []
        self.parent = parent
        self.thickness = thickness
        self.color = color
        self.lineNode = None
        self.lineDrawer = LineSegs()
        self.lineDrawer.setThickness(thickness)
        self.lineSpawnDist = lineSpawnDist
        self.currentPoint = None
        self.startPoint = None
        self.redraw()

    
    def redraw(self):
        self.clearLine()
        self.lineDrawer.reset()
        self.lineDrawer.setThickness(self.thickness)
        self.lineDrawer.setColor(self.color)
        if len(self.points) > 0:
            self.lineDrawer.moveTo(self.points[0])
            for i in range(1, len(self.points)):
                p = self.points[i]
                self.lineDrawer.drawTo(p)
                self.currentPoint = p
            
        
        self.lineNode = NodePath(self.lineDrawer.create())
        self.lineNode.reparentTo(self.parent)
        self.lineNode.setBin('fixed', 37)
        self.lineNode.setTransparency(True)

    
    def update(self, point):
        if self.currentPoint == None or (point - self.currentPoint).length() >= self.lineSpawnDist:
            self.addPoint(point)
            self.redraw()
        

    
    def addPoint(self, p):
        if len(self.points) == 0:
            self.startPoint = p
        
        self.points.append(p)

    
    def clearLine(self):
        if self.lineNode != None:
            self.lineNode.removeNode()
        

    
    def reset(self):
        self.clearLine()
        self.points = []
        self.redraw()
        self.currentPoint = None
        self.startPoint = None

    
    def show(self):
        self.lineNode.unstash()

    
    def hide(self):
        self.lineNode.stash()
コード例 #14
0
class CogdoFlyingCameraManager:
    def __init__(self, cam, parent, player, level):
        self._toon = player.toon
        self._camera = cam
        self._parent = parent
        self._player = player
        self._level = level
        self._enabled = False

    def enable(self):
        if self._enabled:
            return
        self._toon.detachCamera()
        self._prevToonY = 0.0
        levelBounds = self._level.getBounds()
        l = Globals.Camera.LevelBoundsFactor
        self._bounds = (
            (levelBounds[0][0] * l[0], levelBounds[0][1] * l[0]),
            (levelBounds[1][0] * l[1], levelBounds[1][1] * l[1]),
            (levelBounds[2][0] * l[2], levelBounds[2][1] * l[2]),
        )
        self._lookAtZ = self._toon.getHeight() + Globals.Camera.LookAtToonHeightOffset
        self._camParent = NodePath("CamParent")
        self._camParent.reparentTo(self._parent)
        self._camParent.setPos(self._toon, 0, 0, 0)
        self._camParent.setHpr(180, Globals.Camera.Angle, 0)
        self._camera.reparentTo(self._camParent)
        self._camera.setPos(0, Globals.Camera.Distance, 0)
        self._camera.lookAt(self._toon, 0, 0, self._lookAtZ)
        self._cameraLookAtNP = NodePath("CameraLookAt")
        self._cameraLookAtNP.reparentTo(self._camera.getParent())
        self._cameraLookAtNP.setPosHpr(self._camera.getPos(), self._camera.getHpr())
        self._levelBounds = self._level.getBounds()
        self._enabled = True
        self._frozen = False
        self._initCollisions()

    def _initCollisions(self):
        self._camCollRay = CollisionRay()
        camCollNode = CollisionNode("CameraToonRay")
        camCollNode.addSolid(self._camCollRay)
        camCollNode.setFromCollideMask(
            OTPGlobals.WallBitmask
            | OTPGlobals.CameraBitmask
            | ToontownGlobals.FloorEventBitmask
            | ToontownGlobals.CeilingBitmask
        )
        camCollNode.setIntoCollideMask(0)
        self._camCollNP = self._camera.attachNewNode(camCollNode)
        self._camCollNP.show()
        self._collOffset = Vec3(0, 0, 0.5)
        self._collHandler = CollisionHandlerQueue()
        self._collTrav = CollisionTraverser()
        self._collTrav.addCollider(self._camCollNP, self._collHandler)
        self._betweenCamAndToon = {}
        self._transNP = NodePath("trans")
        self._transNP.reparentTo(render)
        self._transNP.setTransparency(True)
        self._transNP.setAlphaScale(Globals.Camera.AlphaBetweenToon)
        self._transNP.setBin("fixed", 10000)

    def _destroyCollisions(self):
        self._collTrav.removeCollider(self._camCollNP)
        self._camCollNP.removeNode()
        del self._camCollNP
        del self._camCollRay
        del self._collHandler
        del self._collOffset
        del self._betweenCamAndToon
        self._transNP.removeNode()
        del self._transNP

    def freeze(self):
        self._frozen = True

    def unfreeze(self):
        self._frozen = False

    def disable(self):
        if not self._enabled:
            return
        self._destroyCollisions()
        self._camera.wrtReparentTo(render)
        self._cameraLookAtNP.removeNode()
        del self._cameraLookAtNP
        self._camParent.removeNode()
        del self._camParent
        del self._prevToonY
        del self._lookAtZ
        del self._bounds
        del self._frozen
        self._enabled = False

    def update(self, dt=0.0):
        self._updateCam(dt)
        self._updateCollisions()

    def _updateCam(self, dt):
        toonPos = self._toon.getPos()
        camPos = self._camParent.getPos()
        x = camPos[0]
        z = camPos[2]
        toonWorldX = self._toon.getX(render)
        maxX = Globals.Camera.MaxSpinX
        toonWorldX = clamp(toonWorldX, -1.0 * maxX, maxX)
        spinAngle = Globals.Camera.MaxSpinAngle * toonWorldX * toonWorldX / (maxX * maxX)
        newH = 180.0 + spinAngle
        self._camParent.setH(newH)
        spinAngle = spinAngle * (pi / 180.0)
        distBehindToon = Globals.Camera.SpinRadius * cos(spinAngle)
        distToRightOfToon = Globals.Camera.SpinRadius * sin(spinAngle)
        d = self._camParent.getX() - clamp(toonPos[0], *self._bounds[0])
        if abs(d) > Globals.Camera.LeewayX:
            if d > Globals.Camera.LeewayX:
                x = toonPos[0] + Globals.Camera.LeewayX
            else:
                x = toonPos[0] - Globals.Camera.LeewayX
        x = self._toon.getX(render) + distToRightOfToon
        boundToonZ = min(toonPos[2], self._bounds[2][1])
        d = z - boundToonZ
        if d > Globals.Camera.MinLeewayZ:
            if self._player.velocity[2] >= 0 and toonPos[1] != self._prevToonY or self._player.velocity[2] > 0:
                z = boundToonZ + d * INVERSE_E ** (dt * Globals.Camera.CatchUpRateZ)
            elif d > Globals.Camera.MaxLeewayZ:
                z = boundToonZ + Globals.Camera.MaxLeewayZ
        elif d < -Globals.Camera.MinLeewayZ:
            z = boundToonZ - Globals.Camera.MinLeewayZ
        if self._frozen:
            y = camPos[1]
        else:
            y = self._toon.getY(render) - distBehindToon
        self._camParent.setPos(x, smooth(camPos[1], y), smooth(camPos[2], z))
        if toonPos[2] < self._bounds[2][1]:
            h = self._cameraLookAtNP.getH()
            if d >= Globals.Camera.MinLeewayZ:
                self._cameraLookAtNP.lookAt(self._toon, 0, 0, self._lookAtZ)
            elif d <= -Globals.Camera.MinLeewayZ:
                self._cameraLookAtNP.lookAt(self._camParent, 0, 0, self._lookAtZ)
            self._cameraLookAtNP.setHpr(h, self._cameraLookAtNP.getP(), 0)
            self._camera.setHpr(smooth(self._camera.getHpr(), self._cameraLookAtNP.getHpr()))
        self._prevToonY = toonPos[1]

    def _updateCollisions(self):
        pos = self._toon.getPos(self._camera) + self._collOffset
        self._camCollRay.setOrigin(pos)
        direction = -Vec3(pos)
        direction.normalize()
        self._camCollRay.setDirection(direction)
        self._collTrav.traverse(render)
        nodesInBetween = {}
        if self._collHandler.getNumEntries() > 0:
            self._collHandler.sortEntries()
            for entry in self._collHandler.getEntries():
                name = entry.getIntoNode().getName()
                if name.find("col_") >= 0:
                    np = entry.getIntoNodePath().getParent()
                    if not nodesInBetween.has_key(np):
                        nodesInBetween[np] = np.getParent()

        for np in nodesInBetween.keys():
            if self._betweenCamAndToon.has_key(np):
                del self._betweenCamAndToon[np]
            else:
                np.setTransparency(True)
                np.wrtReparentTo(self._transNP)
                if np.getName().find("lightFixture") >= 0:
                    if not np.find("**/*floor_mesh").isEmpty():
                        np.find("**/*floor_mesh").hide()
                elif np.getName().find("platform") >= 0:
                    if not np.find("**/*Floor").isEmpty():
                        np.find("**/*Floor").hide()

        for np, parent in self._betweenCamAndToon.items():
            np.wrtReparentTo(parent)
            np.setTransparency(False)
            if np.getName().find("lightFixture") >= 0:
                if not np.find("**/*floor_mesh").isEmpty():
                    np.find("**/*floor_mesh").show()
            elif np.getName().find("platform") >= 0:
                if not np.find("**/*Floor").isEmpty():
                    np.find("**/*Floor").show()

        self._betweenCamAndToon = nodesInBetween
コード例 #15
0
class FishLure(NodePath):
    def __init__(self, gameObject, type):
        NodePath.__init__(self, "FishingLure_%s" % type)
        self.gameObject = gameObject
        self.type = type
        self.initLureModel()
        if FishingGlobals.wantDebugCollisionVisuals:
            self.initCollision()

        self.initLureHelpText()
        self.setLightOff()

    def initLureModel(self):
        self.lureModel = NodePath("lure")
        self.currentLureType = "regular"
        self.lureAttractRadius = FishingGlobals.lureTypeToAttractRadius[self.currentLureType]
        self.lureModel = loader.loadModel(FishingGlobals.lureTypeToModel[self.currentLureType])
        self.lureModel.setScale(2.0)
        self.lureModel.reparentTo(self)
        self.lureModel.setDepthWrite(False)
        self.lureModel.setDepthTest(True)
        self.lureModel.setBin("ground", 25)
        self.mainGui = loader.loadModel("models/gui/gui_main")

    def initCollision(self):
        self.lureCollisionVisual = loader.loadModel("models/ammunition/cannonball")
        self.lureCollisionVisual.setTransparency(1)
        self.lureCollisionVisual.setColor(0.0, 0.0, 1.0, 0.29999999999999999)
        self.lureCollisionVisual.setScale(self.lureAttractRadius)
        self.lureCollisionVisual.reparentTo(self)
        self.lureCollisionVisual.hide()

    def initLureHelpText(self):
        self.helpTextNode = TextNode("fishBitingIcon")
        self.helpTextNodePath = NodePath(self.helpTextNode)
        self.helpTextNodePath.setPos(0.0, 0.0, 0.69999999999999996)
        self.helpTextNode.setText(" ")
        self.helpTextNode.setAlign(TextNode.ACenter)
        self.helpTextNode.setFont(PiratesGlobals.getPirateFont())
        self.helpTextNode.setTextColor(1.0, 1.0, 1.0, 1.0)
        self.helpTextNodePath.reparentTo(self)
        self.helpTextNodePath.setBillboardPointEye()
        self.helpTextNodePath.setBin("fishingGame", 10)
        self.helpTextNodePath.hide()

    def enableLureGlow(self, glowType):
        self.lureGlow = LureGlow.getEffect()
        if self.lureGlow:
            if self.gameObject.fishManager.activeFish is not None:
                self.lureGlow.reparentTo(self.gameObject.fishManager.activeFish.mouthJoint)
            else:
                self.lureGlow.reparentTo(self)
            self.lureGlow.effectColor = _glowColors[glowType]
            self.lureGlow.setShaderOff()
            self.lureGlow.setBin("fishingGame", 5)
            self.lureGlow.play()

    def showHelpText(self, textToShow):
        taskMgr.remove(self.gameObject.distributedFishingSpot.uniqueName("ClearLureText"))
        if textToShow is None:
            self.helpTextNode.setText(" ")
            self.helpTextNodePath.hide()
        elif self.gameObject.fishManager.activeFish is not None:
            self.helpTextNodePath.setScale(
                FishingGlobals.fishSizeToHelpTextScale[self.gameObject.fishManager.activeFish.myData["size"]]
            )
        else:
            self.helpTextNodePath.setScale(1.0)
        self.helpTextNode.setText(textToShow)
        self.helpTextNodePath.show()
        taskMgr.doMethodLater(
            FishingGlobals.lureHelpTextDuration,
            self.showHelpText,
            name=self.gameObject.distributedFishingSpot.uniqueName("ClearLureText"),
            extraArgs=[None],
        )

    def setLureType(self, type):
        self.currentLureType = type
        if type == None:
            self.lureModel.hide()
            self.gameObject.gui.setTackleBoxPulse(True)
        elif type == "regular":
            self.gameObject.gui.setTackleBoxPulse(False)
            self.currentLureType = type
            self.lureModel.removeNode()
            self.lureAttractRadius = FishingGlobals.lureTypeToAttractRadius[type]
            self.lureModel = loader.loadModel(FishingGlobals.lureTypeToModel[type])
            self.lureModel.setScale(2.0)
            self.lureModel.reparentTo(self)
            self.lureModel.setDepthWrite(False)
            self.lureModel.setDepthTest(True)
            self.lureModel.setBin("ground", 25)
        elif type == "legendary":
            self.gameObject.gui.setTackleBoxPulse(False)
            self.currentLureType = type
            self.lureModel.removeNode()
            self.lureAttractRadius = FishingGlobals.lureTypeToAttractRadius[type]
            self.lureModel = loader.loadModel(FishingGlobals.lureTypeToModel[type])
            self.lureModel.setScale(2.0)
            self.lureModel.reparentTo(self)
            self.lureModel.setDepthWrite(False)
            self.lureModel.setDepthTest(True)
            self.lureModel.setBin("ground", 25)

    def showCollisionVisuals(self):
        if FishingGlobals.wantDebugCollisionVisuals:
            self.lureCollisionVisual.show()

    def hideCollisionVisuals(self):
        if FishingGlobals.wantDebugCollisionVisuals:
            self.lureCollisionVisual.hide()

    def requestPitch(self, fish):
        offset = fish.getPos() - self.getPos()
        if fish.getX() < self.getX():
            return math.degrees(math.atan2(offset.getZ(), -offset.getX()))
        else:
            return math.degrees(math.atan2(-offset.getZ(), offset.getX()))

    def resetLureModel(self):
        self.lureModel.reparentTo(self)
        self.lureModel.show()
        self.lureModel.setPosHpr(0, 0, 0, 0, 0, 0.0)
        if self.currentLureType == None:
            self.lureModel.hide()
            self.gameObject.gui.setTackleBoxPulse(True)
        else:
            self.gameObject.gui.setTackleBoxPulse(False)

    def destroy(self):
        self.lureModel.removeNode()
        self.removeNode()
コード例 #16
0
class FishLure(NodePath):
    def __init__(self, gameObject, type):
        NodePath.__init__(self, 'FishingLure_%s' % type)
        self.gameObject = gameObject
        self.type = type
        self.initLureModel()
        if FishingGlobals.wantDebugCollisionVisuals:
            self.initCollision()

        self.initLureHelpText()
        self.setLightOff()

    def initLureModel(self):
        self.lureModel = NodePath('lure')
        self.currentLureType = 'regular'
        self.lureAttractRadius = FishingGlobals.lureTypeToAttractRadius[
            self.currentLureType]
        self.lureModel = loader.loadModel(
            FishingGlobals.lureTypeToModel[self.currentLureType])
        self.lureModel.setScale(2.0)
        self.lureModel.reparentTo(self)
        self.lureModel.setDepthWrite(False)
        self.lureModel.setDepthTest(True)
        self.lureModel.setBin('ground', 25)
        self.mainGui = loader.loadModel('models/gui/gui_main')

    def initCollision(self):
        self.lureCollisionVisual = loader.loadModel(
            'models/ammunition/cannonball')
        self.lureCollisionVisual.setTransparency(1)
        self.lureCollisionVisual.setColor(0.0, 0.0, 1.0, 0.29999999999999999)
        self.lureCollisionVisual.setScale(self.lureAttractRadius)
        self.lureCollisionVisual.reparentTo(self)
        self.lureCollisionVisual.hide()

    def initLureHelpText(self):
        self.helpTextNode = TextNode('fishBitingIcon')
        self.helpTextNodePath = NodePath(self.helpTextNode)
        self.helpTextNodePath.setPos(0.0, 0.0, 0.69999999999999996)
        self.helpTextNode.setText(' ')
        self.helpTextNode.setAlign(TextNode.ACenter)
        self.helpTextNode.setFont(PiratesGlobals.getPirateFont())
        self.helpTextNode.setTextColor(1.0, 1.0, 1.0, 1.0)
        self.helpTextNodePath.reparentTo(self)
        self.helpTextNodePath.setBillboardPointEye()
        self.helpTextNodePath.setBin('fishingGame', 10)
        self.helpTextNodePath.hide()

    def enableLureGlow(self, glowType):
        self.lureGlow = LureGlow.getEffect()
        if self.lureGlow:
            if self.gameObject.fishManager.activeFish is not None:
                self.lureGlow.reparentTo(
                    self.gameObject.fishManager.activeFish.mouthJoint)
            else:
                self.lureGlow.reparentTo(self)
            self.lureGlow.effectColor = _glowColors[glowType]
            self.lureGlow.setShaderOff()
            self.lureGlow.setBin('fishingGame', 5)
            self.lureGlow.play()

    def showHelpText(self, textToShow):
        taskMgr.remove(
            self.gameObject.distributedFishingSpot.uniqueName('ClearLureText'))
        if textToShow is None:
            self.helpTextNode.setText(' ')
            self.helpTextNodePath.hide()
        elif self.gameObject.fishManager.activeFish is not None:
            self.helpTextNodePath.setScale(
                FishingGlobals.fishSizeToHelpTextScale[
                    self.gameObject.fishManager.activeFish.myData['size']])
        else:
            self.helpTextNodePath.setScale(1.0)
        self.helpTextNode.setText(textToShow)
        self.helpTextNodePath.show()
        taskMgr.doMethodLater(
            FishingGlobals.lureHelpTextDuration,
            self.showHelpText,
            name=self.gameObject.distributedFishingSpot.uniqueName(
                'ClearLureText'),
            extraArgs=[None])

    def setLureType(self, type):
        self.currentLureType = type
        if type == None:
            self.lureModel.hide()
            self.gameObject.gui.setTackleBoxPulse(True)
        elif type == 'regular':
            self.gameObject.gui.setTackleBoxPulse(False)
            self.currentLureType = type
            self.lureModel.removeNode()
            self.lureAttractRadius = FishingGlobals.lureTypeToAttractRadius[
                type]
            self.lureModel = loader.loadModel(
                FishingGlobals.lureTypeToModel[type])
            self.lureModel.setScale(2.0)
            self.lureModel.reparentTo(self)
            self.lureModel.setDepthWrite(False)
            self.lureModel.setDepthTest(True)
            self.lureModel.setBin('ground', 25)
        elif type == 'legendary':
            self.gameObject.gui.setTackleBoxPulse(False)
            self.currentLureType = type
            self.lureModel.removeNode()
            self.lureAttractRadius = FishingGlobals.lureTypeToAttractRadius[
                type]
            self.lureModel = loader.loadModel(
                FishingGlobals.lureTypeToModel[type])
            self.lureModel.setScale(2.0)
            self.lureModel.reparentTo(self)
            self.lureModel.setDepthWrite(False)
            self.lureModel.setDepthTest(True)
            self.lureModel.setBin('ground', 25)

    def showCollisionVisuals(self):
        if FishingGlobals.wantDebugCollisionVisuals:
            self.lureCollisionVisual.show()

    def hideCollisionVisuals(self):
        if FishingGlobals.wantDebugCollisionVisuals:
            self.lureCollisionVisual.hide()

    def requestPitch(self, fish):
        offset = fish.getPos() - self.getPos()
        if fish.getX() < self.getX():
            return math.degrees(math.atan2(offset.getZ(), -offset.getX()))
        else:
            return math.degrees(math.atan2(-offset.getZ(), offset.getX()))

    def resetLureModel(self):
        self.lureModel.reparentTo(self)
        self.lureModel.show()
        self.lureModel.setPosHpr(0, 0, 0, 0, 0, 0.0)
        if self.currentLureType == None:
            self.lureModel.hide()
            self.gameObject.gui.setTackleBoxPulse(True)
        else:
            self.gameObject.gui.setTackleBoxPulse(False)

    def destroy(self):
        self.lureModel.removeNode()
        self.removeNode()
コード例 #17
0
ファイル: ShipBlueprints.py プロジェクト: TTGhost/POTCOR-src
def generateHullCache(modelClass):
    geom = loader.loadModel("models/shipparts/pir_m_shp_%s" % HullDict[modelClass])
    stripPrefix(geom, "model:")
    for node in geom.findAllMatches("**/omit"):
        parent = node.getParent()
        omit = parent.attachNewNode(ModelNode("omit"))
        node.reparentTo(omit)
        node.setName("geom")

    preFlatten(geom)
    logic = loader.loadModel("models/shipparts/pir_m_shp_%s_logic" % HullDict[modelClass])
    locators = logic.find("**/locators")
    for side in ["left", "right"]:
        bad = locators.find("**/location_ropeLadder_0_%s" % side)
        if bad:
            bad.setName("location_ropeLadder_%s_0" % side)

        bad = locators.find("**/location_ropeLadder_1_%s" % side)
        if bad:
            bad.setName("location_ropeLadder_%s_1" % side)

        bad = locators.find("**/location_ropeLadder_1_%s1" % side)
        if bad:
            bad.setName("location_ropeLadder_%s_2" % side)
            continue

    collisions = logic.find("**/collisions")
    badPanel = collisions.find("**/collision_panel_3")
    if badPanel:
        badPanel.setName("collision_panel_2")

    collisions.find("**/collision_panel_0").setTag("Hull Code", "0")
    collisions.find("**/collision_panel_1").setTag("Hull Code", "1")
    collisions.find("**/collision_panel_2").setTag("Hull Code", "2")
    walls = collisions.find("**/collision_walls")
    if walls:
        walls.setTag("Hull Code", "255")
    else:
        collisions.attachNewNode("collision_walls")
    shipToShipCollide = collisions.find("**/collision_shiptoship")
    shipToShipCollide.setCollideMask(PiratesGlobals.ShipCollideBitmask)
    deck = collisions.find("**/collision_deck")
    if not deck:
        deck = collisions.attachNewNode("deck")

    mask = deck.getCollideMask()
    mask ^= PiratesGlobals.FloorBitmask
    mask |= PiratesGlobals.ShipFloorBitmask
    deck.setCollideMask(mask)
    floors = collisions.find("**/collision_floors")
    if not floors:
        floors = collisions.find("**/collision_floor")

    mask = floors.getCollideMask()
    mask ^= PiratesGlobals.FloorBitmask
    mask |= PiratesGlobals.ShipFloorBitmask
    floors.setCollideMask(mask)
    floors.setTag("Hull Code", str(255))
    geomHigh = geom.find("**/lod_high")
    geomMed = geom.find("**/lod_medium")
    if not geomMed:
        geomMed = geom.find("**/low_medium")

    if not geomMed:
        geomMed = geomHigh.copyTo(NodePath())

    geomLow = geom.find("**/lod_low")
    if not geomLow:
        geomLow = geomMed.copyTo(NodePath())

    geomSuperLow = geom.find("**/lod_superlow")
    if not geomSuperLow:
        geomSuperLow = geomLow.copyTo(NodePath())

    geomHigh.setName("high")
    geomMed.setName("med")
    geomLow.setName("low")
    geomSuperLow.setName("superlow")
    if modelClass in [21, 22, 23]:
        spike = loader.loadModel("models/shipparts/pir_m_shp_ram_spike")
        spikeTrans = locators.find("**/location_ram").getTransform(locators)
        spike.setTransform(spikeTrans)
        spike.flattenLight()
        spikeHi = spike.find("**/lod_high")
        spikeMed = spike.find("**/lod_medium")
        spikeLow = spike.find("**/lod_low")
        spikeHi.copyTo(geomHigh)
        spikeMed.copyTo(geomMed)
        spikeLow.copyTo(geomLow)
        spikeLow.copyTo(geomSuperLow)

    flipRoot = NodePath("root")
    collisions.reparentTo(flipRoot)
    locators.reparentTo(flipRoot)
    geomHigh.reparentTo(flipRoot)
    geomMed.reparentTo(flipRoot)
    geomLow.reparentTo(flipRoot)
    geomSuperLow.reparentTo(flipRoot)
    flipRoot.setH(180)
    flipRoot.flattenLight()
    omits = flipRoot.findAllMatches("**/omit")
    for node in omits:
        node.flattenStrong()

    for group in ["static", "transparent", "ropeLadder_*", "stripeA", "stripeB", "pattern"]:
        for node in flipRoot.findAllMatches("**/%s" % group):
            name = node.getName()
            for subNode in node.findAllMatches("**/*"):
                subNode.setName(name)

            node.flattenStrong()
            node.setName(name)

    geomHigh.detachNode()
    geomMed.detachNode()
    geomLow.detachNode()
    geomSuperLow.detachNode()
    locators.detachNode()
    collisions.detachNode()
    genericGeoms = [geomHigh, geomMed, geomLow, geomSuperLow]
    customGeoms = [x.copyTo(NodePath()) for x in genericGeoms]
    for np in genericGeoms:
        trans = np.find("**/transparent")
        if trans:
            trans.stash()

        np.flattenLight()
        sails = np.findAllMatches("**/sails")
        sails.stash()
        omits = np.findAllMatches("**/omit")
        omits.stash()
        for node in omits:
            node.node().setPreserveTransform(node.node().PTDropNode)

        generic = NodePath("generic")
        np.findAllMatches("**/+GeomNode").wrtReparentTo(generic)
        np.findAllMatches("*").detach()
        generic.flattenStrong()
        generic.reparentTo(np)
        stripAttribs(generic, TextureAttrib)
        stripAttribs(generic, TransparencyAttrib)
        stripAttribs(generic, CullBinAttrib)
        generic.setBin("ground", 1)
        collapse(generic)
        sails.unstash()
        sails.reparentTo(np)
        for node in sails:
            node.node().setPreserveTransform(node.node().PTDropNode)

        if trans:
            trans.unstash()
            trans.flattenStrong()
            if trans.node().isOfType(ModelNode.getClassType()):
                trans.node().setPreserveTransform(ModelNode.PTDropNode)

        deck = np.find("**/=cam=shground")
        if deck:
            deck.setName("deck")

        omits.unstash()

    for np in customGeoms:
        collapse(np.find("**/static"))

    data = HullCache()
    data.root = NodePath("hull")
    data.genericGeoms = genericGeoms
    data.customGeoms = customGeoms
    data.collisions = collisions
    data.locators = locators
    return data