def doFlatten(self):
        self.geom.find("**/top_surface").removeNode()
        self.geom.find("**/bottom_surface").removeNode()

        boatMdl = self.geom.find('**/*donalds_boat*')
        boatMdl.setMaterial(CIGlobals.getShinyMaterial())
        wheel = boatMdl.find("**/wheel")
        wheelMdl = wheel.getParent().attachNewNode(ModelNode('wheelNode'))
        wheel.wrtReparentTo(wheelMdl)
        wheelMdl.flattenStrong()
        boat = boatMdl.getParent().attachNewNode(ModelNode('ddBoatRoot'))
        boat.setTransform(boatMdl.getTransform())
        boatMdl1 = boat.attachNewNode(ModelNode('ddBoatMdl1'))
        boatMdl.clearTransform()
        boatMdl.reparentTo(boatMdl1)

        self.geom.find("**/donalds_dock_anchor").flattenStrong()

        ddprops = self.geom.attachNewNode('ddprops')
        CIGlobals.moveNodes(self.geom, "*streetlight_DD*_DNARoot", ddprops)
        CIGlobals.moveNodes(self.geom, "prop_crate_DNARoot", ddprops)
        CIGlobals.moveNodes(self.geom, "prop_stovepipe_DNARoot", ddprops)
        CIGlobals.moveNodes(self.geom, "prop_chimney_DNARoot", ddprops)
        CIGlobals.moveNodes(self.geom, "*palm_tree*_DNARoot", ddprops)
        CIGlobals.removeDNACodes(ddprops)
        ddprops.clearModelNodes()
        ddprops.flattenStrong()

        SafeZoneLoader.SafeZoneLoader.doFlatten(self)
예제 #2
0
    def __init__(self, id):
        MapObjectInit.start()

        MapWritable.__init__(self, base.document)
        self.temporary = False
        self.id = id
        self.selected = False
        self.classname = ""
        self.parent = None
        self.children = {}
        self.boundingBox = BoundingBox(Vec3(-0.5, -0.5, -0.5), Vec3(0.5, 0.5, 0.5))
        self.boundsBox = Box()
        self.boundsBox.addView(GeomView.Lines, VIEWPORT_3D_MASK, state = BoundsBox3DState)
        self.boundsBox.addView(GeomView.Lines, VIEWPORT_2D_MASK, state = BoundsBox2DState)
        self.boundsBox.generateGeometry()
        self.collNp = None

        self.group = None

        self.properties = {}

        # All MapObjects have transform
        self.addProperty(OriginProperty(self))
        self.addProperty(AnglesProperty(self))
        self.addProperty(ScaleProperty(self))
        self.addProperty(ShearProperty(self))

        self.np = NodePath(ModelNode(self.ObjectName + ".%i" % self.id))
        self.np.setPythonTag("mapobject", self)
        self.applyCollideMask()
        # Test bounding volume at this node and but nothing below it.
        self.np.node().setFinal(True)

        MapObjectInit.stop()
예제 #3
0
파일: DNAProp.py 프로젝트: nate97/src
 def traverse(self, nodePath, dnaStorage):
     if self.code == 'DCS':
         node = ModelNode(self.name)
         node.setPreserveTransform(ModelNode.PTNet)
         node = nodePath.attachNewNode(node)
     else:
         node = dnaStorage.findNode(self.code)
         if node is None:
             return
         node = node.copyTo(nodePath, 0)
     node.setPosHprScale(self.pos, self.hpr, self.scale)
     node.setName(self.name)
     node.setColorScale(self.color, 0)
     #self.smartFlatten(node)
     for child in self.children_:
         child.traverse(node, dnaStorage)
    def makeInterior(self):
        self.dnaStore = self.cr.playGame.dnaStore
        self.generator = random.Random()
        self.generator.seed(self.zoneId)
        self.interior = loader.loadModel(
            'phase_3.5/models/modules/HQ_interior.bam')
        self.interior.reparentTo(render)
        self.colors = ToonInteriorColors.colors[ZoneUtil.ToontownCentral]
        doorModelName = 'door_double_round_ul'
        if doorModelName[-1:] == 'r':
            doorModelName = doorModelName[:-1] + 'l'
        else:
            doorModelName = doorModelName[:-1] + 'r'
        door = self.dnaStore.findNode(doorModelName)
        color = self.generator.choice(self.colors['TI_door'])
        doorOrigins = render.findAllMatches('**/door_origin*')
        numDoorOrigins = doorOrigins.getNumPaths()

        for npIndex in xrange(numDoorOrigins):
            # Let's not generate the secondary door for the TTC playground interior.
            if npIndex == 0 or (npIndex == 1 and not self.zoneId == 2520):
                doorOrigin = doorOrigins[npIndex]
                doorOriginNPName = doorOrigin.getName()
                doorOriginIndexStr = doorOriginNPName[len('door_origin_'):]
                newNode = ModelNode('door_' + doorOriginIndexStr)
                newNodePath = NodePath(newNode)
                newNodePath.reparentTo(self.interior)
                doorNP = door.copyTo(newNodePath)
                doorOrigin.setScale(0.8, 0.8, 0.8)
                doorOrigin.setPos(doorOrigin, 0, -0.025, 0)
                doorColor = self.generator.choice(self.colors['TI_door'])
                triggerId = str(self.block) + '0' + doorOriginIndexStr
                triggerId = int(triggerId)
                DNADoor.setupDoor(doorNP, newNodePath, doorOrigin,
                                  self.dnaStore, triggerId, doorColor)
                doorFrame = doorNP.find('door_*_flat')
                doorFrame.setColor(doorColor)
        del self.dnaStore
        del self.colors
        del self.generator

        if self.zoneId == 2520:
            # The interior of the TTC playground HQ needs to be populated with this so it doesn't
            # look so bland.
            self.crashedPiano = loader.loadModel(
                'phase_6/models/props/piano.bam')
            self.crashedPiano.reparentTo(self.interior)
            self.crashedPiano.setPosHpr(1.62019231, 66.6371124268,
                                        0.0250000003725, -46.400062561, 0.0,
                                        0.0)

            # This is the ceiling crack above the crashed piano.
            crack = self.crashedPiano.find('**/shadow_crack').copyTo(
                self.crashedPiano)
            crack.setZ(21.425)
            crack.setTwoSided(1)

        self.generateBuildDataBoard(
            self.interior.find('**/empty_board').getChild(0))
        self.interior.flattenMedium()
예제 #5
0
    def traverse(self, np, store):
        if self.code == "DCS":
            node = ModelNode(self.name)
            node.setPreserveTransform(ModelNode.PTNet)
            _np = np.attachNewNode(np)

        else:
            _np = store.findNode(self.code).copyTo(np)
            _np.setName(self.name)

        _np.setTag("DNAAnim", self.animName)

        _np.setPosHprScale(self.pos, self.hpr, self.scale)
        _np.setColorScale(self.color)

        self.traverseChildren(_np, store)
예제 #6
0
    def __init__(self, mapObject):
        MapHelper.__init__(self, mapObject)
        self.modelRoot = NodePath(ModelNode("modelHelper"))
        self.modelRoot.setScale(16.0)
        self.modelRoot.reparentTo(self.mapObject.helperRoot)

        self.vpRoots = []
예제 #7
0
    def __init__(self,
                 scene,
                 suncgDatasetRoot,
                 size=(512, 512),
                 mode='offscreen',
                 zNear=0.1,
                 zFar=1000.0,
                 fov=40.0,
                 cameraTransform=None):

        # Off-screen buffers are not supported in OSX
        if sys.platform == 'darwin':
            mode = 'onscreen'

        super(Panda3dSemanticsRenderer, self).__init__()

        self.__dict__.update(scene=scene,
                             suncgDatasetRoot=suncgDatasetRoot,
                             size=size,
                             mode=mode,
                             zNear=zNear,
                             zFar=zFar,
                             fov=fov,
                             cameraTransform=cameraTransform)

        self.categoryMapping = ModelCategoryMapping(
            os.path.join(self.suncgDatasetRoot, 'metadata',
                         'ModelCategoryMapping.csv'))

        self.cameraMask = BitMask32.bit(1)
        self.graphicsEngine = GraphicsEngine.getGlobalPtr()
        self.loader = Loader.getGlobalPtr()
        self.graphicsEngine.setDefaultLoader(self.loader)

        self._initModels()

        selection = GraphicsPipeSelection.getGlobalPtr()
        self.pipe = selection.makeDefaultPipe()
        logger.debug('Using %s' % (self.pipe.getInterfaceName()))

        # Attach a camera to every agent in the scene
        self.cameras = []
        for agentNp in self.scene.scene.findAllMatches('**/agents/agent*'):
            camera = agentNp.attachNewNode(ModelNode('camera-semantics'))
            if self.cameraTransform is not None:
                camera.setTransform(cameraTransform)
            camera.node().setPreserveTransform(ModelNode.PTLocal)
            self.cameras.append(camera)

            # Reparent node below the existing physic node (if any)
            physicsNp = agentNp.find('**/physics')
            if not physicsNp.isEmpty():
                camera.reparentTo(physicsNp)

        self.rgbBuffers = dict()
        self.rgbTextures = dict()

        self._initRgbCapture()

        self.scene.worlds['render-semantics'] = self
예제 #8
0
    def init(self):
        """setup calls that can be repeated on code reload"""
        self.resetNodes()

        self.base.setBackgroundColor(0, 0, 0)
        self.base.render.setShaderAuto()  # pp shading
        self.base.render.setAttrib(
            AntialiasAttrib.make(AntialiasAttrib.MMultisample))

        if 1:
            cam = self.base.render.find("camera")
            # I don't know how to set cam position

            f = Fog("fog")
            f.setColor(0, 0, 0)
            f.setLinearRange(18, 25)
            self.base.render.setFog(f)

            import videowall
            reload(videowall)
            self.videoWall = videowall.VideoWall(self.base.loader,
                                                 self.base.render)

        self.cubes = self.base.render.attachNewNode(ModelNode("cubes"))
        self.cubes.setPos(-4.3, 18, -3)
        ground = self.makeGround(self.cubes)

        lights = self.base.render.attachNewNode("lights")
        self.makeLights(lights)

        self.centerMessageNode, self.cornerMessageNode = self.makeMessages()

        self.setLighting(self.currentLighting)
        self.base.render.ls()
 def __init__(self):
     NodePath.__init__(self, ModelNode("entity"))
     #DirectObject.__init__(self)
     self.loaded = False
     self.cEntity = None
     self.outputs = []
     self.bspLoader = None
     self.spawnflags = 0
예제 #10
0
 def setup_vehicle(self):
     # place HMMWV on terrain
     self.hmmwv = ModelNode('hmmwv1')
     self.loadModelOntoTerrain(self.render, self.terrain, self.hmmwv, 33.0,
                               1.0, 20.0, 24.0, self.trrHorzSc,
                               self.trrVertSc, 'models/hmmwv',
                               Vec3(0, -90, 0),
                               Point3(-1.21273, -2.49153, -1.10753),
                               Point3(1.21273, 2.49153, 1.10753))
예제 #11
0
 def setup_house(self):
     # place farmhouse on terrain
     self.house = ModelNode('house1')
     self.loadModelOntoTerrain(self.render, self.terrain, self.house, 43.0,
                               0.275, 0.0, 0.0, self.trrHorzSc,
                               self.trrVertSc, 'models/FarmHouse',
                               Vec3(0, 0, 0),
                               Point3(-12.0567, -29.1724, 0.0837742),
                               Point3(12.2229, 21.1915, 21.3668))
예제 #12
0
    def __init__(self, cr):
        DistributedEntity.__init__(self, cr)
        self.assign(NodePath(ModelNode('ambientGeneric')))
        self.node().setPreserveTransform(ModelNode.PTLocal)

        self.sndFile = ""
        self.looping = False
        self.volume = 1.0

        self.numWildcardSounds = 0
예제 #13
0
 def fixEyes(self):
     mode = -3
     self.drawInFront("eyes*", "head-front*", mode)
     if not self.find('**/joint_pupil*').isEmpty():
         self.drawInFront('joint_pupil*', 'eyes*', -1)
     else:
         self.drawInFront('def_*_pupil', 'eyes*', -1)
             
     self.__eyes = self.find('**/eyes*')
     if not self.__eyes.isEmpty():
         self.__eyes.setColorOff()
         self.__lpupil = None
         self.__rpupil = None
         lp = self.pupils[0]
         rp = self.pupils[1]
         # ModelNodes don't get flattened
         leye = self.__eyes.attachNewNode(ModelNode('leye'))
         reye = self.__eyes.attachNewNode(ModelNode('reye'))
         lmat = Mat4(0.802174, 0.59709, 0, 0, -0.586191, 0.787531, 0.190197, 0, 0.113565,
                     -0.152571, 0.981746, 0, -0.233634, 0.418062, 0.0196875, 1)
         leye.setMat(lmat)
         rmat = Mat4(0.786788, -0.617224, 0, 0, 0.602836, 0.768447, 0.214658, 0, -0.132492,
                     -0.16889, 0.976689, 0, 0.233634, 0.418062, 0.0196875, 1)
         reye.setMat(rmat)
         self.__lpupil = leye.attachNewNode('lpupil')
         self.__rpupil = reye.attachNewNode('rpupil')
         lpt = self.__eyes.attachNewNode('')
         rpt = self.__eyes.attachNewNode('')
         lpt.wrtReparentTo(self.__lpupil)
         rpt.wrtReparentTo(self.__rpupil)
         lp.reparentTo(lpt)
         rp.reparentTo(rpt)
         self.__lpupil.adjustAllPriorities(1)
         self.__rpupil.adjustAllPriorities(1)
         if self.animal != 'dog':
             self.__lpupil.flattenStrong()
             self.__rpupil.flattenStrong()
             
         # Make sure pupils don't clip through the head or eyes
         self.__lpupil.setDepthOffset(4, 1)
         self.__rpupil.setDepthOffset(4, 1)
예제 #14
0
    def __init__(self, scene, size=(512, 512), shadowing=False, mode='offscreen', zNear=0.1, zFar=1000.0, fov=40.0,
                 depth=True, modelLightsInfo=None, cameraTransform=None):

        # Off-screen buffers are not supported in OSX
        if sys.platform == 'darwin':
            mode = 'onscreen'

        super(Panda3dRenderer, self).__init__()

        self.__dict__.update(scene=scene, size=size, mode=mode, zNear=zNear, zFar=zFar, fov=fov,
                             depth=depth, shadowing=shadowing, modelLightsInfo=modelLightsInfo,
                             cameraTransform=cameraTransform)

        self.cameraMask = BitMask32.bit(0)
        self.graphicsEngine = GraphicsEngine.getGlobalPtr()
        self.loader = Loader.getGlobalPtr()
        self.graphicsEngine.setDefaultLoader(self.loader)

        # Change some scene attributes for rendering
        self.scene.scene.setAttrib(RescaleNormalAttrib.makeDefault())
        self.scene.scene.setTwoSided(0)

        self._initModels()

        selection = GraphicsPipeSelection.getGlobalPtr()
        self.pipe = selection.makeDefaultPipe()
        logger.debug('Using %s' % (self.pipe.getInterfaceName()))

        # Attach a camera to every agent in the scene
        self.cameras = []
        for agentNp in self.scene.scene.findAllMatches('**/agents/agent*'):
            camera = agentNp.attachNewNode(ModelNode('camera-rgbd'))
            if self.cameraTransform is not None:
                camera.setTransform(cameraTransform)
            camera.node().setPreserveTransform(ModelNode.PTLocal)
            self.cameras.append(camera)

        self.rgbBuffers = dict()
        self.rgbTextures = dict()
        self.depthBuffers = dict()
        self.depthTextures = dict()

        self._initRgbCapture()
        if self.depth:
            self._initDepthCapture()

        self._addDefaultLighting()

        self.scene.worlds['render'] = self
예제 #15
0
 def traverse(self, nodePath, dnaStorage):
     decalNode = nodePath.find('**/sign_decal')
     if decalNode.isEmpty():
         decalNode = nodePath.find('**/*_front')
     if decalNode.isEmpty() or decalNode.getNode(0).isGeomNode():
         decalNode = nodePath.find('**/+GeomNode')
     if self.code:
         np = dnaStorage.findNode(self.code).copyTo(decalNode)
         np.setName('sign')
     else:
         np = decalNode.attachNewNode(ModelNode('sign'))
     np.setDepthOffset(50)
     origin = nodePath.find('**/*sign_origin')
     np.setPosHprScale(origin, self.pos, self.hpr, self.scale)
     np.setColor(self.color)
     np.wrtReparentTo(origin, 0)
     self.traverseChildren(np, dnaStorage)
     np.flattenStrong()
예제 #16
0
def subdiviseLayoutObject(layoutNp):

    objectModelId = layoutNp.getTag('model-id')

    geomNodes = list(layoutNp.findAllMatches('**/+GeomNode'))

    layoutNps = []
    if objectModelId.endswith('w'):
        # Wall

        # Regroup WallInside and WallOutside geom nodes
        maxIdx = np.max([int(geomNodes[i].getName().split('_')[-1])
                         for i in range(len(geomNodes))])
        wallGeomNodes = [[] for _ in range(maxIdx + 1)]
        for i in range(len(geomNodes)):
            name = geomNodes[i].getName()
            idx = int(name.split('_')[-1])
            wallGeomNodes[idx].append(geomNodes[i])

        for i in range(len(wallGeomNodes)):

            instanceId = str(objectModelId) + '-' + str(i)
            objectNp = NodePath('object-' + instanceId)
            objectNp.setTag('model-id', objectModelId)
            objectNp.setTag('instance-id', instanceId)

            model = NodePath(ModelNode('model-' + instanceId))
            # model.setTag('model-filename', os.path.abspath(modelPath))
            model.reparentTo(objectNp)
            model.hide(BitMask32.allOn())

            for geomNode in wallGeomNodes[i]:
                geomNode.reparentTo(model)

            layoutNps.append(objectNp)
    else:
        # Floor or ceiling
        layoutNps.append(layoutNp)

    return layoutNps
예제 #17
0
 def __init__(self, initNode=True):
     if initNode:
         NodePath.__init__(self, ModelNode("entity"))
     self.loaded = False
     self.cEntity = None
     self.outputs = []
     self.bspLoader = None
     self.spawnflags = 0
     self.entState = 0
     self.nextThink = 0.0
     self.lastThink = 0.0
     self.targetName = ""
     self.entnum = 0
     self.entStateTime = 0.0
     self.modelPath = ""
     self.modelIsAnimating = False
     self.modelOrigin = Point3(0)
     self.modelAngles = Vec3(0)
     self.modelScale = Point3(1)
     self.model = None
     self.sequence = None
     self.mapEnt = False
     self.sounds = {}
    def makeInterior(self):
        self.dnaStore = self.cr.playGame.dnaStore
        self.generator = random.Random()
        self.generator.seed(self.zoneId)
        self.interior = loader.loadModel('phase_3.5/models/modules/HQ_interior.bam')
        self.interior.reparentTo(render)
        self.colors = ToonInteriorColors.colors[CIGlobals.ToontownCentral]
        doorModelName = 'door_double_round_ul'
        if doorModelName[-1:] == 'r':
            doorModelName = doorModelName[:-1] + 'l'
        else:
            doorModelName = doorModelName[:-1] + 'r'
        door = self.dnaStore.findNode(doorModelName)
        color = self.generator.choice(self.colors['TI_door'])
        doorOrigins = render.findAllMatches('**/door_origin*')
        numDoorOrigins = doorOrigins.getNumPaths()
        for npIndex in xrange(numDoorOrigins):
            doorOrigin = doorOrigins[npIndex]
            doorOriginNPName = doorOrigin.getName()
            doorOriginIndexStr = doorOriginNPName[len('door_origin_'):]
            newNode = ModelNode('door_' + doorOriginIndexStr)
            newNodePath = NodePath(newNode)
            newNodePath.reparentTo(self.interior)
            doorNP = door.copyTo(newNodePath)
            doorOrigin.setScale(0.8, 0.8, 0.8)
            doorOrigin.setPos(doorOrigin, 0, -0.025, 0)
            doorColor = self.generator.choice(self.colors['TI_door'])
            triggerId = str(self.block) + '0' + doorOriginIndexStr
            triggerId = int(triggerId)
            DNADoor.setupDoor(doorNP, newNodePath, doorOrigin, self.dnaStore, triggerId, doorColor)
            doorFrame = doorNP.find('door_*_flat')
            doorFrame.setColor(doorColor)

        del self.dnaStore
        del self.colors
        del self.generator
        self.interior.flattenMedium()
예제 #19
0
 def traverse(self, nodePath, dnaStorage):
     if self.code == 'DCS':
         node = ModelNode(self.name)
         node.setPreserveTransform(ModelNode.PTNet)
         node = nodePath.attachNewNode(node)
     else:
         node = dnaStorage.findNode(self.code)
         if node.isEmpty():
             return
         node = node.copyTo(nodePath)
     node.setPosHprScale(self.pos, self.hpr, self.scale)
     node.setName(self.name)
     node.setColorScale(self.color)
     self.traverseChildren(node, dnaStorage)
예제 #20
0
    def __init__(self):
        Entity.__init__(self)
        self.assign(NodePath(ModelNode('ambientGeneric')))
        self.node().setPreserveTransform(ModelNode.PTLocal)

        self.sndFile = None
예제 #21
0
 def traverse(self, nodePath, dnaStorage):
     node = None
     if self.code == 'DCS':
         node = ModelNode(self.name)
         node.setPreserveTransform(ModelNode.PTNet)
         node = nodePath.attachNewNode(node)
     else:
         node = dnaStorage.findNode(self.code)
         node = node.copyTo(nodePath)
         node.setName(self.name)
     node.setTag('DNAAnim', self.animName)
     node.setPosHprScale(self.pos, self.hpr, self.scale)
     node.setColorScale(self.color)
     self.traverseChildren(node, dnaStorage)
예제 #22
0
    def traverse(self, nodePath, dnaStorage):
        if self.code == 'DCS':
            node = ModelNode(self.name)
            node.setPreserveTransform(ModelNode.PTNet)
            node = nodePath.attachNewNode(node)
        else:
            node = dnaStorage.findNode(self.code)
            if node is None:
                return
            node = node.copyTo(nodePath, 0)
        node.setPosHprScale(self.pos, self.hpr, self.scale)
        node.setName(self.name)
        node.setColorScale(self.color, 0)
        for child in self.children:
            child.traverse(node, dnaStorage)

        return
    def makeCamera(self,
                   win,
                   sort=0,
                   scene=None,
                   displayRegion=(0, 1, 0, 1),
                   stereo=None,
                   aspectRatio=None,
                   clearDepth=0,
                   clearColor=None,
                   lens=None,
                   camName='cam',
                   mask=None,
                   useCamera=None):
        """
        Makes a new 3-d camera associated with the indicated window,
        and creates a display region in the indicated subrectangle.

        If stereo is True, then a stereo camera is created, with a
        pair of DisplayRegions.  If stereo is False, then a standard
        camera is created.  If stereo is None or omitted, a stereo
        camera is created if the window says it can render in stereo.

        If useCamera is not None, it is a NodePath to be used as the
        camera to apply to the window, rather than creating a new
        camera.
        """
        # self.camera is the parent node of all cameras: a node that
        # we can move around to move all cameras as a group.
        if self.camera == None:
            # We make it a ModelNode with the PTLocal flag, so that
            # a wayward flatten operations won't attempt to mangle the
            # camera.
            self.camera = self.render.attachNewNode(ModelNode('camera'))
            self.camera.node().setPreserveTransform(ModelNode.PTLocal)
            builtins.camera = self.camera

            self.mouse2cam.node().setNode(self.camera.node())

        if useCamera:
            # Use the existing camera node.
            cam = useCamera
            camNode = useCamera.node()
            assert (isinstance(camNode, Camera))
            lens = camNode.getLens()
            cam.reparentTo(self.camera)

        else:
            # Make a new Camera node.
            camNode = Camera(camName)
            if lens == None:
                lens = PerspectiveLens()

                if aspectRatio == None:
                    aspectRatio = self.getAspectRatio(win)
                lens.setAspectRatio(aspectRatio)

            cam = self.camera.attachNewNode(camNode)

        if lens != None:
            camNode.setLens(lens)

        if scene != None:
            camNode.setScene(scene)

        if mask != None:
            if (isinstance(mask, int)):
                mask = BitMask32(mask)
            camNode.setCameraMask(mask)

        if self.cam == None:
            self.cam = cam
            self.camNode = camNode
            self.camLens = lens

        self.camList.append(cam)

        # Now, make a DisplayRegion for the camera.
        if stereo is not None:
            if stereo:
                dr = win.makeStereoDisplayRegion(*displayRegion)
            else:
                dr = win.makeMonoDisplayRegion(*displayRegion)
        else:
            dr = win.makeDisplayRegion(*displayRegion)

        dr.setSort(sort)

        dr.disableClears()

        # By default, we do not clear 3-d display regions (the entire
        # window will be cleared, which is normally sufficient).  But
        # we will if clearDepth is specified.
        if clearDepth:
            dr.setClearDepthActive(1)

        if clearColor:
            dr.setClearColorActive(1)
            dr.setClearColor(clearColor)

        dr.setCamera(cam)

        return cam
예제 #24
0
    def traverse(self, nodePath, dnaStorage):
        decalNode = nodePath.find('**/sign_decal')
        if decalNode.isEmpty():
            decalNode = nodePath.find('**/*_front')
        if decalNode.isEmpty() or not decalNode.getNode(0).isGeomNode():
            decalNode = nodePath.find('**/+GeomNode')
        if self.code:
            node = dnaStorage.findNode(self.code)
            node = node.copyTo(decalNode)
            node.setName('sign')
        else:
            node = ModelNode('sign')
            node = decalNode.attachNewNode(node)
        if 'linktunnel_' in nodePath.getName() and 'hq_' in nodePath.getName():
            node.setDepthOffset(1000)
        else:
            node.setDepthOffset(50)
        signOrigin = nodePath.find('**/*sign_origin')
        node.setPosHprScale(signOrigin, self.pos, self.hpr, self.scale)
        node.setColor(self.color)
        node.wrtReparentTo(signOrigin, 0)
        for child in self.children:
            child.traverse(node, dnaStorage)

        node.flattenStrong()
예제 #25
0
 def traverse(self, nodePath, dnaStorage):
     node = None
     if self.getCode() == 'DCS':
         node = ModelNode(self.getName())
         node.setPreserveTransform(ModelNode.PTNet)
         node = nodePath.attachNewNode(node, 0)
     else:
         node = dnaStorage.findNode(self.getCode())
         node = node.copyTo(nodePath, 0)
         node.setName(self.getName())
     node.setTag('DNAAnim', self.getAnim())
     node.setTag('DNACellIndex', str(self.cellId))
     node.setPosHprScale(self.getPos(), self.getHpr(), self.getScale())
     node.setColorScale(self.getColor(), 0)
     node.flattenStrong()
     for child in self.children:
         child.traverse(node, dnaStorage)
예제 #26
0
    def make_camera(self, output, sort=0, dr_dims=(0, 1, 0, 1),
                    aspect_ratio=None, clear_depth=False, clear_color=None,
                    lens=None, cam_name="camera0", mask=None):
        """
        Makes a new 3-d camera associated with the indicated window,
        and creates a display region in the indicated subrectangle.

        If stereo is True, then a stereo camera is created, with a
        pair of DisplayRegions.  If stereo is False, then a standard
        camera is created.  If stereo is None or omitted, a stereo
        camera is created if the window says it can render in stereo.

        If useCamera is not None, it is a NodePath to be used as the
        camera to apply to the window, rather than creating a new
        camera.

        Args:
            output (GraphicsOutput): Output object.

        Keyword Args:
            sort (int): Sort order.
            dr_dims (Iterable, 4): DisplayRegion dimensions.
            aspect_ratio (float): Aspect ratio.
            clear_depth (bool): Indicator to clear depth buffer.
            clear_color (bool): Indicator to clear color buffer.
            lens (Lens): Lens object.
            cam_name (str): Window name.
            mask (BitMask32): Bit mask that indicates which objects to render.

        Return:
            (NodePath): Camera nodepath.

        """

        # self.cameras is the parent node of all cameras: a node that
        # we can move around to move all cameras as a group.
        if self.cameras is None:
            # We make it a ModelNode with the PTLocal flag, so that a
            # wayward flatten operations won't attempt to mangle the
            # camera.
            self.cameras = self.root.attachNewNode(ModelNode("cameras"))
            self.cameras.node().setPreserveTransform(ModelNode.PTLocal)

        # Make a new Camera node.
        cam_node = Camera(cam_name)
        if lens is None:
            lens = PerspectiveLens()
            if aspect_ratio is None:
                aspect_ratio = self.get_aspect_ratio(output)
            lens.setAspectRatio(aspect_ratio)
            lens.setNear(0.1)
            lens.setFar(1000.0)
        if lens is not None:
            cam_node.setLens(lens)
        camera = self.cameras.attachNewNode(cam_node)
        # Masks out part of scene from camera
        if mask is not None:
            if (isinstance(mask, int)):
                mask = BitMask32(mask)
            cam_node.setCameraMask(mask)
        # Make a display region
        dr = output.makeDisplayRegion(*dr_dims)
        # By default, we do not clear 3-d display regions (the entire
        # window will be cleared, which is normally sufficient).  But
        # we will if clearDepth is specified.
        if clear_depth:
            dr.setClearDepthActive(1)
        if clear_color:
            dr.setClearColorActive(1)
            dr.setClearColor(clear_color)
        dr.setSort(sort)
        dr.setCamera(camera)
        dr.setActive(True)
        return camera
예제 #27
0
def flattenModelNodes(node):
    for np in node.findAllMatches("**"):
        if np.node().isOfType(ModelNode.getClassType()):
            np.flattenStrong()
예제 #28
0
    def initialize(self):
        self.lens = self.makeLens()
        self.camera = self.doc.render.attachNewNode(
            ModelNode("viewportCameraParent"))
        self.camNode = Camera("viewportCamera")
        self.camNode.setLens(self.lens)
        self.camNode.setCameraMask(self.getViewportMask())
        self.cam = self.camera.attachNewNode(self.camNode)

        winprops = WindowProperties.getDefault()
        winprops.setParentWindow(int(self.winId()))
        winprops.setForeground(False)
        winprops.setUndecorated(True)

        gsg = self.doc.gsg

        output = base.graphicsEngine.makeOutput(
            base.pipe, "viewportOutput", 0, FrameBufferProperties.getDefault(),
            winprops,
            (GraphicsPipe.BFFbPropsOptional | GraphicsPipe.BFRequireWindow),
            gsg)

        self.qtWindow = QtGui.QWindow.fromWinId(
            output.getWindowHandle().getIntHandle())
        self.qtWidget = QtWidgets.QWidget.createWindowContainer(
            self.qtWindow, self, QtCore.Qt.WindowDoesNotAcceptFocus
            | QtCore.Qt.WindowTransparentForInput
            | QtCore.Qt.WindowStaysOnBottomHint
            | QtCore.Qt.BypassWindowManagerHint | QtCore.Qt.SubWindow)  #,
        #(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowDoesNotAcceptFocus
        #| QtCore.Qt.WindowTransparentForInput | QtCore.Qt.BypassWindowManagerHint
        #| QtCore.Qt.SubWindow | QtCore.Qt.WindowStaysOnBottomHint))
        self.qtWidget.setFocusPolicy(QtCore.Qt.NoFocus)

        self.inputDevice = output.getInputDevice(0)

        assert output is not None, "Unable to create viewport output!"

        dr = output.makeDisplayRegion()
        dr.disableClears()
        dr.setCamera(self.cam)
        self.displayRegion = dr

        output.disableClears()
        output.setClearColor(Viewport.ClearColor)
        output.setClearColorActive(True)
        output.setClearDepthActive(True)
        output.setActive(True)

        self.win = output

        # keep track of the mouse in this viewport
        mak = MouseAndKeyboard(self.win, 0, "mouse")
        mouse = base.dataRoot.attachNewNode(mak)
        self.mouseAndKeyboard = mouse
        self.mouseWatcher = MouseWatcher()
        self.mouseWatcher.setDisplayRegion(self.displayRegion)
        mw = mouse.attachNewNode(self.mouseWatcher)
        self.mouseWatcherNp = mw

        # listen for keyboard and mouse events in this viewport
        bt = ButtonThrower("kbEvents")
        bt.setButtonDownEvent("btndown")
        bt.setButtonUpEvent("btnup")
        mods = ModifierButtons()
        mods.addButton(KeyboardButton.shift())
        mods.addButton(KeyboardButton.control())
        mods.addButton(KeyboardButton.alt())
        mods.addButton(KeyboardButton.meta())
        bt.setModifierButtons(mods)
        self.buttonThrower = mouse.attachNewNode(bt)

        # collision objects for clicking on objects from this viewport
        self.clickRay = CollisionRay()
        self.clickNode = CollisionNode("viewportClickRay")
        self.clickNode.addSolid(self.clickRay)
        self.clickNp = NodePath(self.clickNode)
        self.clickQueue = CollisionHandlerQueue()

        self.setupRender2d()
        self.setupCamera2d()

        self.gizmo = ViewportGizmo(self)

        self.doc.viewportMgr.addViewport(self)

        self.makeGrid()
    def makeDictionaries(self, dnaStore):
        self.nodeDict = {}
        self.zoneDict = {}
        self.zoneVisDict = {}
        self.nodeList = []
        self.fadeInDict = {}
        self.fadeOutDict = {}
        a1 = Vec4(1, 1, 1, 1)
        a0 = Vec4(1, 1, 1, 0)
        numVisGroups = dnaStore.getNumDNAVisGroupsAI()
        for i in xrange(numVisGroups):
            groupFullName = dnaStore.getDNAVisGroupName(i)
            visGroup = dnaStore.getDNAVisGroupAI(i)
            groupName = base.cr.hoodMgr.extractGroupName(groupFullName)
            zoneId = int(groupName)
            zoneId = ZoneUtil.getTrueZoneId(zoneId, self.zoneId)
            groupNode = self.geom.find('**/' + groupFullName)
            if groupNode.isEmpty():
                continue
            else:
                if ':' in groupName:
                    groupName = '%s%s' % (zoneId,
                                          groupName[groupName.index(':'):])
                else:
                    groupName = '%s' % zoneId
                groupNode.setName(groupName)

            CIGlobals.replaceDecalEffectsWithDepthOffsetAttrib(groupNode)

            #group all the flat walls

            block2flatwall = {}
            flatwalls = groupNode.findAllMatches("**/tb*:*_DNARoot;+s")
            for flatwall in flatwalls:
                if "toon_landmark" in flatwall.getName():
                    print "Skipping", flatwall.getName()
                    continue
                if flatwall.hasTag("DNACode") and flatwall.hasMat():
                    continue
                block = int(flatwall.getName().split(":")[0][2:])
                if not block2flatwall.has_key(block):
                    block2flatwall[block] = groupNode.attachNewNode(
                        ModelNode('toonBuildingsBlock' + str(block)))
                flatwall.wrtReparentTo(block2flatwall[block])

            for node in block2flatwall.values():
                for child in node.findAllMatches("**"):
                    child.clearEffect(DecalEffect.getClassType())
                    child.clearTag("DNACode")
                    child.clearTag("cam")
                CIGlobals.clearModelNodesBelow(node)
                node.flattenStrong()

            flattenGroup = groupNode.attachNewNode('optim')
            flattens = ['street*_DNARoot']
            removes = ['interactive_prop*_DNARoot']
            for remove in removes:
                for np in groupNode.findAllMatches("**/" + remove):
                    np.removeNode()
            for flatten in flattens:
                for np in groupNode.findAllMatches("**/" + flatten):
                    if np.hasTag("DNACode") and np.hasMat():
                        continue
                    for child in np.findAllMatches("**"):
                        child.clearEffect(DecalEffect.getClassType())
                        child.clearTag("DNACode")
                        child.clearTag("cam")
                    np.wrtReparentTo(flattenGroup)
            flattenGroup.clearModelNodes()
            flattenGroup.flattenStrong()

            CIGlobals.flattenModelNodes(groupNode)
            groupNode.flattenStrong()
            #groupNode.ls()

            self.nodeDict[zoneId] = []
            self.nodeList.append(groupNode)
            self.zoneDict[zoneId] = groupNode
            visibles = []
            for i in xrange(visGroup.getNumVisibles()):
                visibles.append(int(visGroup.get_visible(i)))
            visibles.append(ZoneUtil.getBranchZone(zoneId))
            self.zoneVisDict[zoneId] = visibles
            fadeDuration = 0.5
            self.fadeOutDict[groupNode] = Sequence(
                Func(groupNode.setTransparency, 1),
                LerpColorScaleInterval(groupNode,
                                       fadeDuration,
                                       a0,
                                       startColorScale=a1),
                Func(groupNode.clearColorScale),
                Func(groupNode.clearTransparency),
                Func(groupNode.stash),
                Func(base.disablePhysicsNodes, groupNode),
                name='fadeZone-' + str(zoneId),
                autoPause=1)
            self.fadeInDict[groupNode] = Sequence(
                Func(base.enablePhysicsNodes, groupNode),
                Func(groupNode.unstash),
                Func(groupNode.setTransparency, 1),
                LerpColorScaleInterval(groupNode,
                                       fadeDuration,
                                       a1,
                                       startColorScale=a0),
                Func(groupNode.clearColorScale),
                Func(groupNode.clearTransparency),
                name='fadeZone-' + str(zoneId),
                autoPause=1)

        for i in xrange(numVisGroups):
            groupFullName = dnaStore.getDNAVisGroupName(i)
            zoneId = int(base.cr.hoodMgr.extractGroupName(groupFullName))
            zoneId = ZoneUtil.getTrueZoneId(zoneId, self.zoneId)
            for j in xrange(dnaStore.getNumVisiblesInDNAVisGroup(i)):
                visName = dnaStore.getVisibleName(i, j)
                groupName = base.cr.hoodMgr.extractGroupName(visName)
                nextZoneId = int(groupName)
                nextZoneId = ZoneUtil.getTrueZoneId(nextZoneId, self.zoneId)
                visNode = self.zoneDict[nextZoneId]
                self.nodeDict[zoneId].append(visNode)

        self.hood.dnaStore.resetPlaceNodes()
        self.hood.dnaStore.resetDNAGroups()
        self.hood.dnaStore.resetDNAVisGroups()
        self.hood.dnaStore.resetDNAVisGroupsAI()
 def traverse(self, nodePath, dnaStorage):
     node = None
     if self.getCode() == 'DCS':
         node = ModelNode(self.getName())
         node.setPreserveTransform(ModelNode.PTNet)
         node = nodePath.attachNewNode(node, 0)
     else:
         node = dnaStorage.findNode(self.getCode())
         node = node.copyTo(nodePath, 0)
         node.setName(self.getName())
     node.setTag('DNAAnim', self.getAnim())
     node.setTag('DNACellIndex', str(self.cellId))
     node.setPosHprScale(self.getPos(), self.getHpr(), self.getScale())
     node.setColorScale(self.getColor(), 0)
     node.flattenStrong()
     for child in self.children:
         child.traverse(node, dnaStorage)