Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Cocos Lua 熱更新實作全流程:AssetManager 與資源清單

編輯:關於 Android 程式設計

第一次搞熱更新,這裡把整個過程記錄下來,方便日後查閱。

原理

每次登入遊戲時,透過 Cocos 的 AssetManager 從伺服器拉取當前最新的兩個檔案:version.manifest 與 project.manifest,兩者都是描述性的清單檔。前者包含版本資訊,後者則包含遊戲所有資源的 MD5 碼。首先用 version 檔比對本地版本是否相同,若不同,再拿本地的 project 檔比對 MD5,判斷哪些檔案需要重新下載、替換資源。

步驟一:準備測試伺服器

測試時可先架一個 HFS 伺服器,簡單易學。每次把最新專案全部拖進伺服器,再用 GenerateManifest.py 自動產生 version 與 project 檔。

步驟二:編寫清單產生腳本

這支 Python 腳本負責產生對應的 version 與 project 檔。project 檔會為每個資源計算獨一無二的 MD5 碼,相當於每個資源的唯一標記:

#!/usr/bin/env python
#coding:utf-8
import os
import json
import hashlib
import subprocess

assetsDir = {
    "searchDir" : ["src", "res"],
    "ignorDir" : ["cocos", "obj", "version"]
}
versionConfigFile = "res/config/version_info.json"  # 版本資訊設定檔路徑
versionManifestPath = "res/version/version.manifest"  # 產生的 version.manifest
projectManifestPath = "res/version/project.manifest"  # 產生的 project.manifest

class SearchFile:
    def __init__(self):
        self.fileList = []
        for k in assetsDir:
            if (k == "searchDir"):
                for searchdire in assetsDir[k]:
                    self.recursiveDir(searchdire)

    def recursiveDir(self, srcPath):
        '''遞歸指定目錄下的所有檔案'''
        dirList = []
        files = os.listdir(srcPath)
        for f in files:
            if (os.path.isdir(srcPath + '/' + f)):
                if (f[0] == '.' or (f in assetsDir["ignorDir"])):
                    pass
                else:
                    dirList.append(f)
            elif (os.path.isfile(srcPath + '/' + f)):
                self.fileList.append(srcPath + '/' + f)
        for dire in dirList:
            self.recursiveDir(srcPath + '/' + dire)

    def getAllFile(self):
        return tuple(self.fileList)

def GetSvnCurrentVersion():
    popen = subprocess.Popen(['svn', 'info'], stdout=subprocess.PIPE)
    while True:
        next_line = popen.stdout.readline()
        if next_line == '' and popen.poll() != None:
            break
        valList = next_line.split(':')
        if len(valList) < 2:
            continue
        valList[0] = valList[0].strip().lstrip().rstrip(' ')
        valList[1] = valList[1].strip().lstrip().rstrip(' ')
        if (valList[0] == "Revision"):
            return valList[1]
    return ""

def CalcMD5(filepath):
    """用檔案路徑產生 md5"""
    with open(filepath, 'rb') as f:
        md5obj = hashlib.md5()
        md5obj.update(f.read())
        return md5obj.hexdigest()

def getVersionInfo():
    '''取得版本設定資料'''
    configFile = open(versionConfigFile, "r")
    json_data = json.load(configFile)
    configFile.close()
    json_data["version"] = json_data["version"] + '.' + str(GetSvnCurrentVersion())
    return json_data

def GenerateversionManifestPath():
    '''產生大版本的 version.manifest'''
    json_str = json.dumps(getVersionInfo(), indent=2)
    fo = open(versionManifestPath, "w")
    fo.write(json_str)
    fo.close()

def GenerateprojectManifestPath():
    searchfile = SearchFile()
    fileList = list(searchfile.getAllFile())
    project_str = {}
    project_str.update(getVersionInfo())
    dataDic = {}
    for f in fileList:
        dataDic[f] = {"md5": CalcMD5(f)}
    project_str.update({"assets": dataDic})
    json_str = json.dumps(project_str, sort_keys=True, indent=2)
    fo = open(projectManifestPath, "w")
    fo.write(json_str)
    fo.close()

if __name__ == "__main__":
    GenerateversionManifestPath()
    GenerateprojectManifestPath()

步驟三:用 AssetManager 下載並替換資源

這裡所謂的「替換」並非真正刪除舊檔,而是利用 FileUtils->setSearchPath() 設定資源讀取的優先級——舊資源與程式碼並未刪除,只是捨棄不用:

local AssetsManager = class("AssetsManager", function()
    return cc.LayerColor:create(cc.c4b(20, 20, 20, 220))
end)

function AssetsManager:ctor()
    self:onNodeEvent("exit", handler(self, self.onExitCallback))
    self:initUI()
    self:setAssetsManage()
end

function AssetsManager:onExitCallback()
    self.assetsManagerEx:release()
end

function AssetsManager:initUI()
    local hintLabel = cc.Label:createWithTTF("正在更新...", CONFIG.TTF_FONT_2, 20)
        :addTo(self):move(600, 80)
    local progressBg = display.newSprite("sprites/hyd_progress_bg.png")
        :addTo(self):move(600, 40)
    self.progress = cc.ProgressTimer:create(display.newSprite("sprites/hyd_progress.png"))
        :addTo(progressBg):move(380, 19)
    self.progress:setType(cc.PROGRESS_TIMER_TYPE_BAR)
    self.progress:setBarChangeRate(cc.p(1, 0))
    self.progress:setMidpoint(cc.p(0.0, 0.5))
    self.progress:setPercentage(0)
    -- 觸摸吞噬
    self.listener = cc.EventListenerTouchOneByOne:create()
    self.listener:setSwallowTouches(true)
    local onTouchBegan = function(touch, event) return true end
    self.listener:registerScriptHandler(onTouchBegan, cc.Handler.EVENT_TOUCH_BEGAN)
    cc.Director:getInstance():getEventDispatcher():addEventListenerWithSceneGraphPriority(self.listener, self)
end

function AssetsManager:setAssetsManage()
    -- 建立可寫目錄與設定搜尋路徑
    local storagePath = cc.FileUtils:getInstance():getWritablePath() .. "NewRes/"
    local resPath = storagePath .. '/res/'
    local srcPath = storagePath .. '/src/'
    if not (cc.FileUtils:getInstance():isDirectoryExist(storagePath)) then
        cc.FileUtils:getInstance():createDirectory(storagePath)
        cc.FileUtils:getInstance():createDirectory(resPath)
        cc.FileUtils:getInstance():createDirectory(srcPath)
    end
    local searchPaths = cc.FileUtils:getInstance():getSearchPaths()
    table.insert(searchPaths, 1, storagePath)
    table.insert(searchPaths, 2, resPath)
    table.insert(searchPaths, 3, srcPath)
    cc.FileUtils:getInstance():setSearchPaths(searchPaths)
    self.assetsManagerEx = cc.AssetsManagerEx:create("version/project.manifest", storagePath)
    self.assetsManagerEx:retain()
    local eventListenerAssetsManagerEx = cc.EventListenerAssetsManagerEx:create(
        self.assetsManagerEx,
        function(event) self:handleAssetsManagerEvent(event) end)
    local dispatcher = cc.Director:getInstance():getEventDispatcher()
    dispatcher:addEventListenerWithFixedPriority(eventListenerAssetsManagerEx, 1)
    -- 檢查版本並升級
    self.assetsManagerEx:update()
end

function AssetsManager:handleAssetsManagerEvent(event)
    local eventCodeList = cc.EventAssetsManagerEx.EventCode
    local eventCodeHand = {
        [eventCodeList.ERROR_NO_LOCAL_MANIFEST] = function()
            print("發生錯誤:本地資源清單檔案未找到")
        end,
        [eventCodeList.ERROR_DOWNLOAD_MANIFEST] = function()
            print("發生錯誤:遠程資源清單檔案下載失敗")
            self:downloadManifestError()
        end,
        [eventCodeList.ERROR_PARSE_MANIFEST] = function()
            print("發生錯誤:資源清單檔案解析失敗")
        end,
        [eventCodeList.NEW_VERSION_FOUND] = function()
            print("發現新版本")
        end,
        [eventCodeList.ALREADY_UP_TO_DATE] = function()
            print("已經更新到伺服器最新版本")
            self:updateFinished()
        end,
        [eventCodeList.UPDATE_PROGRESSION] = function()
            self.progress:setPercentage(event:getPercentByFile())
        end,
        [eventCodeList.ASSET_UPDATED] = function()
            print("單個資源被更新事件")
        end,
        [eventCodeList.ERROR_UPDATING] = function()
            print("發生錯誤:更新過程中遇到錯誤")
        end,
        [eventCodeList.UPDATE_FINISHED] = function()
            print("更新成功事件")
            self:updateFinished()
        end,
        [eventCodeList.UPDATE_FAILED] = function()
            print("更新失敗事件")
        end,
        [eventCodeList.ERROR_DECOMPRESS] = function()
            print("解壓縮失敗")
        end
    }
    local eventCode = event:getEventCode()
    if eventCodeHand[eventCode] ~= nil then
        eventCodeHand[eventCode]()
    end
end

function AssetsManager:updateFinished()
    self:setVisible(false)
    self.listener:setEnabled(false)
end

function AssetsManager:downloadManifestError()
    self:setVisible(false)
    self.listener:setEnabled(false)
end

return AssetsManager

踩到的坑

測試時發現一個惱人的問題:伺服器設定的 IP 輸出總是不對,與自己設定的有出入。原因是只改了本地的 IP,卻沒更新伺服器端的 IP。正常邏輯下,程式依本地提供的 IP 成功連上伺服器並下載了 version 與 project 檔;但當判定需要更新、要下載資源時,卻是依 project 檔中記錄的 IP 去下載——而伺服器 project 裡的 IP 根本是錯的,於是資源下載失敗。

這個坑提醒我們:熱更新依賴的兩份清單檔(尤其是 project.manifest 中的資源位址)務必指向正確的伺服器位置,否則版本比對成功、資源下載卻會失敗。掌握「版本比對 + MD5 差異比對 + 搜尋路徑優先級」這套核心機制,就能穩穩實作出遊戲的熱更新能力。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved