Exemplo n.º 1
0
 def __init__(self, parent, res=(1024, 768)):
     self.parent = parent
     # Init pipe
     ShowBase()
     base.makeDefaultPipe()
     screen = (base.pipe.getDisplayWidth(), base.pipe.getDisplayHeight())
     win = WindowProperties.getDefault()
     xsize = ConfigVariableInt("resx", res[0]).getValue()
     ysize = ConfigVariableInt("resy", res[1]).getValue()
     win.setSize(xsize, ysize)
     win.setFullscreen(False)
     base.openDefaultWindow(win)
Exemplo n.º 2
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()
Exemplo n.º 3
0
 def __init__(self):
     self._doId2name2data = {}
     # maximum # of objects we will cache data for
     self._size = ConfigVariableInt('crdatacache-size', 10).getValue()
     assert self._size > 0
     # used to preserve the cache size
     self._junkIndex = 0
Exemplo n.º 4
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)
Exemplo n.º 5
0
    def __init__(self):
        self._http_client = HTTPClient()

        max_http_requests = ConfigVariableInt('http-max-requests', 900).value
        self._request_allocator = UniqueIdAllocator(0, max_http_requests)
        self._poll_task = None
        self._requests = {}
Exemplo n.º 6
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)
Exemplo n.º 7
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()
 def __init__(self):
     """initialise the server class"""
     print("SETUP SERVER")
     tcpPort = ConfigVariableInt("server-port", 4400)
     dcFileNames = [
         "interfaces/direct.dc", "interfaces/gameRoom.dc",
         "interfaces/chat.dc"
     ]
     ServerRepository.__init__(self, tcpPort, dcFileNames=dcFileNames)
     print("SETUP SERVER DONE")
Exemplo n.º 9
0
 def __init__(self, namePrefix):
     self._namePrefix = namePrefix
     self._durationAverager = Averager('%s-durationAverager' % namePrefix)
     self._avgSession = None
     if TaskTracker.MinSamples is None:
         # number of samples required before spikes start getting identified
         TaskTracker.MinSamples = ConfigVariableInt(
             'profile-task-spike-min-samples', 30).value
         # defines spike as longer than this multiple of avg task duration
         TaskTracker.SpikeThreshold = TaskProfiler.GetDefaultSpikeThreshold(
         )
Exemplo n.º 10
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')
Exemplo n.º 11
0
    def __init__(self):
        """initialise the server class"""

        # get the port number from the configuration file
        # if it doesn't exist, we use 4400 as the default
        tcpPort = ConfigVariableInt('server-port', 4400).getValue()

        # list of all needed .dc files
        dcFileNames = ['../direct.dc']

        # initialise a threaded server on this machine with
        # the port number and the dc filenames
        ServerRepository.__init__(self,
                                  tcpPort,
                                  dcFileNames=dcFileNames,
                                  threadedNet=True)
Exemplo n.º 12
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])
Exemplo n.º 13
0
    f = open(path+'config.txt', 'r')
    for line in f:        
        if not line.startswith('#'):        
            loadPrcFileData('',line)
except IOError:
    print "No custom config file" 
    
from panda3d.core import WindowProperties
from panda3d.core import ConfigVariableInt
from panda3d.core import ConfigVariableBool
from panda3d.core import ConfigVariableString 
config_nude=ConfigVariableInt('loverslab', 0)   
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', '30') 
config_sfx=ConfigVariableInt('sound-volume', '100') 
config_safemode=ConfigVariableBool('safemode', 0)
#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|enter')
config_action2=ConfigVariableString('key_action2', 'mouse3|space')
config_zoomin=ConfigVariableString('key_zoomin', 'wheel_up|r')
 def execCommand(self, command, mwMgrId, avId, zoneId):
     length = ConfigVariableInt("ai-debug-length", 300)
     text = str(self.__execMessage(command))[:length.value]
     self.notify.info(text)
def getConfigInt(name, default):
    output = ConfigVariableInt(name, default).getValue()
    if RUNTYPE != 'python':
        if AppRunnerGlobal.appRunner.getTokenInt(name):
            output = AppRunnerGlobal.appRunner.getTokenInt(name)
    return output
Exemplo n.º 16
0
except IOError:
    print("No config file, using default")
try:
    f = open(path+'config.txt', 'r')
    for line in f:
        if not line.startswith('#'):
            loadPrcFileData('',line)
except IOError:
    print("No custom config file")


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')
Exemplo n.º 17
0
    def downloadContentsFile(self, http, redownload=False, hashVal=None):
        """ Downloads the contents.xml file for this particular host,
        synchronously, and then reads it.  Returns true on success,
        false on failure.  If hashVal is not None, it should be a
        HashVal object, which will be filled with the hash from the
        new contents.xml file."""

        if self.hasCurrentContentsFile():
            # We've already got one.
            return True

        if self.appRunner and self.appRunner.verifyContents == self.appRunner.P3DVCNever:
            # Not allowed to.
            return False

        rf = None
        if http:
            if not redownload and self.appRunner and self.appRunner.superMirrorUrl:
                # We start with the "super mirror", if it's defined.
                url = self.appRunner.superMirrorUrl + 'contents.xml'
                request = DocumentSpec(url)
                self.notify.info("Downloading contents file %s" % (request))

                rf = Ramfile()
                channel = http.makeChannel(False)
                channel.getDocument(request)
                if not channel.downloadToRam(rf):
                    self.notify.warning("Unable to download %s" % (url))
                    rf = None

            if not rf:
                # Then go to the main host, if our super mirror let us
                # down.

                url = self.hostUrlPrefix + 'contents.xml'
                # Append a uniquifying query string to the URL to force the
                # download to go all the way through any caches.  We use the
                # time in seconds; that's unique enough.
                url += '?' + str(int(time.time()))

                # We might as well explicitly request the cache to be disabled
                # too, since we have an interface for that via HTTPChannel.
                request = DocumentSpec(url)
                request.setCacheControl(DocumentSpec.CCNoCache)

                self.notify.info("Downloading contents file %s" % (request))
                statusCode = None
                statusString = ''
                for attempt in range(
                        int(ConfigVariableInt('contents-xml-dl-attempts', 3))):
                    if attempt > 0:
                        self.notify.info("Retrying (%s)..." % (attempt, ))
                    rf = Ramfile()
                    channel = http.makeChannel(False)
                    channel.getDocument(request)
                    if channel.downloadToRam(rf):
                        self.notify.info("Successfully downloaded %s" %
                                         (url, ))
                        break
                    else:
                        rf = None
                        statusCode = channel.getStatusCode()
                        statusString = channel.getStatusString()
                        self.notify.warning(
                            "Could not contact download server at %s" %
                            (url, ))
                        self.notify.warning("Status code = %s %s" %
                                            (statusCode, statusString))

                if not rf:
                    self.notify.warning("Unable to download %s" % (url, ))
                    try:
                        # Something screwed up.
                        if statusCode == HTTPChannel.SCDownloadOpenError or \
                           statusCode == HTTPChannel.SCDownloadWriteError:
                            launcher.setPandaErrorCode(2)
                        elif statusCode == 404:
                            # 404 not found
                            launcher.setPandaErrorCode(5)
                        elif statusCode < 100:
                            # statusCode < 100 implies the connection attempt itself
                            # failed.  This is usually due to firewall software
                            # interfering.  Apparently some firewall software might
                            # allow the first connection and disallow subsequent
                            # connections; how strange.
                            launcher.setPandaErrorCode(4)
                        else:
                            # There are other kinds of failures, but these will
                            # generally have been caught already by the first test; so
                            # if we get here there may be some bigger problem.  Just
                            # give the generic "big problem" message.
                            launcher.setPandaErrorCode(6)
                    except NameError, e:
                        # no launcher
                        pass
                    except AttributeError, e:
                        self.notify.warning("%s" % (str(e), ))
                        pass
                    return False
Exemplo n.º 18
0
def GetInt(sym, default=0):
    return ConfigVariableInt(sym, default, "DConfig", ConfigFlags.F_dconfig).value
Exemplo n.º 19
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)
Exemplo n.º 20
0
 def getInt(self, var, default):
     return ConfigVariableInt(var, default).getValue()
Exemplo n.º 21
0
 def _loadConfig (self):
     """
         Loads network configuration defaults.
     """
     self._portAddress = ConfigVariableInt("default-port",
                                           DEFAULT_PORT).getValue()
Exemplo n.º 22
0
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",
    "The default model used when placing a prop_static or prop_dynamic entity."
)
Exemplo n.º 23
0
    def __init__(self):
        ShowBase.__init__(self)
        FSM.__init__(self, "mainStateMachine")

        # some basic enhancements
        # window background color
        self.setBackgroundColor(0, 0, 0)
        # set antialias for the complete sceen to automatic
        self.render.setAntialias(AntialiasAttrib.MAuto)
        # shader generator
        render.setShaderAuto()
        # Enhance font readability
        DGG.getDefaultFont().setPixelsPerUnit(100)
        # hide the mouse cursor
        hide_cursor()

        #
        # CONFIGURATION LOADING
        #
        # load given variables or set defaults
        # check if audio should be muted
        mute = ConfigVariableBool("audio-mute", False).getValue()
        if mute:
            self.disableAllAudio()
        else:
            self.enableAllAudio()

        base.sfxManagerList[0].setVolume(
            ConfigVariableDouble("audio-volume-sfx", 1.0).getValue())
        base.difficulty = ConfigVariableInt("difficulty", 0).getValue()

        def setFullscreen():
            """Helper function to set the window fullscreen
            with width and height set to the screens size"""
            # get the displays width and height
            w = self.pipe.getDisplayWidth()
            h = self.pipe.getDisplayHeight()
            # 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(w, h)
            # request the new properties
            base.win.requestProperties(props)

        # check if the config file hasn't been created
        if not os.path.exists(prcFile):
            setFullscreen()
        elif base.appRunner:
            # When the application is started as appRunner instance, it
            # doesn't respect our loadPrcFiles configurations specific
            # to the window as the window is already created, hence we
            # need to manually set them here.
            for dec in range(mainConfig.getNumDeclarations()):
                # check if we have the fullscreen variable
                if mainConfig.getVariableName(dec) == "fullscreen":
                    setFullscreen()
        # automatically safe configuration at application exit
        base.exitFunc = self.__writeConfig

        # due to the delayed window resizing and switch to fullscreen
        # we wait some time until everything is set so we can savely
        # proceed with other setups like the menus
        if base.appRunner:
            # this behaviour only happens if run from p3d files and
            # hence the appRunner is enabled
            taskMgr.doMethodLater(0.5,
                                  self.postInit,
                                  "post initialization",
                                  extraArgs=[])
        else:
            self.postInit()
Exemplo n.º 24
0
tk = Tk()
tk.title("Kettle3D Launcher")
tk.wm_attributes("-topmost", 1)
tk.configure(bg='#47ad73')
canvas = Canvas(tk, width=500, height=500, bd=0, highlightthickness=0)
canvas.pack()
tk.update()

# username_entry = None
# world_entry = None
llBtn = None
cllBtn = None
gllBtn = None

title = ConfigVariableString('window-title', 'Kettle3D')
fullscreen = ConfigVariableInt('fullscreen', settings["config"]["fullscreen"])
notify_level = ConfigVariableString('default-directnotify-level',
                                    settings['config']["log_level"])
c_notify_level = ConfigVariableString('notify-level',
                                      settings['config']["c++_log_level"])
glgsg_notify_level = ConfigVariableString('notify-level-glgsg',
                                          settings['config']['gl_log_level'])

files = pickle.load(open(directory + normpath("assets/files.dat"), 'rb'))

catchAllOutputLog.debug("The launcher window opened successfully.")

fileManagerOutputLog.debug(
    "Have 2 files and 2 versions to check or download...")

downloadfile = txtfile(path='lib/launcherbase.py', version=4)
Exemplo n.º 25
0
#from otp.ai.AIBaseGlobal import *
from direct.directnotify import DirectNotifyGlobal
from direct.showbase.DirectObject import DirectObject
from .ConnectionRepository import *
from panda3d.core import ConfigVariableDouble, ConfigVariableInt, ConfigVariableBool

ASYNC_REQUEST_DEFAULT_TIMEOUT_IN_SECONDS = 8.0
ASYNC_REQUEST_INFINITE_RETRIES = -1
ASYNC_REQUEST_DEFAULT_NUM_RETRIES = 0

if __debug__:
    _overrideTimeoutTimeForAllAsyncRequests = ConfigVariableDouble(
        "async-request-timeout", -1.0)
    _overrideNumRetriesForAllAsyncRequests = ConfigVariableInt(
        "async-request-num-retries", -1)
    _breakOnTimeout = ConfigVariableBool("async-request-break-on-timeout",
                                         False)


class AsyncRequest(DirectObject):
    """
    This class is used to make asynchronos reads and creates to a database.

    You can create a list of self.neededObjects and then ask for each to be
    read or created, or if you only have one object that you need you can
    skip the self.neededObjects because calling askForObject or createObject
    will set the self.neededObjects value for you.

    Once all the objects have been read or created, the self.finish() method
    will be called.  You may override this function to run your code in a
    derived class.
Exemplo n.º 26
0
try:
    f = open(path + 'autoconfig.txt', 'r')
    for line in f:
        if not line.startswith('#'):
            loadPrcFileData('', line)
except IOError:
    print("No config file, using default")

loadPrcFileData('', 'show-frame-rate-meter  #f')
#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')
Exemplo n.º 27
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()
Exemplo n.º 28
0
from panda3d.core import ConfigVariableInt

cl_cmdrate = ConfigVariableInt("cl_cmdrate", 30)
cl_updaterate = ConfigVariableInt("cl_updaterate", 20)