コード例 #1
0
ファイル: DistCogdoCraneCog.py プロジェクト: z010155/c0d3
 def _startMoveIval(self, entranceId, startT):
     self._stopMoveIval()
     unitVecs = (PM.Vec3(1, 0, 0), PM.Vec3(0, 1, 0), PM.Vec3(-1, 0, 0),
                 PM.Vec3(0, -1, 0))
     machineDistance = 4
     entranceDistance = 60
     startPos = unitVecs[entranceId] * entranceDistance
     endPos = unitVecs[entranceId] * machineDistance
     walkDur = (endPos - startPos
                ).length() / GameConsts.CogSettings.CogWalkSpeed.get()
     sceneRoot = self.getGame().getSceneRoot()
     moveIval = IG.Sequence(
         IG.Func(self.reparentTo, sceneRoot),
         IG.Func(self.setPos, startPos), IG.Func(self.lookAt, sceneRoot),
         IG.Func(self.loop, 'walk'),
         IG.LerpPosInterval(self, walkDur, endPos, startPos=startPos))
     interactIval = IG.Sequence(
         IG.Func(self.loop, 'neutral'),
         IG.Wait(GameConsts.CogSettings.CogMachineInteractDuration.get()))
     flyIval = IG.Sequence(
         IG.Func(self.pose, 'landing', 0),
         IG.LerpPosInterval(self,
                            GameConsts.CogSettings.CogFlyAwayDuration.get(),
                            self._getFlyAwayDest,
                            blendType='easeIn'))
     self._moveIval = IG.Sequence(moveIval, interactIval, flyIval)
     self._moveIval.start(globalClock.getFrameTime() - startT)
コード例 #2
0
ファイル: geometry.py プロジェクト: Derfies/p3d
def Cone(radius=1.0,
         height=2.0,
         numSegs=16,
         degrees=360,
         axis=pm.Vec3(0, 0, 1),
         origin=pm.Point3(0, 0, 0)):
    """Return a geom node representing a cone."""
    # Create vetex data format
    gvf = pm.GeomVertexFormat.getV3n3()
    gvd = pm.GeomVertexData('vertexData', gvf, pm.Geom.UHStatic)

    # Create vetex writers for each type of data we are going to store
    gvwV = pm.GeomVertexWriter(gvd, 'vertex')
    gvwN = pm.GeomVertexWriter(gvd, 'normal')

    # Get the points for an arc
    axis2 = pm.Vec3(axis)
    axis2.normalize()
    offset = axis2 * height / 2.0
    points = GetPointsForArc(degrees, numSegs, True)
    for i in range(len(points) - 1):

        # Rotate the points around the desired axis
        p1 = pm.Point3(points[i][0], points[i][1], 0) * radius
        p1 = RotatePoint3(p1, pm.Vec3(0, 0, 1), axis) - origin
        p2 = pm.Point3(points[i + 1][0], points[i + 1][1], 0) * radius
        p2 = RotatePoint3(p2, pm.Vec3(0, 0, 1), axis) - origin

        cross = (p2 - axis).cross(p1 - axis)
        cross.normalize()

        # Facet
        gvwV.addData3f(p1 - offset)
        gvwV.addData3f(offset - origin)
        gvwV.addData3f(p2 - offset)
        for i in range(3):
            gvwN.addData3f(cross)

        # Base
        gvwV.addData3f(p2 - offset)
        gvwV.addData3f(-offset - origin)
        gvwV.addData3f(p1 - offset)
        for i in range(3):
            gvwN.addData3f(-axis)

    geom = pm.Geom(gvd)
    for i in range(0, gvwV.getWriteRow(), 3):

        # Create and add triangle
        geom.addPrimitive(GetGeomTriangle(i, i + 1, i + 2))

    # Return the cone GeomNode
    geomNode = pm.GeomNode('cone')
    geomNode.addGeom(geom)
    return geomNode
コード例 #3
0
ファイル: translation.py プロジェクト: vheuken/panda3d-editor
 def __init__( self, *args, **kwargs ):
     Base.__init__( self, *args, **kwargs )
     
     self._snp = False
     self._snpAmt = 0.5
     
     # Create x, y, z and camera normal axes
     self.axes.append( self.CreateArrow( pm.Vec3(1, 0, 0), RED ) )
     self.axes.append( self.CreateArrow( pm.Vec3(0, 1, 0), GREEN ) )
     self.axes.append( self.CreateArrow( pm.Vec3(0, 0, 1), BLUE ) )
     #self.axes.append( self.CreateArrow( pm.Vec3(1, 1, 0), YELLOW ) )
     #self.axes.append( self.CreateArrow( pm.Vec3(-2, 1, 0), TEAL ) )
     self.axes.append( self.CreateSquare( pm.Vec3(0, 0, 0), TEAL ) )
コード例 #4
0
ファイル: translation.py プロジェクト: vheuken/panda3d-editor
 def OnNodeMouse1Down( self, planar, collEntry ):
     Base.OnNodeMouse1Down( self, planar, collEntry )
     
     self._s = pm.Vec3( 0 )
     
     # If in planar mode, clear the billboard effect on the center square
     # and make it face the selected axis
     axis = self.GetSelectedAxis()
     if self.planar and not axis.planar:
         self.square.clearBillboard()
         self.square.lookAt( self, pm.Point3( axis.vector ) )
     else:
         self.square.setHpr( pm.Vec3(0, 0, 0) )
         self.square.setBillboardPointEye()
コード例 #5
0
ファイル: translation.py プロジェクト: vheuken/panda3d-editor
 def _Snap( self, vec ):
     if vec.length():
         snpLen = ROUND_TO( vec.length(), self._snpAmt )
         snapVec = vec / vec.length() * snpLen
         return snapVec
     else:
         return pm.Vec3( 0 )
コード例 #6
0
 def privGotSpec(self, levelSpec):
     DistCogdoLevelGame.privGotSpec(self, levelSpec)
     levelMgr = self.getEntity(LevelConstants.LevelMgrEntId)
     self.endVault = levelMgr.geom
     self.endVault.reparentTo(self.geomRoot)
     self.endVault.findAllMatches('**/MagnetArms').detach()
     self.endVault.findAllMatches('**/Safes').detach()
     self.endVault.findAllMatches('**/MagnetControlsAll').detach()
     cn = self.endVault.find('**/wallsCollision').node()
     cn.setIntoCollideMask(OTPGlobals.WallBitmask
                           | ToontownGlobals.PieBitmask
                           | PM.BitMask32.lowerOn(3) << 21)
     walls = self.endVault.find('**/RollUpFrameCillison')
     walls.detachNode()
     self.evWalls = self.replaceCollisionPolysWithPlanes(walls)
     self.evWalls.reparentTo(self.endVault)
     self.evWalls.stash()
     floor = self.endVault.find('**/EndVaultFloorCollision')
     floor.detachNode()
     self.evFloor = self.replaceCollisionPolysWithPlanes(floor)
     self.evFloor.reparentTo(self.endVault)
     self.evFloor.setName('floor')
     plane = PM.CollisionPlane(
         PM.Plane(PM.Vec3(0, 0, 1), PM.Point3(0, 0, -50)))
     planeNode = PM.CollisionNode('dropPlane')
     planeNode.addSolid(plane)
     planeNode.setCollideMask(ToontownGlobals.PieBitmask)
     self.geomRoot.attachNewNode(planeNode)
コード例 #7
0
ファイル: camera.py プロジェクト: Derfies/p3d
    def Frame(self, nps):

        # Get a list of bounding spheres for each NodePath in world space.
        allBnds = []
        allCntr = pm.Vec3()
        for np in nps:
            bnds = np.getBounds()
            if bnds.isInfinite():
                continue
            mat = np.getParent().getMat(self.rootNp)
            bnds.xform(mat)
            allBnds.append(bnds)
            allCntr += bnds.getCenter()

        # Now create a bounding sphere at the center point of all the
        # NodePaths and extend it to encapsulate each one.
        bnds = pm.BoundingSphere(pm.Point3(allCntr / len(nps)), 0)
        for bnd in allBnds:
            bnds.extendBy(bnd)

        # Move the camera and the target the the bounding sphere's center.
        self.target.setPos(bnds.getCenter())
        self.setPos(bnds.getCenter())

        # Now move the camera back so the view accomodates all NodePaths.
        # Default the bounding radius to something reasonable if the object
        # has no size.
        fov = self.GetLens().getFov()
        radius = bnds.getRadius() or 0.5
        dist = radius / math.tan(math.radians(min(fov[0], fov[1]) * 0.5))
        self.setY(self, -dist)
コード例 #8
0
def SnapPoint(pnt, amt):
    """
    Return a new point based on the indicated point but snapped to the nearest
    indicated amount.
    """
    return pm.Vec3(ROUND_TO(pnt[0], amt), ROUND_TO(pnt[1], amt),
                   ROUND_TO(pnt[2], amt))
コード例 #9
0
    def __init__(self, *args, **kwargs):
        Base.__init__(self, *args, **kwargs)

        self.AddAttributes(Attr('Half Extents',
                                pm.Vec3,
                                BBS.getHalfExtentsWithMargin,
                                initDefault=pm.Vec3(0.5, 0.5, 0.5)),
                           parent='BulletBoxShape')
コード例 #10
0
    def __init__(self, *args, **kwargs):
        Base.__init__(self, *args, **kwargs)

        self.AddAttributes(Attr('Normal',
                                pm.Vec3,
                                initDefault=pm.Vec3(0, 0, 1)),
                           Attr('Constant', int, initDefault=0),
                           parent='BulletBoxShape')
コード例 #11
0
    def __init__(self, *args, **kwargs):
        PrimitiveNPO.__init__(self, *args, **kwargs)

        self._radius = 1
        self._height = 2
        self._numSegs = 16
        self._degrees = 360
        self._axis = pm.Vec3(0, 0, 1)
        self._origin = pm.Point3(0, 0, 0)
コード例 #12
0
ファイル: geometry.py プロジェクト: Derfies/p3d
def RotatePoint3(p, v1, v2):
    """
    Return the input point rotated around the cross of the input vectors. The
    amount to rotate is the angle between the two vectors.
    """
    v1 = pm.Vec3(v1)
    v2 = pm.Vec3(v2)
    v1.normalize()
    v2.normalize()
    cross = v1.cross(v2)
    cross.normalize()
    if cross.length():
        a = v1.angleDeg(v2)
        quat = pm.Quat()
        quat.setFromAxisAngle(a, cross)
        p = quat.xform(p)

    return p
コード例 #13
0
ファイル: geometry.py プロジェクト: Derfies/p3d
def Circle(radius=1.0,
           numSegs=16,
           axis=pm.Vec3(1, 0, 0),
           thickness=1.0,
           origin=pm.Point3(0, 0, 0)):

    # Create line segments
    ls = pm.LineSegs()
    ls.setThickness(thickness)

    # Get the points for an arc
    for p in GetPointsForArc(360, numSegs):

        # Draw the point rotated around the desired axis
        p = pm.Point3(p[0], p[1], 0) - origin
        p = RotatePoint3(p, pm.Vec3(0, 0, 1), pm.Vec3(axis))
        ls.drawTo(p * radius)

    return ls.create()
コード例 #14
0
    def __init__(self,
                 pos=None,
                 color=(0.6, 0.8, 0.5, 1),
                 scale=12,
                 h=8,
                 size=33,
                 trees=0.7):

        # Initialise primary NodePath which everything else is parented to
        if pos is None: pos = P.Vec3(0, 0, 0)
        self.pos = pos
        self.prime = P.NodePath('Terrain primary NodePath')
        self.prime.setPos(self.pos)

        # Create terrain models (rendering and collision)
        self.tnp, self.collnp = makeTerrain(size=size, h=h)
        self.tnp.reparentTo(self.prime)
        self.tnp.setColor(*color)
        self.tnp.setScale(scale)
        # Shift the collision terrain a bit so rays from trees hit
        self.collnp.setPos(self.collnp, .0001, .0001, 0)
        self.collnp.setCollideMask(C.floorMASK)

        # All trees in the scene are parented to one NodePath for flattening
        self.trees = self.prime.attachNewNode(P.PandaNode('trees'))
        self.treesColl = self.prime.attachNewNode(P.CollisionNode('treesColl'))
        self.treesColl.node().setIntoCollideMask(offMASK)
        self.treesColl.node().setFromCollideMask(obstacleMASK)
        #self.treesColl.show()
        vehicleCTrav.addCollider(self.treesColl, obstacleHandler)

        # Initialise trees
        img = greenNoise(imgSize=(size, size), scale=0.25)
        for x in range(0, size - 1):
            for y in range(0, size - 1):
                if img.getGreen(x, y) > trees:
                    treepos = P.Vec3(x * scale + 0.5 * scale,
                                     y * scale + 0.5 * scale, 50)
                    tree = Tree(pos=treepos)
                    tree.prime.reparentTo(self.trees)

        taskMgr.add(self.flatten, "Terrain flatten task")
コード例 #15
0
ファイル: geometry.py プロジェクト: Derfies/p3d
def Square(width=1,
           height=1,
           axis=pm.Vec3(1, 0, 0),
           thickness=1.0,
           origin=pm.Point3(0, 0, 0)):
    """Return a geom node representing a wire square."""
    # Create line segments
    ls = pm.LineSegs()
    ls.setThickness(thickness)

    # Get the points for a square
    points = GetPointsForSquare(width, height)
    points.append(points[0])
    for p in points:

        # Draw the point rotated around the desired axis
        p = pm.Point3(p[0], p[1], 0) - origin
        p = RotatePoint3(p, pm.Vec3(0, 0, 1), axis)
        ls.drawTo(p)

    # Return the geom node
    return ls.create()
コード例 #16
0
 def rotateCam(self, arc):
     """Setup a lerp interval to rotate the camera about the target."""
     newP = clampScalar(self.target.getP() - arc.getY(),
                        *self.clampP)  #Clamped.
     newH = self.target.getH() + arc.getX()  #Not clamped, just added.
     LERP.LerpHprInterval(
         self.target,
         self.speed,  #Setup the interval\
         P.Vec3(
             newH,
             newP,
             self.target.getR(),
         ),
     ).start()  #and start it.
コード例 #17
0
ファイル: translation.py プロジェクト: vheuken/panda3d-editor
 def CreateSquare( self, vec, colour ):
     
     # Create the geometry and collision
     self.square = pm.NodePath( Square( 0.2, 0.2, pm.Vec3(0, 1, 0) ) )
     self.square.setBillboardPointEye()
     collSphere = pm.CollisionSphere( 0, 0.125 )
     
     # Create the axis, add the geometry and collision
     axis = Axis( self.name, CAMERA_VECTOR, colour, planar=True, default=True )
     axis.AddGeometry( self.square, sizeStyle=NONE )
     axis.AddCollisionSolid( collSphere, sizeStyle=NONE )
     axis.reparentTo( self )
     
     return axis
コード例 #18
0
ファイル: geometry.py プロジェクト: Derfies/p3d
    def __init__(self,
                 radius=1.0,
                 numSegs=16,
                 degrees=360,
                 axis=pm.Vec3(1, 0, 0),
                 thickness=1.0,
                 origin=pm.Point3(0, 0, 0)):

        # Create line segments
        self.ls = pm.LineSegs()
        self.ls.setThickness(thickness)

        # Get the points for an arc
        for p in GetPointsForArc(degrees, numSegs):

            # Draw the point rotated around the desired axis
            p = pm.Point3(p[0], p[1], 0) - origin
            p = RotatePoint3(p, pm.Vec3(0, 0, 1), pm.Vec3(axis))
            self.ls.drawTo(p * radius)

        # Init the node path, wrapping the lines
        node = self.ls.create()
        pm.NodePath.__init__(self, node)
コード例 #19
0
    def __init__(self, *args, **kwargs):
        Base.__init__(self, *args, **kwargs)

        self.AddAttributes(Attr('Origin',
                                pm.Point3,
                                CR.getOrigin,
                                CR.setOrigin,
                                initDefault=pm.Point3(0)),
                           Attr('Direction',
                                pm.Vec3,
                                CR.getDirection,
                                CR.setDirection,
                                initDefault=pm.Vec3(0, 0, 1)),
                           parent='CollisionRay')
コード例 #20
0
    def privGotSpec(self, levelSpec):
        DistCogdoLevelGame.privGotSpec(self, levelSpec)

        levelMgr = self.getEntity(LevelConstants.LevelMgrEntId)
        self.endVault = levelMgr.geom
        self.endVault.reparentTo(self.geomRoot)

        # Clear out unneeded backstage models from the EndVault, if
        # they're in the file.
        self.endVault.findAllMatches('**/MagnetArms').detach()
        self.endVault.findAllMatches('**/Safes').detach()
        self.endVault.findAllMatches('**/MagnetControlsAll').detach()

        # Flag the collisions in the end vault so safes and magnets
        # don't try to go through the wall.
        cn = self.endVault.find('**/wallsCollision').node()
        cn.setIntoCollideMask(OTPGlobals.WallBitmask
                              | ToontownGlobals.PieBitmask
                              | (PM.BitMask32.lowerOn(3) << 21))

        # Find all the wall polygons and replace them with planes,
        # which are solid, so there will be zero chance of safes or
        # toons slipping through a wall.
        walls = self.endVault.find('**/RollUpFrameCillison')
        walls.detachNode()
        self.evWalls = self.replaceCollisionPolysWithPlanes(walls)
        self.evWalls.reparentTo(self.endVault)

        # Initially, these new planar walls are stashed, so they don't
        # cause us trouble in the intro movie or in battle one.  We
        # will unstash them when we move to battle three.
        self.evWalls.stash()

        # Also replace the floor polygon with a plane, and rename it
        # so we can detect a collision with it.
        floor = self.endVault.find('**/EndVaultFloorCollision')
        floor.detachNode()
        self.evFloor = self.replaceCollisionPolysWithPlanes(floor)
        self.evFloor.reparentTo(self.endVault)
        self.evFloor.setName('floor')

        # Also, put a big plane across the universe a few feet below
        # the floor, to catch things that fall out of the world.
        plane = PM.CollisionPlane(
            PM.Plane(PM.Vec3(0, 0, 1), PM.Point3(0, 0, -50)))
        planeNode = PM.CollisionNode('dropPlane')
        planeNode.addSolid(plane)
        planeNode.setCollideMask(ToontownGlobals.PieBitmask)
        self.geomRoot.attachNewNode(planeNode)
コード例 #21
0
    def __init__(self, pos=None):
        """Initialise the tree."""

        # Models and CollisionSolids are parented to one prime NodePath
        if pos is None: pos = P.Vec3(0, 0, 0)
        self.pos = pos
        self.prime = P.NodePath('tree')
        self.prime.setPos(self.pos)

        dir = "models/trees"  # FIXME: hardcoded models dir

        # Choose a random model from dir and load it.
        trees = [
            f for f in os.listdir(dir)
            if os.path.isfile(os.path.join(dir, f)) and f.endswith('.egg')
        ]
        tree = random.choice(trees)
        self.np = loadModel(os.path.join(dir, tree), self.prime)

        # TODO: Give each tree a random orientation

        # Initialise the Tree's CollisionRay which is used with a
        # CollisionHandlerQueue to find the height of the terrain below the
        # tree and move the tree to that height (see self.step)
        self.raynp = self.prime.attachNewNode(P.CollisionNode('colNode'))
        self.raynp.node().addSolid(P.CollisionRay(0, 0, 3, 0, 0, -1))
        self.handler = P.CollisionHandlerQueue()
        cTrav.addCollider(self.raynp, self.handler)
        #self.raynp.show()
        # We only want our CollisionRay to collide with the collision
        # geometry of the terrain, se we set a mask here.
        self.raynp.node().setFromCollideMask(C.floorMASK)
        self.raynp.node().setIntoCollideMask(C.offMASK)

        # Add a task for this Tree to the global task manager.
        taskMgr.add(self.step, "Tree step task")
コード例 #22
0
ファイル: DistCogdoCraneCog.py プロジェクト: z010155/c0d3
 def _getFlyAwayDest(self):
     return self.getPos() + PM.Vec3(
         0, 0, GameConsts.CogSettings.CogFlyAwayHeight.get())
コード例 #23
0
ファイル: geometry.py プロジェクト: Derfies/p3d
def Sphere(radius=1.0,
           numSegs=16,
           degrees=360,
           axis=pm.Vec3(0, 0, 1),
           origin=pm.Point3(0, 0, 0)):
    """Return a geom node representing a cylinder."""
    # Create vetex data format
    gvf = pm.GeomVertexFormat.getV3n3()
    gvd = pm.GeomVertexData('vertexData', gvf, pm.Geom.UHStatic)

    # Create vetex writers for each type of data we are going to store
    gvwV = pm.GeomVertexWriter(gvd, 'vertex')
    gvwN = pm.GeomVertexWriter(gvd, 'normal')

    # Get the points for an arc
    axis = pm.Vec3(axis)
    axis.normalize()
    points = GetPointsForArc(degrees, numSegs, True)
    zPoints = GetPointsForArc(180, numSegs / 2, True)
    for z in range(1, len(zPoints) - 2):
        rad1 = zPoints[z][1] * radius
        rad2 = zPoints[z + 1][1] * radius
        offset1 = axis * zPoints[z][0] * radius
        offset2 = axis * zPoints[z + 1][0] * radius

        for i in range(len(points) - 1):

            # Get points
            p1 = pm.Point3(points[i][0], points[i][1], 0) * rad1
            p2 = pm.Point3(points[i + 1][0], points[i + 1][1], 0) * rad1
            p3 = pm.Point3(points[i + 1][0], points[i + 1][1], 0) * rad2
            p4 = pm.Point3(points[i][0], points[i][1], 0) * rad2

            # Rotate the points around the desired axis
            p1, p2, p3, p4 = [
                RotatePoint3(p, pm.Vec3(0, 0, 1), axis)
                for p in [p1, p2, p3, p4]
            ]

            a = p1 + offset1 - origin
            b = p2 + offset1 - origin
            c = p3 + offset2 - origin
            d = p4 + offset2 - origin

            # Quad
            gvwV.addData3f(d)
            gvwV.addData3f(b)
            gvwV.addData3f(a)
            gvwV.addData3f(d)
            gvwV.addData3f(c)
            gvwV.addData3f(b)

            # Normals
            cross = (b - c).cross(a - c)
            for i in range(6):
                gvwN.addData3f(cross)

    # Get points
    rad1 = zPoints[1][1] * radius
    for m in [1, -2]:
        offset1 = axis * zPoints[m][0] * radius

        clampedM = max(-1, min(m, 1)) * radius

        for i in range(len(points) - 1):
            p1 = pm.Point3(points[i][0], points[i][1], 0) * rad1
            p2 = pm.Point3(points[i + 1][0], points[i + 1][1], 0) * rad1

            # Rotate the points around the desired axis
            p1, p2 = [
                RotatePoint3(p, pm.Vec3(0, 0, 1), axis) for p in [p1, p2]
            ]

            a = p1 + offset1 - origin
            b = p2 + offset1 - origin
            c = -axis * clampedM

            # Quad
            if clampedM > 0:
                gvwV.addData3f(a)
                gvwV.addData3f(b)
                gvwV.addData3f(c)
            else:
                gvwV.addData3f(c)
                gvwV.addData3f(b)
                gvwV.addData3f(a)

            # Normals
            cross = (b - c).cross(a - c)
            for i in range(3):
                gvwN.addData3f(cross * -m)

    geom = pm.Geom(gvd)
    for i in range(0, gvwV.getWriteRow(), 3):

        # Create and add triangle
        geom.addPrimitive(GetGeomTriangle(i, i + 1, i + 2))

    # Return the cylinder GeomNode
    geomNode = pm.GeomNode('cylinder')
    geomNode.addGeom(geom)
    return geomNode
コード例 #24
0
import pandac.PandaModules as pm

X_AXIS = pm.Vec3(1, 0, 0)
Y_AXIS = pm.Vec3(0, 1, 0)
Z_AXIS = pm.Vec3(0, 0, 1)
コード例 #25
0
ファイル: functions.py プロジェクト: Derfies/p3d
def Str2Vec3(string):
    buffer = string.split(' ')
    return pm.Vec3(*[float(buffer[i]) for i in range(3)])
コード例 #26
0
ファイル: translation.py プロジェクト: vheuken/panda3d-editor
 def Transform( self ):
     axis = self.GetSelectedAxis()
     axisPoint = self.GetAxisPoint( axis )
     
     # Calculate delta and snapping.
     d = axisPoint - self.lastAxisPoint
     lastSnap = self._Snap( self._s )
     self._s += d
     thisSnap = self._Snap( self._s )
     
     if self._snp:
         
         # If snapping in planar mode or using the camera axis, snap to a
         # point on the ground plane.
         if axis.vector == CAMERA_VECTOR or self.planar:
             pnt = self.GetMousePlaneCollisionPoint( pm.Point3( 0 ), 
                                                     pm.Vec3( 0, 0, 1 ) )
             pnt = utils.SnapPoint( pnt, self._snpAmt )
             
             self.setPos( render, pnt )
             for np in self.attachedNps:
                 np.setPos( render, pnt )
                 
             return
             
         # If snapping in world space, construct a plane where the mouse
         # clicked the axis and move all NodePaths so they intersect it.
         elif not self.local:
             pnt = utils.SnapPoint( self.startAxisPoint + d, self._snpAmt )
             pl = pm.Plane( axis.vector, pm.Point3( pnt ) )
             
             self.setPos( render, pl.project( self.getPos( render ) ) )
             for np in self.attachedNps:
                 np.setPos( render, pl.project( np.getPos( render ) ) )
                 
             return
         
         # Gone over the snap threshold - set the delta to the snap amount.
         elif thisSnap.compareTo( lastSnap, TOL ):
             d.normalize()
             d *= self._snpAmt
             
             # BUG - need to resize to compensate for cam dist?
             
         # In snapping mode but haven't gone past the snap threshold.
         else:
             d = pm.Vec3( 0 )
         
     d = self.getRelativeVector( self.rootNp, d )
     self.setMat( pm.Mat4().translateMat( d ) * self.getMat() )
     
     # Adjust the size of delta by the gizmo size to get real world units.
     d = utils.ScalePoint( d, self.getScale() )
     
     # Hack for fixing camera vector xforming in local mode.
     if self.local and axis.vector == CAMERA_VECTOR:
         d = self.rootNp.getRelativeVector( self, d )
         d = utils.ScalePoint( d, self.getScale(), True )
     
     # Xform attached NodePaths.
     for np in ( self.attachedNps ):
         if self.local and axis.vector != CAMERA_VECTOR:
             sclD = utils.ScalePoint( d, np.getScale( self.rootNp ), True )
             np.setMat( pm.Mat4().translateMat( sclD ) * np.getMat() )
         else:
             np.setMat( self.rootNp, np.getMat( self.rootNp ) * 
                        pm.Mat4().translateMat( d ) )
     
     self.lastAxisPoint = axisPoint
コード例 #27
0
        def __init__(self):
            """Initialise the test scene."""

            # Show the framerate
            base.setFrameRateMeter(True)

            # Make 4 terrain nodepath objects with different hilliness values
            # and arrange them side-by-side in a 2x2 grid, giving a big terrain
            # with variable hilly and flat areas.

            color = (0.6, 0.8, 0.5, 1)  # Bright green-ish
            scale = 12

            t1 = Terrain(color=color, scale=scale, trees=0.7)
            t1.prime.reparentTo(render)
            t2 = Terrain(color=color,
                         scale=scale,
                         h=24,
                         pos=P.Vec3(32 * scale, 0, 0),
                         trees=0.5)
            t2.prime.reparentTo(render)
            t3 = Terrain(color=color,
                         scale=scale,
                         h=16,
                         pos=P.Vec3(32 * scale, 32 * scale, 0),
                         trees=0.3)
            t3.prime.reparentTo(render)
            t4 = Terrain(color=color,
                         scale=scale,
                         h=2,
                         pos=P.Vec3(0, 32 * scale, 0),
                         trees=0.9)
            t4.prime.reparentTo(render)

            # Setup a camera.
            base.disableMouse()
            self.camera = Camera(P.Vec3(0, 0, 100))
            self.camera.lookAt(320, 320, 0)

            # Setup keyboard controls.
            # Accept some keys to move the camera.
            self.accept("a", self.camera.setControl, ["left", 1])
            self.accept("a-up", self.camera.setControl, ["left", 0])
            self.accept("d", self.camera.setControl, ["right", 1])
            self.accept("d-up", self.camera.setControl, ["right", 0])
            self.accept("w", self.camera.setControl, ["up", 1])
            self.accept("w-up", self.camera.setControl, ["up", 0])
            self.accept("s", self.camera.setControl, ["down", 1])
            self.accept("s-up", self.camera.setControl, ["down", 0])
            self.accept("arrow_up", self.camera.setControl, ["forward", 1])
            self.accept("arrow_up-up", self.camera.setControl, ["forward", 0])
            self.accept("arrow_down", self.camera.setControl, ["backward", 1])
            self.accept("arrow_down-up", self.camera.setControl,
                        ["backward", 0])
            self.accept("arrow_left", self.camera.setControl,
                        ["strafe-left", 1])
            self.accept("arrow_left-up", self.camera.setControl,
                        ["strafe-left", 0])
            self.accept("arrow_right", self.camera.setControl,
                        ["strafe-right", 1])
            self.accept("arrow_right-up", self.camera.setControl,
                        ["strafe-right", 0])
            # Accept the Esc key to exit.
            self.accept("escape", sys.exit)

            # Setup lighting.
            self.alight = P.AmbientLight('alight')
            self.alight.setColor(P.VBase4(0.35, 0.35, 0.35, 1))
            self.alnp = render.attachNewNode(self.alight)
            render.setLight(self.alnp)

            self.dlight = P.DirectionalLight('dlight')
            self.dlight.setColor(P.VBase4(0.4, 0.4, 0.4, 1))
            self.dlnp = render.attachNewNode(self.dlight)
            self.dlnp.setHpr(45, -45, 0)
            render.setLight(self.dlnp)

            self.plight = P.PointLight('plight')
            self.plight.setColor(P.VBase4(0.8, 0.8, 0.5, 1))
            self.plnp = render.attachNewNode(self.plight)
            self.plnp.setPos(160, 160, 50)

            self.slight = P.Spotlight('slight')
            self.slight.setColor(P.VBase4(1, 1, 1, 1))
            lens = P.PerspectiveLens()
            self.slight.setLens(lens)
            self.slnp = render.attachNewNode(self.slight)
            self.slnp.setPos(-20, -20, 20)
            self.slnp.lookAt(50, 50, 0)

            # Setup some scene-wide exponential fog.
            colour = (0.5, 0.8, 0.8)
            self.expfog = P.Fog("Scene-wide exponential Fog object")
            self.expfog.setColor(*colour)
            self.expfog.setExpDensity(0.0005)
            render.setFog(self.expfog)
            base.setBackgroundColor(*colour)
コード例 #28
0
ファイル: translation.py プロジェクト: vheuken/panda3d-editor
 def OnMouse2Down( self ):
     Base.OnMouse2Down( self )
     
     self._s = pm.Vec3( 0 )