Exemplo n.º 1
0
    def onMouseMoveTransforming3D(self, vp):
        now = self.getPointOnGizmo()

        gizmoOrigin = self.getGizmoOrigin()
        gizmoDir = self.getGizmoDirection(self.widget.activeAxis.axisIdx)
        ref = Vec3.forward()
        if gizmoDir == ref:
            ref = Vec3.right()

        nowVec = Vec3(now - gizmoOrigin).normalized()
        origVec = Vec3(self.transformStart - gizmoOrigin).normalized()

        axisToHprAxis = {
            0: 1,  # pitch
            1: 2,  # roll
            2: 0  # yaw
        }

        snap = not vp.mouseWatcher.isButtonDown(KeyboardButton.shift())

        origAngle = origVec.signedAngleDeg(
            ref, self.getGizmoDirection(self.widget.activeAxis.axisIdx))
        angle = nowVec.signedAngleDeg(
            ref, self.getGizmoDirection(self.widget.activeAxis.axisIdx))
        hpr = Vec3(0)
        if snap:
            ang = round(-(angle - origAngle) / 15) * 15
        else:
            ang = -(angle - origAngle)
        hpr[axisToHprAxis[self.widget.activeAxis.axisIdx]] = ang
        self.toolVisRoot.setHpr(hpr)
Exemplo n.º 2
0
    def _dragStart(self, nodeFrame, event):
        # Mark this node as selected
        base.messenger.send("selectNode", [
            self, True,
            base.mouseWatcherNode.isButtonDown(KeyboardButton.shift()), True
        ])
        # tell everyone we started to drag this node
        base.messenger.send("dragNodeStart", [self])

        # Remove any previous started drag tasks
        taskMgr.remove("dragNodeDropTask")

        # get some positions
        vWidget2render2d = nodeFrame.getPos(render2d)
        vMouse2render2d = Point3(0)
        if event is not None:
            # we get the mouse position from the event
            vMouse2render2d = Point3(event.getMouse()[0], 0,
                                     event.getMouse()[1])
        else:
            # we try to get the current mouse position from the mouse watcher
            mwn = base.mouseWatcherNode
            if mwn.hasMouse():
                vMouse2render2d = Point3(mwn.getMouse()[0], 0,
                                         mwn.getMouse()[1])
        editVec = Vec3(vWidget2render2d - vMouse2render2d)
        self.hasMoved = False

        # Initiate the task to move the node and pass it some initial values
        t = taskMgr.add(self.dragTask, "dragNodeDropTask")
        t.nodeFrame = nodeFrame
        t.editVec = editVec
        t.mouseVec = vMouse2render2d
Exemplo n.º 3
0
    def mousePressed(self, event):
        print 'got mouse pressed event from', event.sender
        if (not self.enabled
                or event.modifiers.isDown(KeyboardButton.control())):
            print 'short circuiting'
            return

        shiftDown = event.modifiers.isDown(KeyboardButton.shift())
        if event.sender == self.engine:
            if not shiftDown:
                self.deselectAll()
        else:
            self._setEditMode(event.modifiers.isDown(MouseButton.three()))
            node = event.sender
            if shiftDown:
                # Shift-clicking a node toggles its selected state.
                if node.isSelected():
                    self.selection.remove(node)
                    node.setSelected(False)
                else:
                    self.selection.append(node)
                    node.setSelected(True)
            elif len(self.selection) == 1 and node.isSelected():
                # This is already the only node selected.
                return
            else:
                print 'selecting', node
                self.deselectAll()
                node.setSelected(True)
                self.selection.append(node)
        if self.editMode:
            self.handle.setClients([NodePath(n) for n in self.selection],
                                   self.getSelectionCenter())
        else:
            self.handle.setClients([])
Exemplo n.º 4
0
    def mousePressed(self, event):
        print 'got mouse pressed event from', event.sender
        if (not self.enabled or
                event.modifiers.isDown(KeyboardButton.control())):
            print 'short circuiting'
            return

        shiftDown = event.modifiers.isDown(KeyboardButton.shift())
        if event.sender == self.engine:
            if not shiftDown:
                self.deselectAll()
        else: 
            self._setEditMode(event.modifiers.isDown(MouseButton.three()))
            node = event.sender
            if shiftDown:
                # Shift-clicking a node toggles its selected state.
                if node.isSelected():
                    self.selection.remove(node)
                    node.setSelected(False)
                else:
                    self.selection.append(node)
                    node.setSelected(True)
            elif len(self.selection) == 1 and node.isSelected():
                # This is already the only node selected.
                return
            else:
                print 'selecting', node
                self.deselectAll()
                node.setSelected(True)
                self.selection.append(node)
        if self.editMode:
            self.handle.setClients([NodePath(n) for n in self.selection],
                    self.getSelectionCenter())
        else:
            self.handle.setClients([])
Exemplo n.º 5
0
class InputMapperTecladoMouse(InputMapper):

    # teclas accion defecto
    TeclasAccionDefecto = {
        KeyboardButton.enter(): InputMapper.AccionArrojar,
        KeyboardButton.space(): InputMapper.AccionAscender,
        KeyboardButton.tab(): InputMapper.AccionUsar,
        KeyboardButton.control(): InputMapper.AccionAgachar,
        KeyboardButton.alt(): InputMapper.AccionAgarrar,
        KeyboardButton.asciiKey(b"c"): InputMapper.AccionFlotar,
        KeyboardButton.asciiKey(b"x"): InputMapper.AccionSoltar,
        KeyboardButton.asciiKey(b"z"): InputMapper.AccionFrenar,
        KeyboardButton.asciiKey(b"w"): InputMapper.AccionAvanzar,
        KeyboardButton.asciiKey(b"a"): InputMapper.AccionAvanzar,
        KeyboardButton.asciiKey(b"s"): InputMapper.AccionAvanzar,
        KeyboardButton.asciiKey(b"d"): InputMapper.AccionAvanzar,
        KeyboardButton.asciiKey(b"r"): InputMapper.AccionAvanzar,
        KeyboardButton.asciiKey(b"f"): InputMapper.AccionAvanzar
    }

    # teclas parametro defecto
    TeclasParamDefecto = {
        KeyboardButton.asciiKey(b"w"): InputMapper.ParametroAdelante,
        KeyboardButton.asciiKey(b"a"): InputMapper.ParametroIzquierda,
        KeyboardButton.asciiKey(b"s"): InputMapper.ParametroAtras,
        KeyboardButton.asciiKey(b"d"): InputMapper.ParametroDerecha,
        KeyboardButton.asciiKey(b"r"): InputMapper.ParametroArriba,
        KeyboardButton.asciiKey(b"f"): InputMapper.ParametroAbajo,
        KeyboardButton.asciiKey(b"q"):
        InputMapper.ParametroGirando | InputMapper.ParametroIzquierda,
        KeyboardButton.asciiKey(b"e"):
        InputMapper.ParametroGirando | InputMapper.ParametroDerecha,
        KeyboardButton.shift(): InputMapper.ParametroRapido,
        KeyboardButton.asciiKey(b"v"): InputMapper.ParametroLento
    }

    def __init__(self, base):
        InputMapper.__init__(self, base)

    def update(self):
        # parametros
        self.parametros = InputMapper.ParametroNulo
        for tecla, parametro in InputMapperTecladoMouse.TeclasParamDefecto.items(
        ):
            if self.isButtonDown(tecla):
                self.parametros |= parametro
        # acciones
        self.accion = InputMapper.AccionNula
        for tecla, accion in InputMapperTecladoMouse.TeclasAccionDefecto.items(
        ):
            if self.isButtonDown(tecla):
                self.accion = accion
                break
Exemplo n.º 6
0
 def select(self, event):
     modifiers = event.getModifierButtons()
     if modifiers.isDown(KeyboardButton.shift()):
         incr = -1
     else:
         incr = 1
     new_selection = self.current_selection + incr
     if new_selection < 0:
         new_selection = len(self.current_list) - 1
     if new_selection >= len(self.current_list):
         new_selection = 0
     self.current_selection = new_selection
     self.update_suggestions()
Exemplo n.º 7
0
    def _dragStop(self, event=None):
        self.ignore("mouse1-up")
        # remove the node dragging task
        taskMgr.remove("dragNodeDropTask")

        # check if the node has moved
        if not self.hasMoved:
            # we want to select this node as it has not been moved
            base.messenger.send("selectNode", [
                self, True,
                base.mouseWatcherNode.isButtonDown(KeyboardButton.shift())
            ])
        # tell everyone we stopped moving the node
        base.messenger.send("dragNodeStop", [self])
Exemplo n.º 8
0
    def mouseUp(self):
        SelectTool.mouseUp(self)
        if self.widget.activeAxis:
            self.widget.activeAxis.setState(Rollover)

        if self.isTransforming:
            vp = base.viewportMgr.activeViewport
            if vp.mouseWatcher.isButtonDown(KeyboardButton.shift()):
                # Clone when shift is held
                self.onFinishTransformingClone()
            else:
                self.onFinishTransforming()
            self.onTransformDone()
            self.destroyMoveVis()
            base.selectionMgr.updateSelectionBounds()
        self.isTransforming = False
Exemplo n.º 9
0
    def __init__(self, game, character):
        self.game = game
        self.character = character

        # class properties
        self.buttons = {
            "forward": KeyboardButton.ascii_key("w"),
            "backward": KeyboardButton.ascii_key("s"),
            "left": KeyboardButton.ascii_key("a"),
            "right": KeyboardButton.ascii_key("d"),
            "sprint": KeyboardButton.shift(),
        }
        self.moved = False

        # start movement task
        taskMgr.add(self.move, "Player.move")
        taskMgr.doMethodLater(1.0 / Constants.TICKRATE, self.sendLoc, "Player.sendLoc")
Exemplo n.º 10
0
 def defineKeys(self):
     for k in self.keyState.keys():
         self.keyState[k] = False
     if self.isKeyDown(KeyboardButton.up()):
         self.keyState["WalkFw"] = True
     if self.isKeyDown(KeyboardButton.down()):
         self.keyState["WalkBw"] = True
     if self.isKeyDown(KeyboardButton.left()):
         self.keyState["RotateL"] = True
     if self.isKeyDown(KeyboardButton.right()):
         self.keyState["RotateR"] = True
     if self.isKeyDown(KeyboardButton.shift()):
         self.keyState["Run"] = True
     if self.isKeyDown(KeyboardButton.space()):
         self.keyState["Jump"] = True
     if self.isKeyDown(KeyboardButton.asciiKey("d")):
         self.keyState["Duck"] = True
Exemplo n.º 11
0
    def control_camera(self, task):
        theta = self.eye.yaw / 180 * math.pi
        phi = self.eye.pitch / 180 * math.pi
        eye_dir = np.array([
            math.cos(theta) * math.cos(phi),
            math.sin(theta) * math.cos(phi),
            math.sin(phi),
        ])
        up_dir = np.array([0.0, 0.0, 1.0])
        side_dir = np.cross(eye_dir, up_dir)

        # Update camera based on
        move_speed = 10.0 * globalClock.get_dt()
        if base.mouseWatcherNode.is_button_down(KeyboardButton.shift()):
            move_speed *= 10.0
        if base.mouseWatcherNode.is_button_down(KeyboardButton.ascii_key('w')):
            self.eye.pos[:] += move_speed * eye_dir
        if base.mouseWatcherNode.is_button_down(KeyboardButton.ascii_key('s')):
            self.eye.pos[:] -= move_speed * eye_dir
        if base.mouseWatcherNode.is_button_down(KeyboardButton.ascii_key('d')):
            self.eye.pos[:] += move_speed * side_dir
        if base.mouseWatcherNode.is_button_down(KeyboardButton.ascii_key('a')):
            self.eye.pos[:] -= move_speed * side_dir

        if self.capture_mouse:
            view_speed = 10.0 * globalClock.get_dt()
            win_x, win_y = base.win.getXSize(), base.win.getYSize()
            cursor = base.win.getPointer(0)
            dx = cursor.getX() - base.win.getXSize() // 2
            dy = cursor.getY() - base.win.getYSize() // 2
            self.eye.yaw = (self.eye.yaw - view_speed * dx) % 360.0
            self.eye.pitch = min(85.0,
                                 max(-85.0, self.eye.pitch - move_speed * dy))
            base.win.movePointer(0, win_x // 2, win_y // 2)

        self.update_camera()

        return Task.cont
Exemplo n.º 12
0
    def __init__(self, mainWin=base.win, mainCam=base.cam, scene=render):
        self.lastMousePos = Vec2(-2, -2)
        self.lastId = 0
        self.pressedNode = None
        self.mDownId = 0
        self.idStack = range(1, 256)
        self.idTable = {}
        self.aspectRatio = 1
        self.checkCursorTask = Task(self.checkCursor, 'checkCursorTask')
        self.enabled = True
        self.mouseListeners = []

        self.mainCam = mainCam
        mainCam.node().setCameraMask(BitMask32(1))

        tempnode = NodePath(PandaNode('temp node'))
        tempnode.setShaderAuto()
        tempnode.setShaderInput('hi_id', Vec4(0, 0, 0, 0), 2)
        mainCam.node().setInitialState(tempnode.getState())

        # Set up a node with the silhouetteGen shader. We'll apply this node's
        # state to custom cameras below.
        tempnode.setShader(loader.loadShader('silhouetteGen.sha'), 100)
        tempnode.setShaderInput('hi_id', Vec4(0, 0, 0, 0), 0)
        tempnode.setAntialias(AntialiasAttrib.MNone, 100)
        tempnode.setBin('inactive', 0, 1)
        initialState = tempnode.getState()
        tempnode.setBin('opaque', 0, 1)
        selnodeState = tempnode.getState()

        # We'll be using this a few times, so make an easy name for it.
        mainLens = mainCam.node().getLens()

        # Set up a buffer to which we draw a silhouette of any geometry that
        # we want to outline. We draw the outline by applying a Sobel edge
        # detection shader to the contents of this buffer.
        silhouetteBuffer = mainWin.makeTextureBuffer('silhouetteBuffer', 0, 0)
        silhouetteBuffer.setClearColor(Vec4(0, 0, 0, 1))
        self.silhouetteBuffer = silhouetteBuffer
        silhouetteCamera = base.makeCamera(silhouetteBuffer, lens=mainLens)
        silhouetteCamera.node().setScene(scene)
        silhouetteCamera.node().setInitialState(initialState)
        silhouetteCamera.node().setTagState('sel', selnodeState)
        silhouetteCamera.node().setTagStateKey('sel')
        silhouetteCamera.node().setCameraMask(BitMask32(8))

        tempnode.setShader(loader.loadShader('mousePicker.sha'), 100)
        selnodeState = tempnode.getState()
        tempnode.setBin('inactive', 0, 1)
        initialState = tempnode.getState()

        # Set up a 1-by-1 buffer to which we'll just render the pixel under
        # the mouse.
        selectBuffer = mainWin.makeTextureBuffer('selectBuffer', 1, 1)
        selectBuffer.setClearColor(Vec4(0, 0, 0, 1))
        self.selectBuffer = selectBuffer
        selectLens = PerspectiveLens()
        selectLens.setNearFar(mainLens.getNear(), mainLens.getFar())
        selectLens.setFocalLength(mainLens.getFocalLength())
        selectCamera = base.makeCamera(selectBuffer, lens=selectLens)
        selectCamera.node().setScene(scene)
        selectCamera.node().setInitialState(initialState)
        selectCamera.node().setTagState('sel', selnodeState)
        selectCamera.node().setTagStateKey('sel')
        selectCamera.node().setCameraMask(BitMask32(16))
        self.selectLens = selectLens

        self.selectTex = selectBuffer.getTexture()
        self.selectTex.makeRamImage()
        self.gsg = mainWin.getGsg()

        # Set up a texture card to render the silhouette texture with the
        # Sobel shader, which will draw the edges of the silhouettes.
        silhouetteCard = silhouetteBuffer.getTextureCard()
        silhouetteCard.setTransparency(1)
        inkGen = loader.loadShader('sobel.sha')
        silhouetteCard.setShader(inkGen)
        silhouetteCard.setShaderInput('separation', 0.001, 0)
        silhouetteCard.reparentTo(render2d)
        self.silhouetteCard = silhouetteCard

        self.accept(mainWin.getWindowEvent(), self.windowEventHandler)
        self.accept('mouse1', self.mouseDownHandler, ['l'])
        self.accept('mouse1-up', self.mouseUpHandler, ['l'])
        self.accept('mouse3', self.mouseDownHandler, ['r'])
        self.accept('mouse3-up', self.mouseUpHandler, ['r'])
        self.buttonWatcher = ButtonWatcher([
            KeyboardButton.shift(),
            KeyboardButton.control(),
            MouseButton.one(),
            MouseButton.three(),
        ])

        CameraController.getInstance().addEventHandler(EVT_CAMERA_MODE,
                                                       self._cameraModeHandler)

        self.enable(False)
Exemplo n.º 13
0
    def initialize(self):
        self.lens = self.makeLens()
        self.camera = self.doc.render.attachNewNode(
            ModelNode("viewportCameraParent"))
        self.camNode = Camera("viewportCamera")
        self.camNode.setLens(self.lens)
        self.camNode.setCameraMask(self.getViewportMask())
        self.cam = self.camera.attachNewNode(self.camNode)

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

        gsg = self.doc.gsg

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

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

        self.inputDevice = output.getInputDevice(0)

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

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

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

        self.win = output

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

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

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

        self.setupRender2d()
        self.setupCamera2d()

        self.gizmo = ViewportGizmo(self)

        self.doc.viewportMgr.addViewport(self)

        self.makeGrid()
Exemplo n.º 14
0
    def update(self, entities_by_filter):
        for entity in entities_by_filter['character']:
            character = entity[CharacterController]
            character.jumps = False
            character.sprints = False
            character.crouches = False
            character.move.x = 0.0
            character.move.y = 0.0
            character.heading = 0.0
            character.pitch = 0.0
            # For debug purposes, emulate analog stick on keyboard
            # input, being half-way pressed, by holding shift
            analog = 1
            if base.mouseWatcherNode.is_button_down(KeyboardButton.shift()):
                analog = 0.5
            if base.mouseWatcherNode.is_button_down(
                    KeyboardButton.ascii_key("w")):
                character.move.y += analog
            if base.mouseWatcherNode.is_button_down(
                    KeyboardButton.ascii_key("s")):
                character.move.y -= analog
            if base.mouseWatcherNode.is_button_down(
                    KeyboardButton.ascii_key("a")):
                character.move.x -= analog
            if base.mouseWatcherNode.is_button_down(
                    KeyboardButton.ascii_key("d")):
                character.move.x += analog

            # Rotation
            if base.mouseWatcherNode.is_button_down(KeyboardButton.up()):
                character.pitch += 1
            if base.mouseWatcherNode.is_button_down(KeyboardButton.down()):
                character.pitch -= 1
            if base.mouseWatcherNode.is_button_down(KeyboardButton.left()):
                character.heading += 1
            if base.mouseWatcherNode.is_button_down(KeyboardButton.right()):
                character.heading -= 1

            if TurntableCamera in entity:
                camera = entity[TurntableCamera]
                camera.heading = camera.pitch = 0
                if base.mouseWatcherNode.is_button_down(
                        KeyboardButton.ascii_key("j")):
                    camera.heading = 1
                if base.mouseWatcherNode.is_button_down(
                        KeyboardButton.ascii_key("l")):
                    camera.heading = -1
                if base.mouseWatcherNode.is_button_down(
                        KeyboardButton.ascii_key("i")):
                    camera.pitch = -1
                if base.mouseWatcherNode.is_button_down(
                        KeyboardButton.ascii_key("k")):
                    camera.pitch = 1

            # Special movement modes.
            # By default, you run ("sprint"), unless you press e, in
            # which case you walk. You can crouch by pressing q; this
            # overrides walking and running. Jump by pressing space.
            # This logic is implemented by the Walking system. Here,
            # only intention is signalled.
            if base.mouseWatcherNode.is_button_down(
                    KeyboardButton.ascii_key("e")):
                character.sprints = True
            if base.mouseWatcherNode.is_button_down(
                    KeyboardButton.ascii_key("c")):
                character.crouches = True
            if base.mouseWatcherNode.is_button_down(KeyboardButton.space()):
                character.jumps = True
Exemplo n.º 15
0
    def movePlayer(self, player, dt):
        mw = self.base.mouseWatcherNode

        heading = self.headingTurner.getHeading(
        )  # Heading is the roll value for this model
        lookAngle = player.getP()

        # y is forward/back, x is left/right, z is up/down

        curVel = self.getVelocity(player)

        # Accelerate in the direction the player is currently facing
        y = 0
        if self.keys["front"]:
            y = 1
        elif self.keys["back"]:
            y = -1
        x = 0
        if self.keys["strafeLeft"]:
            x = -1
        elif self.keys["strafeRight"]:
            x = 1

        z = 0
        if self.keys["up"]:
            z = 1
        elif self.keys["down"]:
            z = -1

        if mw.isButtonDown(KeyboardButton.shift()):
            x *= 2
            y *= 2

        if self.keys["jump"]:
            if not self.jumping:
                self.jumpTime = 0
                self.jumping = True
                self.jumpZ = 0

        now = globalClock.getFrameTime()
        if x or y:
            if not self.walkCycle:
                self.walkCycle = now

        heading_rad = DEG_TO_RAD * (360 - heading)

        newFwdBack = Vec3(sin(heading_rad) * y, cos(heading_rad) * y, 0)

        if self.flyMode:
            newFwdBack.z = sin(DEG_TO_RAD * lookAngle) * y

        newStrafe = Vec3(-sin(heading_rad - pi / 2) * x,
                         -cos(heading_rad - pi / 2) * x, 0)

        newUpDown = Vec3(0, 0, z)

        newVel = (newFwdBack + newStrafe + newUpDown) * ACCELERATION
        playerVel = (curVel * (STEPS - 1) + newVel) / STEPS

        self.setVelocity(player, playerVel)

        if self.mouseLook and mw.hasMouse():
            x, y = mw.getMouseX(), mw.getMouseY()

            dx, dy = x, y

            self.headingTurner.setTurnRate(math.sin(dx) * -1440)
            #self.headingTurner.setTarget(dx / pi)
            self.lookTurner.setTurnRate(math.sin(dy) * 1440)
            #self.lookTurner.setTarget(y * 90)

            self.lastMouseX, self.lastMouseY = x, y

            if self.mouseGrabbed:
                self.base.win.movePointer(
                    0, int(self.base.win.getProperties().getXSize() / 2),
                    int(self.base.win.getProperties().getYSize() / 2))

        # Change heading if left or right is being pressed
        now = globalClock.getFrameTime()
        if self.keys["turnRight"]:
            self.headingTurner.updateTurn(-1, dt)

        elif self.keys["turnLeft"]:
            self.headingTurner.updateTurn(1, dt)

        elif self.keys["reverse"]:
            self.headingTurner.setTarget(heading + 180)

        elif not self.mouseLook:
            self.headingTurner.unTurn(dt)

        heading = self.headingTurner.update(dt)

        # Adjust view angle

        if self.keys["lookDown"]:
            self.lookTurner.updateTurn(-1, dt)
            self.lookSticky = True
        elif self.keys["lookUp"]:
            self.lookTurner.updateTurn(1, dt)
            self.lookSticky = True
        elif self.keys["lookReset"]:
            self.lookTurner.setTarget(0)
            self.lookSticky = False
        elif not self.mouseLook:
            self.lookTurner.unTurn(dt)

            if self.lookTurner.getTurnRate() == 0:
                if (x or y or self.jumpZ) and not self.mouseLook:
                    self.lookSticky = False

            if not self.lookSticky:
                self.lookTurner.setTarget(0)

        lookAngle = self.lookTurner.update(dt)

        player.setH(heading)

        player.setP(lookAngle)

        # Finally, update the position as with any other object
        self.updatePos(player, now, dt)
Exemplo n.º 16
0
    def movePlayer(self, player, dt):
        mw = self.base.mouseWatcherNode

        heading = self.headingTurner.getHeading()  # Heading is the roll value for this model
        lookAngle = player.getP()

        # y is forward/back, x is left/right, z is up/down 
        
        curVel = self.getVelocity(player)
        
        # Accelerate in the direction the player is currently facing
        y = 0
        if self.keys["front"]:
            y = 1
        elif self.keys["back"]:
            y = -1
        x = 0
        if self.keys["strafeLeft"]:
            x = -1
        elif self.keys["strafeRight"]:
            x = 1
        
        z = 0
        if self.keys["up"]:
            z = 1
        elif self.keys["down"]:
            z = -1
        
        if mw.isButtonDown(KeyboardButton.shift()):
            x *= 2
            y *= 2
            
        if self.keys["jump"]:
            if not self.jumping:
                self.jumpTime = 0
                self.jumping = True
                self.jumpZ = 0

        now = globalClock.getFrameTime() 
        if x or y:
            if not self.walkCycle:
                self.walkCycle = now
            
        heading_rad = DEG_TO_RAD * (360 - heading)
        
        newFwdBack = Vec3(sin(heading_rad)*y, cos(heading_rad) * y, 0)
        
        if self.flyMode:
            newFwdBack.z = sin(DEG_TO_RAD * lookAngle) * y
         
        newStrafe = Vec3(-sin(heading_rad-pi/2) * x, -cos(heading_rad-pi/2)*x, 0)
        
        newUpDown = Vec3(0, 0, z)
        
        newVel = (newFwdBack + newStrafe + newUpDown) * ACCELERATION
        playerVel = (curVel * (STEPS-1) + newVel) / STEPS
        
        self.setVelocity(player, playerVel)
        
        if self.mouseLook and mw.hasMouse():
            x, y = mw.getMouseX(), mw.getMouseY()
            
            dx, dy = x, y
            
            self.headingTurner.setTurnRate(math.sin(dx) * -1440)
            #self.headingTurner.setTarget(dx / pi)
            self.lookTurner.setTurnRate(math.sin(dy) * 1440)
            #self.lookTurner.setTarget(y * 90)
            
            self.lastMouseX, self.lastMouseY = x, y
            
            if self.mouseGrabbed:
                self.base.win.movePointer(0, 
                                      int(self.base.win.getProperties().getXSize() / 2),
                                      int(self.base.win.getProperties().getYSize() / 2))

                
            
        # Change heading if left or right is being pressed
        now = globalClock.getFrameTime()
        if self.keys["turnRight"]:
            self.headingTurner.updateTurn(-1, dt)

        elif self.keys["turnLeft"]:
            self.headingTurner.updateTurn(1, dt)

        elif self.keys["reverse"]:
            self.headingTurner.setTarget(heading + 180)
            
        elif not self.mouseLook:
            self.headingTurner.unTurn(dt)
                
        heading = self.headingTurner.update(dt)
            
        # Adjust view angle
        
        if self.keys["lookDown"]:
            self.lookTurner.updateTurn(-1, dt)
            self.lookSticky = True
        elif self.keys["lookUp"]:
            self.lookTurner.updateTurn(1, dt)
            self.lookSticky = True
        elif self.keys["lookReset"]:
            self.lookTurner.setTarget(0)
            self.lookSticky = False
        elif not self.mouseLook:
            self.lookTurner.unTurn(dt)
    
            if self.lookTurner.getTurnRate() == 0:            
                if (x or y or self.jumpZ) and not self.mouseLook:
                    self.lookSticky = False

            if not self.lookSticky:
                self.lookTurner.setTarget(0)                    
            
        lookAngle = self.lookTurner.update(dt)
            

        player.setH(heading)
        
        player.setP(lookAngle)
        
        
        # Finally, update the position as with any other object
        self.updatePos(player, now, dt)
Exemplo n.º 17
0
    def __init__(self, mainWin=base.win, mainCam=base.cam, scene=render):
        self.lastMousePos = Vec2(-2, -2)
        self.lastId = 0
        self.pressedNode = None
        self.mDownId = 0
        self.idStack = range(1, 256)
        self.idTable = {}
        self.aspectRatio = 1
        self.checkCursorTask = Task(self.checkCursor, 'checkCursorTask')
        self.enabled = True
        self.mouseListeners = []

        self.mainCam = mainCam
        mainCam.node().setCameraMask(BitMask32(1))

        tempnode = NodePath(PandaNode('temp node'))
        tempnode.setShaderAuto()
        tempnode.setShaderInput('hi_id', Vec4(0, 0, 0, 0), 2)
        mainCam.node().setInitialState(tempnode.getState())
        
        # Set up a node with the silhouetteGen shader. We'll apply this node's
        # state to custom cameras below.
        tempnode.setShader(loader.loadShader('silhouetteGen.sha'), 100)
        tempnode.setShaderInput('hi_id', Vec4(0, 0, 0, 0), 0)
        tempnode.setAntialias(AntialiasAttrib.MNone, 100)
        tempnode.setBin('inactive', 0, 1)
        initialState = tempnode.getState()
        tempnode.setBin('opaque', 0, 1)
        selnodeState = tempnode.getState()

        # We'll be using this a few times, so make an easy name for it.
        mainLens = mainCam.node().getLens()

        # Set up a buffer to which we draw a silhouette of any geometry that
        # we want to outline. We draw the outline by applying a Sobel edge
        # detection shader to the contents of this buffer.
        silhouetteBuffer = mainWin.makeTextureBuffer('silhouetteBuffer', 0, 0)
        silhouetteBuffer.setClearColor(Vec4(0, 0, 0, 1))
        self.silhouetteBuffer = silhouetteBuffer
        silhouetteCamera = base.makeCamera(silhouetteBuffer, lens=mainLens)
        silhouetteCamera.node().setScene(scene)
        silhouetteCamera.node().setInitialState(initialState)
        silhouetteCamera.node().setTagState('sel', selnodeState)
        silhouetteCamera.node().setTagStateKey('sel')
        silhouetteCamera.node().setCameraMask(BitMask32(8))

        tempnode.setShader(loader.loadShader('mousePicker.sha'), 100)
        selnodeState = tempnode.getState()
        tempnode.setBin('inactive', 0, 1)
        initialState = tempnode.getState()

        # Set up a 1-by-1 buffer to which we'll just render the pixel under
        # the mouse.
        selectBuffer = mainWin.makeTextureBuffer('selectBuffer', 1, 1)
        selectBuffer.setClearColor(Vec4(0, 0, 0, 1))
        self.selectBuffer = selectBuffer
        selectLens = PerspectiveLens()
        selectLens.setNearFar(mainLens.getNear(), mainLens.getFar())
        selectLens.setFocalLength(mainLens.getFocalLength())
        selectCamera = base.makeCamera(selectBuffer, lens=selectLens)
        selectCamera.node().setScene(scene)
        selectCamera.node().setInitialState(initialState)
        selectCamera.node().setTagState('sel', selnodeState)
        selectCamera.node().setTagStateKey('sel')
        selectCamera.node().setCameraMask(BitMask32(16))
        self.selectLens = selectLens

        self.selectTex = selectBuffer.getTexture()
        self.selectTex.makeRamImage()
        self.gsg = mainWin.getGsg()

        # Set up a texture card to render the silhouette texture with the
        # Sobel shader, which will draw the edges of the silhouettes.
        silhouetteCard = silhouetteBuffer.getTextureCard()
        silhouetteCard.setTransparency(1)
        inkGen = loader.loadShader('sobel.sha')
        silhouetteCard.setShader(inkGen)
        silhouetteCard.setShaderInput('separation', 0.001, 0)
        silhouetteCard.reparentTo(render2d)
        self.silhouetteCard = silhouetteCard
        
        self.accept(mainWin.getWindowEvent(), self.windowEventHandler)
        self.accept('mouse1', self.mouseDownHandler, ['l'])
        self.accept('mouse1-up', self.mouseUpHandler, ['l'])
        self.accept('mouse3', self.mouseDownHandler, ['r'])
        self.accept('mouse3-up', self.mouseUpHandler, ['r'])
        self.buttonWatcher = ButtonWatcher([
                KeyboardButton.shift(),
                KeyboardButton.control(),
                MouseButton.one(),
                MouseButton.three(),
            ])
        
        CameraController.getInstance().addEventHandler(EVT_CAMERA_MODE,
                self._cameraModeHandler)
        
        self.enable(False)