Ejemplo n.º 1
0
 def create_instance(self):
     #print("Create label for", self.get_name())
     self.label = TextNode(self.parent.get_ascii_name() + '-label')
     if not self.font_init:
         self.load_font()
     if self.font is not None:
         self.label.set_font(self.font)
     name = bayer.decode_name(self.parent.get_label_text())
     self.label.setText(name)
     self.label.setTextColor(*self.parent.get_label_color())
     #node=label.generate()
     #self.instance = self.context.annotation.attachNewNode(node)
     #self.instance.setBillboardPointEye()
     #node.setIntoCollideMask(GeomNode.getDefaultCollideMask())
     #node.setPythonTag('owner', self.parent)
     cardMaker = CardMaker(self.get_ascii_name() + '-labelcard')
     cardMaker.setFrame(self.label.getFrameActual())
     cardMaker.setColor(0, 0, 0, 0)
     card_node = cardMaker.generate()
     self.label_instance = NodePath(card_node)
     tnp = self.label_instance.attachNewNode(self.label)
     self.label_instance.setTransparency(TransparencyAttrib.MAlpha)
     #card.setEffect(DecalEffect.make())
     #Using look_at() instead of billboard effect to also rotate the collision solid
     #card.setBillboardPointEye()
     #Using a card holder as look_at() is changing the hpr parameters
     self.instance = NodePath('label-holder')
     self.label_instance.reparentTo(self.instance)
     self.instance.reparentTo(self.context.annotation_shader)
     self.instance.setCollideMask(GeomNode.getDefaultCollideMask())
     self.instance.set_depth_write(False)
     card_node.setPythonTag('owner', self.parent)
     self.look_at = self.instance.attachNewNode("dummy")
Ejemplo n.º 2
0
    def setupMouseCollision(self):
        """ """
        #Since we are using collision detection to do picking, we set it up
        #any other collision detection system with a traverser and a handler
        self.mPickerTraverser = CollisionTraverser()  #Make a traverser
        self.mCollisionQueue = CollisionHandlerQueue()

        #create a collision solid ray to detect against
        self.mPickRay = CollisionRay()
        #self.mPickRay.setOrigin(base.camera.getPos(render))
        #self.mPickRay.setDirection(render.getRelativeVector(base.camera, Vec3(0,1,0)))

        #create our collison Node to hold the ray
        self.mPickNode = CollisionNode('pickRay')
        self.mPickNode.addSolid(self.mPickRay)

        #Attach that node to the camera since the ray will need to be positioned
        #relative to it, returns a new nodepath
        #well use the default geometry mask
        #this is inefficent but its for mouse picking only

        self.mPickNP = base.camera.attachNewNode(self.mPickNode)

        #well use what panda calls the "from" node.  This is reall a silly convention
        #but from nodes are nodes that are active, while into nodes are usually passive environments
        #this isnt a hard rule, but following it usually reduces processing

        #Everything to be picked will use bit 1. This way if we were doing other
        #collision we could seperate it, we use bitmasks to determine what we check other objects against
        #if they dont have a bitmask for bit 1 well skip them!
        self.mPickNode.setFromCollideMask(GeomNode.getDefaultCollideMask())

        #Register the ray as something that can cause collisions
        self.mPickerTraverser.addCollider(self.mPickNP, self.mCollisionQueue)
Ejemplo n.º 3
0
    def __init__(self):
        self.accept('mouse1', self.onMouse1Down, [])  # Left click
        self.accept('mouse1-up', self.onMouse1Up, [])
        self.accept('mouse3', self.onMouse3Down, [])  # Right click

        self.showCollisions = False

        pickerNode = CollisionNode('mouseRay')
        pickerNP = camera.attachNewNode(pickerNode)
        pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
        self.pickerRay = CollisionRay()
        pickerNode.addSolid(self.pickerRay)
        base.cTrav.addCollider(pickerNP, base.handler)
        if self.showCollisions:
            base.cTrav.showCollisions(render)
        base.disableMouse()

        self.activeCard = None
        self._targeting = False

        self._dragging = None

        # Counts down between clicks to detect double click
        self.doubleClickTimer = -1.0
        self.doubleClickInterval = 1.0

        self.line = attackLine.Line()
    def setupMouseCollision(self):
        """ """
        #Since we are using collision detection to do picking, we set it up
        #any other collision detection system with a traverser and a handler
        self.mPickerTraverser = CollisionTraverser()            #Make a traverser
        self.mCollisionQueue  = CollisionHandlerQueue()

        #create a collision solid ray to detect against
        self.mPickRay = CollisionRay()
        #self.mPickRay.setOrigin(base.camera.getPos(render))
        #self.mPickRay.setDirection(render.getRelativeVector(base.camera, Vec3(0,1,0)))

        #create our collison Node to hold the ray
        self.mPickNode = CollisionNode('pickRay')
        self.mPickNode.addSolid(self.mPickRay)

        #Attach that node to the camera since the ray will need to be positioned
        #relative to it, returns a new nodepath
        #well use the default geometry mask
        #this is inefficent but its for mouse picking only

        self.mPickNP = base.camera.attachNewNode(self.mPickNode)

        #well use what panda calls the "from" node.  This is reall a silly convention
        #but from nodes are nodes that are active, while into nodes are usually passive environments
        #this isnt a hard rule, but following it usually reduces processing

        #Everything to be picked will use bit 1. This way if we were doing other
        #collision we could seperate it, we use bitmasks to determine what we check other objects against
        #if they dont have a bitmask for bit 1 well skip them!
        self.mPickNode.setFromCollideMask(GeomNode.getDefaultCollideMask())

        #Register the ray as something that can cause collisions
        self.mPickerTraverser.addCollider(self.mPickNP, self.mCollisionQueue)
Ejemplo n.º 5
0
    def __init__(self, nick):
        self.player = player.Player(nick=nick)
        self.controller = controller.ClientController(self.player)
        self.handgui = hand.HandGUI(self.player.hand)
        camera.setPos(0, -20, 0)
        self.accept("turn_time_changed", self.update_turn_time)
        self.turn_timer = TurnTimer()

        # Mouse detection:
        base.cTrav = CollisionTraverser()
        self.mouse_ray_handler = CollisionHandlerQueue()
        mouse_ray_node = CollisionNode('mouse_ray')
        mouse_ray_np = camera.attachNewNode(mouse_ray_node)
        mouse_ray_node.setFromCollideMask(GeomNode.getDefaultCollideMask())
        mouse_ray_node.setIntoCollideMask(0)
        self.mouse_ray = CollisionRay()
        mouse_ray_node.addSolid(self.mouse_ray)
        base.cTrav.addCollider(mouse_ray_np, self.mouse_ray_handler)

        self.mouse_overed_entry = None

        self.accept("mouse_enter", self.enlarge_entry)
        self.accept("mouse_leave", self.shrink_entry)

        self.accept("p-up", self.change_card_picture)

        taskMgr.doMethodLater(0.1, self.check_mouse_over, "check_mouse_over")
Ejemplo n.º 6
0
 def setupClickCollision(self):
     self.clickHandler = CollisionHandlerQueue()
     self.traverser = CollisionTraverser('ClickTraverser')
     base.cTrave = self.traverser
     self.clickerNode = CollisionNode('mouseClick')
     self.clickerNodePoint = self.camera.attachNewNode(self.clickerNode)
     self.clickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
     self.clickerRay = CollisionRay()
     self.clickerNode.addSolid(self.clickerRay)
     self.traverser.addCollider(self.clickerNodePoint,self.clickHandler)
Ejemplo n.º 7
0
 def collideWithGeom(self):
     # The into collide mask is the bit pattern colliders look at
     # when deciding whether or not to test for a collision "into"
     # this collision solid.  Set to all Off so this collision solid
     # will not be considered in any collision tests
     self.collisionNode.setIntoCollideMask(BitMask32().allOff())
     # The from collide mask is the bit pattern *this* collision solid
     # compares against the into collide mask of candidate collision solids
     # Turn this mask all off since we're not testing for collisions against
     # collision solids, but we do want to test against geometry
     self.collisionNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
Ejemplo n.º 8
0
 def createRay(self,obj,ent,name,show=False,x=0,y=0,z=0,dx=0,dy=0,dz=-1):
     #create queue
     obj.queue=CollisionHandlerQueue()
     #create ray  
     obj.rayNP=ent.attachNewNode(CollisionNode(name))
     obj.ray=CollisionRay(x,y,z,dx,dy,dz)
     obj.rayNP.node().addSolid(obj.ray)
     obj.rayNP.node().setFromCollideMask(GeomNode.getDefaultCollideMask())
     #base.cTrav.addCollider(obj.rayNP, obj.queue)
     self.cTrav.addCollider(obj.rayNP, obj.queue) 
     if show: obj.rayNP.show()
Ejemplo n.º 9
0
	def setupMouseCollision(self):
		self.mouseTraverser = CollisionTraverser()
		self.mouseCollisionQueue    = CollisionHandlerQueue()
		self.mouseRay = CollisionRay()
		self.mouseRay.setOrigin(self.pandaScene.camera.getPos(self.pandaScene.render))
		self.mouseRay.setDirection(self.pandaScene.render.getRelativeVector(self.pandaScene.camera, Vec3(0,1,0)))
		self.mouseNode = CollisionNode('mouseRay')
		self.mouseNode.addSolid(self.mouseRay)
		self.mouseNodePath = self.pandaScene.camera.attachNewNode(self.mouseNode)
		self.mouseNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
		self.mouseTraverser.addCollider(self.mouseNodePath, self.mouseCollisionQueue)
Ejemplo n.º 10
0
 def __init__(self, camera, level):
     self.camera = camera
     self.level = level
     self.handler = CollisionHandlerQueue()
     self.traverser = CollisionTraverser('traverser')
     pickerNode = CollisionNode('mouseRay')
     pickerNP = self.camera.attachNewNode(pickerNode)
     pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
     self.pickerRay = CollisionRay()
     pickerNode.addSolid(self.pickerRay)
     self.traverser.addCollider(pickerNP, self.handler)
Ejemplo n.º 11
0
 def collideWithGeom(self):
     # The into collide mask is the bit pattern colliders look at
     # when deciding whether or not to test for a collision "into"
     # this collision solid.  Set to all Off so this collision solid
     # will not be considered in any collision tests
     self.collisionNode.setIntoCollideMask(BitMask32().allOff())
     # The from collide mask is the bit pattern *this* collision solid
     # compares against the into collide mask of candidate collision solids
     # Turn this mask all off since we're not testing for collisions against
     # collision solids, but we do want to test against geometry
     self.collisionNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
Ejemplo n.º 12
0
    def mouseDown(self):
        vp = base.viewportMgr.activeViewport
        if not vp:
            return

        if vp.is3D():
            # If we clicked in the 3D viewport, try to intersect with an existing MapObject
            # and immediately place the entity at the intersection point. If we didn't click on any
            # MapObject, place the entity on the grid where we clicked.
            entries = vp.click(GeomNode.getDefaultCollideMask())
            if entries and len(entries) > 0:
                for i in range(len(entries)):
                    entry = entries[i]
                    # Don't backface cull if there is a billboard effect on or above this node
                    if not LEUtils.hasNetBillboard(entry.getIntoNodePath()):
                        surfNorm = entry.getSurfaceNormal(vp.cam).normalized()
                        rayDir = entry.getFrom().getDirection().normalized()
                        if surfNorm.dot(rayDir) >= 0:
                            # Backface cull
                            continue
                    # We clicked on an object, use the contact point as the
                    # location of our new entity.
                    self.pos = entry.getSurfacePoint(self.doc.render)
                    self.hasPlaced = True
                    # Create it!
                    self.confirm()
                    break
            else:
                # Didn't click on an object, intersect our mouse ray with the grid plane.
                plane = LPlane(0, 0, 1, 0)
                worldMouse = vp.viewportToWorld(vp.getMouse())
                theCamera = vp.cam.getPos(render)
                # Ensure that the camera and mouse positions are on opposite
                # sides of the plane, or else the entity would place behind us.
                sign1 = plane.distToPlane(worldMouse) >= 0
                sign2 = plane.distToPlane(theCamera) >= 0
                if sign1 != sign2:
                    pointOnPlane = Point3()
                    ret = plane.intersectsLine(pointOnPlane, theCamera,
                                               worldMouse)
                    if ret:
                        # Our mouse intersected the grid plane. Place an entity at the plane intersection point.
                        self.pos = pointOnPlane
                        self.hasPlaced = True
                        self.confirm()
            return

        # The user clicked in the 2D viewport, draw the visualization where they clicked.
        self.showVis()
        self.updatePosFromViewport(vp)
        self.mouseIsDown = True
        self.hasPlaced = True
Ejemplo n.º 13
0
    def __init__(self, camera_gear, tq_render, mousewatchernode,
                 dragAndDropObjectsManager):
        """ """
        self.dragAndDropObjectsManager = dragAndDropObjectsManager

        # -- things that are needed to do picking from different camera orientations
        self.camera_gear = camera_gear  # e.g. the orbiter class is a camera_gear
        self.tq_render = tq_render

        self.mouse_watcher_node = mousewatchernode

        # -- things that are needed for collision detection by picking a 3d object
        self.pick_traverser = CollisionTraverser()
        self.collision_queue = CollisionHandlerQueue()

        # ---- build the CollisionRay
        self.pick_collision_ray = CollisionRay(
        )  # the pick ray is apparently a 'Solid'

        # -- a ray is a half-inifinite straight line
        # it is supposed to shoot out orthogonally to the view plane and hit an object
        self.pick_collision_ray.setOrigin(
            self.camera_gear.p3d_camera.getPos(
                self.tq_render.get_p3d_nodepath()))

        # -- TODO: update this every time the orbiter camera position changes
        # first, transform the (0,1,0) vector into render's coordinate system

        self.pick_collision_ray.setDirection(
            engine.tq_graphics_basics.tq_render.getRelativeVector(
                camera, Vec3(0, 1, 0)))

        # ---- build the CollisionNode
        self.pick_collision_node = CollisionNode('pick_collision_ray')
        self.pick_collision_node.addSolid(
            self.pick_collision_ray)  # the pick ray is actually a 3d object

        # attach the CollisionNode to the camera (not the CollisionRay)
        self.pick_collision_node_nodepath = self.camera_gear.p3d_camera.attachNewNode(
            self.pick_collision_node)

        # set a collide mask to the pick_collision_node, 2 objects that should be able to collide must have the same collide mask!
        self.pick_collision_node.setFromCollideMask(
            GeomNode.getDefaultCollideMask()
            # DragDropObject.dragMask
        )  # set bit 20 (Default) to the ray

        # add the ray as sth. that can cause collisions, and tell it to fill up our collision queue object when traversing and detecting
        self.pick_traverser.addCollider(self.pick_collision_node_nodepath,
                                        self.collision_queue)
Ejemplo n.º 14
0
 def init_picker(self):
     # Collision traverser
     self.traverser = CollisionTraverser("traverser")
     # Collision handler
     self.handler = CollisionHandlerQueue()
     # Initialize and set up picker ray node and NodePath
     self.picker = CollisionNode("mouse_ray")
     self.pickerNP = self.camera.attachNewNode(self.picker)
     self.picker.setFromCollideMask(GeomNode.getDefaultCollideMask())
     self.picker_ray = CollisionRay()
     self.picker.addSolid(self.picker_ray)
     self.traverser.addCollider(self.pickerNP, self.handler)
     mark_color = (1, 1, 1, 0.3)
     self.base_mark = self.create_mark(color=mark_color)
     connector_color = (1, 1, 1, 1)
     self.base_connector = self.create_connector(color=connector_color)
Ejemplo n.º 15
0
 def init_picker(self):
     # Collision traverser
     self.traverser = CollisionTraverser("traverser")
     # Collision handler
     self.handler = CollisionHandlerQueue()
     # Initialize and set up picker ray node and NodePath
     self.picker = CollisionNode("mouse_ray")
     self.pickerNP = self.camera.attachNewNode(self.picker)
     self.picker.setFromCollideMask(GeomNode.getDefaultCollideMask())
     self.picker_ray = CollisionRay()
     self.picker.addSolid(self.picker_ray)
     self.traverser.addCollider(self.pickerNP, self.handler)
     mark_color = (1, 1, 1, 0.3)
     self.base_mark = self.create_mark(color=mark_color)
     connector_color = (1, 1, 1, 1)
     self.base_connector = self.create_connector(color=connector_color)
Ejemplo n.º 16
0
 def __init__(self, base):
     self.base = base
     if settings.mouse_over:
         taskMgr.add(self.mouse_task, 'mouse-task')
     self.picker = CollisionTraverser()
     self.pq = CollisionHandlerQueue()
     self.pickerNode = CollisionNode('mouseRay')
     self.pickerNP = self.base.cam.attachNewNode(self.pickerNode)
     self.pickerNode.setFromCollideMask(
         CollisionNode.getDefaultCollideMask()
         | GeomNode.getDefaultCollideMask())
     self.pickerRay = CollisionRay()
     self.pickerNode.addSolid(self.pickerRay)
     self.picker.addCollider(self.pickerNP, self.pq)
     #self.picker.showCollisions(render)
     self.over = None
Ejemplo n.º 17
0
 def set_clickable(self, clickable):
     self.clickable = clickable
     if self.use_collision_solid and self.collision_solid is not None:
         if clickable:
             self.collision_solid.node().setIntoCollideMask(
                 CollisionNode.getDefaultCollideMask())
         else:
             self.collision_solid.node().setIntoCollideMask(
                 BitMask32.all_off())
         #The instance itself is not clickable
         self.instance.setCollideMask(BitMask32.all_off())
     else:
         if clickable:
             self.instance.setCollideMask(GeomNode.getDefaultCollideMask())
         else:
             self.instance.setCollideMask(BitMask32.all_off())
Ejemplo n.º 18
0
	def setupMouseCollision(self):

		self.mClicker = CollisionTraverser()          
		self.mCollisionQue    = CollisionHandlerQueue()

		self.mClickRay = CollisionRay()
		self.mClickRay.setOrigin(self.camera.getPos(self.render))
		self.mClickRay.setDirection(render.getRelativeVector(camera, Vec3(0,1,0)))

		self.mClickNode = CollisionNode('clickRay')
		self.mClickNode.addSolid(self.mClickRay)

		self.mClickNP = self.camera.attachNewNode(self.mClickNode)

		self.mClickNode.setFromCollideMask(GeomNode.getDefaultCollideMask())

		self.mClicker.addCollider(self.mClickNP, self.mCollisionQue)
Ejemplo n.º 19
0
 def create_instance(self):
     if not self.orbit:
         return
     self.vertexData = GeomVertexData('vertexData',
                                      GeomVertexFormat.getV3(),
                                      Geom.UHStatic)
     self.vertexWriter = GeomVertexWriter(self.vertexData, 'vertex')
     delta = self.body.parent.get_local_position()
     for i in range(self.nbOfPoints):
         time = self.orbit.period / self.nbOfPoints * i
         pos = self.orbit.get_position_at(time)
         rot = self.orbit.get_rotation_at(time)
         pos = self.orbit.frame.get_local_position(rot.xform(pos)) - delta
         self.vertexWriter.addData3f(*pos)
     self.lines = GeomLines(Geom.UHStatic)
     for i in range(self.nbOfPoints - 1):
         self.lines.addVertex(i)
         self.lines.addVertex(i + 1)
         self.lines.closePrimitive()
     self.lines.addVertex(self.nbOfPoints - 1)
     self.lines.addVertex(0)
     self.lines.closePrimitive()
     self.geom = Geom(self.vertexData)
     self.geom.addPrimitive(self.lines)
     self.node = GeomNode(self.body.get_ascii_name() + '-orbit')
     self.node.addGeom(self.geom)
     self.instance = NodePath(self.node)
     self.instance.setRenderModeThickness(settings.orbit_thickness)
     self.instance.setCollideMask(GeomNode.getDefaultCollideMask())
     self.instance.node().setPythonTag('owner', self)
     self.instance.reparentTo(self.context.annotation_shader)
     if self.color is None:
         self.color = self.parent.get_orbit_color()
     self.instance.setColor(self.color * self.fade)
     self.instance.setAntialias(AntialiasAttrib.MMultisample)
     self.appearance = ModelAppearance(attribute_color=True)
     if settings.use_inv_scaling:
         vertex_control = LargeObjectVertexControl()
     else:
         vertex_control = None
     self.instance_ready = True
     self.shader = BasicShader(lighting_model=FlatLightingModel(),
                               vertex_control=vertex_control)
     self.shader.apply(self, self.appearance)
     self.shader.update(self, self.appearance)
Ejemplo n.º 20
0
    def setupMouseCollision(self):

        self.mClicker = CollisionTraverser()
        self.mCollisionQue = CollisionHandlerQueue()

        self.mClickRay = CollisionRay()
        self.mClickRay.setOrigin(self.camera.getPos(self.render))
        self.mClickRay.setDirection(
            render.getRelativeVector(camera, Vec3(0, 1, 0)))

        self.mClickNode = CollisionNode('clickRay')
        self.mClickNode.addSolid(self.mClickRay)

        self.mClickNP = self.camera.attachNewNode(self.mClickNode)

        self.mClickNode.setFromCollideMask(GeomNode.getDefaultCollideMask())

        self.mClicker.addCollider(self.mClickNP, self.mCollisionQue)
Ejemplo n.º 21
0
    def __init__(self,
                 use_sprites=True,
                 use_sizes=True,
                 points_size=2,
                 sprite=None,
                 background=None,
                 shader=None):
        self.gnode = GeomNode('starfield')
        self.use_sprites = use_sprites
        self.use_sizes = use_sizes
        self.background = background
        if shader is None:
            shader = BasicShader(lighting_model=FlatLightingModel(),
                                 point_shader=False)
        self.shader = shader

        self.reset()

        self.geom = self.makeGeom([], [], [])
        self.gnode.addGeom(self.geom)
        self.instance = NodePath(self.gnode)
        if self.use_sprites:
            if sprite is None:
                sprite = RoundDiskPointSprite()
            self.sprite = sprite
        else:
            self.sprite = SimplePoint(points_size)
        self.min_size = self.sprite.get_min_size()
        self.sprite.apply(self.instance)
        self.instance.setCollideMask(GeomNode.getDefaultCollideMask())
        self.instance.node().setPythonTag('owner', self)
        #TODO: Should not use ModelAppearance !
        self.appearance = ModelAppearance(vertex_color=True)
        if self.appearance is not None:
            self.appearance.bake()
            self.appearance.apply(self, self)
        if self.shader is not None:
            self.shader.apply(self, self.appearance)
        if self.use_sprites:
            self.instance.node().setBounds(OmniBoundingVolume())
            self.instance.node().setFinal(True)
        if self.background is not None:
            self.instance.setBin('background', self.background)
        self.instance.set_depth_write(False)
Ejemplo n.º 22
0
    def __init__(self, topNode, cameraObject = None):
        self.traverser = CollisionTraverser()
        self.handler = CollisionHandlerQueue()
        self.topNode = topNode
        self.cam = cameraObject

        pickerNode  = CollisionNode('MouseRay')

        #NEEDS to be set to global camera. boo hoo
        self.pickerNP = base.camera.attachNewNode(pickerNode)

        # this seems to enter the bowels of the node graph, making it
        # difficult to perform logic on
        pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask())

        self.pickRay = CollisionRay()
        #pickerNode.setCollideMask(BitMask32.allOff())
        pickerNode.addSolid(self.pickRay)
        self.traverser.addCollider(self.pickerNP, self.handler)
Ejemplo n.º 23
0
 def setUpMouseCollider(self):
     # clicking on objects stuff came from here:
     # https://www.panda3d.org/manual/index.php/Collision_Traversers
     # https://www.panda3d.org/manual/index.php/Collision_Handlers
     # will not use the traverser set up by car because slow
     # instead we will render each time clicked
     self.mouseCollideTrav = CollisionTraverser("mouseTraverse")
     self.mousehandler = CollisionHandlerQueue()
     # edit this so that from Object is the camera
     # self.mouseCollideTrav.addCollider(fromObject, queue)
     # self.mouseCollideTrav.traverse(render)
     # this next part came from:
     # https://www.panda3d.org/manual/index.php/Clicking_on_3D_Objects
     pickerNode = CollisionNode("mouseRay")
     pickerNp = camera.attachNewNode(pickerNode)
     pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
     self.pickerRay = CollisionRay()
     pickerNode.addSolid(self.pickerRay)
     self.mouseCollideTrav.addCollider(pickerNp, self.mousehandler)
Ejemplo n.º 24
0
 def create_instance(self):
     self.vertexData = GeomVertexData('vertexData', GeomVertexFormat.getV3(), Geom.UHStatic)
     self.vertexWriter = GeomVertexWriter(self.vertexData, 'vertex')
     delta = self.body.parent.get_local_position()
     if self.orbit.is_periodic():
         epoch = self.context.time.time_full - self.orbit.period / 2
         step = self.orbit.period / (self.nbOfPoints - 1)
     else:
         #TODO: Properly calculate orbit start and end time
         epoch = self.orbit.get_time_of_perihelion() - self.orbit.period * 5.0
         step = self.orbit.period * 10.0 / (self.nbOfPoints - 1)
     for i in range(self.nbOfPoints):
         time = epoch + step * i
         pos = self.orbit.get_position_at(time) - delta
         self.vertexWriter.addData3f(*pos)
     self.lines = GeomLines(Geom.UHStatic)
     for i in range(self.nbOfPoints-1):
         self.lines.addVertex(i)
         self.lines.addVertex(i+1)
     if self.orbit.is_periodic() and self.orbit.is_closed():
         self.lines.addVertex(self.nbOfPoints-1)
         self.lines.addVertex(0)
     self.geom = Geom(self.vertexData)
     self.geom.addPrimitive(self.lines)
     self.node = GeomNode(self.body.get_ascii_name() + '-orbit')
     self.node.addGeom(self.geom)
     self.instance = NodePath(self.node)
     self.instance.setRenderModeThickness(settings.orbit_thickness)
     self.instance.setCollideMask(GeomNode.getDefaultCollideMask())
     self.instance.node().setPythonTag('owner', self)
     self.instance.reparentTo(self.context.annotation)
     if self.color is None:
         self.color = self.parent.get_orbit_color()
     self.instance.setColor(srgb_to_linear(self.color * self.fade))
     self.instance_ready = True
     if self.shader is None:
         self.create_shader()
     self.shader.apply(self, self.appearance)
     self.shader.update(self, self.appearance)
Ejemplo n.º 25
0
    def cameraview(self):
        """
        Cameraview
        """
        # Create picker Node and CollisionRay
        self.pickerNode = CollisionNode('mouseRay')
        self.pickerNP = camera.attachNewNode(self.pickerNode)
        self.pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
        self.pickerRay = CollisionRay()
        self.pickerNode.addSolid(self.pickerRay)

        # Create Collision Traverser and Queue
        self.cameraPickingTraverser = CollisionTraverser('Camera Picking Traverser')
        self.cameraPickingQueue = CollisionHandlerQueue()

        # Link Picker Node to Traverser and Queue
        self.cameraPickingTraverser.addCollider(self.pickerNP, self.cameraPickingQueue)

        # Set tags on Earth and Moon to be pickable

        # Add text to display the camera position
        self.text = OnscreenText(text = "Help: h", pos = (-1.3, .95-.05), fg=(1,1,1,1),align = TextNode.ALeft, scale = .05, mayChange = 1)
        """ self.displayCameraDistanceText = self.genLabelText("Camera distance : " + str(self.cameraDistance * self.planeten[0][1]) + " m", 0)
Ejemplo n.º 26
0
    def __init__(self):
        ShowBase.__init__(self);
        
        # setup the environment or model
        self.model = \
            self.loader.loadModel("/Developer/Panda3D/models/box.egg.pz");
        self.model.reparentTo(self.render);
        self.model.setTag('Model', '1');
        self.model.setScale(1.5, 1.5, 1.5);
        
        # setup camera
        self.camera.setPos(5,5,5)
        self.camera.lookAt(0,0,0)
        
        # Disable mouse control
        self.disableMouse();
        
        # Handle mouse events.
        self.accept('mouse1', self.mouse_down);
        
        # convert image from opencv to panda3d texture
#         self.taskMgr.add(self.read_image_cv, "cvImageTask");
        
        # Setup collision handler
        self.handler = CollisionHandlerQueue()
        self.traverser = CollisionTraverser('ColTraverser')
        self.traverser.traverse(self.model)
        self.ray = CollisionRay()
        pickerNode = CollisionNode('MouseRay')
        pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
        pickerNP = self.camera.attachNewNode(pickerNode)
        pickerNode.addSolid(self.ray)
        self.traverser.addCollider(pickerNP, self.handler)
        
        self.load_shader();
        
        self.first_frame_loaded = False;
    def __init__(self):
        ShowBase.__init__(self);
        
        # setup the environment or model
        self.model = \
            self.loader.loadModel("/usr/share/panda3d/models/box");
        self.model.reparentTo(self.render);
        self.model.setTag('Model', '1');
        self.model.setScale(1.5, 1.5, 1.5);
        
        # setup camera
        self.camera.setPos(5,5,5)
        self.camera.lookAt(0,0,0)
        
        # Disable mouse control
        self.disableMouse();
        
        # Handle mouse events.
        self.accept('mouse1', self.mouse_down);
        
        # convert image from opencv to panda3d texture
#         self.taskMgr.add(self.read_image_cv, "cvImageTask");
        
        # Setup collision handler
        self.handler = CollisionHandlerQueue()
        self.traverser = CollisionTraverser('ColTraverser')
        self.traverser.traverse(self.model)
        self.ray = CollisionRay()
        pickerNode = CollisionNode('MouseRay')
        pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
        pickerNP = self.camera.attachNewNode(pickerNode)
        pickerNode.addSolid(self.ray)
        self.traverser.addCollider(pickerNP, self.handler)
        
        self.load_shader();
        
        self.first_frame_loaded = False;
Ejemplo n.º 28
0
    def __init__(self):
        ShowBase.__init__(self)

        self.scene = self.loader.loadModel("models/test.egg")
        self.scene.reparentTo(self.render)
        self.scene.setScale(1, 3, 1)
        # self.scene.setPos(0, 1000, 0)
        sphere = CollisionSphere(0, 0, 0, 50)
        cnode = self.scene.attachNewNode(CollisionNode('cnode_scene'))
        cnode.node().addSolid(sphere)
        # cnode.show()

        base.setBackgroundColor(0, 0.0, 0)

        base.disableMouse()
        props = WindowProperties()
        props.setCursorHidden(True)
        base.win.requestProperties(props)
        OnscreenText(text='.', pos=(0, 0, 0))

        plight = PointLight('plight')
        plight.setColor(VBase4(2, 2, 2, 1))
        plnp = self.render.attachNewNode(plight)
        plnp.setPos(0, 0, 100)
        self.render.setLight(plnp)

        # dummy node for camera, attach player to it
        self.camparent = self.render.attachNewNode('camparent')
        self.camparent.reparentTo(self.render)  # inherit transforms
        self.camparent.setEffect(CompassEffect.make(
            self.render))  # NOT inherit rotation
        self.camparent.setY(-1000)
        self.camparent.setZ(200)

        # the camera
        base.camera.reparentTo(self.camparent)
        base.camera.lookAt(self.camparent)
        base.camera.setY(0)  # camera distance from model

        self.heading = 0
        self.pitch = 0

        self.taskMgr.add(self.cameraTask, 'cameraTask')

        self.keyMap = {"left": 0, "right": 0, "forward": 0, "reverse": 0}

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", True])
        self.accept("arrow_right", self.setKey, ["right", True])
        self.accept("arrow_up", self.setKey, ["forward", True])
        self.accept("arrow_down", self.setKey, ["reverse", True])
        self.accept("w", self.setKey, ["forward", True])
        self.accept("a", self.setKey, ["left", True])
        self.accept("s", self.setKey, ["reverse", True])
        self.accept("d", self.setKey, ["right", True])
        self.accept("arrow_left-up", self.setKey, ["left", False])
        self.accept("arrow_right-up", self.setKey, ["right", False])
        self.accept("arrow_up-up", self.setKey, ["forward", False])
        self.accept("arrow_down-up", self.setKey, ["reverse", False])
        self.accept("w-up", self.setKey, ["forward", False])
        self.accept("a-up", self.setKey, ["left", False])
        self.accept("s-up", self.setKey, ["reverse", False])
        self.accept("d-up", self.setKey, ["right", False])
        self.accept('mouse1', self.myFunction)

        self.textObject = None

        db = TinyDB('paintings/db.json')
        self.descriptions = dict()

        base.cTrav = CollisionTraverser()

        pickerNode = CollisionNode('mouseRay')
        pickerNP = self.camera.attachNewNode(pickerNode)
        pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
        self.pickerRay = CollisionRay()
        pickerNode.addSolid(self.pickerRay)
        self.queue = CollisionHandlerQueue()
        base.cTrav.addCollider(pickerNP, self.queue)

        id = 0
        for item in db.all():
            self.addImage('paintings/' + item['img'], id=id)
            self.descriptions[id] = item['name']
            id += 1
Ejemplo n.º 29
0
    def entity_select(self):
        if self.panda3d.mouseWatcherNode.hasMouse():
            """traverser = CollisionTraverser("")
            #traverser.show_collisions(render)
            picker_ray = CollisionRay()
            handler = CollisionHandlerQueue()

            picker_node = CollisionNode('mouseRay')
            picker_np = self.panda3d.camera.attachNewNode(picker_node)
            picker_node.setFromCollideMask(GeomNode.getDefaultCollideMask())
            picker_ray = CollisionRay()
            picker_node.addSolid(picker_ray)
            traverser.addCollider(picker_np, handler)

            picker_node.setFromCollideMask(GeomNode.getDefaultCollideMask())
            mpos = self.panda3d.mouseWatcherNode.getMouse()
            picker_ray.setFromLens(self.panda3d.camNode, mpos.getX(), mpos.getY())
            traverser.traverse(self.panda3d.render)"""


            self.picker_node.setFromCollideMask(GeomNode.getDefaultCollideMask())
            mpos = self.panda3d.mouseWatcherNode.getMouse()
            self.picker_ray.setFromLens(self.panda3d.camNode, mpos.getX(), mpos.getY())
            self.traverser.traverse(self.panda3d.render)
            handler = self.handler

            # Assume for simplicity's sake that myHandler is a CollisionHandlerQueue.
            btn = self.panda3d.mouseWatcherNode

            if handler.getNumEntries() > 0:
                # This is so we get the closest object.
                handler.sortEntries()

                entity = handler.getEntry(0).getIntoNodePath()
                entity = entity.findNetTag('entity_id')
                if not entity.isEmpty():

                    #print("entity selected: {}".format(entity.getTag("entity_id")))

                    entity_id = entity.getTag("entity_id")
                    entity_type = entity.getTag("entity_type")
                    #print(entity_type)
                    model = app.model_reg

                    category_type = model.get(entity_type, dict())
                    entity = category_type.get(entity_id, None)


                    #print(entity)
                    if btn.isButtonDown("mouse1"):
                        entity.on_click()
                        if entity.is_editable:
                            prop_editor = app.main_ui.prop_editor
                            prop_editor.entity_read(entity)
                    elif entity.is_selectable:
                        status_bar = app.main_ui.status_bar
                        status_bar.entity_read(entity)

                else:
                    print("Hay {} entidades bajo el mouse".format(handler.getNumEntries()))
            else:
                if btn.isButtonDown("mouse1"):
                    entities = app.model_reg.get("View", {})

                    if entities is None or len(entities) is 0:
                        View()

                    entities = app.model_reg.get("View")
                    entity = list(entities.values())[0]
                    prop_editor = app.main_ui.prop_editor

                    prop_editor.entity_read(entity)
                else:
                    status_bar = app.main_ui.status_bar
                    status_bar.entity_read()
Ejemplo n.º 30
0
    def __init__(self, panda3d):
        # Inicialización de variables
        self.winsize = [0, 0]
        self.panda3d = panda3d
        self.panda3d.mouse_on_workspace = False

        # Desabilita el comportamiento por defecto de la camara
        self.panda3d.disable_mouse()

        # Llama a la función self.window_rezise_event cuando la ventana cambia de tamaño
        self.accept('window-event', self.window_rezise_event)
        # self.panda3d.accept('aspectRatioChanged', lambda: print("ss"))
        # Creamos el punto donde se centrará la cámara
        target_pos = Point3(0., 0., 0.)

        self.panda3d.cam_target = self.panda3d.render.attach_new_node("camera_target")
        self.panda3d.cam_target.set_pos(target_pos)
        self.panda3d.camera.reparent_to(self.panda3d.cam_target)
        self.panda3d.camera.set_y(-50.)
        
        # Definimos la cambinación de teclas para el control de la camara
        self.camera_active = False

        self.orbit_mouse_btn = "mouse2"
        self.orbit_keyboard_btn = "shift"
        self.orbit_mouse_reference = None
        self.orbit_camera_reference = None

        self.pan_mouse_btn = "mouse2"
        self.pan_keyboard_btn = "mouse2"
        self.pan_mouse_reference = None
        self.pan_camera_reference = None

        self.zoom_mouse_btn = "mouse2"
        self.zoom_keyboard_btn = "control"
        self.zoom_mouse_reference = None
        self.zoom_camera_reference = None

        # Establecemos los valores máximos y minimos para el zoom
        
        self.max_zoom = 10
        self.min_zoom = 0.1
        
        # Creamos la tarea de control de la camara
        self.panda3d.task_mgr.add(self.camera_control_task, "camera_control")

        # El movimiento de la rueda del mouse controla el zoom
        self.panda3d.accept("wheel_up", self.zoom_in)
        self.panda3d.accept("wheel_down", self.zoom_out)

        # Una fución de prueba para comprobar la posición del mouse en el modelo 3d
        # self.panda3d.accept("mouse1", self.entity_select)

        # Se establece la lente ortografica en lugar de la perspectiva
        self.lens_type = "OrthographicLens"
        self.set_lens(self.lens_type)

        # Agrega un indicador de ejes en la esquina inferior izquierda
        self.corner = self.panda3d.camera.attachNewNode("corner of screen")
        # self.axis = self.panda3d.loader.loadModel("data/geom/custom-axis")
        # self.axis = self.panda3d.loader.loadModel("data/geom/view_gizmo_F")
        self.view_gizmo = list()
        self.view_gizmo.append(self.panda3d.loader.loadModel("data/geom/view_gizmo_compass"))

        # self.view_gizmo.append(self.panda3d.loader.loadModel("data/geom/view_gizmo_L"))
        # self.view_cube = ViewGizmoZone()
        # self.view_cube.set_geom(self.axis)

        for gizmo_geom in self.view_gizmo:
            gizmo_geom.setLightOff(1)
            # gizmo_geom.setColorScale(1,1,1,1)
            gizmo_geom.setShaderInput("colorborders", LVecBase4(0, 0, 0, 0.25))

            gizmo = ViewGizmoZone()
            gizmo.set_geom(gizmo_geom)
            gizmo_geom.node().setBounds(BoundingSphere(Point3(0, 0, 0), 10))
            gizmo_geom.node().setFinal(True)

            #gizmo_geom.showTightBounds()
            # gizmo_geom.showBounds()



        self.show_view_gizmo()

        # Agregamos una luz puntual en la ubicación de la camara
        plight = DirectionalLight("camera_light")
        plight.setColor((1, 1, 1, 1))
        #plight.setAttenuation((1, 0, 0))
        #print("getMaxDistance {}".format(plight.getMaxDistance()))
        self.panda3d.plight_node = self.panda3d.render.attach_new_node(plight)
        self.panda3d.plight_node.setPos(0, -50, 0)
        self.panda3d.render.setLight(self.panda3d.plight_node)
        self.panda3d.plight_node.reparentTo(self.panda3d.camera)



        # Agregamos luz ambiental que disminuya las zonas oscuras
        alight = AmbientLight('alight')
        alight.setColor((0.3, 0.3, 0.3, 1))

        alnp = self.panda3d.render.attachNewNode(alight)
        self.panda3d.render.setLight(alnp)

        #def init_select_detection(self):
        self.traverser = CollisionTraverser("")
        # self.traverser.show_collisions(self.panda3d.render)
        self.picker_ray = CollisionRay()
        self.handler = CollisionHandlerQueue()

        self.picker_node = CollisionNode('mouseRay')
        self.picker_np = self.panda3d.camera.attachNewNode(self.picker_node)
        self.picker_node.setFromCollideMask(GeomNode.getDefaultCollideMask())
        self.picker_ray = CollisionRay()
        self.picker_node.addSolid(self.picker_ray)
        self.traverser.addCollider(self.picker_np, self.handler)
Ejemplo n.º 31
0
class Game(ShowBase):
    def __init__(self, level, controls):
        super().__init__()

        self.set_background_color(33/255, 46/255, 56/255)

        # set up timing system
        self.timeline = Timeline()
        self.last_time = 0.0

        def extract_tile_id(filename, flags, tileset):
            def inner(rect, flags):
                x, y, w, h = rect
                return x // w + y // h * tileset.columns
            return inner

        tile_list = tiles(self)
        tiled_map = TiledMap(level, image_loader=extract_tile_id)
        level = self.render.attach_new_node("level")
        width = tiled_map.width
        height = tiled_map.height * 3**0.5 / 2
        level.set_pos(width / 2, -height / 2, 0)

        def get_track(x, y):
            for i, layer in enumerate(tiled_map):
                tile = tile_list.get(tiled_map.get_tile_image(x, y, i))
                if isinstance(tile, Track):
                    return tile
            return None

        z = {}
        for layer in tiled_map:
            for x, y, tile_id in layer.tiles():
                if (tile_type := tile_list.get(tile_id)) is not None:
                    tile = level.attach_new_node("tile")
                    tile.set_pos(*from_hex(x, y), z.get((x, y), 0))
                    z[(x, y)] = z.get((x, y), 0) + tile_type.height
                    tile_type.instance_to(tile)
                    tile_type.register(tile, self.timeline, x, y, get_track)

        # use antialiasing
        self.render.set_antialias(AntialiasAttrib.MMultisample)

        # position camera
        self.camera.set_pos(0, 8, 8)
        self.camera.look_at(0, 0, 0)
        self.disable_mouse()

        # create a light
        ambient = ambient_light(colour=(.3, .3, .3, 1))
        ambient = self.render.attach_new_node(ambient)
        self.render.set_light(ambient)

        # create another light
        directional = directional_light(
            colour=(1, 1, 1, 1), direction=(-1, -2, -3))
        directional = self.render.attach_new_node(directional)
        self.render.set_light(directional)
        # load control scheme from file
        self.load_controls(controls)
        self.task_mgr.add(self.loop, 'loop')

        # create a ui
        tile_tray = OnscreenImage(image='data/black.png',
            pos=(0, 0, -1.66), color=(0, 0, 0, .3), parent=self.render2d)
        tile_tray.setTransparency(TransparencyAttrib.MAlpha)

        thumbs = ['straight_thumb.png',
                  'straight_thumb.png',
                  'curved_thumb.png']

        for n, thumb in enumerate(thumbs):
            _thumb = OnscreenImage(image='data/' + thumb,
                pos=((n+1)*2/(len(thumbs) + 1) - 1, 0, -.82),
                scale=.15, parent=self.aspect2d)
            _thumb.setTransparency(TransparencyAttrib.MAlpha)

        selected_track = None

        myHandler = CollisionHandlerQueue()
        myTraverser = CollisionTraverser('traverser')
        pickerNode = CollisionNode('mouseRay')
        pickerNP = self.camera.attachNewNode(pickerNode)
        pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
        pickerRay = CollisionRay()
        pickerNode.addSolid(pickerRay)
        myTraverser.addCollider(pickerNP, myHandler)

        def handle_mouse_move():
            mpos = self.mouseWatcherNode.getMouse()
            pickerRay.setFromLens(self.camNode, mpos.getX(), mpos.getY())
            myTraverser.traverse(self.render)

            if myHandler.getNumEntries() > 0:
                myHandler.sortEntries()
                pickedObj = myHandler.getEntry(0).getIntoNodePath()
                if not pickedObj.isEmpty():
                    tile = pickedObj.parent.parent.parent
                    x, y, z = tile.get_pos()
                    print(to_hex(x, y))

        def handle_mouse_click():
            mpos = self.mouseWatcherNode.getMouse()
            if mpos.y < -2/3:
                for n, thumb in enumerate(thumbs):
                    scale, aspect_ratio = .15, 16/9
                    x, y = (n+1)*2/(len(thumbs) + 1) - 1, -.82
                    if -scale < x - mpos.x*aspect_ratio < scale:
                        if thumbs[n] == 'straight_thumb.png':
                            tile_id = 0
                        elif thumbs[n] == 'curved_thumb.png':
                            tile_id = 1
                        tile_type = tile_list.get(tile_id))
                        tile = level.attach_new_node("tile")
                        tile.set_pos(*from_hex(x, y), z.get((x, y), 0))
                        z[(x, y)] = z.get((x, y), 0) + tile_type.height
                        tile_type.instance_to(tile)
                        tile_type.register(tile, self.timeline, x, y, get_track)

        self.handle_mouse_move = handle_mouse_move
        self.handle_mouse_click = handle_mouse_click
Ejemplo n.º 32
0
# -*- coding: utf-8 -*-

from panda3d.core import BitMask32, GeomNode

LEVELMODEL = 'models/room1'
AZERTY = True
JUMP_FORCE = 25
GRAVITY = 15
RUN_SPEED = 25
PLAYER_TO_FLOOR_TOLERANCE = .3
PLAYER_TO_FLOOR_TOLERANCE_FOR_REJUMP = 1
ORANGE = (242/255., 181/255., 75/255.,1)
BLUE = (89/255.,100/255.,122/255.,1)

COLLISIONMASKS = {
    'player': BitMask32.bit(1),
    'portals': BitMask32.bit(2),
    'mouseRay': BitMask32.bit(3),
    'exit': BitMask32.bit(4),
    'lava': BitMask32.bit(5),
    'geometry': GeomNode.getDefaultCollideMask(),
}

TEXTURES = {}
Ejemplo n.º 33
0
__author__ = 'Lab Hatter'
from panda3d.core import BitMask32, GeomNode


COLLISIONMASKS = {'grabber': BitMask32(1<<31), 'default': GeomNode.getDefaultCollideMask()}
Ejemplo n.º 34
0
    def __init__(self):

        # The standard camera, light and background initialization
        base.setBackgroundColor(0, 0, 0)
        base.disableMouse()
        self.cam_ctrl = CameraController()
        self.cam_ctrl.reset()
        alight = AmbientLight('alight')
        alight.setColor((0.2, 0.2, 0.2, 1))
        alnp = render.attachNewNode(alight)
        render.setLight(alnp)

        # The global variables we use to control the speed and size of objects
        self.yearscale = 900
        self.dayscale = self.yearscale / 365.0 * 30
        self.yearCounter = 0
        self.dayCounter = 0
        self.money = 2000
        self.system_population = 0
        self.orbitscale = 10
        self.sizescale = 0.6

        # Global game balance variables
        self.population_time_delta = 3
        self.tax_factor = 0.1
        self.salvage_factor = 0.75
        self.food_consuming_factor = 0.75
        self.goods_cap = 1000

        self.PlanetInfoModeOn = False
        self.capitalPlanet = None

        self.galaxy_objects = []
        self.BuildingsDB = {}  # Will contain all buildable structures

        # Everything that's needed to detect selecting objects with mouse
        self.pickerNode = CollisionNode('mouseRay')
        self.pickerNP = camera.attachNewNode(self.pickerNode)
        self.pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
        self.pickerRay = CollisionRay()
        self.pickerNode.addSolid(self.pickerRay)
        self.collQueue = CollisionHandlerQueue()
        base.cTrav = CollisionTraverser('myTraverser')
        base.cTrav.addCollider(self.pickerNP, self.collQueue)

        # Set up the start screen
        self.create_gui()
        self.NewPlanetInfoView = PlanetInfoView(self)
        self.NewPlanetBuildView = PlanetBuildView(self)

        self.load_planets()
        self.rotate_planets()
        self.BuildingsDB = buildingsDB.loadDB()
        self.set_capital_planet()

        # Add all constantly running checks to the taskmanager
        taskMgr.add(self.redraw_head_gui, "redrawHeadGUITask")
        taskMgr.doMethodLater(self.population_time_delta,
                              self.populate_planet_task,
                              'populatePlanetTask',
                              extraArgs=[self.Earth],
                              appendTask=True)
        taskMgr.doMethodLater(2, self.generate_money_task, 'generateMoneyTask')

        # Open up all listeners for varous mouse and keyboard inputs
        self.accept("escape", sys.exit)
        self.accept('mouse1', self.handle_mouse_click)
Ejemplo n.º 35
0
    def initialize(self):
        """Reset everything except LevitorNP and selected, also called inside __init__"""
        self.notify = DirectNotify().newCategory('grabberErr')
        self.currPlaneColNorm = Vec3(0.0)
        self.isCameraControlOn = False
        self.isDragging = False
        self.isMultiselect = False
        self.grabScaleFactor = .075
        self.currTransformDir = Point3(0.0)
        self.interFrameMousePosition = Point3(0.0)
        self.init3DemVal = Point3(0.0)
        # initCommVal holds the value before a command operation has taken place
        self.initialCommandTrgVal = None
        # To load the grabber model, this climbs up the absolute path to /barebones/ to gain access to the model folder
        self.grabModelNP = loader.loadModel(Filename.fromOsSpecific(
                                            ntpath.split( ntpath.split(inspect.stack()[0][1])[0] )[0])
                                            + '/EditorModels/widget')
        self.grabModelNP.setPos(0.0, 0.0, 0.0)
        self.grabModelNP.setBin("fixed", 40)
        self.grabModelNP.setDepthTest(False)
        self.grabModelNP.setDepthWrite(False)
        self.transformOpEnum = Enum('rot, scale, trans')
        self.currTransformOperation = None
        # TODO For readability, use this enum in the nested if/else as was the original intent.
        self.grabInd = Enum('xRot, yRot, zRot, xScaler, yScaler, zScaler, xTrans, yTrans, zTrans, xyTrans, xzTrans, zyTrans, grabCore')
        grbrNodLst = [self.grabModelNP.find("**/XRotator;+h-s-i"),       # 0
                       self.grabModelNP.find("**/YRotator;+h-s-i"),      # 1
                       self.grabModelNP.find("**/ZRotator;+h-s-i"),      # 2 end rotate
                       self.grabModelNP.find("**/XScaler;+h-s-i"),       # 3
                       self.grabModelNP.find("**/YScaler;+h-s-i"),       # 4
                       self.grabModelNP.find("**/ZScaler;+h-s-i"),       # 5 end scale
                       self.grabModelNP.find("**/XTranslator;+h-s-i"),   # 6
                       self.grabModelNP.find("**/YTranslator;+h-s-i"),   # 7
                       self.grabModelNP.find("**/ZTranslator;+h-s-i"),   # 8 end translate / end single dir operations
                       self.grabModelNP.find("**/XYTranslator;+h-s-i"),  # 9
                       self.grabModelNP.find("**/XZTranslator;+h-s-i"),  # 10
                       self.grabModelNP.find("**/ZYTranslator;+h-s-i"),  # 11 end bi-directional operations
                       self.grabModelNP.find("**/WidgetCore;+h-s-i")]    # 12
        #Mat4.yToZUpMat()  # change coordinate to z up
        grbrNodLst[12].getParent().setHprScale(0, 0, 0, 1, 1, -1)
        self.grabModelNP.setPythonTag('grabberRoot', grbrNodLst)
        self.grabModelNP.reparentTo(BBGlobalVars.bareBonesObj.levitorNP)
        self.grabModelNP.hide()
        #self.grabIntoBitMask = COLLISIONMASKS
        self.grabModelNP.setCollideMask(COLLISIONMASKS['default'])
        self.grabModelNP.setPythonTag('grabber', self)

        ##############################################################################
        # This whole section is the basics for setting up mouse selection
        # --The mouse events are added in the events section (next)

        # Create the collision node for the picker ray to add traverser as a 'from' collider
        self.grabberColNode = CollisionNode('grabberMouseRay')
        # Set the collision bitmask
        # TODO: define collision bitmask (let user define thiers? likely not)
        self.defaultBitMask = GeomNode.getDefaultCollideMask()
        self.grabberColNode.setFromCollideMask(self.defaultBitMask)
        self.grabberRayColNP = camera.attachNewNode(self.grabberColNode)
        # Create the grabberRay and add it to the picker CollisionNode
        self.grabberRay = CollisionRay(0.0, 0.0, 0.0,
                                       0.0, 1.0, 0.0)
        self.grabberRayNP = self.grabberColNode.addSolid(self.grabberRay)
        # create a collision queue for the traverser
        self.colHandlerQueue = CollisionHandlerQueue()
        # Create collision traverser
        self.colTraverser = CollisionTraverser('grabberTraverser')
        # Set the collision traverser's 'fromObj' and handler
        # e.g. trav.addCollider( fromObj, handler )
        self.colTraverser.addCollider(self.grabberRayColNP, self.colHandlerQueue)


        ############################################################
        # setup event handling with the messenger
        # URGENT remove all of this messenger code throughout Grabber, especially the camera control
        # disable the mouse when the ~ is pressed (w/o shift)
        self.disableCamera()                            # disable camera control by the mouse
        messenger.accept('`', self, self.enableCamera)  # enable camera control when the ~ key is pressed w/o shift
        messenger.accept('`-up', self, self.disableCamera)  # disable camera control when the ~ key is released

        # handle mouse selection/deselection & manipulating the scene
        messenger.accept('mouse1', self, self.handleM1, persistent=1)  # deselect in event handler

        taskMgr.add(self.scaleGrabber, 'scaleGrabber')
Ejemplo n.º 36
0
    def __init__(self, _main):
        self.main = _main

        # Stats
        self.moveSpeed = 8
        self.inventory = []
        self.maxCarryWeight = 20.0 #kg ?
        self.currentInventoryWeight = 0.0

        # Inventory GUI
        self.inventoryGui = Inventory()
        self.inventoryGui.hide()
        self.inventoryActive = False
        self.craftInventory = CraftInventory()
        self.craftInventory.hide()

        # enable movements through the level
        self.keyMap = {"left":0, "right":0, "forward":0, "backward":0}
        self.player = NodePath("Player")#loader.loadModel("smiley")
        self.player.setPos(149.032, 329.324, 11.3384)
        self.player.setH(180)
        self.player.reparentTo(render)

        self.accept("w", self.setKey, ["forward",1])
        self.accept("w-up", self.setKey, ["forward",0])
        self.accept("a", self.setKey, ["left",1])
        self.accept("a-up", self.setKey, ["left",0])
        self.accept("s", self.setKey, ["backward",1])
        self.accept("s-up", self.setKey, ["backward",0])
        self.accept("d", self.setKey, ["right",1])
        self.accept("d-up", self.setKey, ["right",0])
        self.accept("mouse1", self.handleLeftMouse)
        self.accept("i", self.toggleInventory)
        self.accept("c", self.toggleCraftInventory)


        # screen sizes
        self.winXhalf = base.win.getXSize() / 2
        self.winYhalf = base.win.getYSize() / 2

        self.mouseSpeedX = 0.1
        self.mouseSpeedY = 0.1

        camera.setH(180)
        camera.reparentTo(self.player)
        camera.setZ(self.player, 2)
        base.camLens.setFov(75)
        base.camLens.setNear(0.8)

        # Mouse controls
        self.mouseNode = CollisionNode('mouseRay')
        self.mouseNodeNP = camera.attachNewNode(self.mouseNode)
        self.mouseNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
        self.mouseRay = CollisionRay()
        self.mouseNode.addSolid(self.mouseRay)
        self.mouseRayHandler = CollisionHandlerQueue()

        # Collision Traverser
        self.traverser = CollisionTraverser("Player Traverser")
        base.cTrav = self.traverser
        self.traverser.addCollider(self.mouseNodeNP, self.mouseRayHandler)