def loadObject(tex=None, pos=Point2(0, 0), depth=SPRITE_POS, scale=1, transparency=True): obj = loader.loadModel("models/plane") #Every object uses the plane model obj.reparentTo(camera) #Everything is parented to the camera so #that it faces the screen obj.setPos(Point3(pos.getX(), depth, pos.getY())) #Set initial position obj.setScale(scale) #Set initial scale obj.setBin("unsorted", 0) #This tells Panda not to worry about the #order this is drawn in. (it prevents an #effect known as z-fighting) obj.setDepthTest(False) #Tells panda not to check if something #has already drawn in front of it #(Everything in this game is at the same #depth anyway) if transparency: obj.setTransparency(1) #All of our objects are trasnparent if tex: tex = loader.loadTexture("textures/" + tex + ".png") #Load the texture obj.setTexture(tex, 1) #Set the texture return obj
def __startDrag(self, crap): taskMgr.add(self.__drag, 'dragging menu bar', extraArgs=[Point2(base.mouseWatcherNode.getMouse())]) self.__removePopupMenu() self.origBTprefix = self.BT.getPrefix() self.BT.setPrefix('dragging menu bar')
def __update(self, task): active = None for vp in self.viewports: if vp.mouseWatcher.hasMouse(): active = vp vp.tick() if active and (not self.activeViewport or self.activeViewport != active): active.mouseEnter() self.doc.messenger.send('mouseEnter', [active]) elif not active and self.activeViewport: self.activeViewport.mouseExit() self.doc.messenger.send('mouseExit', [self.activeViewport]) if active and active == self.activeViewport: mouse = active.mouseWatcher.getMouse() if not self.lastMouse or self.lastMouse != mouse: active.mouseMove() self.doc.messenger.send('mouseMoved', [active]) self.lastMouse = Point2(mouse) self.activeViewport = active return task.cont
def test_perspectivelens_project(): lens = PerspectiveLens() lens.set_fov(90, 90) lens.set_near_far(0.5, 100) point = Point2() assert not lens.project((0, 0, 0), point) assert not lens.project((-1, 0.5, 0), point) assert lens.project((0, 0.5, 0), point) assert point.almost_equal((0, 0), 0.001) assert lens.project((0, 100, 0), point) assert point.almost_equal((0, 0), 0.001) assert lens.project((-0.5, 0.5, -0.5), point) assert point.almost_equal((-1, -1), 0.001) assert lens.project((-100, 100, -100), point) assert point.almost_equal((-1, -1), 0.001) assert lens.project((0.5, 0.5, 0), point) assert point.almost_equal((1, 0), 0.001) assert lens.project((100, 100, 0), point) assert point.almost_equal((1, 0), 0.001)
def opportunisticAI(self, asteroids, heading, framesToFire): if len(asteroids) == 0: return (False, 0) bullet = MovingObject(1, Point2(0, 0), 90, self.bulletSpeed, self.bulletRad) if (asteroids[0].collideWithObject(bullet)): return (True, 0) return (False, 0)
def __init__(self, world): super(Player, self).__init__() self.obj = utilities.loadObject("tdplayer", depth=20) self.world = world self.health = 100 self.inventory = list() self.depth = self.obj.getPos().y self.location = Point2(10, 0) self.velocity = Vec3(0) self.shape = BulletBoxShape(Vec3(0.3, 1.0, 0.49)) self.bnode = BulletRigidBodyNode('Box') self.bnode.setMass(0.1) self.bnode.setAngularVelocity(Vec3(0)) self.bnode.setAngularFactor(Vec3(0)) self.bnode.addShape(self.shape) self.bnode.setLinearDamping(0.95) self.bnode.setLinearSleepThreshold(0) world.bw.attachRigidBody(self.bnode) self.bnode.setPythonTag("entity", self) self.bnode.setIntoCollideMask(BitMask32.bit(0)) self.node = utilities.app.render.attachNewNode(self.bnode) self.node.setPos(self.obj.getPos()) self.obj.setPos(0, 0, 0) self.obj.setScale(1) self.obj.reparentTo(self.node) self.node.setPos(self.location.x, self.depth, self.location.y)
def coordScreenTo3d(self, screenCoord): x, y = screenCoord screenPoint = Point2(x, y) # Do this calculation using simple geometry, rather than the absurd # collision-traversal nonsense we used to use. Thanks to # https://www.panda3d.org/forums/viewtopic.php?t=5409 # for pointing us at the right methods to make this work. # Get two points along the ray extending from the camera, in the # direction of the mouse click. nearPoint = Point3() farPoint = Point3() self.camLens.extrude(screenPoint, nearPoint, farPoint) # These points are relative to the camera, so need to be converted to # be relative to the render. Thanks to the example code (see link # above) for saving us probably some hours of debugging figuring that # one out again :) nearPoint = self.render.getRelativePoint(self.camera, nearPoint) farPoint = self.render.getRelativePoint(self.camera, farPoint) intersection = Point3() if self.groundPlane.intersectsLine(intersection, nearPoint, farPoint): # Convert to a tuple to ensure no one else is keeping a reference # around. x, y, z = intersection return (x, y, z) # The ray didn't intersect the ground. This is almost certainly going # to happen at some point; all you have to do is find a way to aim the # camera (or manipulate the screen coordinate) so that the ray points # horizontally. But we don't have code to handle it, so for now just # abort. thisIsNotHandled()
def project_2d(lens, img_metadata, pos): center = np.array(img_metadata.camera_pos) heading = np.radians(img_metadata.camera_heading_in_degrees) # Translate according to the camera center p_translated = pos - center # Apply the inverse rotation matrix to the vehicle position, same effect as rotating the camera p_rotated = np.array([ p_translated[0] * np.cos(-heading) - p_translated[1] * np.sin(-heading), p_translated[0] * np.sin(-heading) + p_translated[1] * np.cos(-heading), p_translated[2], ]) v_2d_pos_normalized = Point2() v_3d_pos = Point3( p_rotated[0], p_rotated[2], p_rotated[1]) # y and z are flipped for project() in panda3D x = int(HALF_HEIGHT) y = int(HALF_WIDTH) # project() returns true if given 3d point is within the viewing frustum if lens.project(v_3d_pos, v_2d_pos_normalized): # v_2d_pos_normlized ranges (-1, 1) in both directions, with (-1,-1) being the lower-left corner # Sensor image has non-negative pixel positions, with (0, 0) starting from top-left corner # x and y are swapped between sensor image and the image projected from panda3D lens x = int(-v_2d_pos_normalized[1] * HALF_HEIGHT + HALF_HEIGHT) y = int(v_2d_pos_normalized[0] * HALF_WIDTH + HALF_WIDTH) return x, y
def __init__(self): #self.text contains the text to be displayed -> type: String self.text = "" #self.position contains the position of the button -> type: Point2 self.position = Point2(0, 0) #self.scale contains the size of the button -> type: Float self.scale = .00
def setClickRegionFrame(self, left, right, bottom, top): transform = self.contents.getNetTransform() camTransform = base.cam.getNetTransform().getInverse() transform = camTransform.compose(transform) transform.setQuat(Quat()) mat = transform.getMat() camSpaceTopLeft = mat.xformPoint(Point3(left, 0, top)) camSpaceBottomRight = mat.xformPoint(Point3(right, 0, bottom)) screenSpaceTopLeft = Point2() screenSpaceBottomRight = Point2() base.camLens.project(Point3(camSpaceTopLeft), screenSpaceTopLeft) base.camLens.project(Point3(camSpaceBottomRight), screenSpaceBottomRight) left, top = screenSpaceTopLeft right, bottom = screenSpaceBottomRight self.region.setFrame(left, right, bottom, top)
def get_key_position(self, depth, key=None): #print key #print 'get key position', key pos = Point2(self.small_set[key - 1]) position = (pos.getX(), depth, pos.getY()) #print 'position in position', position return position
def __init__(self, vpType, window, doc): Viewport.__init__(self, vpType, window, doc) self.zoom = 0.25 self.dragging = False self.dragCamStart = Point3() self.dragCamMouseStart = Point3() self.lastMouse = Point2()
def checkMousePos(self, mpos, camPos, camHpr): lens = LenseNode.copyLens(base.camNode) lens.setPos(camPos) lens.setHpr(camHpr) help(mpos) mpos = Point2(mpos.x, mpos.y) pos = self.getClickPosition(mpos, lens) print "mouse clicked at:", pos
def rebuild(self, chunk, diff=Point2(0.0, 0.0)): self.pos -= diff self.chunk = chunk self.chunk.bnode.addShape( self.shape, TransformState.makePos(Point3(self.pos.x, 0, self.pos.y))) self.obj.reparentTo(self.chunk.np) self.obj.setPos(self.pos.x, 0, self.pos.y)
def __renderQuad(mat=None, tex=None): # Build a simple quad that uses the material cm = CardMaker('materialCard') cm.setFrame(-1, 1, -1, 1) cm.setHasUvs(True) cm.setUvRange(Point2(0, 0), Point2(1, 1)) cardNp = NodePath(cm.generate()) if mat: cardNp.setBSPMaterial(mat, 1) elif tex: cardNp.setTexture(tex, 1) # Render it! precacheScene(cardNp) cardNp.removeNode()
def getMouse(self): if base.mouseWatcherNode.hasMouse(): x = base.mouseWatcherNode.getMouseX() y = base.mouseWatcherNode.getMouseY() else: x = 0 y = 0 return Point2(x, y)
def getMoveIvalFromPath(np, path, speed): from direct.interval.IntervalGlobal import Sequence, Func, LerpPosInterval moveIval = Sequence() for i in xrange(len(path)): if i == 0: continue waypoint = path[i] lastWP = path[i - 1] moveIval.append(Func(np.headsUp, Point3(*waypoint))) ival = LerpPosInterval( np, pos=Point3(*waypoint), startPos=Point3(*lastWP), fluid=1, duration=(Point2(waypoint[0], waypoint[1]) - Point2(lastWP[0], lastWP[1])).length() / speed) moveIval.append(ival) return moveIval
def setMoveCamera(self, moveCamera): """Start dragging around the editor area/camera""" # store the mouse position if weh have a mouse if base.mouseWatcherNode.hasMouse(): x = base.mouseWatcherNode.getMouseX() y = base.mouseWatcherNode.getMouseY() self.mousePos = Point2(x, y) # set the variable according to if we want to move the camera or not self.startCameraMovement = moveCamera
def __init__(self): self.activeViewport = None self.action = BoxAction.ReadyToDraw self.handle = ResizeHandle.Center self.boxStart = None self.boxEnd = None self.moveStart = None self.preTransformBoxStart = None self.preTransformBoxEnd = None self.clickStart = Point2(0, 0)
def get_position(self, depth, mode=None): # default is not random, large set if not mode: control_set = self.large_set for i in control_set: #print 'get non-random point' pos = Point2(i) #print 'pos in positions', pos yield (pos.getX(), depth, pos.getY()) elif mode == 'small': control_set = self.small_set for i in control_set: pos = Point2(i) yield (pos.getX(), depth, pos.getY()) else: control_set = self.large_set * self.repeat while len(control_set) > 0: pos = Point2( control_set.pop(random.randrange(len(control_set)))) yield (pos.getX(), depth, pos.getY())
def get_degree_positions(self, depth): # give positions 5 degrees further out every time degree = 0 while degree < 40: if degree == 0: #print 'yup' pos = Point2(0, 0) yield (pos.getX(), depth, pos.getY()) else: deg_per_pix = visual_angle(self.screen, self.res, self.v_dist) #print pix_per_deg pixels = [degree / i for i in deg_per_pix] #print 'x?', pixels[0] #print 'y?', pixels[1] x = [pixels[0], -pixels[0], 0, 0] y = [0, 0, pixels[1], -pixels[1]] for i in range(4): pos = Point2(x[i], y[i]) yield (pos.getX(), depth, pos.getY()) degree += 5
def worldToViewport(self, world): # move into local camera space invMat = Mat4(self.cam.getMat(render)) invMat.invertInPlace() local = invMat.xformPoint(world) point = Point2() self.lens.project(local, point) return point
def loadObject( tex=None, pos=Point2(0,0), depth=SPRITE_POS, scale=1, transparency=True ): obj = loader.loadModel( "models/plane" ) obj.reparentTo( camera ) obj.setPos( Point3( pos.getX( ), depth, pos.getY( ) ) ) obj.setScale( scale ) obj.setBin( "unsorted", 0 ) obj.setDepthTest( False ) if transparency: obj.setTransparency( 1 ) if tex: tex = loader.loadTexture("sprites/"+tex+".png") obj.setTexture(tex, 1) return obj
def mouseMove(self): if self.dragging: mouse = self.mouseWatcher.getMouse() worldPos = self.viewportToWorld(mouse, False, True) delta = worldPos - self.dragCamMouseStart self.camera.setPos(self.dragCamStart - delta) if mouse != self.lastMouse: self.updateView() self.lastMouse = Point2(mouse) world = self.viewportToWorld(self.getMouse(), flatten = False) base.qtWindow.coordsLabel.setText("%i %i %i" % (world.x, world.y, world.z))
def getMoveIvalFromPath(suit, path, elapsedT, isClient, seqName): moveIval = Sequence(name=suit.uniqueName(seqName)) if isClient: moveIval.append(Func(suit.animFSM.request, 'walk')) for i in xrange(len(path)): if i == 0: continue waypoint = path[i] lastWP = path[i - 1] moveIval.append(Func(suit.headsUp, Point3(*waypoint))) ival = NPCWalkInterval( suit, Point3(*waypoint), startPos=Point3(*lastWP), fluid=1, name=suit.uniqueName('doWalkIval' + str(i)), duration=(Point2(waypoint[0], waypoint[1]) - Point2(lastWP[0], lastWP[1])).length() * 0.2) moveIval.append(ival) if isClient: moveIval.append(Func(suit.animFSM.request, 'neutral')) return moveIval
def __init__(self, size): self.bw = BulletWorld() self.bw.setGravity(0, 0, 0) self.size = size self.perlin = PerlinNoise2() #utilities.app.accept('bullet-contact-added', self.onContactAdded) #utilities.app.accept('bullet-contact-destroyed', self.onContactDestroyed) self.player = Player(self) self.player.initialise() self.entities = list() self.bgs = list() self.makeChunk(Point2(0, 0), Point2(3.0, 3.0)) self.cmap = buildMap(self.entities, self.player.location) self.mps = list() self.entities.append( Catcher(Point2(10, 10), self.player, self.cmap, self))
def getPointFromCamLens(self, target_pos): # Get to and from pos in camera coordinates and transform to global coordinates p_from, p_to = Point3(), Point3() self.camLens.extrude(Point2(target_pos), p_from, p_to) p_from = self.render.getRelativePoint(self.cam, p_from) p_to = self.render.getRelativePoint(self.cam, p_to) # Get the target coordinates which correspond to mouse coordinates and walk the camera to this direction result = self.physics_manager.rayTestClosest(p_from, p_to) if result.hasHit(): return result.getNode(), result.getHitPos() else: return None, None
def genBox(world, pos, width, height, tileset): blocks = list() #closest fit, but in practical terms blocksize will mostly be 1 outerX = int(width) outerY = int(height) for x in range(0, outerX): blocks.append( Block(world, Point2(float(x), 0), picktile(tileset), list())) for y in range(1, outerY - 1): blocks.append( Block(world, Point2(float(outerX - 1), float(y)), picktile(tileset), list())) for x in range(0, outerX): blocks.append( Block(world, Point2(float(outerX - 1 - x), float(outerY - 1)), picktile(tileset), list())) for y in range(1, outerY - 1): blocks.append( Block(world, Point2(float(0), float(outerY - 1 - y)), picktile(tileset), list())) #for i in range(0, len(blocks) - 1): # blocks[i].edges.append(blocks[i+1]) # blocks[i+1].edges.append(blocks[i]) #blocks[0].edges.append(blocks[len(blocks) - 1]) #blocks[len(blocks)-1].edges.append(blocks[0]) # connect all the horizontals for block1 in blocks: for block2 in blocks: if (block1 != block2): blockdis(block1, block2) chunk = Chunk(world, blocks, pos) world.addEntity(chunk)
def flush_new(self, task): print "inside flush" #self.ship.remove() #self.ball.remove() #for i in range(0,len(self.bricks)): # self.bricks[i].remove() print "Enter Name:" name = raw_input() print name global SCORE global bricks SCORE = 0 self.ship = loadObject("boardfinal", pos=Point2(0, -13), scale=BOARD_INIT_SCALE) self.ball = loadObject("ball", pos=Point2(0, -10), scale=BALL_INIT_SCALE) self.setVelocity(self.ball, Vec3(0, 0, 0)) #Initial velocity self.bricks = [] for i in range(-18, 19, 2): for j in range(8, 12, 1): self.bricks.append( loadObject("brickfinal", pos=Point2(i, j), scale=BRI_INIT_SCALE)) #As described earlier, this simply sets a key in the self.keys dictionary to #self.setExpires(self.ball,0) self.alive = True #the given value taskMgr.remove('flush') self.title.destroy() self.keys['fire'] = 0 self.gameTask = taskMgr.add(self.gameLoop, "gameLoop")
def __init__(self, world, app): self.world = world self.image = PNMImage(self.world.width, 256) for z in self.world.zlevels(): for x in range(self.world.height): mix = sum([ ZMap.COLORS[self.world.get_block(x, y, z).substance] for y in range(self.world.height) ], VBase3D(0.0)) color_block = mix / float(self.world.height) #print(color_block) #self.image.setXel(int(x), int(z), mix / float(self.world.height)) self.image.setXel( int(x), int(z), LRGBColorf(color_block[0], color_block[1], color_block[2])) self.texture = Texture() self.texture.load(self.image) self.texture.setMagfilter(Texture.FTNearest) self.texture.setMinfilter(Texture.FTNearest) cm = CardMaker('zmap') cm.setFrame(0.95, 1, -1, 1) cm.setUvRange(Point2(1.0, 1.0), Point2(0.0, 1.0 - self.world.depth / 256.0)) self.zcard = app.render2d.attachNewNode(cm.generate()) self.zcard.setTexture(self.texture) cm = CardMaker('zpointer') cm.setFrame(0, 0.05, 0, 1.0 / self.world.depth) self.zpointer = app.render2d.attachNewNode(cm.generate()) self.zpointer.setColorScale(1.0, 0.0, 0.0, 0.4) self.accept('slice-changed', self.slice_changed)