Cocos2dx -- Resource hot update
After a game is launched, we often need updates, such as new gameplay and activities. Such dynamic update resources are called hot game updates. Hot updates are generally only applicable to scripting languages. Because scripts do not need to be compiled, they are an explanatory language, and C ++ languages are difficult to update, the code needs to be re-linked for compilation as long as there are changes (unified interfaces can be implemented using dynamic libraries, but it is too inflexible ).
This chapter describes how to use the Cocos-lua engine to implement hot update. In fact, Cocos also comes with the hot update module (AssetsManager, AssetsManagerEx), but I didn't use the built-in one, I encapsulated a set by myself, and the basic principles are the same.
Basic Idea of hot update
Log on to the game and request the current game version number from the server. if the version number is the same as the local version number, no resources need to be updated to directly enter the game. if the version number is different, it indicates that resources need to be updated to step 1.
Request the list of all current resources (Resource Name + MD5) from the server, and compare it with the local resource list to find the resource to be updated.
Update the resource as needed, and request the server to download the resource. (When many resources are found to be updated, errors may occur when requests are sent to the server in one loop. Therefore, it is best to send requests to the server in the form of a zip package. The client requests only once)
Note: 1. How a program loads a file: first, the path to which a program loads a file on the local hard disk is absolutely full. The reason why we can still find the corresponding file by writing relative paths is that there is also a search path, which is stored in a container, the relative path is like this to get the full path = search path (full path) + relative path. That is, you only need to add the path to the search path. to load the file in the future, you only need to give the file name. The previous path will automatically go to the search path and traverse the search cyclically. Therefore, we generally do not write absolute paths in the program, but add the full paths above to the search path. Then, we only need to write the relative paths below to find them.
2. After a mobile game is installed on a mobile phone, its installation directory is read-only and cannot be modified later. Therefore, hot update resources cannot be downloaded to previous directories. Therefore, you have to create a directory that can be read and written on your mobile phone and update the resources to this directory. The next question is that the update directory is inconsistent with the previous resource directory. How do you prioritize the use of the resources in the update directory in the game? In fact, you only need to add the created read/write directory path to the search path and insert it to the beginning. The code is always an absolute path.
For file operations, we use the FileUtils class encapsulated by cocos. Some related functions, such as fullPathForFilename, return the full path. The cocos file is finally converted to the full path for loading. addSearchPath: add to search path, getWritablePath: returns a read/write path. The following is the Lua code:
-- Create a writable directory and set the search path self. writeRootPath = cc. fileUtils: getInstance (): getWritablePath ().. _ ClientGame2015 _ if not (cc. fileUtils: getInstance (): isDirectoryExist (self. writeRootPath) then cc. fileUtils: getInstance (): createDirectory (self. writeRootPath) end local searchPaths = cc. fileUtils: getInstance (): getSearchPaths () table. insert (searchPaths, 1, self. writeRootPath .. '/') table. insert (searchPaths, 2, self. writeRootPath .. '/res/') table. insert (searchPaths, 3, self. writeRootPath .. '/src/') cc. fileUtils: getInstance (): setSearchPaths (searchPaths)
The encapsulated Hot update requires two local configuration files, one for recording version information and request url, and one for recording the list of all resources. Both configuration files are in json format, and cocos comes with json. lua resolution library, json. decode (js): Convert js to lua table, json. encode (table): Convert the lua table to js. The configuration table is as follows:
We also found a lua io file operation pitfall. local fp = io. open (fullPath, 'R'); these operations are performed in iZ? http://www.bkjia.com/kf/ware/vc/ "Target =" _ blank "class =" keylink "> vc7/Platform + dLUyMi4/NDCzsS8/Platform + KOsYysr0 + Platform + platform/u0rqOsyOe5 + platform/Platform + platform/wLSx7cq + s6S2yKOs0/a1vbb + large + G94cr4oaO2 + M28xqzK/b7dwO/large + DQoJPHA + large/YwveHK + KGjPGJyIC8 + large = "Hot update source code "hot update source code
It can be divided into logic layer and UI Layer. The UI Layer is asynchronously loaded. Therefore, you cannot use addChild to add this module to an existing scenario.
Logic layer:
Require ('common. json ') local UpdateLogicLayer = class (UpdateLogicLayer, cc. node) function UpdateLogicLayer: create (callback) local view = UpdateLogicLayer. new () local function onNodeEvent (eventType) if eventType = enter then view: onEnter () elseif eventType = exit then view: onExit () end view: registerScriptHandler (onNodeEvent) view: init (callback) return viewendfunction UpdateLogicLayer: ctor () self. WriteRootPath = nil -- Mobile Phone writeable path self. manifest = nil -- configure table information (json-> table) self. resConfigInfo = nil -- resource list (json-> table) self. updateResTable = nil -- update resource table self. updateResProgress = 1 -- Update Progress self. updateResPath = nil -- the current update resource path self. eventType = {None = 0, -- initialization status StartGame = 1, -- start game StartUpdate = 2, -- start updating AssetsProgress = 3, -- AssetsFinish = 4 in resource update, -- Resource Update completed} self. callback = nil -- External callback self. status = Self. eventType. none endfunction UpdateLogicLayer: onEnter () endfunction UpdateLogicLayer: onExit () endfunction UpdateLogicLayer: init (callback) self. callback = callback -- create a writable directory and set the search path self. writeRootPath = cc. fileUtils: getInstance (): getWritablePath ().. _ ClientGame2015 _ if not (cc. fileUtils: getInstance (): isDirectoryExist (self. writeRootPath) then cc. fileUtils: getInstance (): createDirectory (self. writeR OotPath) end local searchPaths = cc. fileUtils: getInstance (): getSearchPaths () table. insert (searchPaths, 1, self. writeRootPath .. '/') table. insert (searchPaths, 2, self. writeRootPath .. '/res/') table. insert (searchPaths, 3, self. writeRootPath .. '/src/') cc. fileUtils: getInstance (): setSearchPaths (searchPaths) -- initialize local fullPath = cc In the configuration information. fileUtils: getInstance (): fullPathForFilename ('Project. manifest ') loca L fp = io. open (fullPath, 'R') if fp then local js = fp: read ('* A') io. close (fp) self. manifest = json. decode (js) else print ('Project. manifest read error! ') End -- version comparison self: cmpVersions () end -- version comparison function UpdateLogicLayer: cmpVersions () -- Post local xhr = cc. XMLHttpRequest: new () xhr. responseType = 4 -- json type xhr: open (POST, self. manifest. versionUrl) local function onReadyStateChange () if xhr. readyState = 4 and (xhr. status> = 200 and xhr. status <207) then local localversion = self. manifest. version self. manifest = json. decode (xhr. response) if self. mani Fest. version = localversion then -- start the game self. status = self. eventType. startGame self: noticeEvent () print ('11 started the game !!!!!! ') Else -- find the resource to be updated and download self. status = self. eventType. startUpdate self: noticeEvent () self: findUpdateRes () end else print (cmpVersions = xhr. readyState is:, xhr. readyState, xhr. status is:, xhr. status) end xhr: registerScriptHandler (onReadyStateChange) xhr: send () end -- find the update resource function UpdateLogicLayer: findUpdateRes () local xhr = cc. XMLHttpRequest: new () xhr. responseType = 4 xhr: open (POST, self. manifest. TableResUrl) local function onReadyStateChange () if xhr. readyState = 4 and (xhr. status> = 200 and xhr. status <207) then self. resConfigInfo = json. decode (xhr. response) self. updateResTable = self: findUpdateResTable () self: downloadRes () else print (findUpdateRes = xhr. readyState is:, xhr. readyState, xhr. status is:, xhr. status) end xhr: registerScriptHandler (onReadyStateChange) xhr: send ('filename = /Res_config.lua ') end -- search for the resource table to be updated (updated and added, not considered for deletion) function UpdateLogicLayer: findUpdateResTable () local clientResTable = nil local serverResTable = self. resConfigInfo local fullPath = cc. fileUtils: getInstance (): fullPathForFilename ('resconfig. json ') local fp = io. open (fullPath, 'R') if fp then local js = fp: read ('* A') fp: close (fp) clientResTable = json. decode (js) else print ('resconfig. json read error! ') End local addResTable = {} local isUpdate = true if clientResTable and serverResTable then for key1, var1 in ipairs (serverResTable) do isUpdate = true for key2, var2 in ipairs (clientResTable) do if var2.name = var1.name then if var2.md5 = var1.md5 then isUpdate = false end break end if isUpdate = true then table. insert (addResTable, var1.name) end else print ('local configFile error! (Res_config_local or res_config_server) ') end return addResTableend -- download and update the resource function UpdateLogicLayer: downloadRes () local fileName = self. updateResTable [self. updateResProgress] if fileName then local xhr = cc. XMLHttpRequest: new () xhr: open (POST, self. manifest. downloadResUrl) local function onReadyStateChange () if xhr. readyState = 4 and (xhr. status> = 200 and xhr. status <207) then self: localWriteRes (FileName, xhr. response) else print (downloadRes = xhr. readyState is:, xhr. readyState, xhr. status is:, xhr. status) end xhr: registerScriptHandler (onReadyStateChange) xhr: send ('filename= '.. fileName) else -- Resource Update completed local fp = io. open (self. writeRootPath .. '/res/project. manifest ', 'w') if fp then local js = json. encode (self. manifest) fp: write (js) io. close (fp) end local fp = io. open (self. writeRootPa Th .. '/res/resConfig. json ', 'w') if fp then local js = json. encode (self. resConfigInfo) fp: write (js) io. close (fp) end -- the update is complete. Start the game self. status = self. eventType. assetsFinish self: noticeEvent () print ('22 starts to play !!!!!! ') Endend -- function UpdateLogicLayer: localWriteRes (resName, resData) local lenthTable ={} local tempResName = resName local maxLength = string. len (tempResName) local tag = string. find (tempResName, '/') while tag do if tag ~ = 1 then table. insert (lenthTable, tag) end tempResName = string. sub (tempResName, tag + 1, maxLength) tag = string. find (tempResName, '/') end local sub = 0 for key, var in ipairs (lenthTable) do sub = sub + var end if sub ~ = 0 then local temp = string. sub (resName, 1, sub + 1) local pathName = self. writeRootPath .. temp if not (cc. fileUtils: getInstance (): isDirectoryExist (pathName) then cc. fileUtils: getInstance (): createDirectory (pathName) end self. updateResPath = self. writeRootPath .. resName local fp = io. open (self. updateResPath, 'w') if fp then fp: write (resData) io. close (fp) self. status = self. eventType. assetsProg Ress self: noticeEvent () print (countRes =, self. updateResProgress, nameRes =, resName) self. updateResProgress = self. updateResProgress + 1 self: downloadRes () else print ('downloadres write error !! ') Endendfunction UpdateLogicLayer: noticeEvent () if self. callback then self. callback (self, self. status) else print ('callback is nil') endendreturn UpdateLogicLayer
UI Layer:
-- [Description: 1. Local requirement configuration file: project. manifest, resConfig. json 2 and loop post requests may sometimes crash. You 'd better change it to the zip package format of 3 only once. Currently, only ios is supported, and the lua io library file operations are not supported on andriod, file Operation c implementation (note that lua and c ++ should change the lua binding code when char * ends at/0)] local UpdateLogicLayer = require ('app. views. assets. updateLogicLayer ') local SelectSerAddrLayer = require (app. views. login. selectSerAddrLayer) local UpdateUILayer = class (UpdateUILayer, cc. layer) function UpdateUILayer: create () local vi Ew = UpdateUILayer. new () local function onNodeEvent (eventType) if eventType = enter then view: onEnter () elseif eventType = exit then view: onExit () end view: registerScriptHandler (onNodeEvent) view: init () return viewendfunction UpdateUILayer: ctor () endfunction UpdateUILayer: onEnter () endfunction UpdateUILayer: onExit () endfunction UpdateUILayer: init () local updateLogicLayer = UpdateLogicLayer: crea Te (function (sender, eventType) self: onEventCallBack (sender, eventType) end) self: addChild (updateLogicLayer) endfunction UpdateUILayer: onEventCallBack (sender, eventType) if eventType = sender. eventType. startGame then print (startgame !!!) Local view = SelectSerAddrLayer. new () self: addChild (view) elseif eventType = sender. EventType. StartUpdate then print (startupdate !!!) Self: initAssetsUI () elseif eventType = sender. EventType. AssetsProgress then print (assetsprogress !!!) Self: updateAssetsProgress (sender. updateResPath, sender. updateResTable, sender. updateResProgress) elseif eventType = sender. EventType. AssetsFinish then print (assetsfinish !!!) Self: updateAssetsFinish (sender. writeRootPath) endend -- UI interface initialization function UpdateUILayer: initAssetsUI () local assetsLayer = cc. CSLoader: createNode (csb/assetsUpdate_layer.csb) local visibleSize = cc. director: getInstance (): getVisibleSize () assetsLayer: setAnchorPoint (cc. p (0.5, 0.5) assetsLayer: setPosition (visibleSize. width/2, visibleSize. height/2) self: addChild (assetsLayer) self. rootPanel = assetsLayer: getChildByName (Panel_root) self. widgetTable = {LoadingBar_1 = ccui. helper: seekWidgetByName (self. rootPanel, LoadingBar_1), Text_loadProgress = ccui. helper: seekWidgetByName (self. rootPanel, Text_loadProgress), Text_loadResPath = ccui. helper: seekWidgetByName (self. rootPanel, Text_loadResPath), Image_tag = ccui. helper: seekWidgetByName (self. rootPanel, Image_tag),} self. widgetTable. image_tag: setVisible (false) self. widgetTable. loadingBar_1: setPercent (1) self. widgetTable. text_loadProgress: setString ('0% ') self. widgetTable. text_loadResPath: setString ('Prepare to update... ') end -- Resource Update completed function UpdateUILayer: updateAssetsFinish (writePaht) self. widgetTable. text_loadResPath: setString ('Resource Update completed... ') self. widgetTable. text_loadProgress: setString ('20140901') self: runAction (cc. sequence: create (cc. delayTime: create (1), cc. callFunc: create (function () local view = SelectSerAddrLayer. new () self: addChild (view) end -- function UpdateUILayer: updateAssetsProgress (resPath, updateResTable, updateResProgress) self in resource update. widgetTable. text_loadResPath: setString (resPath) local percentMaxNum = # updateResTable local percentNum = math. floor (updateResProgress/percentMaxNum) * 100) self. widgetTable. loadingBar_1: setPercent (percentNum) self. widgetTable. text_loadProgress: setString (percentNum .. '%') endreturn UpdateUILayer