Пример #1
0
def loader(timer):
    # XXX: Remember, game.XXX -> sys.modules["game.XXX"] because game is set later on. And somehow this causes weird behavior :/
    
    IS_IN_TEST = "trial_temp" in os.getcwd()
    if IS_IN_TEST:
        os.chdir("..")
        # Also ugly hack.
        sys.stdout = StringIO()
        
    # Attempt to get the Merucurial rev
    if os.path.exists(".hg"):
        try:
            # This will work independantly of the OS (no need to have mercurial installed!
            # Not sure if it's 100% accurate, be aware that this is not the active rev, but the latest fetched one.
            # Downloaded packages doesn't have this file, thats why we keep in in a try, it will raise.
            
            MERCURIAL_REV = (os.path.getsize(".hg/store/00changelog.i") // 64) - 1 # Since mercurial start on rev 0, we need to -1 to get the rev number.
            #MERCURIAL_REV = subprocess.check_output(["hg", "parents", "--template={rev}"])
            log.msg("Begin loading (PyOT r%s)" % MERCURIAL_REV)
            if platform.system() == "Windows":
                os.system("title PyOT r%s" % MERCURIAL_REV)
                windowsLoading()
            else:
                sys.stdout.write("\x1b]2;PyOT r%s\x07" % MERCURIAL_REV)

        except (OSError, subprocess.CalledProcessError):
            # hg not in space.
            log.msg("Begin loading...")
            if platform.system() == "Windows":
                os.system("title PyOT")
                windowsLoading()
            else:
                sys.stdout.write("\x1b]2;PyOT\x07")
    else:
        MERCURIAL_REV = "unknown"
        log.msg("Begin loading...")
        if platform.system() == "Windows":
            os.system("title PyOT")
            windowsLoading()
        else:
            sys.stdout.write("\x1b]2;PyOT\x07")      
            
    
    # Begin loading items
    sys.modules["game.item"].loadItems()
    
    # Reset online status
    print "> > Reseting players online status...",
    sql.conn.runOperation("UPDATE players SET online = 0")
    print "%40s\n" % _txtColor("\t[DONE]", "blue")
    
   
    globalData = sql.conn.runQuery("SELECT `key`, `data`, `type` FROM `globals` WHERE `world_id` = %s" % config.worldId)
    groupData = sql.conn.runQuery("SELECT `group_id`, `group_name`, `group_flags` FROM `groups`")
    houseData = sql.conn.runQuery("SELECT `id`,`owner`,`guild`,`paid`,`name`,`town`,`size`,`rent`,`data` FROM `houses` WHERE `world_id` = %s" % config.worldId)

    # Globalize certain things
    print "> > Globalize data...",
    const = sys.modules["game.const"]
    __builtin__.const = const

    for i in dir(const):
        if not "__" in i:
            setattr(__builtin__, i, getattr(const, i))

    for i in dir(sys.modules["game.errors"]):
        if not "__" in i:
            setattr(__builtin__, i, getattr(sys.modules["game.errors"], i))

    for i in sys.modules["game.functions"].globalize:
        setattr(__builtin__, i, getattr(sys.modules["game.functions"], i))

    print "%55s\n" % _txtColor("\t[DONE]", "blue")

    __builtin__.sql = sql.conn
    __builtin__.config = config
    __builtin__.userconfig = userconfig

    import game.pathfinder

    __builtin__.register = game.scriptsystem.register
    __builtin__.registerFirst = game.scriptsystem.registerFirst
    __builtin__.registerForAttr = game.scriptsystem.registerForAttr
    __builtin__.registerClass = game.scriptsystem.registerClass
    __builtin__.defer = defer
    __builtin__.reactor = reactor
    __builtin__.functions = game.functions
    __builtin__.sys = sys
    __builtin__.math = math
    __builtin__.returnValue = returnValue
    __builtin__.Deferred = Deferred
    __builtin__.deque = deque
    __builtin__.random = random
    __builtin__.time = time
    __builtin__.re = re
    __builtin__.spell = game.spell # Simplefy spell making
    __builtin__.callLater = reactor.callLater
    __builtin__.Item = game.item.Item
    __builtin__.itemAttribute = game.item.attribute
    __builtin__.cid = game.item.cid
    __builtin__.idByName = game.item.idByName
    __builtin__.getTile = game.map.getTile
    __builtin__.setTile = game.map.setTile
    __builtin__.getTileConst = game.map.getTileConst
    __builtin__.Boost = game.conditions.Boost
    __builtin__.MultiCondition = game.conditions.MultiCondition
    __builtin__.itemAttribute = game.item.attribute
    __builtin__.getHouseId = game.map.getHouseId
    __builtin__.Position = game.position.Position
    __builtin__.StackPosition = game.position.StackPosition
    __builtin__.getHouseById = game.house.getHouseById
    __builtin__.getGuildById = game.guild.getGuildById
    __builtin__.getGuildByName = game.guild.getGuildByName
    __builtin__.logger = sys.modules["game.logger"]

    # Resources
    __builtin__.genMonster = game.monster.genMonster
    __builtin__.genNPC = game.npc.genNPC
    __builtin__.genQuest = game.resource.genQuest
    __builtin__.genOutfit = game.resource.genOutfit
    __builtin__.genMount = game.resource.genMount
    __builtin__.regVocation = game.vocation.regVocation

    # Spells
    __builtin__.typeToEffect = game.spell.typeToEffect

    # Grab them
    __builtin__.getNPC = game.npc.getNPC
    __builtin__.getMonster = game.monster.getMonster

    # Used alot in monster and npcs
    __builtin__.chance = game.monster.chance

    # We use this in the import system
    __builtin__.scriptInitPaths = game.scriptsystem.scriptInitPaths

    # Access
    __builtin__.access = game.scriptsystem.access
    
    # Conditions
    __builtin__.Condition = game.conditions.Condition
    __builtin__.Boost = game.conditions.Boost
    __builtin__.CountdownCondition = game.conditions.CountdownCondition
    __builtin__.PercentCondition = game.conditions.PercentCondition
    __builtin__.MultiCondition = game.conditions.MultiCondition
    __builtin__.RepeatCondition = game.conditions.RepeatCondition

    # Pathfinder
    __builtin__.pathfinder = game.pathfinder

    # Deathlist
    __builtin__.deathlist = game.deathlist

    # Bans
    __builtin__.ipIsBanned = game.ban.ipIsBanned
    __builtin__.playerIsBanned = game.ban.playerIsBanned
    __builtin__.accountIsBanned = game.ban.accountIsBanned
    __builtin__.addBan = game.ban.addBan

    # Market
    __builtin__.getMarket = game.market.getMarket
    __builtin__.newMarket = game.market.newMarket

    # Creature and Player class. Mainly for test and savings.
    __builtin__.Creature = game.creature.Creature
    __builtin__.Player = game.player.Player
    __builtin__.Monster = game.monster.Monster

    # JSON
    __builtin__.json = otjson

    # Web
    if config.enableWebProtocol:
        import core.service.webserver
        __builtin__.WebPage = core.service.webserver.Page
        from twisted.web.server import NOT_DONE_YET
        __builtin__.NOT_DONE_YET = NOT_DONE_YET

    class Globalizer(object):
        __slots__ = ()
        monster = game.monster
        npc = game.npc
        creature = game.creature
        player = game.player
        map = game.map
        item = game.item
        scriptsystem = game.scriptsystem
        spell = game.spell
        resource = game.resource
        vocation = game.vocation
        const = game.const
        house = game.house
        guild = game.guild
        party = game.party
        errors = game.errors
        chat = game.chat
        deathlist = game.deathlist
        ban = game.ban
        market = game.market

    __builtin__.game = Globalizer()

    print "> > Loading global data...",
    for x in (yield globalData):
        if x['type'] == 'json':
            game.functions.globalStorage[x['key']] = otjson.loads(x['data'])
        elif x['type'] == 'pickle':
            game.functions.globalStorage[x['key']] = pickle.loads(x['data'])
        else:
            game.functions.globalStorage[x['key']] = x['data']
    print "%50s\n" % _txtColor("\t[DONE]", "blue")

    print "> > Loading groups...",
    for x in (yield groupData):
        game.functions.groups[x['group_id']] = (x['group_name'], otjson.loads(x['group_flags']))
    print "%60s\n" % _txtColor("\t[DONE]", "blue")

    print "> > Loading guilds...",
    game.guild.load()
    print "%60s\n" % _txtColor("\t[DONE]", "blue")
        
    print "> > Loading bans...",
    game.ban.refresh()
    print "%60s\n" % _txtColor("\t[DONE]", "blue")

    print "> > Loading market...",
    game.market.load()
    print "%55s\n" % _txtColor("\t[DONE]", "blue")
        
    print "> > Loading house data...",
    for x in (yield houseData):
        game.house.houseData[int(x['id'])] = game.house.House(int(x['id']), int(x['owner']),x['guild'],x['paid'],x['name'],x['town'],x['size'],x['rent'],x['data'])
    print "%55s\n" % _txtColor("\t[DONE]", "blue")
        
    # Load scripts
    print "> > Loading scripts...",
    game.scriptsystem.importer()
    game.scriptsystem.get("startup").runSync()
    print "%55s\n" % _txtColor("\t[DONE]", "blue")
        
    # Load map (if configurated to do so)
    if config.loadEntierMap:
        print "> > Loading the entier map...",
        begin = time.time()
        files = glob.glob('%s/%s/*.sec' % (config.dataDirectory, config.mapDirectory))
        for fileSec in files:
            x, y, junk = fileSec.split(os.sep)[-1].split('.')
            x = int(x)
            y = int(y)
            iX = x // game.map.sectorX
            iY = y // game.map.sectorY
            sectorSum = (iX << 11) + iY
            game.map.load(x,y, 0, sectorSum, False)

        print "%50s\n" % _txtColor("\t[DONE, took: %f]" % (time.time() - begin), "blue")
        
    # Charge rent?
    def _charge(house):
            callLater(config.chargeRentEvery, game.functions.looper, lambda: game.scriptsystem.get("chargeRent").runSync(None, house=house))
            
    for house in game.house.houseData.values():
        if not house.rent or not house.owner: continue
            
        if house.paid < (timer - config.chargeRentEvery):
            game.scriptsystem.get("chargeRent").runSync(None, house=house)
            _charge(house)
        else:
            callLater((timer - house.paid) % config.chargeRentEvery, _charge, house)    
    
    # Loading languages
    if config.enableTranslations:
        print "> > Loading languages... ",
        if language.LANGUAGES:
            print "%s\n" % _txtColor(language.LANGUAGES.keys(), "yellow")
        else:
            print "%s\n" % _txtColor("No languages found, falling back to defaults!", "red")
                
    
    # Load protocols
    print "> > Loading game protocols...",
    for version in config.supportProtocols:
        game.protocol.loadProtocol(version)
    print "%50s\n" % _txtColor("\t[DONE]", "blue")
    
    # Do we issue saves?
    if config.doSaveAll and not IS_IN_TEST:
        print "> > Schedule global save...",
        reactor.callLater(config.saveEvery, game.functions.looper, game.functions.saveAll, config.saveEvery)
        print "%50s\n" % _txtColor("\t[DONE]", "blue")
        
    # Do we save on shutdowns?
    if config.saveOnShutdown:
        game.scriptsystem.get("shutdown").register(lambda **k: game.functions.saveAll(True), False)
        
    # Reset online status on shutdown
    game.scriptsystem.get("shutdown").register(lambda **k: sql.conn.runOperation("UPDATE players SET online = 0"), False)
    # Light stuff
    if not IS_IN_TEST:
        print "> > Turn world time and light on...",
        lightchecks = config.tibiaDayLength / float(config.tibiaFullDayLight - config.tibiaNightLight)

        reactor.callLater(lightchecks, game.functions.looper, game.functions.checkLightLevel, lightchecks)
        print "%45s" % _txtColor("\t[DONE]", "blue")
    
        reactor.callLater(60, game.functions.looper, pathfinder.RouteCache.clear, 60)

    # Now we're online :)
    print _txtColor("Message of the Day: %s" % config.motd, "red")
    log.msg("Loading complete in %fs, everything is ready to roll" % (time.time() - timer))
    global IS_ONLINE
    IS_ONLINE = True

    print "\n\t\t%s\n" % _txtColor("[SERVER IS NOW OPEN!]", "green")
Пример #2
0
def loadItems():
    " Load or refresh items. "

    global items
    global idByNameCache
    global cidToSid

    print "> > Loading items..."
    
    if config.itemCache:
        try:
            with _open("%s/cache/items.cache" % config.dataDirectory, "rb") as f:
                items, idByNameCache, cidToSid = marshal.loads(f.read())
            log.msg("%d Items loaded (from cache)" % len(items))
            return
        except IOError:
            pass    
    
    # Make three new values while we are loading
    loadItems = {}
    idNameCache = {}
    _cidToSid = {}

    """tree = ET.parse("%s/items.xml" % config.dataDirectory)
    flagTree = {'s':1, 'b':3, 't':8192, 'ts':8193, 'tb':8195, 'm':64, 'p':96}    
    for item in tree.getroot():
        _item = item.attrib

        # Stupid elementtree thinks everything are strings....
        # Would have used lxml, but what the heck, I can't benchmark the difference.
        if "flags" in _item:
            flags = _item["flags"]
            try:
                _item["flags"] = flagTree[flags]
            except KeyError:
                _item["flags"] = int(flags)
        if "speed" in _item:
            _item["speed"] = int(_item["speed"])
        if "type" in _item:
            _item["type"] = int(_item["type"])

        if len(item):
            for attr in item:
                key = attr.tag
                val = attr.get("value")
                if key == "fluidSource":
                    val = getattr(game.const, 'FLUID_%s' % val.upper())
                elif key == "weaponType" and val not in ("ammunition", "wand"):
                    _item["weaponSkillType"] = getattr(game.const, 'SKILL_%s' % val.upper())
                elif key == 'shootType':
                    val = getattr(game.const, 'ANIMATION_%s' % val.upper())
                else:
                    try:
                        val = int(val)
                    except:
                        pass

                _item[key] = val
                attr.clear()

             
        id = _item["id"]
        if "-" in id:
            start, end = map(int, id.split('-'))
            for id in xrange(start, end+1):
                loadItems[id] = _item
        else:        
            id = int(id)    
            loadItems[id] = _item
            try:
                # XXX: Ranged items are usually ground stuff witch we never reference by name.
                idNameCache[_item["name"].upper()] = id
            except:
                pass
        del _item["id"]
        item.clear()        
    """

    # JSON format.
    jsonItems = json.loads(_open(config.itemFile, 'r').read())
    flagTree = {'s':1, 'b':3, 't':8192, 'ts':8193, 'tb':8195, 'm':64, 'p':96}
    for item in jsonItems:
        flags = item.get('flags')
        if flags and not isinstance(flags, int):
            item['flags'] = flagTree[flags]

        if 'shootType' in item:
            item['shootType'] = getattr(game.const, 'ANIMATION_%s' % item['shootType'].upper())

        if 'fluidSource' in item:
            item['fluidSource'] = getattr(game.const, 'FLUID_%s' % item['fluidSource'].upper())

        if 'weaponType' in item:
            type = item['weaponType']
            if type not in ("ammunition", "wand"):
                item["weaponSkillType"] = getattr(game.const, 'SKILL_%s' % type.upper())

        id = item['id']
        cid = item.get('cid')

        del item['id']
        if not isinstance(id, int):
            start, end = map(int, id.split('-'))
            fixCid = isinstance(cid, basestring)
            if fixCid:
                bCid = int(cid.split('-')[0])
            elif cid != None:
                _cidToSid[cid] = item

            for id in xrange(start, end+1):
                if fixCid:
                    _newItem = item.copy()
                    _newItem['cid'] = bCid
                    loadItems[id] = _newItem
                    _cidToSid[bCid] = id
                    bCid += 1
                else:
                    loadItems[id] = item

            try:
                name = item["name"].upper()
                if not name in idNameCache:
                    idNameCache[name] = start
            except:
                pass
                 
        else:
            loadItems[id] = item
            if cid != id:
                _cidToSid[cid] = id            
            try:
                name = item["name"].upper()
                if not name in idNameCache:
                    idNameCache[name] = id
            except:
                pass

    print "\n> > Items (%s) loaded..." % len(loadItems),
    print "%45s\n" % "\t[DONE]"

    # Replace the existing items
    items = loadItems
    idByNameCache = idNameCache
    cidToSid = _cidToSid

    # Cache
    if config.itemCache:
        with _open("%s/cache/items.cache" % config.dataDirectory, "wb") as f:
            f.write(marshal.dumps((items, idByNameCache, cidToSid), 2))
Пример #3
0
def loadItems():
    " Load or refresh items. "

    global items
    global idByNameCache
    global cidToSid

    print "> > Loading items..."

    if config.itemCache:
        try:
            with _open("%s/cache/items.cache" % config.dataDirectory,
                       "rb") as f:
                items, idByNameCache, cidToSid = marshal.loads(f.read())
            log.msg("%d Items loaded (from cache)" % len(items))
            return
        except IOError:
            pass

    # Make three new values while we are loading
    loadItems = {}
    idNameCache = {}
    _cidToSid = {}
    """tree = ET.parse("%s/items.xml" % config.dataDirectory)
    flagTree = {'s':1, 'b':3, 't':8192, 'ts':8193, 'tb':8195, 'm':64, 'p':96}    
    for item in tree.getroot():
        _item = item.attrib

        # Stupid elementtree thinks everything are strings....
        # Would have used lxml, but what the heck, I can't benchmark the difference.
        if "flags" in _item:
            flags = _item["flags"]
            try:
                _item["flags"] = flagTree[flags]
            except KeyError:
                _item["flags"] = int(flags)
        if "speed" in _item:
            _item["speed"] = int(_item["speed"])
        if "type" in _item:
            _item["type"] = int(_item["type"])

        if len(item):
            for attr in item:
                key = attr.tag
                val = attr.get("value")
                if key == "fluidSource":
                    val = getattr(game.const, 'FLUID_%s' % val.upper())
                elif key == "weaponType" and val not in ("ammunition", "wand"):
                    _item["weaponSkillType"] = getattr(game.const, 'SKILL_%s' % val.upper())
                elif key == 'shootType':
                    val = getattr(game.const, 'ANIMATION_%s' % val.upper())
                else:
                    try:
                        val = int(val)
                    except:
                        pass

                _item[key] = val
                attr.clear()

             
        id = _item["id"]
        if "-" in id:
            start, end = map(int, id.split('-'))
            for id in xrange(start, end+1):
                loadItems[id] = _item
        else:        
            id = int(id)    
            loadItems[id] = _item
            try:
                # XXX: Ranged items are usually ground stuff witch we never reference by name.
                idNameCache[_item["name"].upper()] = id
            except:
                pass
        del _item["id"]
        item.clear()        
    """

    # JSON format.
    jsonItems = json.loads(_open(config.itemFile, 'r').read())
    flagTree = {
        's': 1,
        'b': 3,
        't': 8192,
        'ts': 8193,
        'tb': 8195,
        'm': 64,
        'p': 96
    }
    for item in jsonItems:
        flags = item.get('flags')
        if flags and not isinstance(flags, int):
            item['flags'] = flagTree[flags]

        if 'shootType' in item:
            item['shootType'] = getattr(
                game.const, 'ANIMATION_%s' % item['shootType'].upper())

        if 'fluidSource' in item:
            item['fluidSource'] = getattr(
                game.const, 'FLUID_%s' % item['fluidSource'].upper())

        if 'weaponType' in item:
            type = item['weaponType']
            if type not in ("ammunition", "wand"):
                item["weaponSkillType"] = getattr(game.const,
                                                  'SKILL_%s' % type.upper())

        id = item['id']
        cid = item.get('cid')

        del item['id']
        if not isinstance(id, int):
            start, end = map(int, id.split('-'))
            fixCid = isinstance(cid, basestring)
            if fixCid:
                bCid = int(cid.split('-')[0])
            elif cid != None:
                _cidToSid[cid] = item

            for id in xrange(start, end + 1):
                if fixCid:
                    _newItem = item.copy()
                    _newItem['cid'] = bCid
                    loadItems[id] = _newItem
                    _cidToSid[bCid] = id
                    bCid += 1
                else:
                    loadItems[id] = item

            try:
                name = item["name"].upper()
                if not name in idNameCache:
                    idNameCache[name] = start
            except:
                pass

        else:
            loadItems[id] = item
            if cid != id:
                _cidToSid[cid] = id
            try:
                name = item["name"].upper()
                if not name in idNameCache:
                    idNameCache[name] = id
            except:
                pass

    print "\n> > Items (%s) loaded..." % len(loadItems),
    print "%45s\n" % "\t[DONE]"

    # Replace the existing items
    items = loadItems
    idByNameCache = idNameCache
    cidToSid = _cidToSid

    # Cache
    if config.itemCache:
        with _open("%s/cache/items.cache" % config.dataDirectory, "wb") as f:
            f.write(marshal.dumps((items, idByNameCache, cidToSid), 2))
Пример #4
0
def loader(timer):
    # XXX: Remember, game.XXX -> sys.modules["game.XXX"] because game is set later on. And somehow this causes weird behavior :/

    IS_IN_TEST = "trial_temp" in os.getcwd()
    if IS_IN_TEST:
        os.chdir("..")
        # Also ugly hack.
        sys.stdout = StringIO()

    # Attempt to get the Merucurial rev
    if os.path.exists(".hg"):
        try:
            # This will work independantly of the OS (no need to have mercurial installed!
            # Not sure if it's 100% accurate, be aware that this is not the active rev, but the latest fetched one.
            # Downloaded packages doesn't have this file, thats why we keep in in a try, it will raise.

            MERCURIAL_REV = (
                os.path.getsize(".hg/store/00changelog.i") // 64
            ) - 1  # Since mercurial start on rev 0, we need to -1 to get the rev number.
            #MERCURIAL_REV = subprocess.check_output(["hg", "parents", "--template={rev}"])
            log.msg("Begin loading (PyOT r%s)" % MERCURIAL_REV)
            if platform.system() == "Windows":
                os.system("title PyOT r%s" % MERCURIAL_REV)
                windowsLoading()
            else:
                sys.stdout.write("\x1b]2;PyOT r%s\x07" % MERCURIAL_REV)

        except (OSError, subprocess.CalledProcessError):
            # hg not in space.
            log.msg("Begin loading...")
            if platform.system() == "Windows":
                os.system("title PyOT")
                windowsLoading()
            else:
                sys.stdout.write("\x1b]2;PyOT\x07")
    else:
        MERCURIAL_REV = "unknown"
        log.msg("Begin loading...")
        if platform.system() == "Windows":
            os.system("title PyOT")
            windowsLoading()
        else:
            sys.stdout.write("\x1b]2;PyOT\x07")

    # Begin loading items
    sys.modules["game.item"].loadItems()

    # Reset online status
    print "> > Reseting players online status...",
    sql.conn.runOperation("UPDATE players SET online = 0")
    print "%40s\n" % _txtColor("\t[DONE]", "blue")

    globalData = sql.conn.runQuery(
        "SELECT `key`, `data`, `type` FROM `globals` WHERE `world_id` = %s" %
        config.worldId)
    groupData = sql.conn.runQuery(
        "SELECT `group_id`, `group_name`, `group_flags` FROM `groups`")
    houseData = sql.conn.runQuery(
        "SELECT `id`,`owner`,`guild`,`paid`,`name`,`town`,`size`,`rent`,`data` FROM `houses` WHERE `world_id` = %s"
        % config.worldId)

    # Globalize certain things
    print "> > Globalize data...",
    const = sys.modules["game.const"]
    __builtin__.const = const

    for i in dir(const):
        if not "__" in i:
            setattr(__builtin__, i, getattr(const, i))

    for i in dir(sys.modules["game.errors"]):
        if not "__" in i:
            setattr(__builtin__, i, getattr(sys.modules["game.errors"], i))

    for i in sys.modules["game.functions"].globalize:
        setattr(__builtin__, i, getattr(sys.modules["game.functions"], i))

    print "%55s\n" % _txtColor("\t[DONE]", "blue")

    __builtin__.sql = sql.conn
    __builtin__.config = config
    __builtin__.userconfig = userconfig

    import game.pathfinder

    __builtin__.register = game.scriptsystem.register
    __builtin__.registerFirst = game.scriptsystem.registerFirst
    __builtin__.registerForAttr = game.scriptsystem.registerForAttr
    __builtin__.registerClass = game.scriptsystem.registerClass
    __builtin__.defer = defer
    __builtin__.reactor = reactor
    __builtin__.functions = game.functions
    __builtin__.sys = sys
    __builtin__.math = math
    __builtin__.returnValue = returnValue
    __builtin__.Deferred = Deferred
    __builtin__.deque = deque
    __builtin__.random = random
    __builtin__.time = time
    __builtin__.re = re
    __builtin__.spell = game.spell  # Simplefy spell making
    __builtin__.callLater = reactor.callLater
    __builtin__.Item = game.item.Item
    __builtin__.itemAttribute = game.item.attribute
    __builtin__.cid = game.item.cid
    __builtin__.idByName = game.item.idByName
    __builtin__.getTile = game.map.getTile
    __builtin__.setTile = game.map.setTile
    __builtin__.getTileConst = game.map.getTileConst
    __builtin__.Boost = game.conditions.Boost
    __builtin__.MultiCondition = game.conditions.MultiCondition
    __builtin__.itemAttribute = game.item.attribute
    __builtin__.getHouseId = game.map.getHouseId
    __builtin__.Position = game.position.Position
    __builtin__.StackPosition = game.position.StackPosition
    __builtin__.getHouseById = game.house.getHouseById
    __builtin__.getGuildById = game.guild.getGuildById
    __builtin__.getGuildByName = game.guild.getGuildByName
    __builtin__.logger = sys.modules["game.logger"]

    # Resources
    __builtin__.genMonster = game.monster.genMonster
    __builtin__.genNPC = game.npc.genNPC
    __builtin__.genQuest = game.resource.genQuest
    __builtin__.genOutfit = game.resource.genOutfit
    __builtin__.genMount = game.resource.genMount
    __builtin__.regVocation = game.vocation.regVocation

    # Spells
    __builtin__.typeToEffect = game.spell.typeToEffect

    # Grab them
    __builtin__.getNPC = game.npc.getNPC
    __builtin__.getMonster = game.monster.getMonster

    # Used alot in monster and npcs
    __builtin__.chance = game.monster.chance

    # We use this in the import system
    __builtin__.scriptInitPaths = game.scriptsystem.scriptInitPaths

    # Access
    __builtin__.access = game.scriptsystem.access

    # Conditions
    __builtin__.Condition = game.conditions.Condition
    __builtin__.Boost = game.conditions.Boost
    __builtin__.CountdownCondition = game.conditions.CountdownCondition
    __builtin__.PercentCondition = game.conditions.PercentCondition
    __builtin__.MultiCondition = game.conditions.MultiCondition
    __builtin__.RepeatCondition = game.conditions.RepeatCondition

    # Pathfinder
    __builtin__.pathfinder = game.pathfinder

    # Deathlist
    __builtin__.deathlist = game.deathlist

    # Bans
    __builtin__.ipIsBanned = game.ban.ipIsBanned
    __builtin__.playerIsBanned = game.ban.playerIsBanned
    __builtin__.accountIsBanned = game.ban.accountIsBanned
    __builtin__.addBan = game.ban.addBan

    # Market
    __builtin__.getMarket = game.market.getMarket
    __builtin__.newMarket = game.market.newMarket

    # Creature and Player class. Mainly for test and savings.
    __builtin__.Creature = game.creature.Creature
    __builtin__.Player = game.player.Player
    __builtin__.Monster = game.monster.Monster

    # JSON
    __builtin__.json = otjson

    # Web
    if config.enableWebProtocol:
        import core.service.webserver
        __builtin__.WebPage = core.service.webserver.Page
        from twisted.web.server import NOT_DONE_YET
        __builtin__.NOT_DONE_YET = NOT_DONE_YET

    class Globalizer(object):
        __slots__ = ()
        monster = game.monster
        npc = game.npc
        creature = game.creature
        player = game.player
        map = game.map
        item = game.item
        scriptsystem = game.scriptsystem
        spell = game.spell
        resource = game.resource
        vocation = game.vocation
        const = game.const
        house = game.house
        guild = game.guild
        party = game.party
        errors = game.errors
        chat = game.chat
        deathlist = game.deathlist
        ban = game.ban
        market = game.market

    __builtin__.game = Globalizer()

    print "> > Loading global data...",
    for x in (yield globalData):
        if x['type'] == 'json':
            game.functions.globalStorage[x['key']] = otjson.loads(x['data'])
        elif x['type'] == 'pickle':
            game.functions.globalStorage[x['key']] = pickle.loads(x['data'])
        else:
            game.functions.globalStorage[x['key']] = x['data']
    print "%50s\n" % _txtColor("\t[DONE]", "blue")

    print "> > Loading groups...",
    for x in (yield groupData):
        game.functions.groups[x['group_id']] = (x['group_name'],
                                                otjson.loads(x['group_flags']))
    print "%60s\n" % _txtColor("\t[DONE]", "blue")

    print "> > Loading guilds...",
    game.guild.load()
    print "%60s\n" % _txtColor("\t[DONE]", "blue")

    print "> > Loading bans...",
    game.ban.refresh()
    print "%60s\n" % _txtColor("\t[DONE]", "blue")

    print "> > Loading market...",
    game.market.load()
    print "%55s\n" % _txtColor("\t[DONE]", "blue")

    print "> > Loading house data...",
    for x in (yield houseData):
        game.house.houseData[int(x['id'])] = game.house.House(
            int(x['id']), int(x['owner']), x['guild'], x['paid'], x['name'],
            x['town'], x['size'], x['rent'], x['data'])
    print "%55s\n" % _txtColor("\t[DONE]", "blue")

    # Load scripts
    print "> > Loading scripts...",
    game.scriptsystem.importer()
    game.scriptsystem.get("startup").runSync()
    print "%55s\n" % _txtColor("\t[DONE]", "blue")

    # Load map (if configurated to do so)
    if config.loadEntierMap:
        print "> > Loading the entier map...",
        begin = time.time()
        files = glob.glob('%s/%s/*.sec' %
                          (config.dataDirectory, config.mapDirectory))
        for fileSec in files:
            x, y, junk = fileSec.split(os.sep)[-1].split('.')
            x = int(x)
            y = int(y)
            iX = x // game.map.sectorX
            iY = y // game.map.sectorY
            sectorSum = (iX << 11) + iY
            game.map.load(x, y, 0, sectorSum, False)

        print "%50s\n" % _txtColor(
            "\t[DONE, took: %f]" % (time.time() - begin), "blue")

    # Charge rent?
    def _charge(house):
        callLater(
            config.chargeRentEvery, game.functions.looper,
            lambda: game.scriptsystem.get("chargeRent").runSync(None,
                                                                house=house))

    for house in game.house.houseData.values():
        if not house.rent or not house.owner: continue

        if house.paid < (timer - config.chargeRentEvery):
            game.scriptsystem.get("chargeRent").runSync(None, house=house)
            _charge(house)
        else:
            callLater((timer - house.paid) % config.chargeRentEvery, _charge,
                      house)

    # Loading languages
    if config.enableTranslations:
        print "> > Loading languages... ",
        if language.LANGUAGES:
            print "%s\n" % _txtColor(language.LANGUAGES.keys(), "yellow")
        else:
            print "%s\n" % _txtColor(
                "No languages found, falling back to defaults!", "red")

    # Load protocols
    print "> > Loading game protocols...",
    for version in config.supportProtocols:
        game.protocol.loadProtocol(version)
    print "%50s\n" % _txtColor("\t[DONE]", "blue")

    # Do we issue saves?
    if config.doSaveAll and not IS_IN_TEST:
        print "> > Schedule global save...",
        reactor.callLater(config.saveEvery, game.functions.looper,
                          game.functions.saveAll, config.saveEvery)
        print "%50s\n" % _txtColor("\t[DONE]", "blue")

    # Do we save on shutdowns?
    if config.saveOnShutdown:
        game.scriptsystem.get("shutdown").register(
            lambda **k: game.functions.saveAll(True), False)

    # Reset online status on shutdown
    game.scriptsystem.get("shutdown").register(
        lambda **k: sql.conn.runOperation("UPDATE players SET online = 0"),
        False)
    # Light stuff
    if not IS_IN_TEST:
        print "> > Turn world time and light on...",
        lightchecks = config.tibiaDayLength / float(config.tibiaFullDayLight -
                                                    config.tibiaNightLight)

        reactor.callLater(lightchecks, game.functions.looper,
                          game.functions.checkLightLevel, lightchecks)
        print "%45s" % _txtColor("\t[DONE]", "blue")

        reactor.callLater(60, game.functions.looper,
                          pathfinder.RouteCache.clear, 60)

    # Now we're online :)
    print _txtColor("Message of the Day: %s" % config.motd, "red")
    log.msg("Loading complete in %fs, everything is ready to roll" %
            (time.time() - timer))
    global IS_ONLINE
    IS_ONLINE = True

    print "\n\t\t%s\n" % _txtColor("[SERVER IS NOW OPEN!]", "green")