Ejemplo n.º 1
0
    def position(self, val):
        x, y = val
        lx, ly = self._position
        winx = render.getWindowWidth()
        winy = render.getWindowHeight()

        if self.clipping or render.getFullScreen():
            #Emulate new position
            _position = (lx - winx / 2) + x * winx, (-y * winy +
                                                     winy) + (ly - winy / 2)
            logic.mouse.position = 0.5, 0.5
            x, y = _position

            #Apply filter
            tx, ty = self._last_position
            if abs(tx - x) < 1 and abs(ty - y) < 1: return

            #Do the actual clipping
            if self.clipping: mx, my = self.clipping
            else: mx, my = 0, 0
            winx = render.getWindowWidth()
            winy = render.getWindowHeight()
            if mx > 1 or my > 1:
                raise ValueError(
                    "clipping x and y values must be lower or equal than 1")
            mx, my = mx * winx / 2, my * winy / 2
            if x < mx: x = mx
            if x > winx - mx: x = winx - mx
            if y < my: y = my
            if y > winy - my: y = winy - my
            self._position = x, y
            self._last_position = self._position

        else:
            self._position = x * winx, -y * winy + winy
Ejemplo n.º 2
0
def resizeHandler():
	'''called when the window dimensions change'''
	# init
	if not hasattr(logic, 'screenSizeOld'):
		logic.screenSizeOld = 1

	# update window dimensions
	logic.screenSize = render.getWindowWidth()*render.getWindowHeight()

	# test for resizing
	if logic.screenSize != logic.screenSizeOld:
		'''
		# set size to multiples of 4, needed for screenshot png bug
		newX = int(x//4*4)
		newY = int(y//4*4)

		render.setWindowSize(newX, newY)
		'''

		# remember current setting
		logic.screenSizeOld = logic.screenSize
		logging.info('Window resized to:\t' + str(render.getWindowWidth()) + 'x' + str(render.getWindowHeight()))

		# hackish update
		logic.timeline.viewUpdate()
		logic.gate.viewUpdate()
		logic.mvb.time = logic.mvb.time 	# updates train
Ejemplo n.º 3
0
	def position(self, val):
		x, y = val
		lx, ly = self._position
		winx = render.getWindowWidth()
		winy = render.getWindowHeight()
			
		if self.clipping  or render.getFullScreen():
			#Emulate new position
			_position = (lx-winx/2)+x*winx, (-y*winy + winy)+(ly-winy/2)
			logic.mouse.position = 0.5, 0.5
			x, y = _position
			
			#Apply filter
			tx, ty = self._last_position
			if abs(tx-x) < 1 and abs(ty-y) < 1: return

			#Do the actual clipping
			if self.clipping: mx, my = self.clipping
			else: mx, my = 0, 0
			winx = render.getWindowWidth()
			winy = render.getWindowHeight()
			if mx > 1 or my > 1: raise ValueError("clipping x and y values must be lower or equal than 1")
			mx, my = mx*winx/2, my*winy/2
			if x < mx: x = mx
			if x > winx-mx: x = winx-mx
			if y < my: y = my
			if y > winy-my: y = winy-my
			self._position = x, y
			self._last_position = self._position
		
		else:
			self._position = x*winx, -y*winy + winy
Ejemplo n.º 4
0
def setViewport(cont):
    ''' On Map scene start, enables viewport and sets the viewport 
	coordinates to top right.
	
	Blend: Main.blend / Scene: Minimap / Object: PlayerArrow '''

    # Objects
    own = cont.owner
    camera = own.scene.active_camera

    # Sensors
    sensor = cont.sensors[0]

    sceneNames = [scn.name for scn in bge.logic.getSceneList()]

    ### PROCESS ###
    if sensor.positive and "Game" in sceneNames:

        # Enable viewport use on map camera
        camera.useViewport = True

        # Pre process the viewport pixel coordinates
        left = getWindowWidth() // 2
        bottom = getWindowHeight() // 2
        right = getWindowWidth()
        top = getWindowHeight()

        # Set viewport coordinates
        camera.setViewport(left, bottom, right, top)

        print('Viewport set: \nleft =', left, '| right =', right, '| top =',
              top, '| bottom =', bottom)
Ejemplo n.º 5
0
def resizeHandler():
    '''called when the window dimensions change'''
    # init
    if not hasattr(logic, 'screenSizeOld'):
        logic.screenSizeOld = 1

    # update window dimensions
    logic.screenSize = render.getWindowWidth() * render.getWindowHeight()

    # test for resizing
    if logic.screenSize != logic.screenSizeOld:
        '''
		# set size to multiples of 4, needed for screenshot png bug
		newX = int(x//4*4)
		newY = int(y//4*4)

		render.setWindowSize(newX, newY)
		'''

        # remember current setting
        logic.screenSizeOld = logic.screenSize
        logging.info('Window resized to:\t' + str(render.getWindowWidth()) +
                     'x' + str(render.getWindowHeight()))

        # hackish update
        logic.timeline.viewUpdate()
        logic.gate.viewUpdate()
        logic.mvb.time = logic.mvb.time  # updates train
Ejemplo n.º 6
0
def draw_names():
    # Get font id to use
    font_id = logic.font_id

    # Collect viewport information
    width = render.getWindowWidth()
    height = render.getWindowHeight()

    # Setup the OpenGL matrices
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glPushMatrix()
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)

    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glPushMatrix()
    bgl.glLoadIdentity()

    # Get the camera
    scene = logic.getCurrentScene()
    camera = scene.active_camera

    # draw the name only for objects (not for lamps or camera)
    for object in [
            i for i in scene.objects if i.__class__ == types.KX_GameObject
    ]:
        # Calculate x and y
        screen_coord = camera.getScreenPosition(object)
        x = screen_coord[0] * render.getWindowWidth()
        y = render.getWindowHeight() - (screen_coord[1] *
                                        render.getWindowHeight())

        # Center the x
        text_width, text_height = blf.dimensions(0, object.name)
        x -= text_width / 2

        # Calculate the amount to scale the font
        distance = camera.getDistanceTo(object)

        if FAR - distance > 0:
            scale = (FAR - distance) / FAR
        else:
            scale = 0

        # Only draw if we'll be able to see it
        if scale:
            blf.size(font_id, int(FONT_SIZE * scale), 72)
            blf.position(font_id, x, y, 0)
            blf.draw(font_id, object.name)

    # Reset the matrices
    bgl.glPopMatrix()
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glPopMatrix()
Ejemplo n.º 7
0
def get_aspect_ratio(width_first=True):
    """
    Returns the aspect ratio of the game window, or the window's width / the window's height.
    If width_first is True (default), then it will return the window's height / the window's width.
    :param width_first: Bool - Whether to divide the height by the width.
    :return: Float - The aspect ratio of the window
    """

    if width_first:

        return render.getWindowWidth() / render.getWindowHeight()

    else:

        return render.getWindowHeight() / render.getWindowWidth()
Ejemplo n.º 8
0
def writeMessageOnScreen():
    """write on screen"""
    width = render.getWindowWidth()
    height = render.getWindowHeight()

    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()

    font_id = logic.font_id
    blf.position(font_id, (width * 0.02), (height * 0.05), 0)
    blf.size(font_id, 35, 50)
    bgl.glColor4f(1, 0, 0, 1)
    blf.draw(font_id, "Hello World!")

    bgl.glColor4f(0, 1, 0, 1)
    blf.position(font_id, (width * 0.02), (height * 0.15), 0)
    blf.size(font_id, 25, 50)
    blf.draw(font_id, "Hello World!")

    bgl.glColor4f(0, 0, 1, 1)
    blf.position(font_id, (width * 0.02), (height * 0.20), 0)
    blf.size(font_id, 25, 50)
    blf.draw(font_id, "Hello World!")
    def look(self):
        sense = self.sensitivity
        x = (0.5 - logic.mouse.position[0]) * render.getWindowWidth()
        y = (0.5 - logic.mouse.position[1]) * render.getWindowHeight()
        if abs(x) <= 1.0:
            x = 0.0
        if abs(y) <= 1.0:
            y = 0.0
        x *= sense
        y *= sense

        head = self.head or self
        laxis_z = head.localOrientation.col[2]
        #laxis_z = self.getAxisVect(AXIS_Z)
        angle = acos(laxis_z.dot(AXIS_Z))
        upper_limit = self.upper_limit - 0.01
        lower_limit = self.lower_limit + 0.01
        if angle + y > upper_limit:
            y = upper_limit - angle
        elif angle + y < lower_limit:
            y = lower_limit - angle

        self.applyRotation((0, 0, x), False)
        head.applyRotation((y, 0, 0), True)

        logic.mouse.position = .5, .5
Ejemplo n.º 10
0
    def update(self):
        if len(self.controls.values()) <= 0: return

        width = render.getWindowWidth()
        height = render.getWindowHeight()
        self.window._width = width
        self.window._height = height

        ex = int(logic.mouse.position[0] * width)  # World X
        ey = int(logic.mouse.position[1] * height)  # World Y

        self.mouse["x"] = ex
        self.mouse["y"] = ey

        self.__zorder_update()

        ctrls = sorted(list(self.controls.values()),
                       key=lambda x: x.zorder,
                       reverse=True)
        for c in ctrls:
            c.update()

        if logic.current_hover != None:
            text, timeout = logic.current_hover.toolTipText, logic.current_hover.toolTipTimeOut
            if text != "":
                self.toolTipHnd.text = text
                self.toolTipHnd.timeOut = timeout
                self.toolTipHnd.show(
                    ex - 4, logic.current_hover.bounds[1] +
                    logic.current_hover.bounds[3] + 10)

            logic.current_hover = None
Ejemplo n.º 11
0
 def draw(self):
     width = render.getWindowWidth()
     height = render.getWindowHeight()
     
     # 2D Projection
     bgl.glMatrixMode(bgl.GL_PROJECTION)
     bgl.glLoadIdentity()
     bgl.glOrtho(0, width, height, 0, -1, 1)
     bgl.glMatrixMode(bgl.GL_MODELVIEW)
     bgl.glLoadIdentity()
     
     # 2D Shading
     bgl.glDisable(bgl.GL_CULL_FACE)
     bgl.glDisable(bgl.GL_LIGHTING)
     bgl.glDisable(bgl.GL_DEPTH_TEST)
     bgl.glShadeModel(bgl.GL_SMOOTH)
     
     # Line antialias
     bgl.glEnable(bgl.GL_LINE_SMOOTH)
     bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)
     
     # 2D Blending (Alpha)
     bgl.glEnable(bgl.GL_BLEND)
     bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
     
     if len(self.controls.values()) <= 0: return
     
     ctrls = sorted(self.controls.values(), key=lambda x: x.zorder)
     for c in ctrls:
         c.draw()
Ejemplo n.º 12
0
    def __init__(self, cont):

        self.body = cont.owner
        self.camera_parent = self.body.children[
            'shortcuts_third_person_camera_parent']
        self.camera_parent_rotation = self.camera_parent.localOrientation.copy(
        )

        # Player movement variables
        self.move_speed = 5.0
        self.run_multiplier = 2.0
        self.jump_force = 5.0

        # Mouse variables
        self.mouse_sensitivity = 0.002
        self.mouse_smoothing = 0.5

        # Used for smoothing the mouselook
        self.old_x = 0.0
        self.old_y = 0.0

        # Screen variables used for the mouselook
        self.screen_width = render.getWindowWidth()
        self.screen_height = render.getWindowHeight()
        self.screen_center = (self.screen_width // 2, self.screen_height // 2)

        # Set the mouse position to the center of the screen
        render.setMousePosition(*self.screen_center)

        # logic.mouse.position is incorrect on the first frame. This variable is used to get around that
        self.delay = 0
Ejemplo n.º 13
0
	def clip_start(self, sx, sy, sw, sh):
		try:
			vp = GL.glGetIntegerv(GL_VIEWPORT)
		except:
			vp = [0, 0, render.getWindowWidth(), render.getWindowHeight()]
		if len(self.__clip_stack) > 0:
			px, py, pw, ph = self.__clip_stack[-1]
			minx = max(px, sx)
			maxx = min(px + pw, sx + sw)
			if maxx - minx < 1:
				return False
			
			miny = max(py, sy)
			maxy = min(py + ph, sy + sh)
			if maxy - miny < 1:
				return False

			sx = minx
			sy = miny
			sw = maxx - minx
			sh = max(1, maxy - miny)
		else:
			glEnable(GL_SCISSOR_TEST)
		sx = vp[0] + sx
		sy = vp[1] + (self.output.height - sy - sh)
		self.__clip_stack.append((sx, sy, sw, sh))
		glScissor(int(sx), int(sy), int(sw), int(sh))
		return True
Ejemplo n.º 14
0
    def __init__(self):
        self.height = render.getWindowHeight()
        self.width = render.getWindowWidth()
        self.scale = self.width / self.height

        self.scene_gui = utils.getSceneByName(constant.CORE_SCENE_GUI)
        module.scene_gui = self.scene_gui
        self.camera = self.scene_gui.active_camera
        self.camera_height = self.camera.worldPosition.z - 0.5
        self.cursor = None
        self.cursor_position = None
        self.hitobj = None
        self.hitpoint = None
        self.hitnormal = None
        self.hitpoly = None
        self.hitproperty = ""
        self.hitxray = 0

        #Scale Camera X/Y
        if self.camera:
            self.scx = self.camera.ortho_scale
            self.scy = self.camera.ortho_scale * (self.height / self.width)
            self.camera.frustum_culling = False

        logic.mouse.position = (0.5, 0.5)
Ejemplo n.º 15
0
def enable_full_viewport(cam):
    # cam is blender object
    W = render.getWindowWidth()
    H = render.getWindowHeight()
    cam.setViewport( 0, 0, W, H)
    cam.useViewport = True
    print("Camera {0} is full viewport".format(cam.name))
Ejemplo n.º 16
0
	def __init__(self):
		self.height = render.getWindowHeight()
		self.width = render.getWindowWidth()
		self.scale = self.width / self.height

		self.scene_gui = utils.getSceneByName(constant.CORE_SCENE_GUI)
		module.scene_gui = self.scene_gui
		self.camera = self.scene_gui.active_camera
		self.camera_height = self.camera.worldPosition.z - 0.5
		self.cursor = None
		self.cursor_position = None
		self.hitobj = None
		self.hitpoint = None
		self.hitnormal = None
		self.hitpoly = None
		self.hitproperty =  ""
		self.hitxray = 0

		#Scale Camera X/Y
		if self.camera:
			self.scx = self.camera.ortho_scale
			self.scy = self.camera.ortho_scale * (self.height / self.width)
			self.camera.frustum_culling = False

		logic.mouse.position = (0.5,0.5)
Ejemplo n.º 17
0
    def look(self):
        sense = self.sensitivity
        x = (0.5 - logic.mouse.position[0]) * render.getWindowWidth()
        y = (0.5 - logic.mouse.position[1]) * render.getWindowHeight()
        if abs(x) <= 1.0:
            x = 0.0
        if abs(y) <= 1.0:
            y = 0.0
        x *= sense
        y *= sense

        head = self.head or self
        laxis_z = head.localOrientation.col[2]
        #laxis_z = self.getAxisVect(AXIS_Z)
        angle = acos(laxis_z.dot(AXIS_Z))
        upper_limit = self.upper_limit - 0.01
        lower_limit = self.lower_limit + 0.01
        if angle + y > upper_limit:
            y = upper_limit - angle
        elif angle + y < lower_limit:
            y = lower_limit - angle

        self.applyRotation((0, 0, x), False)
        head.applyRotation((y, 0, 0), True)

        logic.mouse.position = .5, .5
Ejemplo n.º 18
0
def enable_full_viewport(cam):
    # cam is blender object
    W = render.getWindowWidth()
    H = render.getWindowHeight()
    cam.setViewport(0, 0, W, H)
    cam.useViewport = True
    print("Camera {0} is full viewport".format(cam.name))
Ejemplo n.º 19
0
def write():
    """write on screen"""
    # retrieve timer
    global game_timer
    scene = logic.getCurrentScene()
    game_timer = int(active_camera["Timer"])
    catched = bamboo_counter["catched"]
    total = bamboo_counter["total"]
    vortex = panda.power
    width = render.getWindowWidth()
    height = render.getWindowHeight()

    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()
    
    bgl.glColor4f(1, 1, 1, 1)
    
    # BLF drawing routine
    font_id = logic.font_id
    blf.size(font_id, int(18 * (width/dpi) * 0.06), dpi)
    blf.position(font_id, width*0.02, height*0.95, 0)
    if game_timer < 60:
        blf.draw(font_id, "{0} : {1:02d}".format(l_timer,game_timer))
    else:
        blf.draw(font_id, "{0} : {1}:{2:02d}".format(l_timer,game_timer//60,game_timer%60))
    blf.position(font_id, width*0.02, height*0.90, 0)
    blf.draw(font_id, "{0} : {1}".format(l_level, level))
    blf.position(font_id, width*0.02, height*0.85, 0)
    blf.draw(font_id, "{0} : {1} / {2}".format(l_score, catched, total))
    blf.position(font_id, width*0.02, height*0.80, 0)
    blf.draw(font_id, "{0} : {1}".format(l_vortex, vortex))
Ejemplo n.º 20
0
	def __init__(self, path):
		self.worldPosition = [0,0,0]
		self.visible = True
		self.path = path
		self.fullpath = logic.expandPath("//../data/" + path)
		self.texture = texture.ImageFFmpeg(self.fullpath)
		self.clipping = None
		
		self._tex_id = glGenTextures(1)
		self.size = [0, 0]
		bgl.glTexEnvf(bgl.GL_TEXTURE_ENV, bgl.GL_TEXTURE_ENV_MODE, bgl.GL_MODULATE)
		
		self.reload()
		
		self.texco = [(0, 0), (1, 0), (1, 1), (0, 1)]
		self.color = [1, 1, 1, 1]
		
		x = render.getWindowWidth()/2
		y = render.getWindowHeight()/2
		
		size = [50, 50]
		
		width = size[0]
		height = size[1]
		self._size = [width, height]
		
		# The "private" position returned by setter
		self._position = [x, y]
		self._last_position = self._position
		self.calculate_glposition()
		module.scene_gui.post_draw.append(self.draw)
		self.scale = 0.5, 0.5
Ejemplo n.º 21
0
def writeMessageOnScreen():
    """write on screen"""
    width = render.getWindowWidth()
    height = render.getWindowHeight()

    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()

    font_id = logic.font_id
    blf.position(font_id, (width * 0.02), (height * 0.05), 0)
    blf.size(font_id, 35, 50)
    bgl.glColor4f(1, 0, 0, 1)
    blf.draw(font_id, "Hello World!")

    bgl.glColor4f(0, 1, 0, 1)
    blf.position(font_id, (width * 0.02), (height * 0.15), 0)
    blf.size(font_id, 25, 50)
    blf.draw(font_id, "Hello World!")

    bgl.glColor4f(0, 0, 1, 1)
    blf.position(font_id, (width * 0.02), (height * 0.20), 0)
    blf.size(font_id, 25, 50)
    blf.draw(font_id, "Hello World!")
Ejemplo n.º 22
0
 def update_screen_size(self):
     self.W = R.getWindowWidth()
     self.H = R.getWindowHeight()
     self.size = Vector((self.W, self.H))
     self.w = self.W // 2
     self.h = self.H // 2
     self.screen_center = (self.w, self.h)
Ejemplo n.º 23
0
 def update(self):
     if len(self.controls.values()) <= 0: return
     
     width = render.getWindowWidth()
     height = render.getWindowHeight()
     self.window._width = width
     self.window._height = height
     
     ex = int(logic.mouse.position[0] * width)  # World X
     ey = int(logic.mouse.position[1] * height) # World Y
     
     self.mouse["x"] = ex
     self.mouse["y"] = ey
     
     self.__zorder_update()
     
     ctrls = sorted(list(self.controls.values()), key=lambda x: x.zorder, reverse=True)
     for c in ctrls:
         c.update()
     
     if logic.current_hover != None:
         text, timeout = logic.current_hover.toolTipText, logic.current_hover.toolTipTimeOut
         if text != "":
             self.toolTipHnd.text = text
             self.toolTipHnd.timeOut = timeout
             self.toolTipHnd.show(ex-4, logic.current_hover.bounds[1]+logic.current_hover.bounds[3]+10)
         
         logic.current_hover = None
Ejemplo n.º 24
0
def main():
    
    cont = bge.logic.getCurrentController()
    own = cont.owner

    mouse = cont.sensors ["Mouse"]
    rotx = cont.actuators ["RotX"]
    rotz = cont.actuators ["RotZ"]
    
    cont.activate(rotx)
    cont.activate(rotz)
    
    x = render.getWindowWidth()//2
    y = render.getWindowHeight()//2
    
    screen_center = (x,y)
    center = Vector(screen_center)
    mouse_position = Vector(mouse.position)
    
    offset = (mouse_position - center) * -0.002
    
    rotx.dRot = [offset.y, 0, 0]
    rotz.dRot = [0, 0, offset.x]
    
    render.setMousePosition(x,y)
Ejemplo n.º 25
0
	def __init__(self, font, text, size = 16, align = ALIGN_LEFT, position = [0,0,0], rotation = [0,0,0]):
		position = Vector(position)
		self.blur = 0
		self.shadow = False
		self.shadow_blur = 3
		self.shadow_color = (0, 0, 0, 1)
		self.shadow_offset = (1, -1)
		self.wrap = None
		
		self.scene = module.scene_gui
		self._font = font
		self._position = self.ProxyPosition(position)
		self._rotation = self.ProxyRotation(rotation)
		
		self._glposition = [0,0,0]
		self._glscale = None
		self._glunit = render.getWindowWidth()/self.scene.active_camera.ortho_scale
		self._scale = self.ProxyScale([size/100, size/100, size/100])
		self._color = self.ProxyColor([0,0,0,1])
		self._lines = [] #The labels containing child lines on a multiline label.
		
		self.align = align
		self.leading = 1
		self.font = self._font
		self.text = text
		self.visible = True
		self.scene.post_draw.append(self.draw)
		self.middle_height = False
		
		self._lastscale = None
		self._lastorth = self.scene.active_camera.ortho_scale
Ejemplo n.º 26
0
    def __init__(self, path):
        self.worldPosition = [0, 0, 0]
        self.visible = True
        self.path = path
        self.fullpath = logic.expandPath("//../data/" + path)
        self.texture = texture.ImageFFmpeg(self.fullpath)
        self.clipping = None

        self._tex_id = glGenTextures(1)
        self.size = [0, 0]
        bgl.glTexEnvf(bgl.GL_TEXTURE_ENV, bgl.GL_TEXTURE_ENV_MODE,
                      bgl.GL_MODULATE)

        self.reload()

        self.texco = [(0, 0), (1, 0), (1, 1), (0, 1)]
        self.color = [1, 1, 1, 1]

        x = render.getWindowWidth() / 2
        y = render.getWindowHeight() / 2

        size = [50, 50]

        width = size[0]
        height = size[1]
        self._size = [width, height]

        # The "private" position returned by setter
        self._position = [x, y]
        self._last_position = self._position
        self.calculate_glposition()
        module.scene_gui.post_draw.append(self.draw)
        self.scale = 0.5, 0.5
Ejemplo n.º 27
0
 def __define__(self):
     """ You must only import bge modules here """
     from bge import render
     Vignetting.u_resolution = [
         render.getWindowWidth(),
         render.getWindowHeight()
     ]
Ejemplo n.º 28
0
def main(cont):
	global dest, from_quat, slerp_factor, to_quat
	own = cont.owner
	#where we are going
	dest = cam_defualt_pos.worldPosition.copy()
	diff = dest - own.worldPosition.copy()
	#lerping
	if diff.magnitude > 0.1:
		 diff *= 0.025

	if slerp_factor < 1.0:
		slerp_factor += 0.005
		#print ('slerp', slerp_factor)
	
	own.worldPosition += diff
	#slerping rotation
	quatInterpolation = from_quat.slerp(to_quat, slerp_factor)
	own.worldOrientation = quatInterpolation.to_matrix()
	#reached our destination
	if own.worldPosition == dest:
		#own.orientation = cam_defualt_pos.orientation
		logic.sendMessage('player_unfreeze')
		logic.sendMessage('HUD_on')
		render.setMousePosition(int(render.getWindowWidth() / 2), int(render.getWindowHeight() / 2))
		own.state = logic.KX_STATE1
Ejemplo n.º 29
0
 def __init__(self, cont):
     
     self.body = cont.owner
     self.camera = self.body.children['shortcuts_fps_camera']
     
     # Player movement variables
     self.move_speed = 5.0
     self.run_multiplier = 2.0        
     self.jump_force = 5.0
     
     # Mouse variables
     self.mouse_sensitivity = 0.002
     self.mouse_smoothing = 0.5
 
     # Used for smoothing the mouselook
     self.old_x = 0.0
     self.old_y = 0.0
     
     # Screen variables used for the mouselook
     self.screen_width = render.getWindowWidth()
     self.screen_height = render.getWindowHeight()
     self.screen_center = (self.screen_width//2, self.screen_height//2)
     
     # Set the mouse position to the center of the screen
     render.setMousePosition(*self.screen_center) 
     
     # logic.mouse.position is incorrect on the first frame. This variable is used to get around that
     self.delay = 0
Ejemplo n.º 30
0
    def draw(self):
        width = render.getWindowWidth()
        height = render.getWindowHeight()

        # 2D Projection
        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glLoadIdentity()
        bgl.glOrtho(0, width, height, 0, -1, 1)
        bgl.glMatrixMode(bgl.GL_MODELVIEW)
        bgl.glLoadIdentity()

        # 2D Shading
        bgl.glDisable(bgl.GL_CULL_FACE)
        bgl.glDisable(bgl.GL_LIGHTING)
        bgl.glDisable(bgl.GL_DEPTH_TEST)
        bgl.glShadeModel(bgl.GL_SMOOTH)

        # Line antialias
        bgl.glEnable(bgl.GL_LINE_SMOOTH)
        bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)

        # 2D Blending (Alpha)
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)

        if len(self.controls.values()) <= 0: return

        ctrls = sorted(self.controls.values(), key=lambda x: x.zorder)
        for c in ctrls:
            c.draw()
Ejemplo n.º 31
0
def head_control(contr):
    """ Move the target of the head and camera

    Use the movement of the mouse to determine the rotation
    for the human head and camera. """
    # get the object this script is attached to
    human = contr.owner
    scene = logic.getCurrentScene()
    target = scene.objects['Target_Empty']
    POS_EMPTY = scene.objects['POS_EMPTY']
    Head_Empty = scene.objects['Head_Empty']
    right_hand = scene.objects['Hand_Grab.R']
    mmb = contr.sensors['MMB']


    # If the manipulation mode is active, an object is grabbed
    # and the Middle Mouse Button is pressed, do nothing
    if (human['Manipulate'] and right_hand['selected'] != 'None' and
        right_hand['selected'] != '' and mmb.positive):
        return

    if mmb.positive:
        target = scene.objects['IK_Target_Empty.R']

    # Get sensor named Mouse
    mouse = contr.sensors['Mouse']

    if mouse.positive:
        # get width and height of game window
        width = render.getWindowWidth()
        height = render.getWindowHeight()

        # get mouse movement from function
        move = mouse_move(human, mouse, width, height)

        # set mouse sensitivity
        sensitivity = human['Sensitivity']

        # Amount, direction and sensitivity
        left_right = move[0] * sensitivity
        up_down = move[1] * sensitivity

        if not human['FOCUSED']:
            POS_EMPTY.applyRotation([0.0, 0.0, left_right], True)
            if not ((Head_Empty.localOrientation.to_euler()[1] >= 0.7
                     and up_down < 0) or
                    (Head_Empty.localOrientation.to_euler()[1] <= -0.4
                     and up_down > 0)) and not human['Manipulate']:
                # capping the rotation to prevent the camera to be upside down
                if not mmb.positive:
                    Head_Empty.applyRotation([0.0, -up_down, 0.0], True)
                target.applyMovement([0.0, 0.0, up_down], True)
            elif human['Manipulate']:
                Head_Empty.applyRotation([0.0, -up_down, 0.0], True)
                target.applyMovement([0.0, 0.0, up_down], True)

        # Reset mouse position to the centre of the screen
        # Using the '//' operator (floor division) to produce an integer result
        render.setMousePosition(width//2, height//2)
Ejemplo n.º 32
0
def main(cont):
    own = cont.owner

    mousemove = cont.sensors['mousemove']

    cranezrot = cont.actuators['cranezrot']
    crane_move = cont.actuators['crane_move']
    gear_rot = cont.actuators['gear_rot']
    gear_s_rot = cont.actuators['gear_s_rot']

    #set mouse pos
    screenwidth = render.getWindowWidth()
    screenheight = render.getWindowHeight()

    render.setMousePosition(int(screenwidth / 2), int(screenheight / 2))

    crane_tip = cont.sensors['crane_tip'].owner

    if mousemove.positive:
        zmouse = (screenwidth / 2 - mousemove.position[0]) * own['sensitivity']
        ymouse = (screenheight / 2 -
                  mousemove.position[1]) * own['sensitivity']

        own['previousz'] = (own['previousz'] * .8 + zmouse * .2)
        own['previousy'] = (own['previousy'] * .8 + ymouse * .2)

        zmouse = own['previousz']
        #set max speed
        zmouse = max(min(zmouse, .02), -.02)
        ymouse = max(min(ymouse, .06), -.06)

        #restrict crane tip
        #loc = crane_tip.localPosition[0]
        crane_tip.localPosition[0] = max(min(crane_tip.localPosition[0], 5),
                                         -20)
        #restrict crane rotation
        #print (own['start_rot'])
        crane_angle = own.localOrientation.to_euler()
        crane_angle[2] = max(min(crane_angle[2], (own['start_rot'] + 1.4)),
                             (own['start_rot'] - 1.4))

        crane_angle.to_matrix()
        own.localOrientation = crane_angle
        #rotate the crane
        crane_move.dLoc = (ymouse * 8, 0, 0)
        cranezrot.dRot = (0, 0, -zmouse)
        gear_rot.dRot = (0, 0, zmouse * 2.5)
        gear_s_rot.dRot = (0, -zmouse * 2.5, 0)

        cont.activate(gear_rot)
        cont.activate(gear_s_rot)
        cont.activate(cranezrot)
        cont.activate(crane_move)
    else:
        cont.deactivate(gear_rot)
        cont.deactivate(gear_s_rot)
        cont.deactivate(cranezrot)
        cont.deactivate(crane_move)
Ejemplo n.º 33
0
    def showInfo(self, target):
        delaySecond = 0.05
        if time.time() - logic.mvb._hoverTimer < delaySecond:
            return

        size = [80, 40]
        mousex, mousey = logic.gui.mousePos
        if target and (not logic.mvb.playing) and (not logic.mvb.rendering):
            x, y = logic.viewCamObject.getScreenPosition(target)
            y = 1.0 - y
            centerx, centery = [
                int(x * render.getWindowWidth()),
                int(y * render.getWindowHeight())
            ]
            finalx = int(mousex * 0.2 + centerx * 0.8) - int(size[0] / 2)
            finaly = int(mousey * 0.2 + centery * 0.8) + 100

            try:
                mvbobj = logic.mvb.getMVBObject(target)
            except:
                pass  # not a mvb object
            else:
                if mvbobj.chainData:
                    chainName = mvbobj.chainData.full_name()
                    chainDescription = mvbobj.pdbMetaData.chaininfo[
                        mvbobj.chainData.name]
                else:
                    chainName = mvbobj.name
                    chainDescription = "Blobber Geometry"

                def drawLineBright():
                    drawLine(int(mousex), int(mousey),
                             finalx + int(size[0] / 2), finaly,
                             (0.5, 0.5, 0.5, 0.5))

                size[0] = max(80, len(chainDescription) * 7.5) + 20
                size[0] = int(size[0])
                finalx = finalx - size[0] // 2
                self.infoPanel = bgui.Frame(self.gui,
                                            'infoPanel',
                                            size=size,
                                            pos=[finalx, finaly],
                                            border=1,
                                            radius=3,
                                            sub_theme='medOpacityLight',
                                            options=bgui.BGUI_NO_FOCUS)
                bgui.Label(self.infoPanel,
                           'infoName',
                           text=chainName,
                           pos=[0, 21],
                           options=bgui.BGUI_CENTERX)
                bgui.Label(self.infoPanel,
                           'infoDesc',
                           text=chainDescription,
                           pos=[0, 7],
                           sub_theme='blackLabelSmall',
                           options=bgui.BGUI_CENTERX)
                bgui.Custom(self.infoPanel, 'infoLine', func=drawLineBright)
Ejemplo n.º 34
0
def h_draw_text(fid, text, bounds, color, margin=0, font_size=16, text_align=0, vertical_align=0, shadow=False, clip=True):
    text = str(text)
    width = render.getWindowWidth()
    height = render.getWindowHeight()
    
    #bgl.glColor4f(*(1, 0, 0, 1))
    #h_draw_quad_wire(bounds)
    
    if clip:
        h_clip_begin(bounds)
    
    blf.size(fid, font_size, 72)
    if shadow:
        blf.enable(fid, blf.SHADOW)
        blf.shadow(fid, 3, 0.0, 0.0, 0.0, 1.0)
        blf.shadow_offset(fid, 0, -1)
    else:
        blf.disable(fid, blf.SHADOW)
    bgl.glPushMatrix()
    
    # Fix upside-down text =)
    w, h = blf.dimensions(fid, text)
    bgl.glTranslated(0.0, h, 0.0)
    bgl.glScalef(1.0, -1.0, 1.0)
    
    bgl.glColor4f(*color)

    texts = text.split("\n")
    yn = 0
    if vertical_align == 0:
        yn = margin
    elif vertical_align == 1:
        yn = bounds[3]/2-(h*len(texts))/2
    elif vertical_align == 2:
        yn = (bounds[3]-(h*len(texts)))-margin
    for i in range(len(texts)):            
        texts[i] = texts[i].replace("\t", "        ")
        wl, hl = blf.dimensions(fid, texts[i])
        xn = 0
        
        if text_align == 0:
            xn = margin
        elif text_align == 1:
            xn = bounds[2]/2-wl/2
        elif text_align == 2:
            xn = (bounds[2]-wl)-margin
            
        blf.position(fid, bounds[0]+xn, -bounds[1]-(i*h)-yn, 1)
        
        blf.draw(fid, texts[i])
        
    bgl.glScalef(1.0, 1.0, 1.0)
    bgl.glPopMatrix()
    
    if clip:
        h_clip_end()
Ejemplo n.º 35
0
def applyGraphics():
	graphics = logic.globalDict["GRAPHICS"]

	if config.EMBEDDED_FIX == True:
		return

	if SCREENSHOT not in logic.getSceneList()[0].post_draw:
		logic.getSceneList()[0].post_draw.append(SCREENSHOT)

	## RESOLUTION ##
	X = render.getWindowWidth()
	Y = render.getWindowHeight()

	print("GRAPHICS:\n\tResolution", X, Y)

	## DEBUG ##
	debug = graphics["Debug"]
	render.showFramerate(debug[1] and debug[0])
	render.showProfile(debug[2] and debug[0])
	render.showProperties(debug[3] and debug[0])

	## VSYNC ##
	if graphics["Vsync"] == True:
		render.setVsync(render.VSYNC_ON)
		print("\tVsync ON")
	elif graphics["Vsync"] == False:
		render.setVsync(render.VSYNC_OFF)
		print("\tVsync OFF")

	## SHADERS ##
	glsl = ["lights", "shaders", "shadows", "ramps", "extra_textures"]

	for setting in glsl:
		render.setGLSLMaterialSetting(setting, True)

	if graphics["Shaders"] == "LOW":
		for setting in glsl:
			render.setGLSLMaterialSetting(setting, False)
		render.setAnisotropicFiltering(1)
		print("\tShaders LOW\n\tAnisotrpic OFF\n\tMipmap NEAR")

	elif graphics["Shaders"] == "MEDIUM":
		for setting in glsl:
			if setting == "shaders":
				render.setGLSLMaterialSetting(setting, False)
			else:
				render.setGLSLMaterialSetting(setting, True)
		render.setAnisotropicFiltering(4)
		print("\tShaders MED\n\tAnisotrpic x4\n\tMipmap NEAR")

	elif graphics["Shaders"] == "HIGH":
		for setting in glsl:
			render.setGLSLMaterialSetting(setting, True)
		render.setAnisotropicFiltering(16)
		render.setMipmapping(2)
		print("\tShaders HIGH\n\tAnisotrpic x16\n\tMipmap FAR")
Ejemplo n.º 36
0
def enable_half_viewport(cam1, cam2):
    # cam1 and 2 are blender objects
    W = render.getWindowWidth()
    H = render.getWindowHeight()
    B = int(H / 2)
    cam1.setViewport(0, 0, W, B)
    cam1.useViewport = True
    cam2.setViewport(0, B, W, H)
    cam2.useViewport = True
    print("Cameras {0} and {1} are half viewport".format(cam1.name, cam2.name))
Ejemplo n.º 37
0
 def edge_scroll(self, scene, cam, mouse_pos):
     """Detect if mouse is close to the screen edge
     and if so, move the camera."""
     if mouse_pos.position[0] <= 5:
         self.move_cam(scene, cam, 1)
         if mouse_pos.position[0] < 0:
             render.setMousePosition(2, mouse_pos.position[1])
     elif mouse_pos.position[1] <= 5:
         self.move_cam(scene, cam, 2)
         if mouse_pos.position[1] < 0:
             render.setMousePosition(mouse_pos.position[0], 2)
     elif mouse_pos.position[0] >= render.getWindowWidth() - 5:
         self.move_cam(scene, cam, 3)
         if mouse_pos.position[0] > render.getWindowWidth():
             render.setMousePosition(render.getWindowWidth(), mouse_pos.position[1] - 2)
     elif mouse_pos.position[1] >= render.getWindowHeight() - 5:
         self.move_cam(scene, cam, 4)
         if mouse_pos.position[1] > render.getWindowHeight():
             render.setMousePosition(mouse_pos.position[0], render.getWindowHeight() - 2)
Ejemplo n.º 38
0
def enable_half_viewport(cam1, cam2):
    # cam1 and 2 are blender objects
    W = render.getWindowWidth()
    H = render.getWindowHeight()
    B = int(H/2)
    cam1.setViewport( 0, 0, W, B)
    cam1.useViewport = True
    cam2.setViewport( 0, B, W, H)
    cam2.useViewport = True
    print("Cameras {0} and {1} are half viewport".format(cam1.name, cam2.name))
Ejemplo n.º 39
0
    def draw(self):
        if self.visible == False: return

        module.post_draw_step += 1

        height = render.getWindowHeight()
        width = render.getWindowWidth()

        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glLoadIdentity()
        bgl.gluOrtho2D(0, width, 0, height)
        bgl.glMatrixMode(bgl.GL_MODELVIEW)
        bgl.glLoadIdentity()

        # Enable textures
        bgl.glEnable(bgl.GL_TEXTURE_2D)

        # Enable alpha blending
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
        bgl.glAlphaFunc(bgl.GL_SRC_ALPHA, 1)

        # Bind the texture
        bgl.glBindTexture(bgl.GL_TEXTURE_2D, self._tex_id)

        # Fix position
        w, h = self._size
        bgl.glTranslatef(0, -h, 1)

        #MipLevel
        bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_BASE_LEVEL, 0)
        bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MAX_LEVEL, 0)
        bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MIN_FILTER,
                            bgl.GL_LINEAR)
        bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MAG_FILTER,
                            bgl.GL_LINEAR)

        # Draw the textured quad
        bgl.glColor4f(*self.color)

        bgl.glBegin(bgl.GL_QUADS)
        self.calculate_glposition()
        for i in range(4):
            bgl.glTexCoord2f(self.texco[i][0], self.texco[i][1])
            bgl.glVertex2f(self.gl_position[i][0], self.gl_position[i][1])
        bgl.glEnd()

        bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)

        bgl.glDisable(bgl.GL_BLEND)
        bgl.glDisable(bgl.GL_TEXTURE_2D)

        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glPopMatrix()
        bgl.glMatrixMode(bgl.GL_MODELVIEW)
Ejemplo n.º 40
0
def main(cont):
	own = cont.owner
	
	mousemove = cont.sensors['mousemove']

	cranezrot = cont.actuators['cranezrot']
	crane_move = cont.actuators['crane_move']
	gear_rot = cont.actuators['gear_rot']
	gear_s_rot = cont.actuators['gear_s_rot']

	#set mouse pos
	screenwidth = render.getWindowWidth()
	screenheight = render.getWindowHeight()

	render.setMousePosition(int(screenwidth/2), int(screenheight/2))
	
	crane_tip = cont.sensors['crane_tip'].owner

	if mousemove.positive:
		zmouse = (screenwidth/2 - mousemove.position[0]) * own['sensitivity']
		ymouse = (screenheight / 2 - mousemove.position[1]) * own['sensitivity']
		
		own['previousz'] = (own['previousz'] * .8 + zmouse * .2)
		own['previousy'] = (own['previousy'] * .8 + ymouse * .2)
		
		zmouse = own['previousz']
		#set max speed
		zmouse = max(min(zmouse, .02), -.02)
		ymouse = max(min(ymouse, .06), -.06)
		
		#restrict crane tip
		#loc = crane_tip.localPosition[0]
		crane_tip.localPosition[0] = max(min(crane_tip.localPosition[0], 5), -20)
		#restrict crane rotation
		#print (own['start_rot'])
		crane_angle = own.localOrientation.to_euler()
		crane_angle[2] = max(min(crane_angle[2], (own['start_rot'] + 1.4)), (own['start_rot'] - 1.4))
		
		crane_angle.to_matrix()
		own.localOrientation = crane_angle
		#rotate the crane
		crane_move.dLoc =(ymouse *8, 0, 0)
		cranezrot.dRot =(0, 0, -zmouse)
		gear_rot.dRot =(0, 0, zmouse *2.5)
		gear_s_rot.dRot =(0, -zmouse *2.5, 0)

		cont.activate(gear_rot)
		cont.activate(gear_s_rot)
		cont.activate(cranezrot)
		cont.activate(crane_move)
	else:
		cont.deactivate(gear_rot)
		cont.deactivate(gear_s_rot)
		cont.deactivate(cranezrot)
		cont.deactivate(crane_move)
Ejemplo n.º 41
0
    def centerOnScreen(self, vertical=True, horizontal=True):
        # Since self.parent has a layout, you can't do this.
        if self.parent is not None:
            return
        if horizontal:
            w = render.getWindowWidth()
            self.x = w / 2 - self.width / 2

        if vertical:
            h = render.getWindowHeight()
            self.y = h / 2 - self.height / 2
Ejemplo n.º 42
0
	def centerOnScreen(self, vertical=True, horizontal=True):
		# Since self.parent has a layout, you can't do this.
		if self.parent is not None:
			return
		if horizontal:
			w = render.getWindowWidth()
			self.x = w / 2 - self.width / 2

		if vertical:
			h = render.getWindowHeight()
			self.y = h / 2 - self.height / 2
Ejemplo n.º 43
0
	def secondary_update(self):
		scene_game = module.scene_game
		if not scene_game: return
		x, y = logic.mouse.position
		gcam = scene_game.active_camera
		cx, cy, cz = gcam.position
		if gcam.perspective:
			lens = gcam.lens
			vec = gcam.getScreenVect(x, y)
			vec.negate()
			vec = vec + gcam.position
			self.hitobj, self.hitpoint, self.hitnormal, self.hitpoly = gcam.rayCast(vec, gcam, gcam.far, self.hitproperty, 0, self.hitxray, 1)

		elif render.getWindowWidth() != 0:
			#Needs revision, rotation doesn't work
			scx = gcam.ortho_scale
			scy = gcam.ortho_scale * render.getWindowHeight()/render.getWindowWidth()

			to = [(x-0.5)*scx + cx, (-y+0.5)*scy + cy, 0]
			self.hitobj, self.hitpoint, self.hitnormal = gcam.rayCast(to, (to[0], to[1], gcam.position.z), gcam.far, self.hitproperty, 0, self.hitxray)
Ejemplo n.º 44
0
def rotate(contr):
    """ Read the movements of the mouse and apply them
        as a rotation to the camera. """
    # get the object this script is attached to
    camera = contr.owner

    scene = logic.getCurrentScene()
    if not scene:
        # not ready, main reload(blenderapi)
        return

    # Do not move the camera if the current view is using another camera
    if camera != scene.active_camera:
        return
    camera = scene.cameras["BodyCam"]
    # Get sensor named Mouse
    mouse = contr.sensors['Mouse']
    # Get Blender keyboard sensor

    # Show the cursor
    mouse_visible = True

    # Hide the cursor while we control the camera
    mouse_visible = False
    if mouse.positive:
        # get width and height of game window
        width = render.getWindowWidth()
        height = render.getWindowHeight()

        # get mouse movement from function
        move = mouse_move(camera, mouse, width, height)

        # set mouse sensitivity
        sensitivity = 0.003  # camera['Sensitivity']
        print(camera.localOrientation)
        # Amount, direction and sensitivity
        leftRight = move[0] * sensitivity
        upDown = move[1] * sensitivity

        print(upDown, leftRight)
        # set the values
        camera.localOrientation = Euler((upDown, 0.0, leftRight), 'XYZ')
        print(Euler((upDown, 0.0, leftRight), 'XYZ'))

        # Center mouse in game window
        # Using the '//' operator (floor division) to produce an integer result

        render.setMousePosition(width // 2, height // 2)

    # Show the cursor
    mouse_visible = True

    # Set the cursor visibility
    render.showMouse(mouse_visible)
Ejemplo n.º 45
0
def activate_mouse():
	cont = logic.getCurrentController()
	own = cont.owner
	mPosi = cont.sensors['MousePosi']

	if own['init']:
	    render.setMousePosition( render.getWindowWidth() // 2, render.getWindowHeight() // 2 )
	    own['init'] = 0
	    
	### move cursor to mouse position
	own.localPosition = mPosi.raySource
Ejemplo n.º 46
0
	def draw(self):
		if self.visible == False: return
		
		module.post_draw_step += 1
		
		height = render.getWindowHeight()
		width = render.getWindowWidth()
	
		bgl.glMatrixMode(bgl.GL_PROJECTION)
		bgl.glLoadIdentity()
		bgl.gluOrtho2D(0, width, 0, height)
		bgl.glMatrixMode(bgl.GL_MODELVIEW)
		bgl.glLoadIdentity()
	
		# Enable textures
		bgl.glEnable(bgl.GL_TEXTURE_2D)

		# Enable alpha blending
		bgl.glEnable(bgl.GL_BLEND)
		bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
		bgl.glAlphaFunc(bgl.GL_SRC_ALPHA, 1)

		# Bind the texture
		bgl.glBindTexture(bgl.GL_TEXTURE_2D, self._tex_id)

		# Fix position
		w, h = self._size
		bgl.glTranslatef(0, -h, 1)

		#MipLevel
		bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_BASE_LEVEL, 0);
		bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MAX_LEVEL, 0);
		bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MIN_FILTER, bgl.GL_LINEAR);
		bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MAG_FILTER, bgl.GL_LINEAR);
		
		# Draw the textured quad
		bgl.glColor4f(*self.color)

		bgl.glBegin(bgl.GL_QUADS)
		self.calculate_glposition()
		for i in range(4):
			bgl.glTexCoord2f(self.texco[i][0], self.texco[i][1])
			bgl.glVertex2f(self.gl_position[i][0], self.gl_position[i][1])
		bgl.glEnd()

		bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)
		
		bgl.glDisable(bgl.GL_BLEND)
		bgl.glDisable(bgl.GL_TEXTURE_2D)

		bgl.glMatrixMode(bgl.GL_PROJECTION)
		bgl.glPopMatrix()
		bgl.glMatrixMode(bgl.GL_MODELVIEW)
Ejemplo n.º 47
0
def _mouselook_core(self, id):
    deadzone = 0.001  # used to prevent floating when mouse isn't moving
    screen_x = 0.5 - logic.mouse.position[0]
    if -deadzone < screen_x < deadzone:
        screen_x = 0
    screen_y = 0.5 - logic.mouse.position[1]
    if -deadzone < screen_y < deadzone:
        screen_y = 0

    self.applyRotation([screen_y * sensitivity_x, 0, screen_x * sensitivity_y], True, per_second=True)

    render.setMousePosition(int(render.getWindowWidth() / 2), int(render.getWindowHeight() / 2))
Ejemplo n.º 48
0
def Player():
#T# get the scene from where the module was called
    scene1 = logic.getCurrentScene()

#T# get a particular object in the scene
    scene_obj1 = scene1.objects['Object_name']

#T# get the controller that called the module
    controller1 = logic.getCurrentController()

#T# get the owner of the controller
    object1 = controller1.owner

#T# get a named actuator connected to the controller
    motion = controller1.actuators['motion_actuator_name1']

#T# get a named sensor connected to the controller
    sensor1 = controller1.sensors['sensor_name1']

#T# get the UPBGE window width and height
    win_width1 = render.getWindowWidth()
    win_height1 = render.getWindowHeight()

#T# an enum dictionary with the keyboard keys can be accessed with
    key = logic.keyboard.events

#T# save the value of interesting keys pressed from the keyboard, 0 not pressed, 1 started, 2 hold, 3 released
    kb_left = key[events.LEFTARROWKEY]
    kb_right = key[events.RIGHTARROWKEY]

    x_pos1 = 480
    y_pos1 = 240
#T# set the mouse position
    render.setMousePosition(x_pos1, y_pos1)
    
#T# the Update() function is common and executes in each frame
    def Update():
        movespd = 0.2
        deltaX = 0
        deltaY = 0
        
        if kb_left > 0:
            deltaX += -movespd
        if kb_right > 0:
            deltaX += movespd

#T# change the location
        motion.dLoc = [deltaX, deltaY, 0.0]

#T# activate the actuator connected to the controller
        controller1.activate(motion)
        
    Update()
Ejemplo n.º 49
0
def mouseMove():
    cont = logic.getCurrentController()
    logic.car = cont.owner
    mouse = cont.sensors["Mouse"]

    # Set mouse sensitivity
    sensitivity = 0.07

    h = r.getWindowHeight()//2
    w = r.getWindowWidth()//2
    x = (h - mouse.position[0])*sensitivity
    y = (w - mouse.position[1])*sensitivity

    #  reset mouse for next frame and keep mouse in the game window
    r.setMousePosition(h, w)

    rot = logic.car.localOrientation.to_euler()

    #  Bank / Lean when gliding, but not for car shapes
    if logic.car["onGround"] == False and logic.car["activeShape"] <= 4:
        yaw = math.degrees(rot[2]) + x / 6
        rot[2] = math.radians(yaw)

        roll = math.degrees(rot[1]) + x * -1
        rot[1] = math.radians(roll)

        pitch = math.degrees(rot[0]) + y / 4
        rot[0] = math.radians(pitch)

        #  Apply rotation
        logic.car.localOrientation = rot.to_matrix()

    # Mouse "dead zone" 0.45 to help moving straight
    #  Right
    if x < -0.45:
        #  Turn Wheels
        logic.car["steer"] -= logic.car["steerAmount"] / 2
        if logic.car["onGround"] == False:
            #  Vector thrust to move (and stay in the air)
            logic.car.linearVelocity[0] += logic.car["glideJumpZ"]
            logic.car.linearVelocity[2] += logic.car["glideBonusZ"] / 4
    #  Left
    if x > 0.45:
        #  Turn Wheels
        logic.car["steer"] += logic.car["steerAmount"] / 2
        if logic.car["onGround"] == False:
            #  Vector thrust to move (and stay in the air)
            logic.car.linearVelocity[0] -= logic.car["glideJumpZ"]
            logic.car.linearVelocity[2] += logic.car["glideBonusZ"] / 4


    #  reset mouse for next frame and keep mouse in the game window
    r.setMousePosition(h, w)
Ejemplo n.º 50
0
def enable_stereo_viewport(cam1, cam2):
    '''cam1 and 2 are blender objects'''

    W = render.getWindowWidth()
    H = render.getWindowHeight()
    A = int(W / 2)
    cam1.setViewport(0, 0, A, H)
    cam1.useViewport = True
    cam2.setViewport(A, 0, W, H)
    cam2.useViewport = True
    print("Cameras {0} and {1} are stereo viewport".format(
        cam1.name, cam2.name))
Ejemplo n.º 51
0
def follow_mouse(sensor):

    screen_width = R.getWindowWidth()
    screen_height = R.getWindowHeight()

    win_x, win_y = sensor.position

    x = win_x - screen_width / 2  # / screen_width - 0.5
    y = screen_height / 2 - win_y  # - 0.5 #/ 2#/ screen_height - 0.5

    G.stimLocation = [x, y, G.stim.worldPosition[2]]
    G.holeLocation = [x, y, G.hole.worldPosition[2]]
def main():
    #get screen size
    screen_width = render.getWindowWidth()
    screen_height = render.getWindowHeight()
    #center the mouse
    render.setMousePosition(int(screen_width / 2), int(screen_height / 2))
    #if mouse is moving
    if mouse_move.positive:

        x_mouse = (screen_width / 2 -
                   mouse_move.position[0]) * own['SENSITIVITY']
        y_mouse = (screen_height / 2 -
                   mouse_move.position[1]) * own['SENSITIVITY']

        own['previous_x'] = (own['previous_x'] * .8 + x_mouse * .2)
        own['previous_y'] = (own['previous_y'] * .8 + y_mouse * .2)
        #limit camera rotation
        cam_angle = own.localOrientation.to_euler()
        #print (cam_angle)
        #cam_angle[0] = max(min(cam_angle[0], 0), 3)
        cam_angle.to_matrix()
        own.localOrientation = cam_angle
        #move the camera
        cam_x_rot.dRot = (0, 0, x_mouse)
        cam_y_rot.dRot = (y_mouse, 0, 0)

        cont.activate(cam_x_rot)
        cont.activate(cam_y_rot)
    else:
        cont.deactivate(cam_x_rot)
        cont.deactivate(cam_y_rot)

    #camera lense transition - thanks to YoFrankie
    old_lens = player_camera.lens
    if sintel_col['RUNNING'] == True and sintel_col['MOVING'] == True:
        lens = 22
        own['SENSITIVITY'] = .00075
    if sintel_col['RUNNING'] == True and sintel_col['MOVING'] == False:
        lens = 35
        own['SENSITIVITY'] = .001
    if sintel_col['RUNNING'] == False:
        lens = 35
        own['SENSITIVITY'] = .001
    if lens != old_lens:
        player_camera.lens = (lens * 0.02) + (old_lens * 0.98)

    #camera collision
    if cam_col_check.positive:
        player_camera.worldPosition = cam_col_check.hitPosition
        player_camera.localPosition.y += MARGIN
    else:
        player_camera.worldPosition = cam_col.worldPosition
        player_camera.localPosition.y -= cam_col_check.range - MARGIN
Ejemplo n.º 53
0
    def __init__(self, cont):

        #get Dependencies
        self.cont = cont
        self.camera = cont.owner
        self.mouse = logic.mouse

        x = render.getWindowWidth() // 2
        y = render.getWindowHeight() // 2
        self.screen_center = (x, y)
        render.setMousePosition(x + 1, y + 1)
        #show Mouse
        render.showMouse(1)
Ejemplo n.º 54
0
def show_das_points():
	''' expects that opengl mode is setup corrently '''
	width = render.getWindowWidth()
	height = render.getWindowHeight()

	text = 'Points: '+str(logic.getCurrentScene().objects["PinsRoof"]["points"])

	# BLF drawing routine
	font_id = logic.font_id
	#blf.position(font_id, width - 160, height - 24, 0) 
	blf.position(font_id, width * 0.2, height * 0.2, 0)
	blf.size(font_id, 24, 72)
	blf.draw(font_id, text)
Ejemplo n.º 55
0
def showResidue(mvbObj, loc):
	''' point to the residue in screenspace'''
	mousex, mousey = logic.gui.mousePos
	mousey = render.getWindowHeight() - 180

	finalx,finaly = logic.viewCamObject.getScreenPosition(loc)[:]
	finaly = 1- finaly
	finalx *= render.getWindowWidth()
	finaly *= render.getWindowHeight()

	def drawLineDark():
		drawLine(int(mousex),int(mousey), int(finalx),int(finaly), (0.0, 0.0, 0.0, 0.2))
	bgui.Custom(logic.gui, 'residueInfoLine', func=drawLineDark)
Ejemplo n.º 56
0
def maintain_asr(ratio: float, width=None):
    """
    Sets the window's size to be the width specified and the width divided by the desired aspect ratio as the height.
    You can use this to ensure you maintain a 16:9 view, or 4:3, or whatever ratio you desire.
    :param width:Int - Desired width of the window. If left to None, is left to the current window width.
    :param ratio:Float - Desired aspect ratio to maintain.
    :return:None
    """

    if width is None:
        width = render.getWindowWidth()

    render.setWindowSize(int(width), int(width / ratio))
Ejemplo n.º 57
0
def main():
	#get screen size
	screen_width = render.getWindowWidth()
	screen_height = render.getWindowHeight()
	#center the mouse
	render.setMousePosition(int(screen_width/2), int(screen_height/2))
	#if mouse is moving
	if mouse_move.positive:
		
		x_mouse = (screen_width / 2 - mouse_move.position[0]) * own['SENSITIVITY']
		y_mouse = (screen_height / 2 - mouse_move.position[1]) * own['SENSITIVITY']
		
		own['previous_x'] = (own['previous_x'] * .8 + x_mouse * .2)
		own['previous_y'] = (own['previous_y'] * .8 + y_mouse * .2)
		#limit camera rotation
		cam_angle = own.localOrientation.to_euler()
		#print (cam_angle)
		#cam_angle[0] = max(min(cam_angle[0], 0), 3)
		cam_angle.to_matrix()
		own.localOrientation = cam_angle
		#move the camera
		cam_x_rot.dRot =(0, 0, x_mouse)
		cam_y_rot.dRot =(y_mouse, 0, 0)
			
		cont.activate(cam_x_rot)
		cont.activate(cam_y_rot)
	else:
		cont.deactivate(cam_x_rot)
		cont.deactivate(cam_y_rot)
		
	#camera lense transition - thanks to YoFrankie
	old_lens = player_camera.lens	
	if sintel_col['RUNNING']==True and sintel_col['MOVING'] ==True:
		lens = 22
		own['SENSITIVITY'] = .00075
	if sintel_col['RUNNING']==True and sintel_col['MOVING'] ==False:
		lens = 35
		own['SENSITIVITY'] = .001
	if sintel_col['RUNNING']==False:
		lens = 35
		own['SENSITIVITY'] = .001
	if lens != old_lens:
		player_camera.lens = (lens*0.02) + (old_lens*0.98)
	
	#camera collision
	if cam_col_check.positive:
		player_camera.worldPosition = cam_col_check.hitPosition
		player_camera.localPosition.y += MARGIN
	else:
		player_camera.worldPosition = cam_col.worldPosition
		player_camera.localPosition.y -= cam_col_check.range - MARGIN
Ejemplo n.º 58
0
def init(cont):
	own = cont.owner
	
	try:
		if logic.globalDict['player_hp'] == None:
			logic.globalDict['player_hp'] = 100
	except:
		logic.globalDict['player_hp'] = 100
		
	try:
		logic.loadGlobalDict()
		if logic.globalDict['cfg_UI'] =='Small':
			UI_SCALE = .50
		elif logic.globalDict['cfg_UI'] =='Normal':
			UI_SCALE = .75
		elif logic.globalDict['cfg_UI'] =='Large':
			UI_SCALE = 1
	except:
		print ('No cfg_UI option found')
		UI_SCALE = .75

	#print ('GOT IT')
	screen_width = render.getWindowWidth()
	screen_height = render.getWindowHeight()
	#print (screen_width, screen_height)
	
	HUD_compass.position = mathutils.Vector((5.5, -2.65, 0.0))
	full_hp.position = mathutils.Vector((5.5, -2.65, 0.02))
	
	hp_add.position = mathutils.Vector((5.5, -2.65, 0.01))
	hp_hit.position = mathutils.Vector((5.5, -2.65, 0.01))
	
	HUD_compass.localScale =  mathutils.Vector((UI_SCALE, UI_SCALE, UI_SCALE))
	full_hp.localScale =  mathutils.Vector((UI_SCALE, UI_SCALE, UI_SCALE))
	
	hp_add.localScale =  mathutils.Vector((UI_SCALE, UI_SCALE, UI_SCALE))
	hp_hit.localScale =  mathutils.Vector((UI_SCALE, UI_SCALE, UI_SCALE))
	
	if own['show_hud']:
		HUD_compass.playAction('fade_in', 1, 10, layer=0, play_mode=logic.KX_ACTION_MODE_PLAY, speed = 1)
		full_hp.playAction('fade_in', 1, 10, layer=0, play_mode=logic.KX_ACTION_MODE_PLAY, speed = 1)
	else:
		HUD_compass.playAction('fade_in', 1, 1, layer=0, play_mode=logic.KX_ACTION_MODE_PLAY, speed = 1)
		full_hp.playAction('fade_in', 1, 1, layer=0, play_mode=logic.KX_ACTION_MODE_PLAY, speed = 1)
		
	hp_add.playAction('hp_notify', 30, 30, layer=0, play_mode=logic.KX_ACTION_MODE_PLAY, speed = 1)
	hp_hit.playAction('hp_notify', 30, 30, layer=0, play_mode=logic.KX_ACTION_MODE_PLAY, speed = 1)
	
	HUD_fade.playAction('fade_in', 10, 1, layer=0, play_mode=logic.KX_ACTION_MODE_PLAY, speed = .2)