Cocos 项目结构

参考

Cocos 热更新原理与过程

  1. 服务端和本地均保存完整版本的游戏资源。(前提)
  2. 本地向服务器发送请求,判断当前版本是否为最新。
  3. 对比本地和服务器的Manifest文件,判断的要更新的资源文件。
  4. 服务器端下载需要更新的资源文件。
  5. 修改游戏启动时候加载资源文件的位置,使用下载的最新资源。
  6. 重启游戏,使用最新的资源文件。

热更新相关文件

  • version_generator.js:Cocos 引擎提供的热更新工具,用于生成 Manifest 文件。
  • version.manifest:热更新版本信息文件,包含以下信息:
    • 当前版本号
    • 远程manifest文件地址
  • project.manifest:热更新项目信息文件,包含以下信息:
    • 当前版本号
    • 远程manifest文件地址
    • 热更新项目资源信息

热更新实现流程

  1. 构建发布对应平台的Native项目
  2. 下载version_generator.js
  3. 修改version_generator.js当中的热更新远程包地址,与对应平台构建出项目的位置
  4. 执行node version_generator.js -v 1.0.0命令生成对应版本的热更新包
  5. 将热更新包中的manifest文件放到项目中
  6. 将热更新包上传到到服务器端
  7. 修改服务器端获取版本号的接口

注意事项

  • 资源热更新只适用于原生发布版本
  • 要在main.js中修改热更新资源路径,不然第一次更新后成功,后面重新进入又是旧的资源。

代码示例与解析

生成热更新文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
// version_generator.js 热更新包生成脚本
// var fs = require('fs');
var fs = require('fs-extra');//先安装 npm install fs-extra
var path = require('path');
var crypto = require('crypto');

//热更新包远程地址(按照后端给的地址)
var remoteUrl = `https://xglxs.26joy.com/Upload/xyx/hotUpdate/remote-assets`;
var version = `1.0.0`;

var manifest = {
packageUrl: `${remoteUrl}${version}/`,
remoteManifestUrl: `${remoteUrl}${version}/project.manifest`,
remoteVersionUrl: `${remoteUrl}${version}/version.manifest`,
version: version,
assets: {},
searchPaths: []
};

//生成的manifest文件存放位置地址
var dest = './assets/';

//默认构建发布出的项目地址(按照发布的平台修改)
var src = './build/windows/assets/';

//热更新文件
var remoteDir = `./packages-hot-update/`;

// Parse arguments 解析参数
var i = 2;
while (i < process.argv.length) {
var arg = process.argv[i];

switch (arg) {
case '--url':
case '-u':
remoteUrl = process.argv[i + 1];
manifest.packageUrl = `${remoteUrl}${version}/`;
manifest.remoteManifestUrl = `${remoteUrl}${version}/project.manifest`;
manifest.remoteVersionUrl = `${remoteUrl}${version}/version.manifest`;
i += 2;
break;
case '--version':
case '-v':
version = process.argv[i + 1];
manifest.version = version;
manifest.packageUrl = `${remoteUrl}${version}/`;
manifest.remoteManifestUrl = `${remoteUrl}${version}/project.manifest`;
manifest.remoteVersionUrl = `${remoteUrl}${version}/version.manifest`;
i += 2;
break;
case '--src':
case '-s':
src = process.argv[i + 1];
i += 2;
break;
case '--dest':
case '-d':
dest = process.argv[i + 1];
i += 2;
break;
default:
i++;
break;
}
}


function readDir(dir, obj) {
var stat = fs.statSync(dir);
if (!stat.isDirectory()) {
return;
}
var subPaths = fs.readdirSync(dir), subpath, size, md5, compressed, relative;
for (var i = 0; i < subPaths.length; ++i) {
if (subPaths[i][0] === '.') {
continue;
}
subpath = path.join(dir, subPaths[i]);
stat = fs.statSync(subpath);
if (stat.isDirectory()) {
readDir(subpath, obj);
}
else if (stat.isFile()) {
// Size in Bytes
size = stat['size'];
md5 = crypto.createHash('md5').update(fs.readFileSync(subpath)).digest('hex');
compressed = path.extname(subpath).toLowerCase() === '.zip';

relative = path.relative(src, subpath);
relative = relative.replace(/\\/g, '/');
relative = encodeURI(relative);
obj[relative] = {
'size': size,
'md5': md5
};
if (compressed) {
obj[relative].compressed = true;
}
}
}
}

var mkdirSync = function (path) {
try {
fs.mkdirSync(path);
} catch (e) {
if (e.code != 'EEXIST') throw e;
}
}

// Iterate assets and src folder
readDir(path.join(src, 'src'), manifest.assets);
readDir(path.join(src, 'assets'), manifest.assets);

var destManifest = path.join(dest, 'project.manifest');
var destVersion = path.join(dest, 'version.manifest');

mkdirSync(dest);

var copyDir = `${remoteDir}remote-assets${version}/`;

fs.copy(path.join(src, 'src'), path.join(copyDir, 'src'), (err) => {
if (err) throw err;
console.log('src successfully copy');
});

fs.copy(path.join(src, 'assets'), path.join(copyDir, 'assets'), (err) => {
if (err) throw err;
console.log('assets successfully copy');
});

fs.writeFile(destManifest, JSON.stringify(manifest), (err) => {
if (err) throw err;
console.log('Manifest successfully generated');

fs.copyFile(destManifest, path.join(copyDir, `project.manifest`), (err) => {
if (err) throw err;
console.log('Manifest successfully copy');
});
});

delete manifest.assets;
delete manifest.searchPaths;
fs.writeFile(destVersion, JSON.stringify(manifest), (err) => {
if (err) throw err;
console.log('Version successfully generated');
fs.copyFile(destVersion, path.join(copyDir, `version.manifest`), (err) => {
if (err) throw err;
console.log('Version successfully copy');
});
});

/**
* 检查main.js (不怎么必要)
*/
var mainPath = path.join(src, `main.js`)
var mainIs = fs.existsSync(mainPath);
if (mainIs) {
var content = fs.readFileSync(mainPath).toString();
if (content.indexOf(`jsb.fileUtils.setSearchPaths`) != -1) {
console.log("main.js check successfully");
}

var add = `!function(){if("object"==typeof window.jsb){var e=localStorage.getItem("HotUpdateSearchPaths");if(e){var i=JSON.parse(e);jsb.fileUtils.setSearchPaths(i);var s=[],t=i[0]||"",l=t+"_temp/",r=l.length;jsb.fileUtils.isDirectoryExist(l)&&!jsb.fileUtils.isFileExist(l+"project.manifest.temp")&&(jsb.fileUtils.listFilesRecursively(l,s),s.forEach(e=>{var i=e.substr(r),s=t+i;"/"===e[e.length]?jsb.fileUtils.createDirectory(s):(jsb.fileUtils.isFileExist(s)&&jsb.fileUtils.removeFile(s),jsb.fileUtils.renameFile(e,s))}),jsb.fileUtils.removeDirectory(l))}}}();`
content = add + content;
fs.writeFile(mainPath, content, (err) => {
if (err) throw err;
console.log("main.js write successfully");
});
} else {
console.warn("Warn: main.js 文件不存在");
}

热更新功能类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
// HotUpdate.ts 自定义热更新功能实现类
/*****************************
*@file: HotUpdate
*@author: 陈吕唐
*@desc: 热更新组件 node version_generator.js -v 1.0.0
*@date: 2022-01-22 15:45
*****************************/
/****************************
* 使用
* 1. 构建项目
* 2. 修改 version_generator 相关参数 remoteUrl src dest
* 3. node version_generator.js -v 1.0.0 执行生成 .manifest 文件
* 4. 将.manifest 和 src 下的 assets src 资源文件放到 远程remoteUrl
* 5. 修改main.js 在编辑器代码前添加 !function(){if("object"==typeof window.native){var e=localStorage.getItem("HotUpdateSearchPaths");if(e){var i=JSON.parse(e);native.fileUtils.setSearchPaths(i);var s=[],t=i[0]||"",l=t+"_temp/",r=l.length;native.fileUtils.isDirectoryExist(l)&&!native.fileUtils.isFileExist(l+"project.manifest.temp")&&(native.fileUtils.listFilesRecursively(l,s),s.forEach(e=>{var i=e.substr(r),s=t+i;"/"===e[e.length]?native.fileUtils.createDirectory(s):(native.fileUtils.isFileExist(s)&&native.fileUtils.removeFile(s),native.fileUtils.renameFile(e,s))}),native.fileUtils.removeDirectory(l))}}}();
* 不添加这代码的话,热更新成功后,关闭应用重新打开又是旧的代码
* ***************************/
/****************************
*
*
****************************/

import { game, native, sys } from 'cc';
export default class HotUpdate {
/****************************************************************************************************************
*Readonly 常量
****************************************************************************************************************/
/**
* 热更新资源存储路径
*/
private readonly STORAGE_PATH = `remotePath/`;

/**
* 热更新搜索路径
*/
private readonly HOT_UP_DATE_SEARCH_PATHS = `HotUpdateSearchPaths`;
/****************************************************************************************************************
*Property 定义变量
****************************************************************************************************************/
/**
* 热更新管理器
*/
private assetManger: native.AssetsManager = null;


/**
* 下载失败重试次数
*/
protected againDownFailAssetNumber: number = 3;

/**
* 热更新配置文件地址
*/
protected nativeUrl: string = undefined!;

/**
* 远程版本
*/
protected remoteVersion: string = "1.0.0";
/***************************************************************
* 热更新回调方法
***************************************************************/
/**
* 更新完成
*/
public completeFunc: () => void = undefined!;

/**
* 更新失败
*/
public updateFailFunc: (event: string) => void = undefined!;

/**
* 更新中
*/
public updatingFunc: (event: native.EventAssetsManager) => void = undefined!;

/**
* 为大版本更新
*/
public bigUpdateFunc: () => void = undefined!;
/****************************************************************************************************************
* Lifecycle 生命周期相关方法
****************************************************************************************************************/
/**
*
* @param nativeUrl 热更新文件地址:project.manifest文件资源(类型:Asset) 资源的地址 manifest.nativeUrl
* @param remoteVersion 远程版本:从后端接口获取
*/
constructor(nativeUrl: string, remoteVersion: string) {
this.nativeUrl = nativeUrl;
this.remoteVersion = remoteVersion;
this.initHotUpdate();
}
/****************************************************************************************************************
* Public 公有方法
****************************************************************************************************************/
/****************************************************************************************************************
* Project 公有方法
****************************************************************************************************************/
/**
* 检查更新
*/
public checkUpdate() {
if (this.isHotUpdate()) {
this.checkUpdateByRemote();
} else {
this.checkUpdateComplete();
}
}

/**
* 获取本地版本号
* @returns 当前manifest文件中的版本号,热更新不可用情况下返回默认版本号
*/
public getLocalVersion(defaultVersion: string = `1.0.0`): string {
if (this.isHotUpdate()) {
defaultVersion = this.manifest.version;
}
return defaultVersion;
}
/****************************************************************************************************************
* private 私有方法
****************************************************************************************************************/
/**
* 检查更新
*/
private async checkUpdateByRemote() {
let localVersion = this.manifest.version;
let remoteVersion = this.remoteVersion;

/**
* 检查是否为大版本更新,需要用户重新下载。
*/
if (this.versionBigUpdate(localVersion, remoteVersion)) {
this.checkBigUpdate();
return;
}

/**
* 对比本地版本与远程版本
*/
let check = this.versionCompareHandle(localVersion, remoteVersion);
if (check < 0) {

this.manifest = this.updateManifestRemoteUrl(this.manifest, remoteVersion);
await new Promise<void>((resolve, reject) => { setTimeout(() => { resolve() }, 1000) })
if (this.manifest) {
this.assetManger.loadLocalManifest(this.manifestFilePath);
this.assetManger.setEventCallback(this.checkUpdateEvent.bind(this));
this.assetManger.checkUpdate();
} else {
this.checkUpdateFail(`写入Manifest失败`);
}
} else {
this.checkUpdateComplete();
}
}


/**
* 监听版本检查相关事件
* @param event
*/
private checkUpdateEvent(event: native.EventAssetsManager) {
switch (event.getEventCode()) {
case native.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST:
case native.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST:
case native.EventAssetsManager.ERROR_PARSE_MANIFEST:
this.checkUpdateFail(event.getMessage());
break;
case native.EventAssetsManager.NEW_VERSION_FOUND:
this.checkUpNew();
break;
case native.EventAssetsManager.ALREADY_UP_TO_DATE:
//已更新到最新版本
this.checkUpdateComplete();
break;
default:
break;
}
}

/**
* 监听热更新事件
* @param event
*/
private hotUpdateEvent(event: native.EventAssetsManager) {
switch (event.getEventCode()) {
case native.EventAssetsManager.UPDATE_PROGRESSION:
//更新中 更新进度
this.updating(event)
break;
case native.EventAssetsManager.UPDATE_FAILED:
this.updateFailAgain(event);
break;
case native.EventAssetsManager.UPDATE_FINISHED:
//更新完成
this.updateGameComplete();
break;
default:
break;
}
}
/****************************************************
* Init
***************************************************/
/**
* 在热更新位置创建和初始一样的备份
* @param path 文件位置
* @param defaultAssets 用于备份的资源
*/
private initManifestFilePath(path: string = this.manifestFilePath, nativeUrl: string = this.nativeUrl) {
if (!native.fileUtils.isDirectoryExist(this.storagePath)) {
native.fileUtils.createDirectory(this.storagePath);
}
/**
* 创建热更新位置的Project
*/
let read = native.fileUtils.getStringFromFile(nativeUrl);
return native.fileUtils.writeStringToFile(read, path);
}

/**
* 初始热更新管理器
* @param assetsNativeUrl
* @returns
*/
private initHotUpdate(): void {
if (!this.isHotUpdate()) {
return;
}

/**
* 热更新文件存放地址(一定要能写入地址,不然下载资源失败)
*/

this.assetManger = new native.AssetsManager(``, this.storagePath, this.versionCompareHandle);
this.assetManger.setVerifyCallback(this.assetsVerify.bind(this))
}
/****************************************************
* 热更新管理器事件处理
***************************************************/
/**
* 检测到新版本处理
*/
private checkUpNew() {
//发现有新版本
this.assetManger.setEventCallback(this.hotUpdateEvent.bind(this));
this.assetManger.update();
}

/**
* 更新失败处理(下载失败重试)
*/
private updateFailAgain(event: native.EventAssetsManager) {
if (this.againDownFailAssetNumber > 0) {
this.assetManger.downloadFailedAssets();
this.againDownFailAssetNumber--;
} else {
this.checkUpdateFail(event.getMessage());
}
}


/**
* 热更新游戏完成(重启游戏)
*/
private updateGameComplete() {
let paths: string[] = this.assetManger.getLocalManifest().getSearchPaths();

if (paths && paths.length > 0) {
localStorage.setItem(this.HOT_UP_DATE_SEARCH_PATHS, JSON.stringify(paths));
}

setTimeout(() => {
game.restart();
}, 3000)
}
/****************************************
* 更新结果处理
****************************************/
/**
* 更新中
*/
private updating(event: native.EventAssetsManager) {
if (this.updatingFunc) {
this.updatingFunc(event);
}
}
/**
* 更新失败
* @param event
*/
private checkUpdateFail(event: string) {
if (this.updateFailFunc) {
this.updateFailFunc(event)
}
}


/**
* 检查更新结果为大版本更新需要重新下载游戏
*/
private checkBigUpdate() {
if (this.bigUpdateFunc) {
this.bigUpdateFunc();
}
}

/**
* 检查更新完成,进入游戏
*/
private checkUpdateComplete() {
if (this.completeFunc) {
this.completeFunc();
}
}
/****************************************
* Utils
***************************************/
/**
* 判断的热更新是否可用
* @returns
*/
private isHotUpdate(): boolean {

/**
* 热更新只有Native平台可用
*/
return sys.isNative;
}
/**
* 是否为大版本更新,需要重新下载安装包
* @param versionA 当前版本
* @param versionB 远程版本
* @returns true 是大版本需要重新下载 false 只需要热更新就好了
*/
protected versionBigUpdate(versionA: string, versionB: string): boolean {
let vA = versionA.split('.');
let vB = versionB.split('.');

let a = parseInt(vA[0]);
let b = parseInt(vB[0]);

return a < b;
}

/**
* 资源验证
* @param path
* @param assets
*/
protected assetsVerify(path: string, assets: native.ManifestAsset): boolean {
return true;
}

/**
*
* @param versionA 本地版本
* @param versionB 远程版本
* @returns
*/
private versionCompareHandle(versionA: string, versionB: string): number {
// //`当前版本 : ${versionA} , 远程版本 : ${versionB}`);
let vA = versionA.split('.');
let vB = versionB.split('.');
for (let i = 0; i < vA.length && i < vB.length; ++i) {
let a = parseInt(vA[i]);
let b = parseInt(vB[i]);
if (a === b) {
continue;
}
else {
return a - b;
}
}
if (vB.length > vA.length) {
return -1;
}
return 0;
}


/**
* 修改manifest远程资源路径(本方法未写入文件)
* @param manifest 资源
* @param version 版本
* @returns
*/
private updateManifestRemoteUrl(manifest: Manifest, version: string): Manifest {
let beforePackageUrl: string = manifest.packageUrl;

/**
* 远程地址字符串去除版本
*/
let latestDir = "remote-assets";
let position = beforePackageUrl.lastIndexOf(latestDir);
if (position > 0) {
beforePackageUrl = beforePackageUrl.substring(0, position + latestDir.length);
}
if (beforePackageUrl[beforePackageUrl.length - 1] == "/") {
beforePackageUrl = beforePackageUrl.substring(0, beforePackageUrl.length - 1);
}

/**
* 加上新的版本字符串
*/
let afterPackageUrl = `${beforePackageUrl}${version}/`;

/**
* 修改manifest
*/
manifest.packageUrl = afterPackageUrl;
manifest.remoteManifestUrl = afterPackageUrl + "project.manifest";
manifest.remoteVersionUrl = afterPackageUrl + "version.manifest";

return manifest;
}
/****************************************************************************************************************
* Property Get && Set 属性的 get && set 函数
****************************************************************************************************************/
/**
* 热更新资源存放位置
*/
private get storagePath(): string {
/**
* 热更新文件存放地址(一定要能写入地址,不然下载资源失败)
*/
return native.fileUtils.getWritablePath() + `/${this.STORAGE_PATH}`;;
}

/**
* 实际读取的热更新配置文件地址
*/
private get manifestFilePath(): string {
return `${this.storagePath}project.manifest`;
}

/**
* 热更新文件
*/
private get manifest(): Manifest {
let manifest: Manifest = undefined!;

/**
* 文件位置
*/
let localFilePath = this.manifestFilePath

if (!native.fileUtils.isFileExist(localFilePath)) {
this.initManifestFilePath();
}

manifest = JSON.parse(native.fileUtils.getStringFromFile(localFilePath));
return manifest;
}

private set manifest(value: Manifest) {
/**
* 文件位置
*/
let localFilePath = this.manifestFilePath;

/**
* 写入的Json字符串
*/
let writeString = JSON.stringify(value);

native.fileUtils.writeStringToFile(writeString, localFilePath)
}
}

/**
* 热更新配置文件结构
*/
interface Manifest {
packageUrl: string;
/**
* 远程manifest文件地址
*/
remoteManifestUrl: string;
remoteVersionUrl: string;
/**
* 版本号
*/
version: string;
}

功能类使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import HotUpdate from '../../libs/HotUpdate';

@property({ type: Label, tooltip: `显示热更新进程文本` })
private updateLabel: Label = undefined;

@property({ type: Asset, tooltip: `热更新文件(project.manifest引用)` })
private manifest: Asset = undefined!;


private initHot() {
//远程版本,实际上应该上后端接口异步获取
let remoteVersion = '1.0.1';

let path = this.manifest.nativeUrl;

//创建热更新对象
let hot = new HotUpdate(path, remoteVersion);

//绑定热更新回调
hot.completeFunc = this.complete.bind(this);
hot.updatingFunc = this.updating.bind(this);
hot.updateFailFunc = this.hotFail.bind(this);

//显示当前版本
this.versionLabel.string = hot.getLocalVersion();

//检查更新
hot.checkUpdate();
}
/*******************************
* 热更新方法回调
*******************************/
private hotFail(error: string) {
this.updateLabel.string = `热更新失败:${error}`;
}

private updating(evet: jsb.EventAssetsManager) {
this.updateLabel.string = `更新中${evet.getMessage()}`;
}

private complete() {
this.updateLabel.string = `已经是最新版本`;
}