Esempio n. 1
0
 def setFullscreen():
     """Helper function to set the window fullscreen
     with width and height set to the screens size"""
     # set window properties
     # clear all properties not previously set
     base.win.clearRejectedProperties()
     # setup new window properties
     props = WindowProperties()
     # Fullscreen
     props.setFullscreen(True)
     # set the window size to the screen resolution
     props.setSize(self.dispWidth, self.dispHeight)
     # request the new properties
     base.win.requestProperties(props)
     # Set the config variables so we correctly store the
     # new size and fullscreen setting later
     winSize = ConfigVariableString("win-size")
     winSize.setValue("{} {}".format(self.dispWidth, self.dispHeight))
     fullscreen = ConfigVariableBool("fullscreen")
     fullscreen.setValue(True)
     # Render a frame to make sure the fullscreen is applied
     # before we do anything else
     self.taskMgr.step()
     # make sure to propagate the new aspect ratio properly so
     # the GUI and other things will be scaled appropriately
     aspectRatio = self.dispWidth / self.dispHeight
     self.adjustWindowAspectRatio(aspectRatio)
Esempio n. 2
0
 def render(self):
     user32 = ctypes.windll.user32
     screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
     resolution = ConfigVariableString('win-size')
     val = '{0} {1}'.format(*screensize)
     resolution.setValue(val)
     app = ShowBase()
     self.env.render(render, base)
     taskMgr.doMethodLater(0.01, self.update, 'update')
     app.run()
Esempio n. 3
0
    def __init__(self):
        dcFileNames = ['../direct.dc']

        # a distributed object of our game.
        self.distributedObject = None
        self.aiDGameObect = None

        ClientRepository.__init__(
            self,
            dcFileNames = dcFileNames,
            threadedNet = True)

        # Set the same port as configured on the server to be able to connect
        # to it
        tcpPort = ConfigVariableInt('server-port', 4400).getValue()

        # Set the IP or hostname of the server we want to connect to
        hostname = ConfigVariableString('server-host', '127.0.0.1').getValue()

        # Build the URL from the server hostname and port. If your server
        # uses another protocol then http you should change it accordingly.
        # Make sure to pass the connectMethod to the  ClientRepository.__init__
        # call too.  Available connection methods are:
        # self.CM_HTTP, self.CM_NET and self.CM_NATIVE
        self.url = URLSpec('http://{}:{}'.format(hostname, tcpPort))

        # Attempt a connection to the server
        self.connect([self.url],
                     successCallback = self.connectSuccess,
                     failureCallback = self.connectFailure)
Esempio n. 4
0
    def __init__(self):
        """ The AI Repository usually lives on a server and is responsible for
        server side logic that will handle game objects """

        # List of all dc files that are of interest to this AI Repository
        dcFileNames = ['../direct.dc', 'sample.dc']

        # Initialize the repository.  We pass it the dc files and as this is an
        # AI repository the dcSuffix AI.  This will make sure any later calls to
        # createDistributedObject will use the correct version.
        # The connectMethod
        ClientRepository.__init__(self,
                                  dcFileNames=dcFileNames,
                                  dcSuffix='AI',
                                  threadedNet=True)

        # Set the same port as configured on the server to be able to connect
        # to it
        tcpPort = ConfigVariableInt('server-port', 4400).getValue()

        # Set the IP or hostname of the server we want to connect to
        hostname = ConfigVariableString('server-host', '127.0.0.1').getValue()

        # Build the URL from the server hostname and port. If your server
        # doesn't use http you should change it accordingly. Make sure to pass
        # the connectMethod to the  ClientRepository.__init__ call too.
        # Available connection methods are:
        # self.CM_HTTP, self.CM_NET and self.CM_NATIVE
        url = URLSpec('http://{}:{}'.format(hostname, tcpPort))

        # Attempt a connection to the server
        self.connect([url],
                     successCallback=self.connectSuccess,
                     failureCallback=self.connectFailure)
Esempio n. 5
0
    def __init__(self):

        self.hasConfig = False
        # if exist load the config file
        if os.path.exists(prcFile):
            self.hasConfig = True
            loadPrcFile(Filename.fromOsSpecific(prcFile))
        # set the variables using the config files content or set a default value
        self.MOTD = ConfigVariableString('motd',
                                         'Welcome to net_core!').getValue()
        self.HOSTNAME = ConfigVariableString('hostname',
                                             '127.0.0.1').getValue()
        self.TCPPORT = ConfigVariableInt('tcp-port', '6000').getValue()
        self.BACKLOG = ConfigVariableInt('backlog', '10').getValue()
        self.UDPPORT = ConfigVariableInt('udp-port', '6001').getValue()
        self.ISPERSISTENT = ConfigVariableInt('isPersistent', '0').getValue()
Esempio n. 6
0
    def _recompile_pbr(self):
        gles = ConfigVariableString("load-display").getValue()
        if gles == "pandagles2":
            pbr_defines = {
                'MAX_LIGHTS': self.max_lights,
            }
            if self.use_normal_maps:
                pbr_defines['USE_NORMAL_MAP'] = ''
            if self.use_emission_maps:
                pbr_defines['USE_EMISSION_MAP'] = ''
            if self.enable_shadows:
                pbr_defines['ENABLE_SHADOWS'] = ''
            if self.enable_fog:
                pbr_defines['ENABLE_FOG'] = ''
            if self.use_occlusion_maps:
                pbr_defines['USE_OCCLUSION_MAP'] = ''

            pbr_vert_str = _load_shader_str('simplepbr_gles.vert', pbr_defines)
            pbr_frag_str = _load_shader_str('simplepbr_gles.frag', pbr_defines)
            pbrshader = Shader.make(
                Shader.SL_GLSL,
                vertex=pbr_vert_str,
                fragment=pbr_frag_str,
            )
            self.render_node.set_shader(pbrshader)
        else:
            super(OurPipeline, self)._recompile_pbr()
    def setDconfigLevel(self, categoryName):
        """
        Check to see if this category has a dconfig variable
        to set the notify severity and then set that level. You cannot
        set these until config is set.
        """

        # We use ConfigVariableString instead of base.config, in case
        # we're running before ShowBase has finished initializing
        from panda3d.core import ConfigVariableString

        dconfigParam = ("notify-level-" + categoryName)
        cvar = ConfigVariableString(dconfigParam, "")
        level = cvar.getValue()

        if not level:
            # see if there's an override of the default config level
            cvar2 = ConfigVariableString('default-directnotify-level', 'info')
            level = cvar2.getValue()
        if not level:
            level = 'error'

        category = self.getCategory(categoryName)
        # Note - this print statement is making it difficult to
        # achieve "no output unless there's an error" operation - Josh
        # print ("Setting DirectNotify category: " + categoryName +
        #        " to severity: " + level)
        if level == "error":
            category.setWarning(0)
            category.setInfo(0)
            category.setDebug(0)
        elif level == "warning":
            category.setWarning(1)
            category.setInfo(0)
            category.setDebug(0)
        elif level == "info":
            category.setWarning(1)
            category.setInfo(1)
            category.setDebug(0)
        elif level == "debug":
            category.setWarning(1)
            category.setInfo(1)
            category.setDebug(1)
        else:
            print ("DirectNotify: unknown notify level: " + str(level)
                   + " for category: " + str(categoryName))
Esempio n. 8
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.accept('discord-ready', self.on_discord_ready)
        self.accept('discord-disconnect', self.on_discord_disconnect)
        self.userExit = self.showbase_shutdown

        self.application_id = ConfigVariableString('discord-application-id',
                                                   '').value
        self.steam_id = ConfigVariableString('discord-steam-id', '').value
        self.connection = DiscordConnection.get_global_ptr()
        self.connection.connect(self.application_id, self.steam_id)

        self.max_users = ConfigVariableInt('match-max-users', 4).value
        self.current_users = 1

        self.taskMgr.add(self.update_discord_task, 'discord-update-task')

        self.accept('a', self.adjust_users, [1])
        self.accept('z', self.adjust_users, [-1])
 def setDconfigLevel(self, categoryName):
     from panda3d.core import ConfigVariableString
     dconfigParam = 'notify-level-' + categoryName
     cvar = ConfigVariableString(dconfigParam, '')
     level = cvar.getValue()
     if not level:
         cvar2 = ConfigVariableString('default-directnotify-level', 'info')
         level = cvar2.getValue()
     if not level:
         level = 'error'
     category = self.getCategory(categoryName)
     if level == 'error':
         category.setWarning(0)
         category.setInfo(0)
         category.setDebug(0)
     else:
         if level == 'warning':
             category.setWarning(1)
             category.setInfo(0)
             category.setDebug(0)
         else:
             if level == 'info':
                 category.setWarning(1)
                 category.setInfo(1)
                 category.setDebug(0)
             else:
                 if level == 'debug':
                     category.setWarning(1)
                     category.setInfo(1)
                     category.setDebug(1)
                 else:
                     print 'DirectNotify: unknown notify level: ' + str(
                         level) + ' for category: ' + str(categoryName)
Esempio n. 10
0
 def __init__(self):
     loglevel = ConfigVariableString('log-level', 'info').getValue()
     if loglevel == "error":
         self.loglevel = 4
     elif loglevel == "warning":
         self.loglevel = 3
     elif loglevel == "info":
         self.loglevel = 2
     elif loglevel == "debug":
         self.loglevel = 1
     elif loglevel == "manager":
         self.loglevel = 0
     self.debug("Level", loglevel)
Esempio n. 11
0
    def __init__(self):
        #setup logger
        self.logger = logging.getLogger('ClientLog')
        hdlr = logging.FileHandler('Client.log')
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        hdlr.setFormatter(formatter)
        self.logger.addHandler(hdlr)
        self.logger.setLevel(logging.DEBUG)

        #PStatClient.connect()

        #menu data
        self.players = None
        self.active_games = None
        self.unaccepted_games = None
        self.waiting_games = None
        self.news_items = None
        self.levels = None
        self.game_id = None
        self.map = None
        self.budget = None
        self.game_name = None
        self.browser = None
        self.lobby = None

        #setup screen (initialize ShowBase to create window)
        self.screen = Screen(self, (980, 720))
        self.rRegion = RocketRegion.make('main_menu', base.win)
        self.rContext = self.rRegion.getContext()
        ih = RocketInputHandler()
        base.mouseWatcher.attachNewNode(ih)
        self.rRegion.setInputHandler(ih)

        # Setup FSM
        self.fsm = AppFSM(self, 'AppFSM')

        # Init Network parameters
        server_ip = ConfigVariableString("server-ip", "127.0.0.1").getValue()
        server_port = ConfigVariableInt("server-port", "56005").getValue()
        ClientMsg.setupAddress(server_ip, server_port)
        ClientMsg.notify = self.logger

        # Initialize network communicator
        self.net_manager = Net(self)
        self.net_manager.startNet()

        base.accept('i', render.ls)

        # Start with Login screen
        self.fsm.request('Login')
Esempio n. 12
0
 def __init__(self):
     self.hasConfig = False
     # if exist load the config file
     if os.path.exists(prcFile):
         loadPrcFile(Filename.fromOsSpecific(prcFile))
         self.hasConfig = True
     # set the variables using the config files content or set a default value
     self.UDPPORT = ConfigVariableInt('udp-port', '6002').getValue()
     self.TCPPORT = ConfigVariableInt('tcp-port', '6000').getValue()
     self.UDPPORTSERVER = ConfigVariableInt('udp-port-server',
                                            '6001').getValue()
     self.SERVERIP = ConfigVariableString('server-ip',
                                          '127.0.0.1').getValue()
     self.TIMEOUT = ConfigVariableInt('timeout-in-ms', '3000').getValue()
Esempio n. 13
0
    def __init__(self, pure_background: bool = False):
        super(SkyBox, self).__init__()
        self._accumulate = 0
        self.f = 1
        if not self.render or pure_background:
            self.node_path = NodePath("pure_background")
            return
        skybox = self.loader.loadModel(
            AssetLoader.file_path("models", "skybox.bam"))

        skybox.hide(CamMask.MiniMap | CamMask.RgbCam | CamMask.Shadow
                    | CamMask.ScreenshotCam)
        skybox.set_scale(20000)

        skybox_texture = self.loader.loadTexture(
            AssetLoader.file_path("textures", "skybox.jpg"))
        skybox_texture.set_minfilter(SamplerState.FT_linear)
        skybox_texture.set_magfilter(SamplerState.FT_linear)
        skybox_texture.set_wrap_u(SamplerState.WM_repeat)
        skybox_texture.set_wrap_v(SamplerState.WM_mirror)
        skybox_texture.set_anisotropic_degree(16)
        skybox.set_texture(skybox_texture)

        gles = ConfigVariableString("load-display").getValue()
        if gles == "pandagles2":
            skybox_shader = Shader.load(
                Shader.SL_GLSL,
                AssetLoader.file_path("shaders", "skybox_gles.vert.glsl"),
                # FIXME a potential bug here?
                AssetLoader.file_path("shaders", "skybox_gles.frag.glsl"))
        else:
            if is_mac():
                vert_file = "skybox_mac.vert.glsl"
                frag_file = "skybox_mac.frag.glsl"
            else:
                vert_file = "skybox.vert.glsl"
                frag_file = "skybox.frag.glsl"
            skybox_shader = Shader.load(
                Shader.SL_GLSL,
                AssetLoader.file_path("shaders", vert_file),
                # FIXME a potential bug here?
                AssetLoader.file_path("shaders", frag_file))
        skybox.set_shader(skybox_shader)
        self.node_path = skybox
        skybox.setZ(-4400)
        skybox.setH(30)
Esempio n. 14
0
    def setDconfigLevel(self, categoryName):
        """
        Check to see if this category has a dconfig variable
        to set the notify severity and then set that level. You cannot
        set these until config is set.
        """

        # We use ConfigVariableString instead of base.config, in case
        # we're running before ShowBase has finished initializing; and
        # we import it directly from libpandaexpress, in case we're
        # running before libpanda.dll is available.
        from panda3d.core import ConfigVariableString

        dconfigParam = ("notify-level-" + categoryName)
        cvar = ConfigVariableString(dconfigParam, "")
        level = cvar.getValue()

        if not level:
            # see if there's an override of the default config level
            cvar2 = ConfigVariableString('default-directnotify-level', 'info')
            level = cvar2.getValue()
        if not level:
            level = 'error'

        category = self.getCategory(categoryName)
        # Note - this print statement is making it difficult to
        # achieve "no output unless there's an error" operation - Josh
        # print ("Setting DirectNotify category: " + categoryName +
        #        " to severity: " + level)
        if level == "error":
            category.setWarning(0)
            category.setInfo(0)
            category.setDebug(0)
        elif level == "warning":
            category.setWarning(1)
            category.setInfo(0)
            category.setDebug(0)
        elif level == "info":
            category.setWarning(1)
            category.setInfo(1)
            category.setDebug(0)
        elif level == "debug":
            category.setWarning(1)
            category.setInfo(1)
            category.setDebug(1)
        else:
            print("DirectNotify: unknown notify level: " + str(level) +
                  " for category: " + str(categoryName))
# ConfigVariableManager.getGlobalPtr().listVariables()
import sys
from panda3d.core import ConfigVariableString, ConfigVariableManager

my_game_server = ConfigVariableString('my-game-server', '127.0.0.1')
print('Server specified in config file: ', my_game_server.getValue())

# Allow the user to change servers on the command-line
if sys.argv[1] == '--server':
    my_game_server.setValue(sys.argv[2])
# end if

print('Server that we will user: ', my_game_server.getValue())

print(ConfigVariableString("my-game-server"))

cvMgr = ConfigVariableManager.get_global_ptr()
cvMgr.list_variables()
Esempio n. 16
0
    def __init__(self, params, pipe, dir):
        self.game_directory = dir
        self.game_pipe = pipe
        self.gs_window = ConfigVariableString('win-size')
        self.gs_window.setValue(str(params.get('width', 800)) +' '+str(params.get('height', 600)))
        
        self.gs_multi = ConfigVariableBool('framebuffer-multisample')
        self.gs_multi.setValue(params.get('multisample', 1))
        
        self.gs_sync = ConfigVariableBool('sync-video', str(params.get('sync', 1)))
        self.gs_sync.setValue(params.get('sync', 1))

        loadPrcFileData('', 'win-size '+ str(params.get('width', 800)) +' '+str(params.get('height', 600)))
        loadPrcFileData('', 'win-fixed-size 1')
        loadPrcFileData('', 'text-default-font data/HanZi.ttf')
        loadPrcFileData('', 'multisamples ' + str(params.get('samples', 0)))

        #loadPrcFileData('', 'fullscreen 1')
        #loadPrcFileData('', 'textures-power-2 pad')
        #loadPrcFileData('', 'notify-level spam')
        #loadPrcFileData('', 'default-directnotify-level spam')
        #loadPrcFileData('', 'notify-output I:\\Users\\User\\My Documents\\Aptana Studio 3 Workspace\\sg\\out2.txt')
        #nout = MultiplexStream()
        #Notify.ptr().setOstreamPtr(nout, 0)
        #nout.addFile(Filename("out.txt"))

        '''for i in xrange(ConfigVariableManager.getGlobalPtr().getNumVariables()):
            if ConfigVariableManager.getGlobalPtr().isVariableUsed(i) :
                name = ConfigVariableManager.getGlobalPtr().getVariableName(i)
                v = ConfigVariable(name)
        '''

        self.p3d = ShowBase.ShowBase()
        self.p3d.buttonThrowers[0].node().setButtonDownEvent('buttonDown') 
        self.p3d.buttonThrowers[0].node().setButtonRepeatEvent('buttonRep')
        self.p3d.buttonThrowers[0].node().setButtonUpEvent('buttonUp')
        self.p3d.accept('buttonDown', self.keyboard, [0,])
        self.p3d.accept('buttonRep', self.keyboard, [2,])
        self.p3d.accept('buttonUp', self.keyboard, [1,])

        self.p3d.disableMouse()       #Disable default mouse-based camera control

        self.screen = render2d.attachNewNode("Screen Coord Node")
        self.screen.setBin("fixed", 100)
        self.flat = render.attachNewNode("2d Objects in 3d world")
        self.flat.setBin('background', 0)
        self.flat.setDepthTest(False)
        self.flat.setDepthWrite(False)
        
        render.setAntialias(AntialiasAttrib.MAuto)
        
        self.props = WindowProperties(self.p3d.win.getProperties())

        #Screen size
        self.width = params['width']
        self.height = params['height']
        self.aratio = float(self.width)/self.height #aspect ratio
        self.p3d.camera.setZ(1000)
        self.p3d.camera.lookAt(0,0,0)
        self.p3d.camLens.setFov(80)
        #self.props.setSize(size[0],size[1])

        self.screen.setScale(2.0/self.width,1,2.0/self.height)
        
        self.dt = 0.0
        self.fps = 0
        
        self.title_last_update_time = 0
        
        self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0))
        
        self.elements = {}
        
        #self.MModel = self.create_model_xt((0,0,0), 'models\\chinesegfx_city_1_1.x', 'models\\houses_chinesegfx.tga', (3,3))[1]
        #self.MModel.reparentTo(hidden)
        #sys.stdout.flush()
        #self.p3d.taskMgr.run()
        #self.myShader = Shader.load(Shader.SLGLSL, "modules\\myvertexshader.glsl", "modules\\myfragmentshader.glsl")
        
        #self.plane2.setShader(self.myShader)

        self.mouse_pos = (0, 0)
        self.mouse_on_map_pos = (0, 0)
        self.p3d.accept('wheel_up',self.zoom_in)
        self.p3d.accept('wheel_down',self.zoom_out)
        self.p3d.accept('mouse1',self.mouse_click_left)
        self.p3d.accept('mouse3',self.mouse_click_right)
        
        self.parents = {}
        
        self.gui_surface = aspect2d.attachNewNode("GUI Node")
        self.gui_surface.setScale(2.0/self.height,1,2.0/self.height)
        self.gui_surface.setBin("fixed", 50)
        
        self.map_node = self.add_node('map_node', 'background', 0, self.flat)
        self.paths_node = self.add_node('paths_node', 'background', 3, self.flat)
        self.paths_all_node = self.add_node('paths_all_node', 'background', 3, self.flat)
        self.map_mode_node = self.add_node('map_mode_node', 'background', 1, self.map_node)
        self.selecties_node = self.add_node('selecties_node', 'background', 2, self.map_node)

        self.parents['render'] = render
        self.parents['gui_surface'] = self.gui_surface
        
        self.elements['city_map_model'] = self.create_model_xt(fname = 'models\\chinesegfx_city_1_1.x', texname = 'models\\houses_chinesegfx.tga', size = (3, 3), name = 'city_map_model')
        
        self.minimap = Minimap(self.width, self.height, self)
Esempio n. 17
0
"""LEConfig module: contains the level editor configuration variables"""

from panda3d.core import ConfigVariableList, ConfigVariableString, ConfigVariableDouble, ConfigVariableInt

fgd_files = ConfigVariableList(
    "fgd-file", "List of FGD files that are to be loaded by the level editor")

default_material = ConfigVariableString(
    "default-material",
    #"materials/dev/dev_measuregeneric01.mat",
    "maps/smiley.txo",
    "The default material to use for solids")

default_point_entity = ConfigVariableString("default-point-entity",
                                            "prop_static",
                                            "The default point entity")

default_solid_entity = ConfigVariableString(
    "default-solid-entity", "func_wall",
    "The default solid/brush entity. Brushes that get tied to entities are this "
    "entity by default.")

default_texture_scale = ConfigVariableDouble(
    "default-texture-scale", 1.0, "The default texture scale for solid faces.")

default_lightmap_scale = ConfigVariableInt(
    "default-lightmap-scale", 16,
    "The default lightmap scale for solid faces. Lower value = more detailed")

default_prop_model = ConfigVariableString(
    "default-prop-model", "models/misc/smiley.bam",
Esempio n. 18
0
import sys
from panda3d.core import ConfigVariableString, loadPrcFile, loadPrcFileData, ConfigVariableManager

config = loadPrcFile("Config.prc")
loadPrcFileData('', 'fullscreen true')

myGameServer = ConfigVariableString('my-game-server', '127.0.0.1')
print('Server specified in config file: ', myGameServer.getValue())

cvMgr = config.getGlobalPtr()
cvMgr.listVariables()
Esempio n. 19
0
 def getSourceFileName(self):
     if self.sourceFileName is None:
         SpriteParticleRendererExt.sourceFileName = ConfigVariableString(
             'particle-sprite-model', 'models/misc/smiley').value
     # Return instance copy of class variable
     return self.sourceFileName
from panda3d.core import ConfigVariableString
from direct.directnotify.DirectNotify import DirectNotify

language = ConfigVariableString('language', 'English')
language = language.getValue()

notify = DirectNotify().newCategory("OTPLocalizer")

def getLanguage():
    return language

_languageModule = 'otp.otpbase.OTPLocalizer' + language

try:
    exec 'from ' + _languageModule + ' import *'
    print ":OTPLocalizer: Running in language: %s" % language
except:
    notify.warning("Error, Language %s not found!" % language)
    notify.warning("Setting language to default (English)")
    from otp.otpbase.OTPLocalizerEnglish import *
    

Esempio n. 21
0
 def getSourceNodeName(self):
     if self.sourceNodeName is None:
         SpriteParticleRendererExt.sourceNodeName = ConfigVariableString(
             'particle-sprite-node', '**/*').value
     # Return instance copy of class variable
     return self.sourceNodeName
Esempio n. 22
0
 def getSourceTextureName(self):
     if self.sourceTextureName is None:
         SpriteParticleRendererExt.sourceTextureName = ConfigVariableString(
             'particle-sprite-texture', 'maps/lightbulb.rgb').value
     # Return instance copy of class variable
     return self.sourceTextureName
Esempio n. 23
0
from panda3d.core import WindowProperties
from panda3d.core import ConfigVariableInt
from panda3d.core import ConfigVariableBool
from panda3d.core import ConfigVariableString
config_aa=ConfigVariableInt('multisamples', 0)
buff_size=ConfigVariableInt('buffer-size', 1024)
config_fulscreen=ConfigVariableBool('fullscreen')
config_win_size=ConfigVariableInt('win-size', '640 480')
config_autoshader=ConfigVariableBool('use-shaders', 0)
config_bloom=ConfigVariableBool('bloom', 1)
config_music=ConfigVariableInt('music-volume', '10')
config_sfx=ConfigVariableInt('sound-volume', '100')
config_safemode=ConfigVariableBool('safemode', 0)
#keys
config_menuitems=ConfigVariableString('key_menuitems', 'v')
config_useitem=ConfigVariableString('key_useitem', 'u')
config_nextitem=ConfigVariableString('key_nextitem', 'i')
config_forward=ConfigVariableString('key_forward', 'w|arrow_up')
config_back=ConfigVariableString('key_back', 's|arrow_down')
config_left=ConfigVariableString('key_left', 'a|arrow_left')
config_right=ConfigVariableString('key_right', 'd|arrow_right')
config_camera_left=ConfigVariableString('key_cam_left', 'q|delete')
config_camera_right=ConfigVariableString('key_cam_right', 'e|page_down')
config_action1=ConfigVariableString('key_action1', 'mouse1|enter')
config_action2=ConfigVariableString('key_action2', 'mouse3|space')
config_zoomin=ConfigVariableString('key_zoomin', 'wheel_up|r')
config_zoomout=ConfigVariableString('key_zoomout', 'wheel_down|f')
#if(config_aa.getValue()>0):
#    loadPrcFileData('','multisamples '+str(config_aa.getValue()))
wp = WindowProperties.getDefault()
Esempio n. 24
0
    def writeConfig(self):
        """Save current config in the prc file or if no prc file exists
        create one. The prc file is set in the prcFile variable"""
        page = None

        #
        #TODO: add any configuration variable names that you have added
        #      to the dictionaries in the next lines. Set the current
        #      configurations value as value in this dictionary and it's
        #      name as key.
        configVariables = {
            # set the window size in the config file
            "win-size":
            ConfigVariableString(
                "win-size", "{} {}".format(self.dispWidth,
                                           self.dispHeight)).getValue(),
            # set the default to fullscreen in the config file
            "fullscreen":
            "#t"
            if ConfigVariableBool("fullscreen", True).getValue() else "#f",
            # particles
            "particles-enabled":
            "#t" if self.particleMgrEnabled else "#f",
            # audio
            "audio-volume":
            str(round(self.musicManager.getVolume(), 2)),
            "audio-music-active":
            "#t" if self.musicActive else "#f",
            "audio-sfx-active":
            "#t" if self.sfxActive else "#f",
            # logging
            "notify-output":
            os.path.join(basedir, "game.log"),
            # window
            "framebuffer-multisample":
            "#t" if ConfigVariableBool("framebuffer-multisample").getValue()
            else "#f",
            "multisamples":
            str(ConfigVariableInt("multisamples", 8).getValue()),
            "texture-anisotropic-degree":
            str(ConfigVariableInt("texture-anisotropic-degree").getValue()),
            "textures-auto-power-2":
            "#t" if ConfigVariableBool("textures-auto-power-2",
                                       True).getValue() else "#f",
            # server connection
            "server-host":
            base.serverHost.getValue(),
        }

        page = None
        # Check if we have an existing configuration file
        if os.path.exists(prcFile):
            # open the config file and change values according to current
            # application settings
            page = loadPrcFile(Filename.fromOsSpecific(prcFile))
            removeDecls = []
            for dec in range(page.getNumDeclarations()):
                # Check if our variables are given.
                # NOTE: This check has to be done to not loose our base
                #       or other manual config changes by the user
                if page.getVariableName(dec) in configVariables.keys():
                    removeDecls.append(page.modifyDeclaration(dec))
            for dec in removeDecls:
                page.deleteDeclaration(dec)
        else:
            # Create a config file and set default values
            cpMgr = ConfigPageManager.getGlobalPtr()
            page = cpMgr.makeExplicitPage("Application Config")

        # always write custom configurations
        for key, value in configVariables.items():
            page.makeDeclaration(key, value)
        # create a stream to the specified config file
        configfile = OFileStream(prcFile)
        # and now write it out
        page.write(configfile)
        # close the stream
        configfile.close()
Esempio n. 25
0
class graphica :
    elements = None #drawing elements
    map_zoom = 1
    map_pos = (0, 0)
    width = 0
    height = 0
    
    title_update_time = 0.5
    
    p3d = None #Panda Engine
    flat = None #floor of the world
    screen = None #screen surface
    
    def __init__(self, params, pipe, dir):
        self.game_directory = dir
        self.game_pipe = pipe
        self.gs_window = ConfigVariableString('win-size')
        self.gs_window.setValue(str(params.get('width', 800)) +' '+str(params.get('height', 600)))
        
        self.gs_multi = ConfigVariableBool('framebuffer-multisample')
        self.gs_multi.setValue(params.get('multisample', 1))
        
        self.gs_sync = ConfigVariableBool('sync-video', str(params.get('sync', 1)))
        self.gs_sync.setValue(params.get('sync', 1))

        loadPrcFileData('', 'win-size '+ str(params.get('width', 800)) +' '+str(params.get('height', 600)))
        loadPrcFileData('', 'win-fixed-size 1')
        loadPrcFileData('', 'text-default-font data/HanZi.ttf')
        loadPrcFileData('', 'multisamples ' + str(params.get('samples', 0)))

        #loadPrcFileData('', 'fullscreen 1')
        #loadPrcFileData('', 'textures-power-2 pad')
        #loadPrcFileData('', 'notify-level spam')
        #loadPrcFileData('', 'default-directnotify-level spam')
        #loadPrcFileData('', 'notify-output I:\\Users\\User\\My Documents\\Aptana Studio 3 Workspace\\sg\\out2.txt')
        #nout = MultiplexStream()
        #Notify.ptr().setOstreamPtr(nout, 0)
        #nout.addFile(Filename("out.txt"))

        '''for i in xrange(ConfigVariableManager.getGlobalPtr().getNumVariables()):
            if ConfigVariableManager.getGlobalPtr().isVariableUsed(i) :
                name = ConfigVariableManager.getGlobalPtr().getVariableName(i)
                v = ConfigVariable(name)
        '''

        self.p3d = ShowBase.ShowBase()
        self.p3d.buttonThrowers[0].node().setButtonDownEvent('buttonDown') 
        self.p3d.buttonThrowers[0].node().setButtonRepeatEvent('buttonRep')
        self.p3d.buttonThrowers[0].node().setButtonUpEvent('buttonUp')
        self.p3d.accept('buttonDown', self.keyboard, [0,])
        self.p3d.accept('buttonRep', self.keyboard, [2,])
        self.p3d.accept('buttonUp', self.keyboard, [1,])

        self.p3d.disableMouse()       #Disable default mouse-based camera control

        self.screen = render2d.attachNewNode("Screen Coord Node")
        self.screen.setBin("fixed", 100)
        self.flat = render.attachNewNode("2d Objects in 3d world")
        self.flat.setBin('background', 0)
        self.flat.setDepthTest(False)
        self.flat.setDepthWrite(False)
        
        render.setAntialias(AntialiasAttrib.MAuto)
        
        self.props = WindowProperties(self.p3d.win.getProperties())

        #Screen size
        self.width = params['width']
        self.height = params['height']
        self.aratio = float(self.width)/self.height #aspect ratio
        self.p3d.camera.setZ(1000)
        self.p3d.camera.lookAt(0,0,0)
        self.p3d.camLens.setFov(80)
        #self.props.setSize(size[0],size[1])

        self.screen.setScale(2.0/self.width,1,2.0/self.height)
        
        self.dt = 0.0
        self.fps = 0
        
        self.title_last_update_time = 0
        
        self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0))
        
        self.elements = {}
        
        #self.MModel = self.create_model_xt((0,0,0), 'models\\chinesegfx_city_1_1.x', 'models\\houses_chinesegfx.tga', (3,3))[1]
        #self.MModel.reparentTo(hidden)
        #sys.stdout.flush()
        #self.p3d.taskMgr.run()
        #self.myShader = Shader.load(Shader.SLGLSL, "modules\\myvertexshader.glsl", "modules\\myfragmentshader.glsl")
        
        #self.plane2.setShader(self.myShader)

        self.mouse_pos = (0, 0)
        self.mouse_on_map_pos = (0, 0)
        self.p3d.accept('wheel_up',self.zoom_in)
        self.p3d.accept('wheel_down',self.zoom_out)
        self.p3d.accept('mouse1',self.mouse_click_left)
        self.p3d.accept('mouse3',self.mouse_click_right)
        
        self.parents = {}
        
        self.gui_surface = aspect2d.attachNewNode("GUI Node")
        self.gui_surface.setScale(2.0/self.height,1,2.0/self.height)
        self.gui_surface.setBin("fixed", 50)
        
        self.map_node = self.add_node('map_node', 'background', 0, self.flat)
        self.paths_node = self.add_node('paths_node', 'background', 3, self.flat)
        self.paths_all_node = self.add_node('paths_all_node', 'background', 3, self.flat)
        self.map_mode_node = self.add_node('map_mode_node', 'background', 1, self.map_node)
        self.selecties_node = self.add_node('selecties_node', 'background', 2, self.map_node)

        self.parents['render'] = render
        self.parents['gui_surface'] = self.gui_surface
        
        self.elements['city_map_model'] = self.create_model_xt(fname = 'models\\chinesegfx_city_1_1.x', texname = 'models\\houses_chinesegfx.tga', size = (3, 3), name = 'city_map_model')
        
        self.minimap = Minimap(self.width, self.height, self)
    
    def add_node(self, name, mode1, mode2, parent = None):
        node = None
        if parent == None :
            node = render.attachNewNode(name)
        else :
            node = parent.attachNewNode(name)
        if (mode1 <> None) and (mode2 <> None ): node.setBin(mode1, mode2)
        self.parents[name] = node
        self.elements[name] = node
        return node
        
    def get_parent(self, p):
        if p in self.parents :
            return self.parents[p]
        elif p in self.elements :
            return self.elements[p]
        else :
            return render
    
    def gr_loop(self):
        self.mouse_control()
        self.frame()
            
    def Start(self):
        print 'Starting graphic loop'
        sys.stdout.flush()
        while(1):
            #считывает отправленные данные
            start_time = globalClock.getRealTime()

            try:
                while self.game_pipe.poll(False) and ((globalClock.getRealTime() - start_time) < 0.5) :
                    m = self.game_pipe.recv()
                    
                    
                    try:
                        if m[0] == 'setitem' :
                            if m[1]['key'] == 'pos' : self.elements[m[1]['name']].setPos(m[1]['value'])
                            elif m[1]['key'] == 'image' : 
                                self.elements[m[1]['name']]['image'] = textures.get(m[1]['value'], None)
                            elif m[1]['key'] == 'scale' : self.elements[m[1]['name']].setScale(m[1]['value'])
                            else : self.elements[m[1]['name']][m[1]['key']] = m[1]['value']
                        
                        elif m[0] == 'set_map_pos' : self.set_map_pos(m[1][0], m[1][1])
                        
                        elif m[0] == 'set_map_zoom' : self.set_map_zoom(m[1])
    
                        elif m[0] == 'draw_image2d' : self.draw_image2d(**m[1])
                        
                        elif m[0] == 'draw_image' : self.draw_image(**m[1])
                        
                        elif m[0] == 'draw_line' : 
                            self.draw_line(**m[1])
                            #continue
                        
                        elif m[0] == 'draw_line2d' : 
                            self.draw_line2d(**m[1])
                        
                        elif m[0] == 'draw_circle' : self.draw_circle(**m[1])
                        
                        elif m[0] == 'draw_triangles' : self.draw_triangles(**m[1])
                        
                        elif m[0] == 'delete_el_mask' : self.delete_el_mask(m[1])
                        
                        elif m[0] == 'delete_el' : self.delete_el(m[1])
                        
                        elif m[0] == 'gui_hide' :
                            self.elements[m[1]].hide()
                            
                        elif m[0] == 'gui_show' :
                            self.elements[m[1]].show()
                            
                        elif m[0] == 'gui_removeAndDestroyAllItems' :
                            self.elements[m[1]].removeAndDestroyAllItems()
                            
                        elif m[0] == 'reparentTo' :
                            self.elements[m[1]].reparentTo( self.elements[m[2]] )
                            
                        elif m[0] == 'setTexture' :
                            self.elements[m[1]].setTexture(textures[m[2]])
                            
                        elif m[0] == 'setPos' :
                            self.elements[m[1]].setPos(m[2][0], m[2][1], m[2][2])
                            
                        elif m[0] == 'setHpr' :
                            self.elements[m[1]].setHpr(m[2][0], m[2][1], m[2][2])
                            
                        elif m[0] == 'instanceTo' :
                            self.elements[m[2]] = render.attachNewNode('Placeholder')
                            self.elements[m[1]].instanceTo(self.elements[m[2]])
                        
                            
                        elif m[0] == 'resetFrameSize' :
                            self.elements[m[1]].resetFrameSize()
                            
                        elif m[0] == 'setTransparency' :
                            self.elements[m[1]].setTransparency(TransparencyAttrib.MAlpha)
                            
                        elif m[0] == 'RemoveGuiElement' :
                            try:
                                self.elements[m[1]].destroy()
                            except:
                                self.elements[m[1]].removeNode()
                                
                        elif m[0] == 'removeNode' :
                            self.elements[m[1]].removeNode()
                            
                        elif m[0] == 'removeAllChildren' :
                            self.elements[m[1]].node().removeAllChildren()
                                
                        elif m[0] == 'gui_addItem' :
                            self.elements[m[1]].addItem(self.elements[m[2]])
                            
                        
                        elif m[0] == 'DirectLabel' :
                            params = dict(m[1])
                            params['parent'] = self.get_parent(params.get('parent', 'render') )
                            self.elements[m[2]['name']] = DirectLabel(**params)
                        
                        elif m[0] == 'DirectButton' :
                            params = dict(m[1])
                            params['parent'] = self.get_parent(params.get('parent', 'render') )
                            params['command'] = self.GUI_pressed
                            params['extraArgs'] = (m[2]['name'],)
                            self.elements[m[2]['name']] = DirectButton(**params)
                        
                        elif m[0] == 'DirectFrame' :
                            params = dict(m[1])
                            params['parent'] = self.get_parent( params.get('parent', 'render') )
                            self.elements[m[2]['name']] = DirectFrame(**params)
                            
                        
                        elif m[0] == 'DirectScrolledList' :
                            params = dict(m[1])
                            params['parent'] = self.get_parent( params.get('parent', 'render') )
                            self.elements[m[2]['name']] = DirectScrolledList(**params)
                            
                        elif m[0] == 'DirectCheckButton' :
                            params = dict(m[1])
                            params['parent'] = self.get_parent( params.get('parent', 'render') )
                            self.elements[m[2]['name']] = DirectCheckButton(**params)
                            
                        elif m[0] == 'DirectWaitBar' :
                            params = dict(m[1])
                            params['parent'] = self.get_parent( params.get('parent', 'render') )
                            self.elements[m[2]['name']] = DirectWaitBar(**params)
                            
                        elif m[0] == 'create_actor_egg' :
                            self.create_actor_egg(**m[1])
                            
                        elif m[0] == 'anim_loop' :
                            if len(m) == 3 : 
                                m = list(m)
                                m.append({})
                            self.elements[m[1]].loop(m[2], **m[3])
                            
                            
                        elif m[0] == 'image_data_new' :
                            t = PNMImage()
                            #print 'RECV', m[2]
                            sys.stdout.flush()
                            if t.read(StringStream(m[2])) :
                                pass
                            else :
                                raise ValueError()
                            sys.stdout.flush()
                            tex = Texture()
                            tex.load(t)
                            textures[m[1]] = tex 
                            
                        elif m[0] == 'create_minimap' :
                            im = PNMImage()
                            self.elements['phyz'].getTexture().store(im)
                            self.minimap.create_minimap(im, m[1], m[2])
                            self.draw_image2d(pos = (self.width/2 - 200, -self.height/2), texname = 'minimap_tex', name = 'minimap_image', parent = 'gui_surface' )
                            
                        
                        else :
                            print 'Unknown command:', m
                            sys.stdout.flush()
                        #print m
                        #sys.stdout.flush()
                        
                        
                    except:
                        print m
                        print 'error1', sys.exc_info()
                        sys.stdout.flush()
                
            except:
                print 'error2', sys.exc_info()
                sys.stdout.flush()    
                
            try:
                self.gr_loop()
            except Exception:
                print 'error3', sys.exc_info() 
                sys.stdout.flush()  
            
            try:
                pass
                #if not(self.game_queue.full()):
                #    self.game_queue.put(('mouse_pos', self.mouse_pos))
                #    self.game_queue.put(('mouse_on_map_pos', self.mouse_on_map_pos))
                #else :
                #    print 'game full'
                #    sys.stdout.flush()
                    
            except:
                print 'error4', sys.exc_info()
                sys.stdout.flush()   
                

            sys.stdout.flush()
            #time.sleep(0.01)

    def GUI_pressed(self, name):
        self.game_pipe.send(('gui_pressed',name))
    
    def mouse_control(self):
        if self.p3d.mouseWatcherNode.hasMouse():
            mp = (self.p3d.mouseWatcherNode.getMouse()[0], 0, self.p3d.mouseWatcherNode.getMouse()[1])
            self.mouse_pos[0] =  self.screen.getRelativePoint(render2d, mp)[0]
            self.mouse_pos[1] = self.screen.getRelativePoint(render2d, mp)[2]

            self.ttt = globalClock.getRealTime()
            mpos = self.p3d.mouseWatcherNode.getMouse()
            tmp = self.scr_to_map(mpos)
            self.mouse_on_map_pos[0] = tmp[0]
            self.mouse_on_map_pos[1] = tmp[1]
            X_ = self.p3d.camera.getX()
            Y_ = self.p3d.camera.getY()
            C = 0.5*self.dt
            if self.mouse_pos[0] < self.width * -0.47 :
                X_ -= self.p3d.camera.getZ()*C
                self.minimap.update_pos()
            if self.mouse_pos[0] > self.width * 0.47 :  
                X_ += self.p3d.camera.getZ()*C
                self.minimap.update_pos()
            if self.mouse_pos[1] < self.height * -0.47 :  
                Y_ -= self.p3d.camera.getZ()*C
                self.minimap.update_pos()
            if self.mouse_pos[1] > self.height * 0.47 : 
                Y_ += self.p3d.camera.getZ()*C
                self.minimap.update_pos()
            self.p3d.camera.setX( X_ )
            self.p3d.camera.setY( Y_ )
    
    def mouse_click_left(self):
        self.game_pipe.send(('mouse_click_left',))
    
    def mouse_click_right(self):
        self.game_pipe.send(('mouse_click_right',))
    
    def frame(self):
        self.p3d.taskMgr.step()
        self.dt = globalClock.getDt()
        
        if globalClock.getRealTime() - self.title_last_update_time > self.title_update_time :
            self.props = WindowProperties(self.p3d.win.getProperties())
            self.title_last_update_time = globalClock.getRealTime()
            self.fps = globalClock.getAverageFrameRate()
            title = str(self.fps) + str(self.mouse_pos[:]) + str(self.mouse_on_map_pos[:])
            self.props.setTitle(title)
            self.p3d.win.requestProperties(self.props)

    def draw_line(self, **kwargs):
        ps = kwargs.get('points',[])
        name = ''
        if 'name' in kwargs.keys() :
            name = kwargs['name']
            if self.check_name(name) :
                #print 'draw_line name duplicated', name
                return None
        else :
            name = self.generate_name()
            
        ls = LineSegs()
        if 'width' in kwargs.keys() : ls.setThickness( kwargs['width'] ) 
        if 'color' in kwargs.keys() : ls.setColor( (kwargs['color'][0], kwargs['color'][1], kwargs['color'][2], kwargs['color'][3]) )
        
        for i in ps :
            ls.drawTo(i[0], i[1], i[2])
        node = ls.create()
        np = NodePath(node)
        
        if 'parent' in kwargs.keys() and kwargs['parent'] <> None :
            self.get_parent(kwargs['parent']).attachNewNode(np.node())
        else :
            render.attachNewNode(np.node())
            
        
        self.elements[ name ] = np
        
        return name, np

    def draw_line2d(self, **kwargs):
        ps = None
        if 'points' in kwargs.keys():
            ps = kwargs['points']
        else :
            return None
        
        name = ''
        if 'name' in kwargs.keys() :
            name = kwargs['name']
            if self.check_name(name) :
                #print 'draw_line name duplicated', name
                return None
        else :
            name = self.generate_name()
            
        ls = LineSegs()
        if 'width' in kwargs.keys() : ls.setThickness( kwargs['width'] ) 
        if 'color' in kwargs.keys() : ls.setColor( Vec4(kwargs['color'][0], kwargs['color'][1], kwargs['color'][2], kwargs['color'][3]) )
        
        for i in ps :
            ls.drawTo(i[0], 0, i[1])
        node = ls.create()
        np = NodePath(node)

        if 'parent' in kwargs.keys() and kwargs['parent'] <> None :
            self.get_parent(kwargs['parent']).attachNewNode(np.node())
        else :
            self.screen.attachNewNode(np.node())

        self.elements[ name ] = np
        
        return name, np
    
    def draw_circle(self, **kw):#x, color, r, width, name, prec = 10, parent = None, hpr = None):
        x = kw.get('pos',(0,0,0))
        color = kw.get('color',(0,0,0,255))
        r = kw.get('radius',5)
        width = kw.get('width',1)
        prec = kw.get('prec', 10)
        parent = self.get_parent(kw.get('parent', None))
        hpr = kw.get('hpr', None)
        name = kw.get('name', self.generate_name())
        if self.check_name(name) :
                #print 'draw_circle name duplicated', name
                return None
        ls = LineSegs()
        ls.setThickness( width ) 
        ls.setColor( Vec4(float(color[0])/256,float(color[1])/256,float(color[2])/256,float(color[3])/256) )
        
        for i in xrange(prec) :
            angle = math.pi*i*2/prec
            ls.drawTo(x[0] + math.sin(angle) * r, x[1] + math.cos(angle) * r,0)
        
        ls.drawTo(x[0] + math.sin(math.pi*i*2/1) * r, x[1] + math.cos(math.pi*i*2/1) * r, 0)
        
        node = ls.create()
        np = NodePath(node)
        if color[3] <> 255 : np.setTransparency(TransparencyAttrib.MAlpha)
        if hpr <> None : np.setHpr(hpr[0],hpr[1],hpr[2])
        
        if parent == None :
            self.flat.attachNewNode(np.node())
        else :
            parent.attachNewNode(np.node())
        
        self.elements[name] = np
    
    def draw_circle2d(self, x, color, r, width, name, prec = 10, parent = None):
        ls = LineSegs()
        ls.setThickness( width ) 
        ls.setColor( Vec4(float(color[0])/256,float(color[1])/256,float(color[2])/256,float(color[3])/256) )
        for i in xrange(prec) :
            angle = math.pi*i*2/prec
            ls.drawTo(x[0] + math.sin(angle) * r, 0, x[1] + math.cos(angle) * r)
        
        ls.drawTo(x[0] + math.sin(math.pi*i*2/1) * r, 0, x[1] + math.cos(math.pi*i*2/1) * r)
        
        node = ls.create()
        np = NodePath(node)
        
        if parent == None :
            self.screen.attachNewNode(np.node())
        else :
            parent.attachNewNode(np.node())
        
        self.elements[name] = np

    def draw_text(self,msg,x,rgba,size,font = 'HanZi.ttf', surface = None):
        pass
    
    def draw_image(self,pos = (0,0,0), fname = '', name = None, scale = (1,1), size = None, parent = None, image = None, **kw):
        if name == None :
            name = self.generate_name()
            
        
        tex = Texture()
        texname = kw.get('texname', None)
        if texname <> None :
            if texname in textures.keys() :
                tex.load(textures[texname])
            else :
                tex = loader.loadTexture(texname)
        else : return None, None

        xframe = tex.getXSize()
        if tex.getOrigFileXSize() <> 0 : xframe = tex.getOrigFileXSize()

        yframe = tex.getYSize()
        if tex.getOrigFileYSize() <> 0 : yframe = tex.getOrigFileYSize()
        
        if size <> None :
            scale = (float(scale[0]) * size[0]/tex.getOrigFileXSize(), float(scale[1]) * size[1]/tex.getOrigFileYSize() )
        cm = CardMaker('card')
        cm.setFrame(0,xframe*scale[0],0,yframe*scale[1])
        
        card = None
        if parent == None :
            card = render.attachNewNode(cm.generate())
        else :
            card = self.get_parent(parent).attachNewNode(cm.generate())
        
        card.setTexture(tex)
        card.setPos(pos[0],pos[1],pos[2])
        card.setHpr(0,-90,0)

        self.elements[name] = card
        
        return name, card 
    
    def draw_polygon(self,ps,color,name):
        color = ( float(color[0])/255, float(color[1])/255, float(color[2])/255, float(color[3])/255)
        
        vdata = GeomVertexData('trig', GeomVertexFormat.getV3(), Geom.UHStatic) 
        vwriter = GeomVertexWriter(vdata, 'vertex')
        #cwriter = GeomVertexWriter(vdata, 'color')
        
        trig = Triangulator()
        
        for i in ps :
            vi = trig.addVertex(i[0], i[1])
            vwriter.addData3f(i[0], i[2], i[1])
            #cwriter.addData4f(color[0], color[1], color[2], color[3])
            trig.addPolygonVertex(vi)

        trig.triangulate()
        
        prim = GeomTriangles(Geom.UHStatic)
        
        for i in range(trig.getNumTriangles()): 
            prim.addVertices(trig.getTriangleV0(i), 
                             trig.getTriangleV1(i), 
                             trig.getTriangleV2(i)) 
            prim.closePrimitive() 
        
        geom = Geom(vdata) 
        geom.addPrimitive(prim)
        
        geomNode = GeomNode('trig') 
        geomNode.addGeom(geom)
        
        np = NodePath(geomNode)
        np.reparentTo(render)
        #fill=self.screen.attachNewNode(geomNode) 
        #fill.analyze()
        
        
        self.elements[name] = np
    
    def draw_tristrips(self, ps, color, name, parent = None):
        vdata = GeomVertexData('trig', GeomVertexFormat.getV3(), Geom.UHStatic) 
        vwriter = GeomVertexWriter(vdata, 'vertex')
        
        for i in ps :
            vwriter.addData3f(i[0], i[1], i[0])

        prim = GeomTristrips(Geom.UHStatic)
        
        for i in range(len(ps)) :
            prim.addVertex(i) 
        prim.closePrimitive() 
        
        geom = Geom(vdata) 
        geom.addPrimitive(prim)
        
        geomNode = GeomNode('trig') 
        geomNode.addGeom(geom)
        
        np = NodePath(geomNode)
        
        if parent == None :
            render.attachNewNode(np.node())
        else :
            parent.attachNewNode(np.node())
        #fill=self.screen.attachNewNode(geomNode) 
        #fill.analyze()
        
        
        self.elements[name] = np
        
    def draw_triangles(self, points = None, color = None, name = None, parent = None):
        
        vdata = GeomVertexData('trig', GeomVertexFormat.getV3c4(), Geom.UHStatic) 
        vwriter = GeomVertexWriter(vdata, 'vertex')
        cwriter = GeomVertexWriter(vdata, 'color')
        
        for i in points :
            vwriter.addData3f(i[0], i[1], i[2])
            cwriter.addData4f(color[0], color[1], color[2], color[3])
        
        geom = Geom(vdata)
        
        prim = GeomTriangles(Geom.UHStatic)
        for i in range(len(points)) :            
            prim.addVertex(i)
        prim.closePrimitive()
        geom.addPrimitive(prim) 
        
        geomNode = GeomNode('trig') 
        geomNode.addGeom(geom)
        
        np = NodePath(geomNode)
        
        if parent == None :
            render.attachNewNode(np.node())
        else :
            self.get_parent(parent).attachNewNode(np.node())

        np.setTransparency(TransparencyAttrib.MAlpha)
        #fill=self.screen.attachNewNode(geomNode) 
        #fill.analyze()
        
        
        
        self.elements[name] = np
        
        return np
    
    def draw_trianglefan(self, ps, color, name, parent = None):
        vdata = GeomVertexData('trig', GeomVertexFormat.getV3(), Geom.UHStatic) 
        vwriter = GeomVertexWriter(vdata, 'vertex')
        
        for i in ps :
            vwriter.addData3f(i[0], i[1], i[2])

        prim = GeomTrifans(Geom.UHStatic)
        
        for i in range(len(ps)) :
            prim.addVertex(i) 
        prim.closePrimitive() 
        
        geom = Geom(vdata) 
        geom.addPrimitive(prim)
        
        geomNode = GeomNode('trig') 
        geomNode.addGeom(geom)
        
        np = NodePath(geomNode)
        
        if parent == None :
            render.attachNewNode(np.node())
        else :
            parent.attachNewNode(np.node())
        #fill=self.screen.attachNewNode(geomNode) 
        #fill.analyze()
        
        
        self.elements[name] = np
    
    def draw_polygon2d(self,ps,color,name):
        vdata = GeomVertexData('trig', GeomVertexFormat.getV3(), Geom.UHStatic) 
        vwriter = GeomVertexWriter(vdata, 'vertex')
        
        trig = Triangulator()
        
        for i in ps :
            vi = trig.addVertex(i[0], i[1])
            vwriter.addData3f(i[0], 0, i[1])
            trig.addPolygonVertex(vi)

        trig.triangulate()
        
        prim = GeomTriangles(Geom.UHStatic)
        
        for i in range(trig.getNumTriangles()): 
            prim.addVertices(trig.getTriangleV0(i), 
                             trig.getTriangleV1(i), 
                             trig.getTriangleV2(i)) 
            prim.closePrimitive() 
        
        geom = Geom(vdata) 
        geom.addPrimitive(prim)
        
        geomNode = GeomNode('trig') 
        geomNode.addGeom(geom)
        
        np = NodePath(geomNode)
        np.reparentTo(self.screen)
        #fill=self.screen.attachNewNode(geomNode) 
        #fill.analyze()
        
        
        self.elements[name] = np
          
    def draw_image2d(self, **kw):
        '''
        tex = loader.loadTexture(texname)
        
        vdata = GeomVertexData('trig', GeomVertexFormat.getV3t2(), Geom.UHStatic)
        vwriter = GeomVertexWriter(vdata, 'vertex')
        twriter = GeomVertexWriter(vdata, 'texcoord')
        
        vwriter.addData3f(i[0], 0, i[1])
        vwriter.addData3f(i[0], 0, i[1])
            
        twriter.addData2f(0, 0)
        twriter.addData2f(0, 1)
        twriter.addData2f(1, 1)
        twriter.addData2f(1, 0)
        
        geom = Geom(vdata)
        tris = GeomTristrips(Geom.UHStatic)
        tris.addVertex(0)
        tris.addVertex(1)
        tris.addVertex(3)
        tris.addVertex(2)
        tris.closePrimitive()
        geom.addPrimitive(tris)
        node = GeomNode(name)
        node.addGeom(geom)
        
        np = self.screen.attachNewNode(node)
        
        np.setTexture(tex)
        np.getTexture().setMinfilter(Texture.FTLinearMipmapLinear)
        
        self.elements[name] = node
        '''
        pos = kw.get('pos', (0, 0))
        size = kw.get('size', None)
        texname = kw.get('texname', None)
        scaleX = kw.get('scaleX', 1)
        scaleY = kw.get('scaleY', 1)
        parent = self.get_parent( kw.get('parent', 'gui_surface') )
        name = kw.get('name', self.generate_name())
        
        tex = Texture()
        if texname <> None :
            if texname in textures.keys() :
                tex = textures[texname]
            else :
                tex = loader.loadTexture(texname)
        

        cm = CardMaker('card')
        xframe = tex.getXSize()
        if tex.getOrigFileXSize() <> 0 : xframe = tex.getOrigFileXSize()

        yframe = tex.getYSize()
        if tex.getOrigFileYSize() <> 0 : yframe = tex.getOrigFileYSize()
        
        if size == None :            
            size = (tex.getXSize(), tex.getYSize())
        cm.setFrame(0,size[0]*scaleX,0,size[1]*scaleY)
        
        card = None
        if parent == None :
            card = self.screen.attachNewNode(cm.generate())
        else :
            card = parent.attachNewNode(cm.generate())
        
        if texname <> None :
            card.setTexture(tex)
        card.setDepthTest(False)
        card.setPos(pos[0],0,pos[1])
        
        #card.setHpr(0,-90,0)

        self.elements[name] = card
        
        return card
    
    def create_image2d(self, **kwargs):
        pos = kwargs.get('pos', (0, 0))
        size = kwargs.get('size', None)
        texname = kwargs.get('texname', None)
        UVmap = kwargs.get('UVmap', 0)
        name = kwargs.get('name', self.generate_name())
        rotate = 0
        for i in kwargs.keys() :
            if i == 'rotate' : rotate = kwargs['rotate']
        cm = CardMaker('card')
        tex = None
        if texname <> None : 
            tex = loader.loadTexture(texname)
            
        if size == None and texname <> None :            
            size = (tex.getOrigFileXSize(), tex.getOrigFileYSize())
            
        cm.setFrame(-float(size[0])/2,float(size[0])/2,-float(size[1])/2,float(size[1])/2)
        
        if tex <> None and UVmap :
            fU, fV = 1, 1 
            if UVmap == 3 or UVmap == 1: fU = float(size[0])/tex.getOrigFileXSize()
            if UVmap == 3 or UVmap == 2: fV = float(size[1])/tex.getOrigFileYSize()
            cm.setUvRange((0, 0),(fU, fV))

        card = NodePath(cm.generate())
        
        if texname <> None :
            card.setTexture(tex)

        card.setDepthTest(False)
        card.setPos(pos[0]+float(size[0])/2,0,pos[1]+float(size[1])/2)
        card.setHpr(0,0,rotate)
        card.setTransparency(TransparencyAttrib.MAlpha)
        
        return card

    def create_model_xt(self, **kw):#pos, model, texture, size, name = None):
        pos = kw.get('pos', (0, 0, 0))
        model = kw.get('fname', None)
        texture = kw.get('texname', None)
        size = kw.get('size', (1, 1))
        name = kw.get('name', self.generate_name())
        if self.check_name(name) :
                #print 'create_model_xt name duplicated', name
                return None
        
        model = self.game_directory + Filename.fromOsSpecific('\\' + model).getFullpath()
        
        a = loader.loadModel(model)
        texture = self.game_directory + Filename.fromOsSpecific('\\' + texture).getFullpath()
        a.setTexture(loader.loadTexture(texture))
        a.reparentTo(render)
        cmin, cmax = a.getTightBounds()
        smax = 0
        
        sx = size[0]/(cmax[0] - cmin[0])
        sy = size[1]/(cmax[1] - cmin[1])
        if sx > sy : smax = sx
        else : smax = sy
        a.setScale(smax)
        
        shiftx = ( (cmax[0] + cmin[0])/2 ) * smax
        shifty = ( (cmax[1] + cmin[1])/2 ) * smax
        
        a.setPos(pos[0] - shiftx,pos[1] - shifty,pos[2])
        
        #m.flattenLight()
        #a.analyze()
        
        if name == None : name = self.generate_name()        
        self.elements[name] = a
        
        return a
    
    def create_model_egg(self, pos, model, texture, size, name = None):
        model = self.game_directory + Filename.fromOsSpecific('\\' + model).getFullpath()
        a = loader.loadModel(model)
        a.reparentTo(render)
        cmin, cmax = a.getTightBounds()
        smax = 0
        sx = size[0]/(cmax[0] - cmin[0])
        sy = size[1]/(cmax[1] - cmin[1])
        if sx > sy : smax = sx
        else : smax = sy
        a.setScale(smax)
        
        shiftx = ( (cmax[0] + cmin[0])/2 ) * smax
        shifty = ( (cmax[1] + cmin[1])/2 ) * smax

        a.setPos(pos[0] - shiftx,pos[1] - shifty,pos[2])
        
        #m.flattenLight()
        #a.analyze()
        
        if name == None : name = self.generate_name()        
        self.elements[name] = a
        print '!!!'
        
        return name
    
    def create_actor_egg(self, **kw):
        model = self.game_directory + Filename.fromOsSpecific('\\' + kw['model']).getFullpath()
        m = loader.loadModel(model)
        a = Actor(m, kw['anims'])
        a.reparentTo(render)
        cmin, cmax = a.getTightBounds()
        smax = 0
        size = kw['size']
        sx = size[0]/(cmax[0] - cmin[0])
        sy = size[1]/(cmax[1] - cmin[1])
        if sx > sy : smax = sx
        else : smax = sy
        a.setScale(smax)
        
        shiftx = ( (cmax[0] + cmin[0])/2 ) * smax
        shifty = ( (cmax[1] + cmin[1])/2 ) * smax
        pos = kw['pos']
        a.setPos(pos[0] - shiftx,pos[1] - shifty,pos[2])
        
        #m.flattenLight()
        #a.analyze()
        name = kw.get('name', None)
        if name == None : name = self.generate_name()
        self.elements[name] = a
        
        return name

    def map_to_scr(self, a):
        #print 'mts', self.map_pos, a, [ (a[0] - self.map_pos[0])*self.map_zoom, (a[1] - self.map_pos[1])*self.map_zoom ], self.width, self.height
        return [ (a[0] - self.map_pos[0])*self.map_zoom, (a[1] - self.map_pos[1])*self.map_zoom ]
    
    def scr_to_map(self, a):
        #a is (-1,-1) to (1,1)
        pos3d = Point3() 
        nearPoint = Point3() 
        farPoint = Point3() 
        self.p3d.camLens.extrude(a, nearPoint, farPoint)
        self.plane.intersectsLine(pos3d, 
                                     render.getRelativePoint(self.p3d.camera, nearPoint), 
                                     render.getRelativePoint(self.p3d.camera, farPoint))
        return pos3d[0],pos3d[1]

    def set_map_pos(self, posx, posy):
        self.p3d.camera.setX(posx)
        self.p3d.camera.setY(posy)
        #self.gr.p3d.camera.lookAt(250,0,550)
        self.map_pos = (posx, posy)

    def set_map_zoom(self, zoom):
        self.p3d.camera.setZ( zoom )

    def zoom_in(self):
        self.p3d.camera.setZ( self.p3d.camera.getZ()*0.9 )
        self.minimap.update_pos(True)
        
        if self.p3d.camera.getZ() < 200 :
            self.paths_all_node.show()

    def zoom_out(self):
        self.p3d.camera.setZ( self.p3d.camera.getZ()*1.1 )
        self.minimap.update_pos(True)
        
        if self.p3d.camera.getZ() > 200 :
            self.paths_all_node.hide()

    def generate_name(self):
        name = str(RANDINT(0,9))
        while name in self.elements.keys() :
            name += str(RANDINT(0,9))
        return name

    def delete_el(self, name):
        if name in self.elements.keys() :
            self.elements[name].removeNode()
            self.elements.pop(name)
    
    def delete_el_mask(self,mask):
        for i in self.elements.keys() :
            if mask in i :
                self.delete_el(i)
                
    def get_num_nodes_rec(self, a):
        x = 0
        l = len(a.getChildren())
        if l == 0 : 
            return 1
        else : 
            for c in a.getChildren() : 
                x += self.get_num_nodes_rec(c)
        return x
    
    def get_num_nodes(self):
        a = self.get_num_nodes_rec(render)
        b = self.get_num_nodes_rec(render2d)
        c = self.get_num_nodes_rec(aspect2d)
        print 'render', a, 'render2d', b, 'aspect2d', c
        
    def check_name(self, name):
        if name in self.elements.keys() : return True
        else : return False

    def keyboard(self, st, keyname):
        if st == 0 : self.game_pipe.send(('key_down', keyname))
        elif st == 1 : self.game_pipe.send(('key_up', keyname))
        elif st == 2 : self.game_pipe.send(('key_rep', keyname))
Esempio n. 26
0
from panda3d.core import ConfigVariableBool, ConfigVariableString, ConfigVariableInt

# Server related config variables
sv_max_clients = ConfigVariableInt("sv_max_clients", 24)
sv_password = ConfigVariableString("sv_password", "")
sv_minupdaterate = ConfigVariableInt("sv_minupdaterate", 1)
sv_maxupdaterate = ConfigVariableInt("sv_maxupdaterate", 255)
sv_tickrate = ConfigVariableInt("sv_tickrate", 66)
# How many past snapshots do we save?
sv_snapshot_history = ConfigVariableInt("sv_snapshot_history", 50)
sv_port = ConfigVariableInt("sv_port", 27015)
sv_alternateticks = ConfigVariableBool("sv_alternateticks", False)
Esempio n. 27
0
    def __init__(self):
        ShowBase.__init__(self)
        FSM.__init__(self, "FSM-Game")

        #
        # BASIC APPLICATION CONFIGURATIONS
        #
        self.disableMouse()
        self.setBackgroundColor(0, 0, 0)
        self.camLens.setFov(75)
        self.camLens.setNear(0.8)

        # check if the config file hasn't been created
        base.textWriteSpeed = 0.05
        mute = ConfigVariableBool("audio-mute", False).getValue()
        if mute:
            self.disableAllAudio()
        else:
            self.enableAllAudio()
        particles = ConfigVariableBool("particles-enabled", True).getValue()
        if particles:
            self.enableParticles()
        base.textWriteSpeed = ConfigVariableDouble("text-write-speed",0.05).getValue()
        base.controlType = ConfigVariableString("control-type", "Gamepad").getValue()
        base.mouseSensitivity = ConfigVariableDouble("mouse-sensitivity",1.0).getValue()
        if not os.path.exists(prcFile):
            self.__writeConfig()
            # set window properties
            # clear all properties not previously set
            self.win.clearRejectedProperties()
            # setup new window properties
            props = WindowProperties()
            # Fullscreen
            props.setFullscreen(True)
            # window icon
            print props.hasIconFilename()
            props.setIconFilename(windowicon)
            # get the displays width and height
            w = self.pipe.getDisplayWidth()
            h = self.pipe.getDisplayHeight()
            # set the window size to the screen resolution
            props.setSize(w, h)
            # request the new properties
            self.win.requestProperties(props)
        atexit.register(self.__writeConfig)

        # enable collision handling
        base.cTrav = CollisionTraverser("base collision traverser")
        base.pusher = CollisionHandlerPusher()
        base.pusher.addInPattern('%fn-in-%in')
        base.pusher.addOutPattern('%fn-out-%in')

        self.menu = Menu()
        self.options = OptionsMenu()

        self.musicMenu = loader.loadMusic("MayanJingle6_Menu.ogg")
        self.musicMenu.setLoop(True)

        cm = CardMaker("menuFade")
        cm.setFrameFullscreenQuad()
        self.menuCoverFade = NodePath(cm.generate())
        self.menuCoverFade.setTransparency(TransparencyAttrib.MAlpha)
        self.menuCoverFade.setBin("fixed", 1000)
        self.menuCoverFade.reparentTo(render2d)
        self.menuCoverFade.hide()
        self.menuCoverFadeOutInterval = Sequence(
            Func(self.menuCoverFade.show),
            LerpColorScaleInterval(
                self.menuCoverFade,
                1,
                LVecBase4f(0.0,0.0,0.0,1.0),
                LVecBase4f(0.0,0.0,0.0,0.0)),
            Func(self.menuCoverFade.hide))
        self.menuCoverFadeInInterval = Sequence(
            Func(self.menuCoverFade.show),
            LerpColorScaleInterval(
                self.menuCoverFade,
                1,
                LVecBase4f(0.0,0.0,0.0,0.0),
                LVecBase4f(0.0,0.0,0.0,1.0)),
            Func(self.menuCoverFade.hide))
        self.lerpAudioFadeOut = LerpFunc(
            self.audioFade,
            fromData=1.0,
            toData=0.0,
            duration=0.25,
            extraArgs=[self.musicMenu])
        self.fadeMusicOut = Sequence(
            self.lerpAudioFadeOut,
            Func(self.musicMenu.stop))
        self.lerpAudioFadeIn = LerpFunc(
            self.audioFade,
            fromData=0.0,
            toData=1.0,
            duration=1,
            extraArgs=[self.musicMenu])
        self.fadeMusicIn = Sequence(
                Func(self.musicMenu.play),
                self.lerpAudioFadeIn)

        self.seqFade = None
        self.acceptAll()

        self.request("Intro")
Esempio n. 28
0
if __name__ == "__main__":

    import builtins
    from src.coginvasion.base.Metadata import Metadata
    metadata = Metadata()
    builtins.metadata = metadata

    from panda3d.core import loadPrcFile, loadPrcFileData, ConfigVariableString, ConfigVariableDouble
    loadPrcFile('config/Confauto.prc')
    loadPrcFile('config/config_client.prc')
    loadPrcFileData(
        '', 'model-path ./resources')  # Don't require mounting of phases

    if ConfigVariableString("threading-model", "").getValue() == "Cull/Draw":
        metadata.MULTITHREADED_PIPELINE = 1

    from src.coginvasion.settings.SettingsManager import SettingsManager
    from src.coginvasion.settings.Setting import SHOWBASE_PREINIT, SHOWBASE_POSTINIT
    jsonFile = "settings.json"

    sm = SettingsManager()

    from src.coginvasion.globals import CIGlobals
    CIGlobals.SettingsMgr = sm
    sm.loadFile(jsonFile)
    sm.doSunriseFor(sunrise=SHOWBASE_PREINIT)

    from src.mod.ModBase import ModBase
    base = ModBase()

    sm.doSunriseFor(sunrise=SHOWBASE_POSTINIT)
Esempio n. 29
0
from direct.directnotify.DirectNotifyGlobal import directNotify
from panda3d.core import ConfigVariableString

notify = directNotify.newCategory('PLocalizer')

language = ConfigVariableString('language', 'English').getValue()
_PLocalizer = 'pirates.piratesbase.PLocalizer' + language
_PQuestStrings = 'pirates.piratesbase.PQuestStrings' + language
_PDialogStrings = 'pirates.piratesbase.PDialogStrings' + language
_PGreetingStrings = 'pirates.piratesbase.PGreetingStrings' + language

try:
    exec 'from ' + _PLocalizer + ' import *'
    exec 'from ' + _PQuestStrings + ' import *'
    exec 'from ' + _PDialogStrings + ' import *'
    exec 'from ' + _PGreetingStrings + ' import *'
    notify.info("Running in language: %s" % language)
except:
    notify.warning("Language '%s' not found! Setting as default (English)" %
                   language)
    from pirates.piratesbase.PLocalizerEnglish import *
    from pirates.piratesbase.PQuestStringsEnglish import *
    from pirates.piratesbase.PDialogStringsEnglish import *
    from pirates.piratesbase.PGreetingStringsEnglish import *


def getLanguage():
    return language
Esempio n. 30
0
#loadPrcFileData('','win-origin -2 -2')

from panda3d.core import ConfigVariableInt
from panda3d.core import ConfigVariableBool
from panda3d.core import ConfigVariableString

config_aa = ConfigVariableInt('multisamples', 0)
config_fulscreen = ConfigVariableBool('fullscreen')
config_win_size = ConfigVariableInt('win-size', '640 480')
config_bloom = ConfigVariableBool('bloom', 1)
config_safemode = ConfigVariableBool('safemode', 0)
config_eye_enabled = ConfigVariableBool('eye_enabled', 0)
config_music = ConfigVariableInt('music-volume', '30')
config_sfx = ConfigVariableInt('sound-volume', '100')
#keys
config_forward = ConfigVariableString('key_forward', 'w|arrow_up')
config_back = ConfigVariableString('key_back', 's|arrow_down')
config_left = ConfigVariableString('key_left', 'a|arrow_left')
config_right = ConfigVariableString('key_right', 'd|arrow_right')
config_camera_left = ConfigVariableString('key_cam_left', 'q|delete')
config_camera_right = ConfigVariableString('key_cam_right', 'e|page_down')
config_action1 = ConfigVariableString('key_action1', 'mouse1|left_eye')
config_action2 = ConfigVariableString('key_action2', 'mouse3|right_eye')
config_zoomin = ConfigVariableString('key_zoomin', 'wheel_up|r')
config_zoomout = ConfigVariableString('key_zoomout', 'wheel_down|f')

from panda3d.core import WindowProperties

wp = WindowProperties.getDefault()
wp.setFixedSize(True)
wp.setCursorHidden(False)
Esempio n. 31
0
    def __init__(self):
        #
        # BASIC APPLICATION CONFIGURATIONS
        #
        # disable pandas default camera driver
        self.disableMouse()
        # set antialias for the complete sceen to automatic
        self.render.setAntialias(AntialiasAttrib.MAuto)
        # shader generator
        #render.setShaderAuto()
        # Enhance font readability
        font = loader.loadFont("assets/fonts/OldaniaADFStd-Regular.otf")
        DGG.setDefaultFont(font)
        DGG.getDefaultFont().setPixelsPerUnit(100)
        # get the displays width and height for later usage
        self.dispWidth = self.pipe.getDisplayWidth()
        self.dispHeight = self.pipe.getDisplayHeight()

        base.serverHost = ConfigVariableString("server-host", "127.0.0.1:4400")

        #
        # CONFIGURATION LOADING
        #
        # load given variables or set defaults
        # check if particles should be enabled
        # NOTE: If you use the internal physics engine, this always has
        #       to be enabled!
        particles = ConfigVariableBool("particles-enabled", True).getValue()
        if particles:
            self.enableParticles()

        def setFullscreen():
            """Helper function to set the window fullscreen
            with width and height set to the screens size"""
            # set window properties
            # clear all properties not previously set
            base.win.clearRejectedProperties()
            # setup new window properties
            props = WindowProperties()
            # Fullscreen
            props.setFullscreen(True)
            # set the window size to the screen resolution
            props.setSize(self.dispWidth, self.dispHeight)
            # request the new properties
            base.win.requestProperties(props)
            # Set the config variables so we correctly store the
            # new size and fullscreen setting later
            winSize = ConfigVariableString("win-size")
            winSize.setValue("{} {}".format(self.dispWidth, self.dispHeight))
            fullscreen = ConfigVariableBool("fullscreen")
            fullscreen.setValue(True)
            # Render a frame to make sure the fullscreen is applied
            # before we do anything else
            self.taskMgr.step()
            # make sure to propagate the new aspect ratio properly so
            # the GUI and other things will be scaled appropriately
            aspectRatio = self.dispWidth / self.dispHeight
            self.adjustWindowAspectRatio(aspectRatio)

        # check if the config file hasn't been created
        if not os.path.exists(prcFile):
            setFullscreen()

        # automatically safe configuration at application exit
        base.exitFunc = self.writeConfig
DODGEBLUE = (0.11, 0.53, 0.93, 1)
DARKGRAIN = (0.5, 0.5, 0.5, 0.5)
OLIVE = (0.33, 0.42, 0.18, 1)
YELLOWGREEN = (0.60, 0.80, 0.20, 1)
KHAKI = (0.74, 0.72, 0.42, 1)
FIREBRICK = (0.70, 0.13, 0.13, 1)
MARRON = (0.69, 0.19, 0.38, 1)
VIOLET = (0.78, 0.08, 0.52, 1)
BROWN = (0.55, 0.27, 0.07, 1)
SNOW = (0.55, 0.27, 0.07, 1)
GOLD = (1, 0.84, 0, 1)
RED = (1, 0, 0, 1)
GREEN = (0, 1, 0, 1)
BLUE = (0, 0, 1, 1)
BLACK = (0, 0, 0, 1)
WHITE = (1, 1, 1, 1)

#PANDA
#www.panda3d.org/manual/index.php/List_of_all_config_variables
ConfigVariableString("window-title",
                     'Panda').setStringValue(PROJECT_NAME + ' - ' + VERSION)

ConfigVariableBool('fullscreen', 0).setValue(FULLSCREEN)
ConfigVariableString(
    'win-size', '640 480').setValue(str(WINSIZE[0]) + ' ' + str(WINSIZE[1]))
ConfigVariableBool('show-frame-rate-meter', '').setValue(DEBUG)

#ConfigVariableString('load-display', 'pandagl').setValue('pandagl') #pandagl, pandadx9, pandadx8, tinydisplay
#ConfigVariableString ('aux-display', 'pandagl').setValue('pandagl')  #pandagl, pandadx9, pandadx8, tinydisplay
#ConfigVariableBool  ('undecorated', '').setValue(True)
Esempio n. 33
0
    def setP3DFilename(self,
                       p3dFilename,
                       tokens,
                       argv,
                       instanceId,
                       interactiveConsole,
                       p3dOffset=0,
                       p3dUrl=None):
        """ Called by the browser to specify the p3d file that
        contains the application itself, along with the web tokens
        and/or command-line arguments.  Once this method has been
        called, the application is effectively started. """

        # One day we will have support for multiple instances within a
        # Python session.  Against that day, we save the instance ID
        # for this instance.
        self.instanceId = instanceId

        self.tokens = tokens
        self.argv = argv

        # We build up a token dictionary with care, so that if a given
        # token appears twice in the token list, we record only the
        # first value, not the second or later.  This is consistent
        # with the internal behavior of the core API.
        self.tokenDict = {}
        for token, keyword in tokens:
            self.tokenDict.setdefault(token, keyword)

        # Also store the arguments on sys, for applications that
        # aren't instance-ready.
        sys.argv = argv

        # That means we now know the altHost in effect.
        self.altHost = self.tokenDict.get('alt_host', None)

        # Tell the browser that Python is up and running, and ready to
        # respond to queries.
        self.notifyRequest('onpythonload')

        # Now go load the applet.
        fname = Filename.fromOsSpecific(p3dFilename)
        vfs = VirtualFileSystem.getGlobalPtr()

        if not vfs.exists(fname):
            raise ArgumentError, "No such file: %s" % (p3dFilename)

        fname.makeAbsolute()
        fname.setBinary()
        mf = Multifile()
        if p3dOffset == 0:
            if not mf.openRead(fname):
                raise ArgumentError, "Not a Panda3D application: %s" % (
                    p3dFilename)
        else:
            if not mf.openRead(fname, p3dOffset):
                raise ArgumentError, "Not a Panda3D application: %s at offset: %s" % (
                    p3dFilename, p3dOffset)

        # Now load the p3dInfo file.
        self.p3dInfo = None
        self.p3dPackage = None
        self.p3dConfig = None
        self.allowPythonDev = False

        i = mf.findSubfile('p3d_info.xml')
        if i >= 0 and hasattr(core, 'readXmlStream'):
            stream = mf.openReadSubfile(i)
            self.p3dInfo = core.readXmlStream(stream)
            mf.closeReadSubfile(stream)
        if self.p3dInfo:
            self.p3dPackage = self.p3dInfo.FirstChildElement('package')
        if self.p3dPackage:
            self.p3dConfig = self.p3dPackage.FirstChildElement('config')

            xhost = self.p3dPackage.FirstChildElement('host')
            while xhost:
                self.__readHostXml(xhost)
                xhost = xhost.NextSiblingElement('host')

        if self.p3dConfig:
            allowPythonDev = self.p3dConfig.Attribute('allow_python_dev')
            if allowPythonDev:
                self.allowPythonDev = int(allowPythonDev)
            guiApp = self.p3dConfig.Attribute('gui_app')
            if guiApp:
                self.guiApp = int(guiApp)

            trueFileIO = self.p3dConfig.Attribute('true_file_io')
            if trueFileIO:
                self.trueFileIO = int(trueFileIO)

        # The interactiveConsole flag can only be set true if the
        # application has allow_python_dev set.
        if not self.allowPythonDev and interactiveConsole:
            raise StandardError, "Impossible, interactive_console set without allow_python_dev."
        self.interactiveConsole = interactiveConsole

        if self.allowPythonDev:
            # Set the fps text to remind the user that
            # allow_python_dev is enabled.
            ConfigVariableString('frame-rate-meter-text-pattern').setValue(
                'allow_python_dev %0.1f fps')

        if self.guiApp:
            init_app_for_gui()

        self.initPackedAppEnvironment()

        # Mount the Multifile under self.multifileRoot.
        vfs.mount(mf, self.multifileRoot, vfs.MFReadOnly)
        self.p3dMultifile = mf
        VFSImporter.reloadSharedPackages()

        self.loadMultifilePrcFiles(mf, self.multifileRoot)
        self.gotP3DFilename = True
        self.p3dFilename = fname
        if p3dUrl:
            # The url from which the p3d file was downloaded is
            # provided if available.  It is only for documentation
            # purposes; the actual p3d file has already been
            # downloaded to p3dFilename.
            self.p3dUrl = core.URLSpec(p3dUrl)

        # Send this call to the main thread; don't call it directly.
        messenger.send('AppRunner_startIfReady', taskChain='default')
Esempio n. 34
0
def GetString(sym, default=""):
    return ConfigVariableString(sym, default, "DConfig", ConfigFlags.F_dconfig).value