class CogdoMazeFactory:

    def __init__(self, randomNumGen, width, height, frameWallThickness = Globals.FrameWallThickness, cogdoMazeData = CogdoMazeData):
        self._rng = RandomNumGen(randomNumGen)
        self.width = width
        self.height = height
        self.frameWallThickness = frameWallThickness
        self._cogdoMazeData = cogdoMazeData
        self.quadrantSize = self._cogdoMazeData.QuadrantSize
        self.cellWidth = self._cogdoMazeData.QuadrantCellWidth

    def getMazeData(self):
        if not hasattr(self, '_data'):
            self._generateMazeData()
        return self._data

    def createCogdoMaze(self, flattenModel = True):
        if not hasattr(self, '_maze'):
            self._loadAndBuildMazeModel(flatten=flattenModel)
        return CogdoMaze(self._model, self._data, self.cellWidth)

    def _gatherQuadrantData(self):
        self.openBarriers = []
        barrierItems = range(Globals.TotalBarriers)
        self._rng.shuffle(barrierItems)
        for i in barrierItems[0:len(barrierItems) - Globals.NumBarriers]:
            self.openBarriers.append(i)

        self.quadrantData = []
        quadrantKeys = self._cogdoMazeData.QuadrantCollisions.keys()
        self._rng.shuffle(quadrantKeys)
        i = 0
        for y in range(self.height):
            for x in range(self.width):
                key = quadrantKeys[i]
                collTable = self._cogdoMazeData.QuadrantCollisions[key]
                angle = self._cogdoMazeData.QuadrantAngles[self._rng.randint(0, len(self._cogdoMazeData.QuadrantAngles) - 1)]
                self.quadrantData.append((key, collTable[angle], angle))
                i += 1
                if x * y >= self._cogdoMazeData.NumQuadrants:
                    i = 0

    def _generateBarrierData(self):
        data = []
        for y in range(self.height):
            data.append([])
            for x in range(self.width):
                if x == self.width - 1:
                    ax = -1
                else:
                    ax = 1
                if y == self.height - 1:
                    ay = -1
                else:
                    ay = 1
                data[y].append([ax, ay])

        dirUp = 0
        dirDown = 1
        dirLeft = 2
        dirRight = 3

        def getAvailableDirections(ax, ay, ignore = None):
            dirs = []
            if ax - 1 >= 0 and data[ay][ax - 1][BARRIER_DATA_RIGHT] == 1 and (ax, ay) != ignore:
                dirs.append(dirLeft)
            if ax + 1 < self.width and data[ay][ax][BARRIER_DATA_RIGHT] == 1 and (ax, ay) != ignore:
                dirs.append(dirRight)
            if ay - 1 >= 0 and data[ay - 1][ax][BARRIER_DATA_TOP] == 1 and (ax, ay) != ignore:
                dirs.append(dirDown)
            if ay + 1 < self.height and data[ay][ax][BARRIER_DATA_TOP] == 1 and (ax, ay) != ignore:
                dirs.append(dirUp)
            return dirs

        visited = []

        def tryVisitNeighbor(ax, ay, ad):
            if ad == dirUp:
                if data[ay][ax] in visited:
                    return None
                visited.append(data[ay][ax])
                data[ay][ax][BARRIER_DATA_TOP] = 0
                ay += 1
            elif ad == dirDown:
                if data[ay - 1][ax] in visited:
                    return None
                visited.append(data[ay - 1][ax])
                data[ay - 1][ax][BARRIER_DATA_TOP] = 0
                ay -= 1
            elif ad == dirLeft:
                if data[ay][ax - 1] in visited:
                    return None
                visited.append(data[ay][ax - 1])
                data[ay][ax - 1][BARRIER_DATA_RIGHT] = 0
                ax -= 1
            elif ad == dirRight:
                if data[ay][ax] in visited:
                    return None
                visited.append(data[ay][ax])
                data[ay][ax][BARRIER_DATA_RIGHT] = 0
                ax += 1
            return ax, ay

        def openBarriers(x, y):
            dirs = getAvailableDirections(x, y)
            for dir in dirs:
                next = tryVisitNeighbor(x, y, dir)
                if next is not None:
                    openBarriers(*next)

        x = self._rng.randint(0, self.width - 1)
        y = self._rng.randint(0, self.height - 1)
        openBarriers(x, y)
        self._barrierData = data

    def _generateMazeData(self):
        if not hasattr(self, 'quadrantData'):
            self._gatherQuadrantData()
        self._data = {'width': (self.width + 1) * self.frameWallThickness + self.width * self.quadrantSize,
                      'height': (self.height + 1) * self.frameWallThickness + self.height * self.quadrantSize}
        self._data['originX'] = int(self._data['width'] / 2)
        self._data['originY'] = int(self._data['height'] / 2)
        collisionTable = []
        horizontalWall = [ 1 for x in range(self._data['width']) ]
        collisionTable.append(horizontalWall)
        for i in range(0, len(self.quadrantData), self.width):
            for y in range(self.quadrantSize):
                row = [1]
                for x in range(i, i + self.width):
                    if x == 1 and y < self.quadrantSize / 2 - 2:
                        newData = []
                        for j in self.quadrantData[x][1][y]:
                            if j == 0:
                                newData.append(2)
                            else:
                                newData.append(j + 0)

                        row += newData + [1]
                    else:
                        row += self.quadrantData[x][1][y] + [1]

                collisionTable.append(row)

            collisionTable.append(horizontalWall[:])

        barriers = Globals.MazeBarriers
        for i in range(len(barriers)):
            for coords in barriers[i]:
                collisionTable[coords[1]][coords[0]] = 0

        y = self._data['originY']
        for x in range(len(collisionTable[y])):
            if collisionTable[y][x] == 0:
                collisionTable[y][x] = 2

        x = self._data['originX']
        for y in range(len(collisionTable)):
            if collisionTable[y][x] == 0:
                collisionTable[y][x] = 2

        self._data['collisionTable'] = collisionTable

    def _loadAndBuildMazeModel(self, flatten = False):
        self.getMazeData()
        self._model = NodePath('CogdoMazeModel')
        levelModel = CogdoUtil.loadMazeModel('level')
        self.quadrants = []
        quadrantUnitSize = int(self.quadrantSize * self.cellWidth)
        frameActualSize = self.frameWallThickness * self.cellWidth
        size = quadrantUnitSize + frameActualSize
        halfWidth = int(self.width / 2)
        halfHeight = int(self.height / 2)
        i = 0
        for y in range(self.height):
            for x in range(self.width):
                ax = (x - halfWidth) * size
                ay = (y - halfHeight) * size
                extension = ''
                if hasattr(getBase(), 'air'):
                    extension = '.bam'
                filepath = self.quadrantData[i][0] + extension
                angle = self.quadrantData[i][2]
                m = self._createQuadrant(filepath, i, angle, quadrantUnitSize)
                m.setPos(ax, ay, 0)
                m.reparentTo(self._model)
                self.quadrants.append(m)
                i += 1

        quadrantHalfUnitSize = quadrantUnitSize * 0.5
        barrierModel = CogdoUtil.loadMazeModel('grouping_blockerDivider').find('**/divider')
        y = 3
        for x in range(self.width):
            if x == (self.width - 1) / 2:
                continue
            ax = (x - halfWidth) * size
            ay = (y - halfHeight) * size - quadrantHalfUnitSize - (self.cellWidth - 0.5)
            b = NodePath('barrier')
            barrierModel.instanceTo(b)
            b.setPos(ax, ay, 0)
            b.reparentTo(self._model)

        offset = self.cellWidth - 0.5
        for x in (0, 3):
            for y in range(self.height):
                ax = (x - halfWidth) * size - quadrantHalfUnitSize - frameActualSize + offset
                ay = (y - halfHeight) * size
                b = NodePath('barrier')
                barrierModel.instanceTo(b)
                b.setPos(ax, ay, 0)
                b.setH(90)
                b.reparentTo(self._model)

            offset -= 2.0

        barrierModel.removeNode()
        levelModel.getChildren().reparentTo(self._model)
        for np in self._model.findAllMatches('**/*lightCone*'):
            CogdoUtil.initializeLightCone(np, 'fixed', 3)

        if flatten:
            self._model.flattenStrong()
        return self._model

    def _createQuadrant(self, filepath, serialNum, angle, size):
        root = NodePath('QuadrantRoot-%i' % serialNum)
        quadrant = loader.loadModel(filepath)
        quadrant.getChildren().reparentTo(root)
        root.setH(angle)
        return root
예제 #2
0
class AreaMap(Map):
    def __init__(self, area):
        Map.__init__(self, "map-" + area.getName())
        self.capturePoints = {}
        mapNode = area.getMapNode()
        if mapNode and not mapNode.isEmpty():
            geom = mapNode.getChild(0)
            geom.setScale(mapNode.getScale())
            geom.flattenStrong()
            mapNode.setScale(1)
            self.worldNode = mapNode
            self.map = self.worldNode.copyTo(NodePath())
            (a, b) = self.map.getTightBounds()
            diff = b - a
            h = diff[1]
            w = diff[0]
        else:
            self.worldNode = area
            self.map = NodePath("no map found")
            (a, b) = self.worldNode.geom.getTightBounds()
            diff = b - a
            h = diff[1]
            w = diff[0]
        ratio = h / w
        if ratio < 0.98999999999999999:
            normalScale = 2 / w
            screenScale = 1
        else:
            normalScale = 2 / h
            screenScale = 0.75
        self.map.clearTransform()
        self.map.show()
        self.screenNode = NodePath("Minimap-screenNode")
        self.screenNode.setP(90)
        self.screenNode.setScale(screenScale * normalScale)
        self.screenNode.hide()
        self.map.reparentTo(self.screenNode)
        self.mapOverlay = self.map.attachNewNode("mapOverlay")
        self.mapOverlay.wrtReparentTo(self.screenNode)
        self.radarTransformNode = NodePath("radarTransform")
        self.radarTransformNode.setScale(self.worldNode.getScale()[0])
        self.map.instanceTo(self.radarTransformNode)
        localAvatar.guiMgr.addMinimap(self)
        if self.allowOnScreen():
            self.addObject(MinimapFootprint(area))

        if self.allowOnScreen():
            if area.getUniqueId() not in [LocationIds.RAVENS_COVE_ISLAND]:
                for shop in area.getShopNodes():
                    uid = shop.getTag("Uid")
                    shopType = shop.getTag("ShopType")
                    self.addObject(MinimapShop(uid, shop, shopType))

            self.map.findAllMatches("**/=Holiday").stash()
            if base.cr.newsManager:
                for holiday in base.cr.newsManager.getHolidayList():
                    self.handleHolidayStarted(area, HolidayGlobals.getHolidayName(holiday))

        self.zoomLevels = area.getZoomLevels()
        self.accept("landMapRadarAxisChanged", self.setRadarAxis)

    def destroy(self):
        self.ignore("landMapRadarAxisChanged")
        if hasattr(base, "localAvatar"):
            localAvatar.guiMgr.removeMinimap(self)

        for holiday in self.capturePoints.keys():
            zones = self.capturePoints.pop(holiday, {})
            for object in zones.itervalues():
                self.removeObject(object)

        Map.destroy(self)

    def allowOnScreen(self):
        return self.map.find("minimap-card").isEmpty()

    def getZoomLevels(self):
        return self.zoomLevels

    def getWorldNode(self):
        return self.worldNode

    def getScreenNode(self):
        return self.screenNode

    def getOverlayNode(self):
        return self.mapOverlay

    def getCapturePoint(self, holidayId, zone):
        if self.capturePoints.has_key(holidayId):
            return self.capturePoints[holidayId][zone]

    def updateTask(self, task):
        self.update()
        return task.cont

    def update(self):
        for obj in self.objects:
            obj.updateOnMap(self)

    def addObject(self, object):
        Map.addObject(self, object)
        mapNode = object.getMapNode()
        mapNode.reparentTo(self.map, sort=object.SORT)
        object.getOverlayNode().reparentTo(self.mapOverlay, sort=object.SORT)
        object.addedToMap(self)

    def removeObject(self, object):
        Map.removeObject(self, object)
        object.getMapNode().detachNode()
        object.getOverlayNode().detachNode()
        object.removedFromMap(self)

    def updateRadarTransform(self, av):
        if self.radarAxis == Options.RadarAxisMap:
            self.radarTransformNode.setPosHprScale(-av.getPos(self.worldNode), VBase3(0), VBase3(1))
        else:
            holdHpr = av.getHpr()
            av.setH(camera.getH(render) - self.worldNode.getH(render))
            self.radarTransformNode.setTransform(self.worldNode.getTransform(av))
            av.setHpr(holdHpr)
        localAvatar.guiMgr.radarGui.updateDial(self)

    def getRadarNode(self):
        return self.radarTransformNode

    def handleHolidayStarted(self, area, holiday):
        self.map.findAllMatches("**/=Holiday=%s;+s" % (holiday,)).unstash()
        for node in area.getCapturePointNodes(holiday):
            zones = self.capturePoints.setdefault(holiday, {})
            zone = int(node.getTag("Zone"))
            if zone not in zones:
                object = MinimapCapturePoint(node, holiday, zone)
                zones[zone] = object
                self.addObject(object)
                continue

    handleHolidayStarted = report(types=["frameCount", "args"], dConfigParam="minimap")(handleHolidayStarted)

    def handleHolidayEnded(self, area, holiday, override=False):
        if holiday in InvasionGlobals.INVASION_IDS and not override:
            taskMgr.doMethodLater(10, self.handleInvasionEnded, "handleInvasionEnded", extraArgs=[area, holiday])
        else:
            self.map.findAllMatches("**/=Holiday=%s;+s" % (holiday,)).stash()
            for object in self.capturePoints.pop(holiday, {}).itervalues():
                self.removeObject(object)

    handleHolidayEnded = report(types=["frameCount", "args"], dConfigParam="minimap")(handleHolidayEnded)

    def handleInvasionEnded(self, area, holiday):
        if not localAvatar.guiMgr.invasionScoreboard:
            self.map.findAllMatches("**/=Holiday=%s;+s" % (holiday,)).stash()
            for object in self.capturePoints.pop(holiday, {}).itervalues():
                self.removeObject(object)
예제 #3
0
    def getShip(self,
                shipClass,
                style=ShipGlobals.Styles.Undefined,
                logo=ShipGlobals.Logos.Undefined,
                hullDesign=None,
                detailLevel=2,
                wantWheel=True,
                hullMaterial=None,
                sailMaterial=None,
                sailPattern=None,
                prowType=None,
                invertLogo=False):
        Ship = Ship
        import pirates.ship
        modelClass = ShipGlobals.getModelClass(shipClass)
        shipConfig = ShipGlobals.getShipConfig(shipClass)
        if style == ShipGlobals.Styles.Undefined:
            style = shipConfig['defaultStyle']

        complexCustomization = 0
        if sailPattern and sailMaterial and hullMaterial or SailReplace.has_key(
                shipClass):
            complexCustomization = 1

        if not prowType:
            prowType = shipConfig['prow']

        if not hullMaterial:
            hullMaterial = style

        if not sailMaterial:
            if SailReplace.has_key(shipClass):
                sailMaterial = SailReplace[shipClass]
            else:
                sailMaterial = style

        if not sailPattern:
            sailPattern = style

        shipHullTexture = ShipBlueprints.getShipTexture(hullMaterial)
        shipTextureSail = ShipBlueprints.getShipTexture(sailMaterial)
        logoTex = None
        if logo:
            logoTex = ShipBlueprints.getLogoTexture(logo)

        sailPatternTex = None
        if sailPattern:
            sailPatternTex = ShipBlueprints.getSailTexture(sailPattern)

        self.notify.debug('%s %s' % (sailPattern, logo))
        if logo == ShipGlobals.Logos.Undefined:
            logo = shipConfig['sailLogo']

        if logo in ShipGlobals.MAST_LOGO_PLACEMENT_LIST:
            placeLogos = 1
        else:
            placeLogos = 0
        if modelClass <= ShipGlobals.INTERCEPTORL3:
            mastHax = True
        else:
            mastHax = False
        customHull = hullDesign is not None
        if not logo != 0:
            pass
        customMasts = sailPattern != 0
        hull = self.getHull(modelClass, customHull)
        breakAnims = {}
        metaAnims = {}
        hitAnims = {}
        root = NodePath('Ship')
        hull.locators.reparentTo(root)
        charRoot = root.attachNewNode(Character('ShipChar'))
        collisions = root.attachNewNode('collisions')
        lodNode = charRoot.attachNewNode(LODNode('lod'))
        if detailLevel == 0:
            lodNode.node().addSwitch(200, 0)
            lodNode.node().addSwitch(800, 200)
            lodNode.node().addSwitch(100000, 800)
            high = lodNode.attachNewNode('high')
            low = lodNode.attachNewNode('low')
            med = NodePath('med')
            superlow = lodNode.attachNewNode('superlow')
        elif detailLevel == 1:
            lodNode.node().addSwitch(300, 0)
            lodNode.node().addSwitch(1000, 300)
            lodNode.node().addSwitch(2000, 1000)
            lodNode.node().addSwitch(100000, 2000)
            high = lodNode.attachNewNode('high')
            med = lodNode.attachNewNode('med')
            low = lodNode.attachNewNode('low')
            superlow = lodNode.attachNewNode('superlow')
        else:
            lodNode.node().addSwitch(750, 0)
            lodNode.node().addSwitch(3000, 750)
            lodNode.node().addSwitch(8000, 3000)
            lodNode.node().addSwitch(100000, 8000)
            high = lodNode.attachNewNode('high')
            med = lodNode.attachNewNode('med')
            low = lodNode.attachNewNode('low')
            superlow = lodNode.attachNewNode('superlow')
        mastSetup = ShipGlobals.getMastSetup(shipClass)
        for data in [(0, 'location_mainmast_0'), (1, 'location_mainmast_1'),
                     (2, 'location_mainmast_2'), (3, 'location_aftmast*'),
                     (4, 'location_foremast*')]:
            mastData = mastSetup.get(data[0])
            if mastData:
                mast = self.mastSets[mastData[0]].getMastSet(
                    mastData[1] - 1, customMasts)
                mastRoot = hull.locators.find('**/%s' % data[1]).getTransform(
                    hull.locators)
                model = NodePath(mast.charRoot)
                model.setTransform(mastRoot)
                if complexCustomization:
                    model.setTexture(shipTextureSail)

                useLogoTex = logoTex
                if placeLogos:
                    mastNum = data[0]
                    if mastNum not in ShipGlobals.MAST_LOGO_PLACEMENT.get(
                            modelClass):
                        useLogoTex = None

                charBundle = mast.charRoot.getBundle(0)
                if data[0] < 3:
                    for side in ['left', 'right']:
                        ropeNode = hull.locators.find(
                            '**/location_ropeLadder_%s_%s' % (side, data[0]))
                        if ropeNode:
                            transform = ropeNode.getTransform(
                                NodePath(mast.charRoot))
                            charBundle.findChild('def_ladder_0_%s' %
                                                 side).applyFreeze(transform)
                            continue

                if sailPatternTex and useLogoTex:
                    for node in model.findAllMatches('**/sails'):
                        node.setTextureOff(TextureStage.getDefault())
                        node.setTexture(self.colorLayer, sailPatternTex)
                        if invertLogo:
                            node.setTexture(self.logoLayerInv, logoTex)
                        else:
                            node.setTexture(self.logoLayer, logoTex)
                        node.setTexture(self.vertLayer, shipTextureSail)
                        node.setTexture(self.baseLayer, shipTextureSail)

                elif sailPatternTex:
                    for node in model.findAllMatches('**/sails'):
                        node.setTextureOff(TextureStage.getDefault())
                        node.setTexture(self.colorLayer, sailPatternTex)
                        node.setTexture(self.vertLayer, shipTextureSail)
                        node.setTexture(self.baseLayer, shipTextureSail)

                elif useLogoTex:
                    for node in model.findAllMatches('**/sails'):
                        node.setTextureOff(TextureStage.getDefault())
                        if invertLogo:
                            node.setTexture(self.logoLayerNoColorInv, logoTex)
                        else:
                            node.setTexture(self.logoLayerNoColor, logoTex)
                        node.setTexture(self.vertLayer, shipTextureSail)
                        node.setTexture(self.baseLayer, shipTextureSail)

                model.flattenLight()
                if detailLevel == 0:
                    model.find('**/low').copyTo(high)
                    model.find('**/low').copyTo(low)
                    model.find('**/superlow').copyTo(superlow)
                elif detailLevel == 1:
                    model.find('**/med').copyTo(high)
                    model.find('**/med').copyTo(med)
                    low.node().stealChildren(model.find('**/low').node())
                    superlow.node().stealChildren(
                        model.find('**/superlow').node())
                elif detailLevel == 2:
                    high.node().stealChildren(model.find('**/high').node())
                    med.node().stealChildren(model.find('**/med').node())
                    low.node().stealChildren(model.find('**/low').node())
                    superlow.node().stealChildren(
                        model.find('**/superlow').node())

                mastRoot = mast.collisions.find('**/collision_masts')
                if modelClass > ShipGlobals.INTERCEPTORL3 or data[0] != 3:
                    mastCode = str(data[0])
                    mastRoot.setTag('Mast Code', mastCode)
                else:
                    mastRoot.setName('colldision_sub_mast')
                    mastRoot.reparentTo(collisions.find('**/collision_masts'))
                    mastCode = '0'
                for coll in mast.collisions.findAllMatches(
                        '**/collision_sail_*'):
                    coll.setName('Sail-%s' % data[0])
                    coll.setTag('Mast Code', mastCode)

                for coll in mast.collisions.findAllMatches('**/sail_*'):
                    coll.setName('Sail-%s' % data[0])
                    coll.setTag('Mast Code', mastCode)

                collisions.node().stealChildren(mast.collisions.node())
                charBundle = mast.charRoot.getBundle(0)
                if mastHax and data[0] == 3:
                    breakAnims[0][0].storeAnim(
                        charBundle.loadBindAnim(loader.loader,
                                                mast.breakAnim[0], -1,
                                                MastSubset, True), '1')
                    breakAnims[0][1].storeAnim(
                        charBundle.loadBindAnim(loader.loader,
                                                mast.breakAnim[1], -1,
                                                MastSubset, True), '1')
                    tempHit = hitAnims[0]
                    tempHit[0].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.hitAnim,
                                                -1, HitMastSubset, True), '1')
                    tempHit[1].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.hitAnim,
                                                -1, PartSubset(), True), '1')
                else:
                    breakAnims[data[0]] = (AnimControlCollection(),
                                           AnimControlCollection())
                    breakAnims[data[0]][0].storeAnim(
                        charBundle.loadBindAnim(loader.loader,
                                                mast.breakAnim[0], -1,
                                                MastSubset, True), '0')
                    breakAnims[data[0]][1].storeAnim(
                        charBundle.loadBindAnim(loader.loader,
                                                mast.breakAnim[1], -1,
                                                MastSubset, True), '0')
                    tempHit = [
                        AnimControlCollection(),
                        AnimControlCollection()
                    ]
                    tempHit[0].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.hitAnim,
                                                -1, HitMastSubset, True), '0')
                    tempHit[1].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.hitAnim,
                                                -1, PartSubset(), True), '0')
                    hitAnims[data[0]] = tempHit
                for (anim, fileName) in mast.metaAnims.iteritems():
                    if anim not in metaAnims:
                        metaAnims[anim] = AnimControlCollection()

                    if anim not in MissingAnims.get(modelClass, []):
                        ac = charBundle.loadBindAnim(loader.loader, fileName,
                                                     -1, SailSubset, True)
                        if ac:
                            metaAnims[anim].storeAnim(
                                ac, str(metaAnims[anim].getNumAnims()))

                charRoot.node().combineWith(mast.charRoot)
                continue

        if self.wantProws and prowType:
            (highSprit, medSprit, lowSprit) = self.sprits[prowType].getAsset()
            transform = hull.locators.find(
                '**/location_bowsprit').getTransform(hull.locators)
            highSprit.setTransform(transform)
            medSprit.setTransform(transform)
            lowSprit.setTransform(transform)
            highSprit.reparentTo(hull.geoms[0])
            medSprit.reparentTo(hull.geoms[1])
            lowSprit.reparentTo(hull.geoms[2])

        if wantWheel:
            shipWheel = ShipBlueprints.getWheel()
            wheelPoint = hull.locators.find(
                '**/location_wheel;+s').getTransform(hull.locators)
            shipWheel.setTransform(wheelPoint)
            shipWheel.flattenLight()
            shipWheel.find('**/collisions').copyTo(collisions)
            hull.geoms[0].node().stealChildren(
                shipWheel.find('**/high').node())
            hull.geoms[1].node().stealChildren(shipWheel.find('**/med').node())
            hull.geoms[2].node().stealChildren(shipWheel.find('**/low').node())

        if complexCustomization:
            hull.geoms[0].setTexture(shipHullTexture)
            hull.geoms[0].flattenLight()
            hull.geoms[1].setTexture(shipHullTexture)
            hull.geoms[1].flattenLight()
            hull.geoms[2].setTexture(shipHullTexture)
            hull.geoms[2].flattenLight()
            hull.geoms[3].setTexture(shipHullTexture)
            hull.geoms[3].flattenLight()

        high.attachNewNode(ModelNode('non-animated')).node().stealChildren(
            hull.geoms[0].node())
        med.attachNewNode(ModelNode('non-animated')).node().stealChildren(
            hull.geoms[1].node())
        low.attachNewNode(ModelNode('non-animated')).node().stealChildren(
            hull.geoms[2].node())
        superlow.attachNewNode(ModelNode('non-animated')).node().stealChildren(
            hull.geoms[3].node())
        collisions.node().stealChildren(hull.collisions.node())
        hull.locators.stash()
        charRoot.flattenStrong()
        ship = Ship.Ship(shipClass, root, breakAnims, hitAnims, metaAnims,
                         collisions, hull.locators)
        if not complexCustomization:
            ship.char.setTexture(shipHullTexture)

        return ship
    def getShip(
        self,
        shipClass,
        style=ShipGlobals.Styles.Undefined,
        logo=ShipGlobals.Logos.Undefined,
        hullDesign=None,
        detailLevel=2,
        wantWheel=True,
        hullMaterial=None,
        sailMaterial=None,
        sailPattern=None,
        prowType=None,
    ):
        Ship = Ship
        import pirates.ship

        modelClass = ShipGlobals.getModelClass(shipClass)
        shipConfig = ShipGlobals.getShipConfig(shipClass)
        if style == ShipGlobals.Styles.Undefined:
            style = shipConfig["defaultStyle"]

        complexCustomization = 0
        if sailPattern and sailMaterial and hullMaterial or SailReplace.has_key(shipClass):
            complexCustomization = 1

        if not prowType:
            prowType = shipConfig["prow"]

        if not hullMaterial:
            hullMaterial = style

        if not sailMaterial:
            if SailReplace.has_key(shipClass):
                sailMaterial = SailReplace[shipClass]
            else:
                sailMaterial = style

        if not sailPattern:
            sailPattern = style

        shipHullTexture = ShipBlueprints.getShipTexture(hullMaterial)
        shipTextureSail = ShipBlueprints.getShipTexture(sailMaterial)
        logoTex = None
        if logo:
            logoTex = ShipBlueprints.getLogoTexture(logo)

        sailPatternTex = None
        if sailPattern:
            sailPatternTex = ShipBlueprints.getSailTexture(sailPattern)

        self.notify.debug("%s %s" % (sailPattern, logo))
        if logo == ShipGlobals.Logos.Undefined:
            logo = shipConfig["sailLogo"]

        if logo in ShipGlobals.MAST_LOGO_PLACEMENT_LIST:
            placeLogos = 1
        else:
            placeLogos = 0
        if modelClass <= ShipGlobals.INTERCEPTORL3:
            mastHax = True
        else:
            mastHax = False
        customHull = hullDesign is not None
        if not logo != 0:
            pass
        customMasts = sailPattern != 0
        hull = self.getHull(modelClass, customHull)
        breakAnims = {}
        metaAnims = {}
        hitAnims = {}
        root = NodePath("Ship")
        hull.locators.reparentTo(root)
        charRoot = root.attachNewNode(Character("ShipChar"))
        collisions = root.attachNewNode("collisions")
        lodNode = charRoot.attachNewNode(LODNode("lod"))
        if detailLevel == 0:
            lodNode.node().addSwitch(200, 0)
            lodNode.node().addSwitch(800, 200)
            lodNode.node().addSwitch(100000, 800)
            high = lodNode.attachNewNode("high")
            low = lodNode.attachNewNode("low")
            med = NodePath("med")
            superlow = lodNode.attachNewNode("superlow")
        elif detailLevel == 1:
            lodNode.node().addSwitch(300, 0)
            lodNode.node().addSwitch(1000, 300)
            lodNode.node().addSwitch(2000, 1000)
            lodNode.node().addSwitch(100000, 2000)
            high = lodNode.attachNewNode("high")
            med = lodNode.attachNewNode("med")
            low = lodNode.attachNewNode("low")
            superlow = lodNode.attachNewNode("superlow")
        else:
            lodNode.node().addSwitch(750, 0)
            lodNode.node().addSwitch(3000, 750)
            lodNode.node().addSwitch(8000, 3000)
            lodNode.node().addSwitch(100000, 8000)
            high = lodNode.attachNewNode("high")
            med = lodNode.attachNewNode("med")
            low = lodNode.attachNewNode("low")
            superlow = lodNode.attachNewNode("superlow")
        mastSetup = ShipGlobals.getMastSetup(shipClass)
        for data in [
            (0, "location_mainmast_0"),
            (1, "location_mainmast_1"),
            (2, "location_mainmast_2"),
            (3, "location_aftmast*"),
            (4, "location_foremast*"),
        ]:
            mastData = mastSetup.get(data[0])
            if mastData:
                mast = self.mastSets[mastData[0]].getMastSet(mastData[1] - 1, customMasts)
                mastRoot = hull.locators.find("**/%s" % data[1]).getTransform(hull.locators)
                model = NodePath(mast.charRoot)
                model.setTransform(mastRoot)
                if complexCustomization:
                    model.setTexture(shipTextureSail)

                useLogoTex = logoTex
                if placeLogos:
                    mastNum = data[0]
                    if mastNum not in ShipGlobals.MAST_LOGO_PLACEMENT.get(modelClass):
                        useLogoTex = None

                charBundle = mast.charRoot.getBundle(0)
                if data[0] < 3:
                    for side in ["left", "right"]:
                        ropeNode = hull.locators.find("**/location_ropeLadder_%s_%s" % (side, data[0]))
                        if ropeNode:
                            transform = ropeNode.getTransform(NodePath(mast.charRoot))
                            charBundle.findChild("def_ladder_0_%s" % side).applyFreeze(transform)
                            continue

                if sailPatternTex and useLogoTex:
                    for node in model.findAllMatches("**/sails"):
                        node.setTextureOff(TextureStage.getDefault())
                        node.setTexture(self.colorLayer, sailPatternTex)
                        node.setTexture(self.logoLayer, logoTex)
                        node.setTexture(self.vertLayer, shipTextureSail)
                        node.setTexture(self.baseLayer, shipTextureSail)

                elif sailPatternTex:
                    for node in model.findAllMatches("**/sails"):
                        node.setTextureOff(TextureStage.getDefault())
                        node.setTexture(self.colorLayer, sailPatternTex)
                        node.setTexture(self.vertLayer, shipTextureSail)
                        node.setTexture(self.baseLayer, shipTextureSail)

                elif useLogoTex:
                    for node in model.findAllMatches("**/sails"):
                        node.setTextureOff(TextureStage.getDefault())
                        node.setTexture(self.logoLayerNoColor, logoTex)
                        node.setTexture(self.vertLayer, shipTextureSail)
                        node.setTexture(self.baseLayer, shipTextureSail)

                model.flattenLight()
                if detailLevel == 0:
                    model.find("**/low").copyTo(high)
                    model.find("**/low").copyTo(low)
                    model.find("**/superlow").copyTo(superlow)
                elif detailLevel == 1:
                    model.find("**/med").copyTo(high)
                    model.find("**/med").copyTo(med)
                    low.node().stealChildren(model.find("**/low").node())
                    superlow.node().stealChildren(model.find("**/superlow").node())
                elif detailLevel == 2:
                    high.node().stealChildren(model.find("**/high").node())
                    med.node().stealChildren(model.find("**/med").node())
                    low.node().stealChildren(model.find("**/low").node())
                    superlow.node().stealChildren(model.find("**/superlow").node())

                mastRoot = mast.collisions.find("**/collision_masts")
                if modelClass > ShipGlobals.INTERCEPTORL3 or data[0] != 3:
                    mastCode = str(data[0])
                    mastRoot.setTag("Mast Code", mastCode)
                else:
                    mastRoot.setName("colldision_sub_mast")
                    mastRoot.reparentTo(collisions.find("**/collision_masts"))
                    mastCode = "0"
                for coll in mast.collisions.findAllMatches("**/collision_sail_*"):
                    coll.setName("Sail-%s" % data[0])
                    coll.setTag("Mast Code", mastCode)

                for coll in mast.collisions.findAllMatches("**/sail_*"):
                    coll.setName("Sail-%s" % data[0])
                    coll.setTag("Mast Code", mastCode)

                collisions.node().stealChildren(mast.collisions.node())
                charBundle = mast.charRoot.getBundle(0)
                if mastHax and data[0] == 3:
                    breakAnims[0][0].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.breakAnim[0], -1, MastSubset, True), "1"
                    )
                    breakAnims[0][1].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.breakAnim[1], -1, MastSubset, True), "1"
                    )
                    tempHit = hitAnims[0]
                    tempHit[0].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.hitAnim, -1, HitMastSubset, True), "1"
                    )
                    tempHit[1].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.hitAnim, -1, PartSubset(), True), "1"
                    )
                else:
                    breakAnims[data[0]] = (AnimControlCollection(), AnimControlCollection())
                    breakAnims[data[0]][0].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.breakAnim[0], -1, MastSubset, True), "0"
                    )
                    breakAnims[data[0]][1].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.breakAnim[1], -1, MastSubset, True), "0"
                    )
                    tempHit = [AnimControlCollection(), AnimControlCollection()]
                    tempHit[0].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.hitAnim, -1, HitMastSubset, True), "0"
                    )
                    tempHit[1].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.hitAnim, -1, PartSubset(), True), "0"
                    )
                    hitAnims[data[0]] = tempHit
                for (anim, fileName) in mast.metaAnims.iteritems():
                    if anim not in metaAnims:
                        metaAnims[anim] = AnimControlCollection()

                    if anim not in MissingAnims.get(modelClass, []):
                        ac = charBundle.loadBindAnim(loader.loader, fileName, -1, SailSubset, True)
                        if ac:
                            metaAnims[anim].storeAnim(ac, str(metaAnims[anim].getNumAnims()))

                charRoot.node().combineWith(mast.charRoot)
                continue

        if self.wantProws and prowType:
            (highSprit, medSprit, lowSprit) = self.sprits[prowType].getAsset()
            transform = hull.locators.find("**/location_bowsprit").getTransform(hull.locators)
            highSprit.setTransform(transform)
            medSprit.setTransform(transform)
            lowSprit.setTransform(transform)
            highSprit.reparentTo(hull.geoms[0])
            medSprit.reparentTo(hull.geoms[1])
            lowSprit.reparentTo(hull.geoms[2])

        if wantWheel:
            shipWheel = ShipBlueprints.getWheel()
            wheelPoint = hull.locators.find("**/location_wheel;+s").getTransform(hull.locators)
            shipWheel.setTransform(wheelPoint)
            shipWheel.flattenLight()
            shipWheel.find("**/collisions").copyTo(collisions)
            hull.geoms[0].node().stealChildren(shipWheel.find("**/high").node())
            hull.geoms[1].node().stealChildren(shipWheel.find("**/med").node())
            hull.geoms[2].node().stealChildren(shipWheel.find("**/low").node())

        if complexCustomization:
            hull.geoms[0].setTexture(shipHullTexture)
            hull.geoms[0].flattenLight()
            hull.geoms[1].setTexture(shipHullTexture)
            hull.geoms[1].flattenLight()
            hull.geoms[2].setTexture(shipHullTexture)
            hull.geoms[2].flattenLight()
            hull.geoms[3].setTexture(shipHullTexture)
            hull.geoms[3].flattenLight()

        high.attachNewNode(ModelNode("non-animated")).node().stealChildren(hull.geoms[0].node())
        med.attachNewNode(ModelNode("non-animated")).node().stealChildren(hull.geoms[1].node())
        low.attachNewNode(ModelNode("non-animated")).node().stealChildren(hull.geoms[2].node())
        superlow.attachNewNode(ModelNode("non-animated")).node().stealChildren(hull.geoms[3].node())
        collisions.node().stealChildren(hull.collisions.node())
        hull.locators.stash()
        charRoot.flattenStrong()
        ship = Ship.Ship(shipClass, root, breakAnims, hitAnims, metaAnims, collisions, hull.locators)
        if not complexCustomization:
            ship.char.setTexture(shipHullTexture)

        return ship
예제 #5
0
class CogdoMazeFactory:
    def __init__(self,
                 randomNumGen,
                 width,
                 height,
                 frameWallThickness=Globals.FrameWallThickness,
                 cogdoMazeData=CogdoMazeData):
        self._rng = RandomNumGen(randomNumGen)
        self.width = width
        self.height = height
        self.frameWallThickness = frameWallThickness
        self._cogdoMazeData = cogdoMazeData
        self.quadrantSize = self._cogdoMazeData.QuadrantSize
        self.cellWidth = self._cogdoMazeData.QuadrantCellWidth

    def getMazeData(self):
        if not hasattr(self, '_data'):
            self._generateMazeData()
        return self._data

    def createCogdoMaze(self, flattenModel=True):
        if not hasattr(self, '_maze'):
            self._loadAndBuildMazeModel(flatten=flattenModel)
        return CogdoMaze(self._model, self._data, self.cellWidth)

    def _gatherQuadrantData(self):
        self.openBarriers = []
        barrierItems = range(Globals.TotalBarriers)
        self._rng.shuffle(barrierItems)
        for i in barrierItems[0:len(barrierItems) - Globals.NumBarriers]:
            self.openBarriers.append(i)

        self.quadrantData = []
        quadrantKeys = self._cogdoMazeData.QuadrantCollisions.keys()
        self._rng.shuffle(quadrantKeys)
        i = 0
        for y in xrange(self.height):
            for x in xrange(self.width):
                key = quadrantKeys[i]
                collTable = self._cogdoMazeData.QuadrantCollisions[key]
                angle = self._cogdoMazeData.QuadrantAngles[self._rng.randint(
                    0,
                    len(self._cogdoMazeData.QuadrantAngles) - 1)]
                self.quadrantData.append((key, collTable[angle], angle))
                i += 1
                if x * y >= self._cogdoMazeData.NumQuadrants:
                    i = 0

    def _generateBarrierData(self):
        data = []
        for y in xrange(self.height):
            data.append([])
            for x in xrange(self.width):
                if x == self.width - 1:
                    ax = -1
                else:
                    ax = 1
                if y == self.height - 1:
                    ay = -1
                else:
                    ay = 1
                data[y].append([ax, ay])

        dirUp = 0
        dirDown = 1
        dirLeft = 2
        dirRight = 3

        def getAvailableDirections(ax, ay, ignore=None):
            dirs = []
            if ax - 1 >= 0 and data[ay][ax - 1][BARRIER_DATA_RIGHT] == 1 and (
                    ax, ay) != ignore:
                dirs.append(dirLeft)
            if ax + 1 < self.width and data[ay][ax][
                    BARRIER_DATA_RIGHT] == 1 and (ax, ay) != ignore:
                dirs.append(dirRight)
            if ay - 1 >= 0 and data[ay - 1][ax][BARRIER_DATA_TOP] == 1 and (
                    ax, ay) != ignore:
                dirs.append(dirDown)
            if ay + 1 < self.height and data[ay][ax][
                    BARRIER_DATA_TOP] == 1 and (ax, ay) != ignore:
                dirs.append(dirUp)
            return dirs

        visited = []

        def tryVisitNeighbor(ax, ay, ad):
            if ad == dirUp:
                if data[ay][ax] in visited:
                    return None
                visited.append(data[ay][ax])
                data[ay][ax][BARRIER_DATA_TOP] = 0
                ay += 1
            elif ad == dirDown:
                if data[ay - 1][ax] in visited:
                    return None
                visited.append(data[ay - 1][ax])
                data[ay - 1][ax][BARRIER_DATA_TOP] = 0
                ay -= 1
            elif ad == dirLeft:
                if data[ay][ax - 1] in visited:
                    return None
                visited.append(data[ay][ax - 1])
                data[ay][ax - 1][BARRIER_DATA_RIGHT] = 0
                ax -= 1
            elif ad == dirRight:
                if data[ay][ax] in visited:
                    return None
                visited.append(data[ay][ax])
                data[ay][ax][BARRIER_DATA_RIGHT] = 0
                ax += 1
            return (ax, ay)

        def openBarriers(x, y):
            dirs = getAvailableDirections(x, y)
            for dir in dirs:
                next = tryVisitNeighbor(x, y, dir)
                if next is not None:
                    openBarriers(*next)

            return

        x = self._rng.randint(0, self.width - 1)
        y = self._rng.randint(0, self.height - 1)
        openBarriers(x, y)
        self._barrierData = data

    def _generateMazeData(self):
        if not hasattr(self, 'quadrantData'):
            self._gatherQuadrantData()

        self._data = {}
        self._data['width'] = (
            self.width +
            1) * self.frameWallThickness + self.width * self.quadrantSize
        self._data['height'] = (
            self.height +
            1) * self.frameWallThickness + self.height * self.quadrantSize
        self._data['originX'] = int(self._data['width'] / 2)
        self._data['originY'] = int(self._data['height'] / 2)
        collisionTable = []
        horizontalWall = [1 for x in xrange(self._data['width'])]
        collisionTable.append(horizontalWall)
        for i in xrange(0, len(self.quadrantData), self.width):
            for y in xrange(self.quadrantSize):
                row = [1]
                for x in xrange(i, i + self.width):
                    if x == 1 and y < self.quadrantSize / 2 - 2:
                        newData = []
                        for j in self.quadrantData[x][1][y]:
                            if j == 0:
                                newData.append(2)
                            else:
                                newData.append(j + 0)

                        row += newData + [1]
                    else:
                        row += self.quadrantData[x][1][y] + [1]

                collisionTable.append(row)

            collisionTable.append(horizontalWall[:])

        barriers = Globals.MazeBarriers
        for i in xrange(len(barriers)):
            for coords in barriers[i]:
                collisionTable[coords[1]][coords[0]] = 0

        y = self._data['originY']
        for x in xrange(len(collisionTable[y])):
            if collisionTable[y][x] == 0:
                collisionTable[y][x] = 2

        x = self._data['originX']
        for y in xrange(len(collisionTable)):
            if collisionTable[y][x] == 0:
                collisionTable[y][x] = 2

        self._data['collisionTable'] = collisionTable

    def _loadAndBuildMazeModel(self, flatten=False):
        self.getMazeData()
        self._model = NodePath('CogdoMazeModel')
        levelModel = CogdoUtil.loadMazeModel('level')
        self.quadrants = []
        quadrantUnitSize = int(self.quadrantSize * self.cellWidth)
        frameActualSize = self.frameWallThickness * self.cellWidth
        size = quadrantUnitSize + frameActualSize
        halfWidth = int(self.width / 2)
        halfHeight = int(self.height / 2)
        i = 0
        for y in xrange(self.height):
            for x in xrange(self.width):
                ax = (x - halfWidth) * size
                ay = (y - halfHeight) * size
                extension = ''
                if hasattr(getBase(), 'air'):
                    extension = '.bam'
                filepath = self.quadrantData[i][0] + extension
                angle = self.quadrantData[i][2]
                m = self._createQuadrant(filepath, i, angle, quadrantUnitSize)
                m.setPos(ax, ay, 0)
                m.reparentTo(self._model)
                self.quadrants.append(m)
                i += 1

        quadrantHalfUnitSize = quadrantUnitSize * 0.5
        barrierModel = CogdoUtil.loadMazeModel('grouping_blockerDivider').find(
            '**/divider')
        y = 3
        for x in xrange(self.width):
            if x == (self.width - 1) / 2:
                continue
            ax = (x - halfWidth) * size
            ay = (y - halfHeight) * size - quadrantHalfUnitSize - (
                self.cellWidth - 0.5)
            b = NodePath('barrier')
            barrierModel.instanceTo(b)
            b.setPos(ax, ay, 0)
            b.reparentTo(self._model)

        offset = self.cellWidth - 0.5
        for x in (0, 3):
            for y in xrange(self.height):
                ax = (
                    x - halfWidth
                ) * size - quadrantHalfUnitSize - frameActualSize + offset
                ay = (y - halfHeight) * size
                b = NodePath('barrier')
                barrierModel.instanceTo(b)
                b.setPos(ax, ay, 0)
                b.setH(90)
                b.reparentTo(self._model)

            offset -= 2.0

        barrierModel.removeNode()
        levelModel.getChildren().reparentTo(self._model)
        for np in self._model.findAllMatches('**/*lightCone*'):
            CogdoUtil.initializeLightCone(np, 'fixed', 3)

        if flatten:
            self._model.flattenStrong()

        return self._model

    def _createQuadrant(self, filepath, serialNum, angle, size):
        root = NodePath('QuadrantRoot-%i' % serialNum)
        quadrant = loader.loadModel(filepath)
        quadrant.getChildren().reparentTo(root)
        root.setH(angle)
        return root
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
예제 #7
0
class CogdoFlyingLevelQuadrant():
    __module__ = __name__
    notify = directNotify.newCategory('CogdoFlyingLevelQuadrant')

    def __init__(self, serialNum, model, level, parent):
        self.serialNum = serialNum
        self._model = model
        self._level = level
        self._root = NodePath('Quadrant' + ` serialNum `)
        self._model.reparentTo(self._root)
        self._root.reparentTo(parent)
        self._visible = True
        self.platforms = {}
        self.gatherables = []
        self.obstacles = []
        self._playing = False
        self._obstaclesRoot = NodePath('obstacles')
        self._obstaclesRoot.reparentTo(self._root)
        self._initObstacles(self._obstaclesRoot)
        self._gatherablesRoot = NodePath('gatherables')
        self._gatherablesRoot.reparentTo(self._root)
        self._initGatherables(self._gatherablesRoot)
        self._platformsRoot = NodePath('platforms')
        self._platformsRoot.reparentTo(self._model)
        self._initPlatforms(self._platformsRoot)
        self._optimize()
        self.place()

    def _optimize(self):
        lightCones = NodePath('lightCones')
        for np in self._platformsRoot.findAllMatches('**/*lightCone*'):
            np.wrtReparentTo(lightCones)

        lightCones.reparentTo(self._model)
        node = self._model.find('**/ducts')
        if not node.isEmpty():
            node.flattenStrong()
            for np in node.getChildren():
                np.wrtReparentTo(self._model)

        node = self._model.find('**/nests')
        if not node.isEmpty():
            for np in node.getChildren():
                np.flattenStrong()
                np.wrtReparentTo(self._model)

        for np in self._model.findAllMatches('**/*LayerStack*'):
            np.wrtReparentTo(self._model)

        for np in self._model.find('**/static').getChildren():
            np.wrtReparentTo(self._model)

        self._model.flattenMedium()

    def _initPlatforms(self, parent):
        platformModels = self._model.findAllMatches('**/%s' %
                                                    Globals.Level.PlatformName)
        for platformModel in platformModels:
            platform = CogdoFlyingPlatform(platformModel, parent=parent)
            self.platforms[platform.getName()] = platform

    def _destroyPlatforms(self):
        for platform in self.platforms.values():
            platform.destroy()

        del self.platforms

    def _initGatherables(self, parent):
        self.generateGatherables(self._model, parent=parent)
        if Globals.Level.SpawnLaffPowerupsInNests:
            self.generateNestPowerups(self._model, parent=parent)

    def generateNestPowerups(self, gatherableModel, parent):
        nests = gatherableModel.findAllMatches(
            '**/%s;+s' % Globals.Level.LegalEagleNestName)
        for nest in nests:
            offset = Globals.Level.LaffPowerupNestOffset
            pickup = self._level.gatherableFactory.createPowerup(
                Globals.Level.GatherableTypes.LaffPowerup)
            pickup.reparentTo(parent)
            pickup.setPos(parent, nest.getPos(parent) + offset)
            if Globals.Level.AddSparkleToPowerups:
                sparkles = self._level.gatherableFactory.createSparkles(
                    Vec4(1, 1, 1, 1), Vec4(1, 1, 0, 1), 10.0)
                sparkles.reparentTo(pickup)
                sparkles.setPos(0, 0, 1)
                sparkles.start()
            self.gatherables.append(pickup)

    def generateGatherables(self,
                            gatherableModel,
                            parent=None,
                            spread=Globals.Level.GatherablesDefaultSpread):
        parent = parent or self._root
        mopath = Mopath.Mopath(name='gatherables')

        def generateMemos():
            gatherPaths = gatherableModel.findAllMatches(
                '**/%s' % Globals.Level.GatherablesPathName)
            for gatherPath in gatherPaths:
                mopath.loadNodePath(gatherPath)
                t = 0.0
                while t < mopath.getMaxT():
                    pickup = self._level.gatherableFactory.createMemo()
                    pickup.reparentTo(parent)
                    mopath.goTo(pickup, t)
                    self.gatherables.append(pickup)
                    t += spread

                gatherPath.removeNode()

            angleSpread = 360.0 / Globals.Level.NumMemosInRing
            gatherPaths = gatherableModel.findAllMatches(
                '**/%s' % Globals.Level.GatherablesRingName)
            for gatherPath in gatherPaths:
                mopath.loadNodePath(gatherPath)
                t = 0.0
                while t < mopath.getMaxT():
                    angle = 0
                    r = 3
                    while angle < 360.0:
                        pickup = self._level.gatherableFactory.createMemo()
                        pickup.reparentTo(parent)
                        mopath.goTo(pickup, t)
                        pickup.setX(
                            parent,
                            pickup.getX() + r * math.cos(math.radians(angle)))
                        pickup.setZ(
                            parent,
                            pickup.getZ() + r * math.sin(math.radians(angle)))
                        self.gatherables.append(pickup)
                        angle += angleSpread

                    t += spread + 0.5

                gatherPath.removeNode()

        def generatePropellers():
            gatherables = gatherableModel.findAllMatches(
                '**/%s' % Globals.Level.PropellerName)
            for gatherable in gatherables:
                pickup = self._level.gatherableFactory.createPropeller()
                pickup.reparentTo(gatherable.getParent())
                pickup.setPos(parent, gatherable.getPos(parent))
                self.gatherables.append(pickup)
                gatherable.removeNode()

        def generatePowerUps():
            for powerupType, locName in Globals.Level.PowerupType2Loc.iteritems(
            ):
                if powerupType == Globals.Level.GatherableTypes.LaffPowerup and Globals.Level.IgnoreLaffPowerups:
                    continue
                gatherables = gatherableModel.findAllMatches('**/%s' % locName)
                for gatherable in gatherables:
                    pickup = self._level.gatherableFactory.createPowerup(
                        powerupType)
                    pickup.reparentTo(parent)
                    pickup.setPos(parent, gatherable.getPos(parent))
                    if Globals.Level.AddSparkleToPowerups:
                        sparkles = self._level.gatherableFactory.createSparkles(
                            Vec4(1, 1, 1, 1), Vec4(1, 1, 0, 1), 10.0)
                        sparkles.reparentTo(pickup)
                        sparkles.setPos(0, 0, 1)
                        sparkles.start()
                    self.gatherables.append(pickup)
                    gatherable.removeNode()

        generateMemos()
        generatePropellers()
        generatePowerUps()

    def _initObstacles(self, parent):
        def initWhirlwinds():
            obstacles = self._root.findAllMatches('**/%s' %
                                                  Globals.Level.WhirlwindName)
            for obstacleLoc in obstacles:
                motionPath = self._model.find(
                    '**/%s%s' %
                    (obstacleLoc.getName(), Globals.Level.WhirlwindPathName))
                if motionPath.isEmpty():
                    motionPath = None
                obstacle = self._level.obstacleFactory.createWhirlwind(
                    motionPath=motionPath)
                obstacle.model.reparentTo(parent)
                obstacle.model.setPos(parent, obstacleLoc.getPos(parent))
                self.obstacles.append(obstacle)
                obstacleLoc.removeNode()

            return

        def initStreamers():
            obstacles = self._model.findAllMatches('**/%s' %
                                                   Globals.Level.StreamerName)
            for obstacleLoc in obstacles:
                obstacle = self._level.obstacleFactory.createFan()
                obstacle.model.reparentTo(parent)
                obstacle.model.setPos(parent, obstacleLoc.getPos(parent))
                obstacle.model.setHpr(parent, obstacleLoc.getHpr(parent))
                obstacle.model.setScale(parent, obstacleLoc.getScale(parent))
                obstacle.setBlowDirection()
                if Globals.Level.AddParticlesToStreamers:
                    particles = self._level.obstacleFactory.createStreamerParticles(
                        Vec4(1, 1, 1, 1), Vec4(1, 1, 1, 1), 10.0)
                    particles.reparentTo(obstacle.model)
                    particles.start()
                self.obstacles.append(obstacle)
                obstacleLoc.removeNode()

        def initWalkingMinions():
            motionPaths = self._model.findAllMatches(
                '**/%s' % Globals.Level.MinionWalkingPathName)
            for motionPath in motionPaths:
                obstacle = self._level.obstacleFactory.createWalkingMinion(
                    motionPath=motionPath)
                obstacle.model.reparentTo(parent)
                obstacle.model.setPos(parent, motionPath.getPos(parent))
                self.obstacles.append(obstacle)

        def initFlyingMinions():
            motionPaths = self._model.findAllMatches(
                '**/%s' % Globals.Level.MinionFlyingPathName)
            for motionPath in motionPaths:
                obstacle = self._level.obstacleFactory.createFlyingMinion(
                    motionPath=motionPath)
                obstacle.model.reparentTo(parent)
                obstacle.model.setPos(parent, motionPath.getPos(parent))
                self.obstacles.append(obstacle)

        initWhirlwinds()
        initStreamers()
        initWalkingMinions()
        initFlyingMinions()

    def place(self):
        self._root.setPos(0, self._level.convertQuadNumToY(self.serialNum), 0)

    def destroy(self):
        if self._visible:
            self.offstage()
        self._destroyPlatforms()
        for obstacle in self.obstacles:
            obstacle.destroy()

        for gatherable in self.gatherables:
            gatherable.destroy()

        self._root.removeNode()
        del self._root
        del self._gatherablesRoot
        del self._obstaclesRoot
        del self._platformsRoot
        del self._level

    def onstage(self, elapsedTime=0.0):
        if self._visible:
            return
        self._root.unstash()
        for obstacle in self.obstacles:
            obstacle.startMoving(elapsedTime)

        for gatherable in self.gatherables:
            gatherable.show()

        self._visible = True

    def offstage(self):
        if not self._visible:
            return
        self._root.stash()
        for obstacle in self.obstacles:
            obstacle.stopMoving()

        for gatherable in self.gatherables:
            gatherable.hide()

        self._visible = False

    def update(self, dt):
        if self._visible:
            for gatherable in self.gatherables:
                gatherable.update(dt)

            for obstacle in self.obstacles:
                obstacle.update(dt)

    def getModel(self):
        return self._root
예제 #8
0
파일: Minimap.py 프로젝트: Kealigal/POS2013
class AreaMap(Map):
    
    def __init__(self, area):
        Map.__init__(self, 'map-' + area.getName())
        self.capturePoints = { }
        mapNode = area.getMapNode()
        if mapNode and not mapNode.isEmpty():
            geom = mapNode.getChild(0)
            geom.setScale(mapNode.getScale())
            geom.flattenStrong()
            mapNode.setScale(1)
            self.worldNode = mapNode
            self.map = self.worldNode.copyTo(NodePath())
            (a, b) = self.map.getTightBounds()
            diff = b - a
            h = diff[1]
            w = diff[0]
        else:
            self.worldNode = area
            self.map = NodePath('no map found')
            (a, b) = self.worldNode.geom.getTightBounds()
            diff = b - a
            h = diff[1]
            w = diff[0]
        ratio = h / w
        if ratio < 0.98999999999999999:
            normalScale = 2 / w
            screenScale = 1
        else:
            normalScale = 2 / h
            screenScale = 0.75
        self.map.clearTransform()
        self.map.show()
        self.screenNode = NodePath('Minimap-screenNode')
        self.screenNode.setP(90)
        self.screenNode.setScale(screenScale * normalScale)
        self.screenNode.hide()
        self.map.reparentTo(self.screenNode)
        self.mapOverlay = self.map.attachNewNode('mapOverlay')
        self.mapOverlay.wrtReparentTo(self.screenNode)
        self.radarTransformNode = NodePath('radarTransform')
        self.radarTransformNode.setScale(self.worldNode.getScale()[0])
        self.map.instanceTo(self.radarTransformNode)
        localAvatar.guiMgr.addMinimap(self)
        if self.allowOnScreen():
            self.addObject(MinimapFootprint(area))
        
        self.shops = set()
        if self.allowOnScreen():
            if area.getUniqueId() not in [
                LocationIds.RAVENS_COVE_ISLAND]:
                for shop in area.getShopNodes():
                    uid = shop.getTag('Uid')
                    shopType = shop.getTag('ShopType')
                    self.addObject(MinimapShop(uid, shop, shopType))
                
            
            self.map.findAllMatches('**/=Holiday').stash()
            if base.cr.newsManager:
                for holiday in base.cr.newsManager.getHolidayList():
                    self.handleHolidayStarted(area, HolidayGlobals.getHolidayName(holiday))
                
            
        
        self.zoomLevels = area.getZoomLevels()
        self.accept('landMapRadarAxisChanged', self.setRadarAxis)

    
    def destroy(self):
        self.ignore('landMapRadarAxisChanged')
        if hasattr(base, 'localAvatar'):
            localAvatar.guiMgr.removeMinimap(self)
        
        for shop in self.shops:
            self.removeObject(shop)
        
        self.shops = set()
        for holiday in self.capturePoints.keys():
            zones = self.capturePoints.pop(holiday, { })
            for object in zones.itervalues():
                self.removeObject(object)
            
        
        Map.destroy(self)

    
    def allowOnScreen(self):
        return self.map.find('minimap-card').isEmpty()

    
    def getZoomLevels(self):
        return self.zoomLevels

    
    def getWorldNode(self):
        return self.worldNode

    
    def getScreenNode(self):
        return self.screenNode

    
    def getOverlayNode(self):
        return self.mapOverlay

    
    def getCapturePoint(self, holidayId, zone):
        if self.capturePoints.has_key(holidayId):
            return self.capturePoints[holidayId][zone]
        

    
    def updateTask(self, task):
        self.update()
        return task.cont

    
    def update(self):
        for obj in self.objects:
            obj.updateOnMap(self)
        

    
    def addObject(self, object):
        Map.addObject(self, object)
        mapNode = object.getMapNode()
        mapNode.reparentTo(self.map, sort = object.SORT)
        object.getOverlayNode().reparentTo(self.mapOverlay, sort = object.SORT)
        object.addedToMap(self)

    
    def removeObject(self, object):
        Map.removeObject(self, object)
        object.getMapNode().detachNode()
        object.getOverlayNode().detachNode()
        object.removedFromMap(self)

    
    def updateRadarTransform(self, av):
        if self.radarAxis == Options.RadarAxisMap:
            self.radarTransformNode.setPosHprScale(-av.getPos(self.worldNode), VBase3(0), VBase3(1))
        else:
            holdHpr = av.getHpr()
            av.setH(camera.getH(render) - self.worldNode.getH(render))
            self.radarTransformNode.setTransform(self.worldNode.getTransform(av))
            av.setHpr(holdHpr)
        localAvatar.guiMgr.radarGui.updateDial(self)

    
    def getRadarNode(self):
        return self.radarTransformNode

    
    def handleHolidayStarted(self, area, holiday):
        self.map.findAllMatches('**/=Holiday=%s;+s' % (holiday,)).unstash()
        for node in area.getCapturePointNodes(holiday):
            zones = self.capturePoints.setdefault(holiday, { })
            zone = int(node.getTag('Zone'))
            if zone not in zones:
                object = MinimapCapturePoint(node, holiday, zone)
                zones[zone] = object
                self.addObject(object)
                continue
        

    handleHolidayStarted = report(types = [
        'frameCount',
        'args'], dConfigParam = 'minimap')(handleHolidayStarted)
    
    def handleHolidayEnded(self, area, holiday, override = False):
        if holiday in InvasionGlobals.INVASION_IDS and not override:
            taskMgr.doMethodLater(10, self.handleInvasionEnded, 'handleInvasionEnded', extraArgs = [
                area,
                holiday])
        else:
            self.map.findAllMatches('**/=Holiday=%s;+s' % (holiday,)).stash()
            for object in self.capturePoints.pop(holiday, { }).itervalues():
                self.removeObject(object)
            

    handleHolidayEnded = report(types = [
        'frameCount',
        'args'], dConfigParam = 'minimap')(handleHolidayEnded)
    
    def handleInvasionEnded(self, area, holiday):
        if not localAvatar.guiMgr.invasionScoreboard:
            self.map.findAllMatches('**/=Holiday=%s;+s' % (holiday,)).stash()
            for object in self.capturePoints.pop(holiday, { }).itervalues():
                self.removeObject(object)
class CogdoFlyingLevelQuadrant:
    notify = directNotify.newCategory('CogdoFlyingLevelQuadrant')

    def __init__(self, serialNum, model, level, parent):
        self.serialNum = serialNum
        self._model = model
        self._level = level
        self._root = NodePath('Quadrant' + `serialNum`)
        self._model.reparentTo(self._root)
        self._root.reparentTo(parent)
        self._visible = True
        self.platforms = {}
        self.gatherables = []
        self.obstacles = []
        self._playing = False
        self._obstaclesRoot = NodePath('obstacles')
        self._obstaclesRoot.reparentTo(self._root)
        self._initObstacles(self._obstaclesRoot)
        self._gatherablesRoot = NodePath('gatherables')
        self._gatherablesRoot.reparentTo(self._root)
        self._initGatherables(self._gatherablesRoot)
        self._platformsRoot = NodePath('platforms')
        self._platformsRoot.reparentTo(self._model)
        self._initPlatforms(self._platformsRoot)
        self._optimize()
        self.place()

    def _optimize(self):
        lightCones = NodePath('lightCones')
        for np in self._platformsRoot.findAllMatches('**/*lightCone*'):
            np.wrtReparentTo(lightCones)

        lightCones.reparentTo(self._model)
        node = self._model.find('**/ducts')
        if not node.isEmpty():
            node.flattenStrong()
            for np in node.getChildren():
                np.wrtReparentTo(self._model)

        node = self._model.find('**/nests')
        if not node.isEmpty():
            for np in node.getChildren():
                np.flattenStrong()
                np.wrtReparentTo(self._model)

        for np in self._model.findAllMatches('**/*LayerStack*'):
            np.wrtReparentTo(self._model)

        if not self._model.find('**/static').isEmpty():
            for np in self._model.find('**/static').getChildren():
                np.wrtReparentTo(self._model)

        self._model.flattenMedium()

    def _initPlatforms(self, parent):
        platformModels = self._model.findAllMatches('**/%s' % Globals.Level.PlatformName)
        for platformModel in platformModels:
            platform = CogdoFlyingPlatform(platformModel, parent=parent)
            self.platforms[platform.getName()] = platform

    def _destroyPlatforms(self):
        for platform in self.platforms.values():
            platform.destroy()

        del self.platforms

    def _initGatherables(self, parent):
        self.generateGatherables(self._model, parent=parent)
        if Globals.Level.SpawnLaffPowerupsInNests:
            self.generateNestPowerups(self._model, parent=parent)

    def generateNestPowerups(self, gatherableModel, parent):
        nests = gatherableModel.findAllMatches('**/%s;+s' % Globals.Level.LegalEagleNestName)
        for nest in nests:
            offset = Globals.Level.LaffPowerupNestOffset
            pickup = self._level.gatherableFactory.createPowerup(Globals.Level.GatherableTypes.LaffPowerup)
            pickup.reparentTo(parent)
            pickup.setPos(parent, nest.getPos(parent) + offset)
            if Globals.Level.AddSparkleToPowerups:
                sparkles = self._level.gatherableFactory.createSparkles(Vec4(1, 1, 1, 1), Vec4(1, 1, 0, 1), 10.0)
                sparkles.reparentTo(pickup)
                sparkles.setPos(0, 0, 1)
                sparkles.start()
            self.gatherables.append(pickup)

    def generateGatherables(self, gatherableModel, parent = None, spread = Globals.Level.GatherablesDefaultSpread):
        parent = parent or self._root
        mopath = Mopath.Mopath(name='gatherables')

        def generateMemos():
            gatherPaths = gatherableModel.findAllMatches('**/%s' % Globals.Level.GatherablesPathName)
            for gatherPath in gatherPaths:
                mopath.loadNodePath(gatherPath)
                t = 0.0
                while t < mopath.getMaxT():
                    pickup = self._level.gatherableFactory.createMemo()
                    pickup.reparentTo(parent)
                    mopath.goTo(pickup, t)
                    self.gatherables.append(pickup)
                    t += spread

                gatherPath.removeNode()

            angleSpread = 360.0 / Globals.Level.NumMemosInRing
            gatherPaths = gatherableModel.findAllMatches('**/%s' % Globals.Level.GatherablesRingName)
            for gatherPath in gatherPaths:
                mopath.loadNodePath(gatherPath)
                t = 0.0
                while t < mopath.getMaxT():
                    angle = 0
                    r = 3
                    while angle < 360.0:
                        pickup = self._level.gatherableFactory.createMemo()
                        pickup.reparentTo(parent)
                        mopath.goTo(pickup, t)
                        pickup.setX(parent, pickup.getX() + r * math.cos(math.radians(angle)))
                        pickup.setZ(parent, pickup.getZ() + r * math.sin(math.radians(angle)))
                        self.gatherables.append(pickup)
                        angle += angleSpread

                    t += spread + 0.5

                gatherPath.removeNode()

        def generatePropellers():
            gatherables = gatherableModel.findAllMatches('**/%s' % Globals.Level.PropellerName)
            for gatherable in gatherables:
                pickup = self._level.gatherableFactory.createPropeller()
                pickup.reparentTo(gatherable.getParent())
                pickup.setPos(parent, gatherable.getPos(parent))
                self.gatherables.append(pickup)
                gatherable.removeNode()

        def generatePowerUps():
            for powerupType, locName in Globals.Level.PowerupType2Loc.iteritems():
                gatherables = gatherableModel.findAllMatches('**/%s' % locName)
                for gatherable in gatherables:
                    pickup = self._level.gatherableFactory.createPowerup(powerupType)
                    pickup.reparentTo(parent)
                    pickup.setPos(parent, gatherable.getPos(parent))
                    if Globals.Level.AddSparkleToPowerups:
                        sparkles = self._level.gatherableFactory.createSparkles(Vec4(1, 1, 1, 1), Vec4(1, 1, 0, 1), 10.0)
                        sparkles.reparentTo(pickup)
                        sparkles.setPos(0, 0, 1)
                        sparkles.start()
                    self.gatherables.append(pickup)
                    gatherable.removeNode()

        generateMemos()
        generatePropellers()
        generatePowerUps()

    def _initObstacles(self, parent):

        def initWhirlwinds():
            obstacles = self._root.findAllMatches('**/%s' % Globals.Level.WhirlwindName)
            for obstacleLoc in obstacles:
                motionPath = self._model.find('**/%s%s' % (obstacleLoc.getName(), Globals.Level.WhirlwindPathName))
                if motionPath.isEmpty():
                    motionPath = None
                obstacle = self._level.obstacleFactory.createWhirlwind(motionPath=motionPath)
                obstacle.model.reparentTo(parent)
                obstacle.model.setPos(parent, obstacleLoc.getPos(parent))
                self.obstacles.append(obstacle)
                obstacleLoc.removeNode()

        def initStreamers():
            obstacles = self._model.findAllMatches('**/%s' % Globals.Level.StreamerName)
            for obstacleLoc in obstacles:
                obstacle = self._level.obstacleFactory.createFan()
                obstacle.model.reparentTo(parent)
                obstacle.model.setPos(parent, obstacleLoc.getPos(parent))
                obstacle.model.setHpr(parent, obstacleLoc.getHpr(parent))
                obstacle.model.setScale(parent, obstacleLoc.getScale(parent))
                obstacle.setBlowDirection()
                if Globals.Level.AddParticlesToStreamers:
                    particles = self._level.obstacleFactory.createStreamerParticles(Vec4(1, 1, 1, 1), Vec4(1, 1, 1, 1), 10.0)
                    particles.reparentTo(obstacle.model)
                    particles.start()
                self.obstacles.append(obstacle)
                obstacleLoc.removeNode()

        def initWalkingMinions():
            motionPaths = self._model.findAllMatches('**/%s' % Globals.Level.MinionWalkingPathName)
            for motionPath in motionPaths:
                obstacle = self._level.obstacleFactory.createWalkingMinion(motionPath=motionPath)
                obstacle.model.reparentTo(parent)
                obstacle.model.setPos(parent, motionPath.getPos(parent))
                self.obstacles.append(obstacle)

        def initFlyingMinions():
            motionPaths = self._model.findAllMatches('**/%s' % Globals.Level.MinionFlyingPathName)
            for motionPath in motionPaths:
                obstacle = self._level.obstacleFactory.createFlyingMinion(motionPath=motionPath)
                obstacle.model.reparentTo(parent)
                obstacle.model.setPos(parent, motionPath.getPos(parent))
                self.obstacles.append(obstacle)

        initWhirlwinds()
        initStreamers()
        initWalkingMinions()
        initFlyingMinions()

    def place(self):
        self._root.setPos(0, self._level.convertQuadNumToY(self.serialNum), 0)

    def destroy(self):
        if self._visible:
            self.offstage()
        self._destroyPlatforms()
        for obstacle in self.obstacles:
            obstacle.destroy()

        for gatherable in self.gatherables:
            gatherable.destroy()

        self._root.removeNode()
        del self._root
        del self._gatherablesRoot
        del self._obstaclesRoot
        del self._platformsRoot
        del self._level

    def onstage(self, elapsedTime = 0.0):
        if self._visible:
            return
        self._root.unstash()
        for obstacle in self.obstacles:
            obstacle.startMoving(elapsedTime)

        for gatherable in self.gatherables:
            gatherable.show()

        self._visible = True

    def offstage(self):
        if not self._visible:
            return
        self._root.stash()
        for obstacle in self.obstacles:
            obstacle.stopMoving()

        for gatherable in self.gatherables:
            gatherable.hide()

        self._visible = False

    def update(self, dt):
        if self._visible:
            for gatherable in self.gatherables:
                gatherable.update(dt)

            for obstacle in self.obstacles:
                obstacle.update(dt)

    def getModel(self):
        return self._root
예제 #10
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)
            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
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)
        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