-
Notifications
You must be signed in to change notification settings - Fork 470
/
gulpfile.js
1098 lines (982 loc) · 35.3 KB
/
gulpfile.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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const path = require('path');
const fs = require('fs');
const rimrafSync = require('rimraf').sync;
const matched = require('matched');
const ts = require('typescript');
const gulp = require('gulp');
const gulpts = require('gulp-typescript');
const concat = require('gulp-concat');
const inject = require('gulp-inject-string');
const sourcemaps = require('gulp-sourcemaps');
const rollup = require('rollup');
const glsl = require('rollup-plugin-glsl');
const rollupSourcemaps = require('rollup-plugin-sourcemaps');
const merge = require('merge2');
const tscOutPath = "./bin/tsc/";
const sourcemap = true;
//引用插件模块
const typescript = require('rollup-plugin-typescript2'); //typescript2 plugin
const samplesBathURL = './src/samples';
//编译新的库文件只需要在packsDef中配置一下新的库就可以了
const packsDef = [{
'libName': "core",
'input': [
'./layaAir/Decorators.ts',
'./layaAir/Config.ts',
'./layaAir/laya/Const.ts',
'./layaAir/laya/ModuleDef.ts',
'./layaAir/ILaya.ts',
'./layaAir/Laya.ts',
'./layaAir/LayaEnv.ts',
'./layaAir/laya/components/**/*.*',
'./layaAir/laya/display/**/*.*',
'./layaAir/laya/effect/**/*.*',
'./layaAir/laya/events/**/*.*',
'./layaAir/laya/filters/**/*.*',
'./layaAir/laya/layagl/**/*.*',
'./layaAir/laya/webgl/**/*.*',
'./layaAir/laya/RenderDriver/DriverDesign/RenderDevice/**/*.*',
'./layaAir/laya/RenderDriver/DriverDesign/2DRenderPass/**/*.*',
'./layaAir/laya/RenderEngine/RenderEnum/**/*.*',
'./layaAir/laya/RenderEngine/RenderInterface/**/*.*',
'./layaAir/laya/RenderEngine/RenderShader/**/*.*',
'./layaAir/laya/RenderEngine/*.*',
'./layaAir/laya/RenderDriver/RenderModuleData/Design/IDefineDatas.ts',
'./layaAir/laya/RenderDriver/RenderModuleData/Design/IUnitRenderModuleDataFactory.ts',
'./layaAir/laya/RenderDriver/RenderModuleData/Design/RenderState.ts',
'./layaAir/laya/RenderDriver/RenderModuleData/Design/ShaderDefine.ts',
'./layaAir/laya/loaders/**/*.*',
'./layaAir/laya/maths/**/*.*',
'./layaAir/laya/media/**/*.*',
'./layaAir/laya/net/**/*.*',
'./layaAir/laya/NodeRender2D/**/*.*',
'./layaAir/laya/renders/**/*.*',
'./layaAir/laya/resource/**/*.*',
'./layaAir/laya/system/**/*.*',
'./layaAir/laya/utils/**/*.*',
'./layaAir/laya/tools/**/*.*',
'./layaAir/laya/html/**/*.*',
'./layaAir/Config3D.ts',
"./layaAir/laya/bt/**/*.*"
],
},
{
'libName': "d3",
'input': [
'./layaAir/laya/d3/animation/**/*.*',
'./layaAir/laya/d3/component/**/*.*',
'./layaAir/laya/d3/core/**/*.*',
'./layaAir/laya/d3/depthMap/*.*',
'./layaAir/laya/d3/graphics/**/*.*',
'./layaAir/laya/d3/loaders/**/*.*',
'./layaAir/laya/d3/math/**/*.*',
'./layaAir/laya/d3/resource/**/*.*',
'./layaAir/laya/d3/shader/**/*.*',
'./layaAir/laya/d3/shadowMap/**/*.*',
'./layaAir/laya/d3/text/**/*.*',
'./layaAir/laya/d3/utils/**/*.*',
'./layaAir/laya/d3/WebXR/**/*.*',
'./layaAir/laya/d3/Input3D.ts',
'./layaAir/laya/d3/MouseTouch.ts',
'./layaAir/laya/d3/Touch.ts',
'./layaAir/laya/d3/ModuleDef.ts',
'./layaAir/laya/RenderDriver/DriverDesign/RenderDevice/**/*.*',
'./layaAir/laya/RenderDriver/DriverDesign/3DRenderPass/**/*.*',
'./layaAir/laya/RenderDriver/RenderModuleData/Design/**/*.*',
'./layaAir/laya/d3/RenderObjs/NativeOBJ/*.*',
'./layaAir/laya/d3/RenderObjs/RenderObj/*.*',
'./layaAir/laya/d3/RenderObjs/IRenderEngine3DOBJFactory.ts',
'./layaAir/laya/d3/RenderObjs/Laya3DRender.ts',
'./layaAir/laya/d3/ModuleDef.ts',
'./layaAir/ILaya3D.ts',
'./layaAir/Laya3D.ts',
// interface and enum
'./layaAir/laya/Physics3D/interface/**/*.*',
'./layaAir/laya/Physics3D/physicsEnum/**/*.*',
'./layaAir/laya/d3/physics/HitResult.ts',
'./layaAir/laya/d3/physics/PhysicsSettings.ts',
'./layaAir/laya/d3/physics/Collision.ts',
'./layaAir/laya/d3/physics/ContactPoint.ts',
],
},
{
'libName': "opengl_2D",
'input': [
'./layaAir/laya/RenderDriver/OpenGLESDriver/RenderDevice/**/*.*',
'./layaAir/laya/RenderDriver/OpenGLESDriver/2DRenderPass/**/*.*',
'./layaAir/laya/RenderDriver/RenderModuleData/RuntimeModuleData/*.*',
],
},
{
'libName': "opengl_3D",
'input': [
'./layaAir/laya/RenderDriver/OpenGLESDriver/3DRenderPass/**/*.*',
'./layaAir/laya/RenderDriver/RenderModuleData/RuntimeModuleData/3D/*.*',
],
},
{
'libName': "webgl_2D",
'input': [
'./layaAir/laya/RenderDriver/WebGLDriver/RenderDevice/**/*.*',
'./layaAir/laya/RenderDriver/WebGLDriver/2DRenderPass/**/*.*',
'./layaAir/laya/RenderDriver/RenderModuleData/WebModuleData/*.*',
],
},
{
'libName': "webgl_3D",
'input': [
'./layaAir/laya/RenderDriver/DriverCommon/**/*.*',
'./layaAir/laya/RenderDriver/WebGLDriver/3DRenderPass/**/*.*',
'./layaAir/laya/RenderDriver/RenderModuleData/WebModuleData/3D/*.*',
],
},
{
'libName': "webgpu_2D",
'input': [
'./layaAir/laya/RenderDriver/WebGPUDriver/RenderDevice/**/*.*',
'./layaAir/laya/RenderDriver/WebGPUDriver/ShaderCompile/**/*.*',
'./layaAir/laya/RenderDriver/WebGPUDriver/2DRenderPass/**/*.*',
'./layaAir/laya/RenderDriver/RenderModuleData/WebModuleData/*.*',
],
},
{
'libName': "webgpu_3D",
'input': [
'./layaAir/laya/RenderDriver/DriverCommon/**/*.*',
'./layaAir/laya/RenderDriver/WebGPUDriver/ShaderCompile/**/*.*',
'./layaAir/laya/RenderDriver/WebGPUDriver/3DRenderPass/**/*.*',
'./layaAir/laya/RenderDriver/RenderModuleData/WebModuleData/3D/*.*',
],
},
{
'libName': "physics3D",
'input': [
'./layaAir/laya/d3/physics/constraints/**/*.*',
'./layaAir/laya/d3/physics/shape/**/*.*',
'./layaAir/laya/d3/physics/ModuleDef.ts',
'./layaAir/laya/d3/physics/CharacterController.ts',
'./layaAir/laya/d3/physics/Constraint3D.ts',
'./layaAir/laya/d3/physics/PhysicsCollider.ts',
'./layaAir/laya/d3/physics/PhysicsColliderComponent.ts',
'./layaAir/laya/d3/physics/PhysicsUpdateList.ts',
'./layaAir/laya/d3/physics/RaycastVehicle.ts',
'./layaAir/laya/d3/physics/RaycastWheel.ts',
'./layaAir/laya/d3/physics/Rigidbody3D.ts',
],
},
{
'libName': "gltf",
'input': [
'./layaAir/laya/gltf/**/*.*',
],
},
{
'libName': "bullet",
'input': [
// use this compile order to solve C_D problem
'./layaAir/laya/Physics3D/Bullet/btPhysicsCreateUtil.ts',
'./layaAir/laya/Physics3D/Bullet/Collider/**/*.*',
'./layaAir/laya/Physics3D/Bullet/Shape/**/*.*',
'./layaAir/laya/Physics3D/Bullet/Joint/**/*.*',
'./layaAir/laya/Physics3D/Bullet/btInteractive.ts',
'./layaAir/laya/Physics3D/Bullet/CollisionTool.ts',
'./layaAir/laya/Physics3D/Bullet/btPhysicsManager.ts',
'./layaAir/laya/Physics3D/Bullet/**/*.*',
],
},
{
'libName': "physX",
'input': [
'./layaAir/laya/Physics3D/PhysX/pxPhysicsCreateUtil.ts',
'./layaAir/laya/Physics3D/PhysX/Collider/**/*.*',
'./layaAir/laya/Physics3D/PhysX/Shape/**/*.*',
'./layaAir/laya/Physics3D/PhysX/Joint/**/*.*',
'./layaAir/laya/Physics3D/PhysX/pxPhysicsManager.ts',
'./layaAir/laya/Physics3D/PhysX/pxPhysicsMaterial.ts',
'./layaAir/laya/Physics3D/PhysX/**/*.*',
],
},
{
'libName': 'device',
'input': [
'./layaAir/laya/device/**/*.*'
],
},
{
'libName': 'tiledmap',
'input': [
'./layaAir/laya/map/**/*.*'
],
},
{
'libName': 'physics2D',
'input': [
'./layaAir/laya/physics/Collider2D/*.*',
'./layaAir/laya/physics/joint/*.*',
'./layaAir/laya/physics/IPhysiscs2DFactory.ts',
'./layaAir/laya/physics/ModuleDef.ts',
'./layaAir/laya/physics/Physics2D.ts',
'./layaAir/laya/physics/Physics2DOption.ts',
'./layaAir/laya/physics/RigidBody.ts',
'./layaAir/laya/physics/RigidBody2DInfo.ts',
'./layaAir/laya/physics/Physics2DDebugDraw.ts',
],
},
{
'libName': 'box2D',
'input': [
'./layaAir/laya/physics/factory/physics2DwasmFactory.ts',
],
},
{
'libName': 'box2D.wasm',
'input': [
'./layaAir/laya/physics/factory/physics2DwasmFactory.ts',
],
},
{
'libName': 'ui',
'input': [
'./layaAir/laya/ui/**/*.*',
'./layaAir/UIConfig.ts',
],
},
{
'libName': 'spine',
'input': [
'./layaAir/laya/spine/**/*.*'
],
},
{
'libName': 'ani',
'input': [
'./layaAir/laya/ani/**/*.*'
],
},
{
'libName': 'debugtool',
'input': [
'./extensions/debug/**/*.*'
],
},
{
"libName": 'performancetool',
'input': [
'./extensions/performanceTool/**/*.*'
],
},
{
'libName': "navMesh",
'input': [
'./layaAir/laya/navigation/**/**.ts'
],
},
{
'libName': "legacyParser",
'input': [
'./layaAir/laya/legacy/**/**.ts'
],
},
];
/*
并非所有循环引用都会引起加载问题,如果两个模块只是使用对方的类型声明,没有使用继承/构造行为,是允许的。
这里忽略这类情况。
*/
const ignoreCirclarDependencyWarnings = true;
const onwarn = warning => {
let msg = warning.message;
if (warning.code === 'CIRCULAR_DEPENDENCY') {
if (ignoreCirclarDependencyWarnings)
return;
let arr = msg.split("->");
arr = arr.map(e => {
e = e.trim();
return path.basename(e, path.extname(e));
});
msg = arr.join(" -> ");
msg = "(C_D) " + msg;
console.warn(msg);
} else
console.warn(warning);
}
gulp.task('compileLayaAir', () => {
rimrafSync(tscOutPath + 'layaAir');
const proj = gulpts.createProject("./src/layaAir/tsconfig.json", {
removeComments: true,
});
return merge(
proj.src()
.pipe(sourcemaps.init())
.pipe(proj())
.pipe(sourcemaps.write('.', {
sourceRoot: './',
includeContent: false
}))
.pipe(gulp.dest(tscOutPath + 'layaAir')),
gulp.src([
'./src/layaAir/**/*.vs',
'./src/layaAir/**/*.fs',
'./src/layaAir/**/*.glsl',
'./src/layaAir/**/*.wgsl'
], {
base: "src"
})
.pipe(gulp.dest(tscOutPath))
);
});
gulp.task('compileExtension', () => {
rimrafSync(tscOutPath + 'extensions');
const proj = gulpts.createProject("./src/extensions/tsconfig.json", {
removeComments: true
});
return proj.src().pipe(proj()).pipe(gulp.dest(tscOutPath + 'extensions'));
});
gulp.task('compile', gulp.series('compileLayaAir', 'compileExtension'));
gulp.task("buildJs", async () => {
rimrafSync("./build/libs");
const rootPath = process.cwd();
const outPath = path.join(rootPath, tscOutPath);
const mentry = '[entry]';
function myMultiInput(pkgDef, files, fileSet) {
return {
resolveId(id, importer) {
if (id === mentry)
return mentry;
if (importer == null)
return;
var ext = path.extname(id);
if (ext == ".js" || ext == "") {
var importfile = path.join(importer === mentry ? rootPath : path.dirname(importer), id);
if (ext == "")
importfile += ".js";
if (!fileSet.has(importfile)) {
if (pkgDef.libName == "core")
console.warn(`external: ${path.relative(outPath, importer)} ==> ${path.relative(outPath, importfile)}`);
return {
id: 'Laya',
external: true
};
}
}
},
load(id) {
if (id === mentry)
return files.map(ele => `export * from ${JSON.stringify(tscOutPath + ele)};`).join('\n');
}
};
}
async function getFiles(input) {
var include = [];
var exclude = [];
if (typeof input === 'string') {
include = [input];
} else if (Array.isArray(input)) {
include = input;
} else {
include = input.include || [];
exclude = input.exclude || [];
}
var patterns = include.concat(exclude.map(function (pattern) {
return '!' + pattern;
}));
return matched.promise(patterns, {
cwd: path.join(process.cwd(), "./src"),
realpath: false
});
}
for (let i = 0; i < packsDef.length; ++i) {
let files = await getFiles(packsDef[i].input);
files = files.filter(ele => ele.endsWith(".ts")).map(ele => ele = ele.substring(0, ele.length - 3) + ".js");
let fileSet = new Set(files.map(ele => path.normalize(outPath + ele)));
let config = {
input: mentry,
output: {
extend: true,
globals: {
'Laya': 'Laya'
}
},
external: ['Laya'],
onwarn: onwarn,
plugins: [
myMultiInput(packsDef[i], files, fileSet),
rollupSourcemaps(),
glsl({
include: /.*(.glsl|.vs|.fs)$/,
sourceMap: sourcemap,
compress: false
})
],
};
let outputOption = {
file: path.join("./build/libs", "laya." + packsDef[i].libName + ".js"),
format: 'iife',
esModule: false,
name: 'Laya',
globals: {
'Laya': 'Laya'
},
sourcemap: sourcemap
};
if (packsDef[i].libName != "core")
outputOption.extend = true;
const bundle = await rollup.rollup(config);
await bundle.write(outputOption);
}
await new Promise(resolve => {
merge(packsDef.map(pack => {
return gulp.src(path.join("./build/libs", "laya." + pack.libName + ".js"))
.pipe(inject.replace(/var Laya = \(function \(exports.*\)/, "window.Laya = (function (exports)"))
.pipe(inject.replace(/}\)\({}, Laya\);/, "})({});"))
.pipe(inject.replace(/Laya\$1\./g, "exports."))
.pipe(inject.replace(/\(this.Laya = this.Laya \|\| {}, Laya\)/, "(window.Laya = window.Laya || {}, Laya)"))
.pipe(gulp.dest(process.platform == 'win32' ? '.' : './build/libs')); //在win下dest竟然突然变成src的相对目录
})).on("queueDrain", resolve);
});
});
//拷贝引擎的第三方js库
gulp.task("copyJsLibs", async () => {
return gulp.src([
'./src/layaAir/jsLibs/*.js',
'./src/layaAir/jsLibs/*.mjs',
'./src/layaAir/jsLibs/*.wasm',
'!./src/layaAir/jsLibs/laya.Box2D.js',
'!./src/layaAir/jsLibs/laya.Box2D.wasm.js',
'!./src/layaAir/jsLibs/cannon.js',
'!./src/layaAir/jsLibs/bullet.js',
'!./src/layaAir/jsLibs/bullet.wasm.js',
'!./src/layaAir/jsLibs/physx.release.js',
'!./src/layaAir/jsLibs/physx.wasm.js',
'!./src/layaAir/jsLibs/recast-navigation.js',
'!./src/layaAir/jsLibs/recast-navigation-wasm.js',
])
.pipe(gulp.dest('./build/libs'));
});
//合并physics2D 和 box2d
gulp.task('buildBox2dPhysics', () => {
return gulp.src([
'./build/libs/laya.box2D.js',
'./src/layaAir/jsLibs/laya.Box2D.js',
]).pipe(concat('laya.box2D.js'))
.pipe(gulp.dest('./build/libs/'));
});
gulp.task('buildBox2dWasmPhysics', () => {
return gulp.src([
'./build/libs/laya.box2D.wasm.js',
'./src/layaAir/jsLibs/laya.Box2D.wasm.js',
]).pipe(concat('laya.box2D.wasm.js'))
.pipe(gulp.dest('./build/libs/'));
});
//合并bullet物理引擎库 和 编译出来的physics.bullet.js
gulp.task('buildBulletPhysics', () => {
return gulp.src([
'./build/libs/laya.bullet.js',
'./src/layaAir/jsLibs/bullet.js',
]).pipe(concat('laya.bullet.js'))
.pipe(gulp.dest('./build/libs/'));
});
//合并bullet的wasm物理库 和 编译出来的physics.bullet.js
gulp.task('buildBulletWASMPhysics', () => {
return gulp.src([
'./build/libs/laya.bullet.js',
'./src/layaAir/jsLibs/bullet.wasm.js',
]).pipe(concat('laya.bullet.wasm.js'))
.pipe(gulp.dest('./build/libs/'));
});
//合并physX的wasm物理引擎库 和 编译出来的physics.physX.js
gulp.task('buildPhysXWASMPhysics', () => {
return gulp.src([
'./build/libs/laya.physX.js',
'./src/layaAir/jsLibs/physx.wasm.js',
])
.pipe(concat('laya.physX.wasm.js'))
.pipe(gulp.dest('./build/libs/'));
});
gulp.task('buildNavMesh_wasm', () => {
return gulp.src([
'./src/layaAir/jsLibs/recast-navigation-wasm.js',
'./build/libs/laya.navMesh.js',
]).pipe(concat('laya.navMesh_wasm.js'))
.pipe(gulp.dest('./build/libs/'));
});
gulp.task('buildNavMesh', () => {
return gulp.src([
'./src/layaAir/jsLibs/recast-navigation.js',
'./build/libs/laya.navMesh.js',
]).pipe(concat('laya.navMesh.js'))
.pipe(gulp.dest('./build/libs/'));
});
//合并physX物理引擎库 和 编译出来的physics.physX.js
gulp.task('buildPhysXPhysics', () => {
return gulp.src([
'./build/libs/laya.physX.js',
'./src/layaAir/jsLibs/physx.release.js',
])
.pipe(concat('laya.physX.js'))
.pipe(gulp.dest('./build/libs/'));
});
//生成性能统计Json文件
gulp.task('buildPerf', async () => {
const perfList = [];
const pattern = path.join("./src/layaAir", "**/*.ts");
function getMethodDeclarations(classDeclaration) {
const methodDeclarations = [];
ts.forEachChild(classDeclaration, (node) => {
if (ts.isMethodDeclaration(node)) {
methodDeclarations.push(node);
}
});
return methodDeclarations;
}
// 获取所有的ts文件, 并依次处理
const files = await matched.promise(pattern, { realpath: true, nosort: false });
const fileList = files.map(file => {
const code = fs.readFileSync(file, "utf-8");
return ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true);
});
for (const sourceFile of fileList) {
// 获取所有的类声明
const classDecList = sourceFile.statements.filter(node => ts.isClassDeclaration(node));
for (let i = 0; i < classDecList.length; i++) {
const classDec = classDecList[i];
// 获取类中的所有方法声明
const methodDeclarations = getMethodDeclarations(classDec);
for (let j = 0, len = methodDeclarations.length; j < len; j++) {
const methodDec = methodDeclarations[j];
// 获取方法上的perfTag标签
const jsonTags = ts.getAllJSDocTags(methodDec, tag => tag.tagName.escapedText === "perfTag");
if (!jsonTags || !jsonTags.length) continue;
for (const jsonTag of jsonTags) {
const className = classDec.name.escapedText;
const methodName = methodDec.name.escapedText;
const perfContent = jsonTag.comment;
perfList.push({
clz: className, func: methodName, tag: perfContent
});
}
}
}
}
// 保存到文件
const perfJson = JSON.stringify(perfList);
const perfDir = "./build/performanceTool";
// 如果目录不存在则创建
if (!fs.existsSync(perfDir)) {
fs.mkdirSync(perfDir, { recursive: true });
}
fs.writeFileSync(path.join(perfDir, "statistic.json"), perfJson);
});
gulp.task('genDts', () => {
rimrafSync("./build/temp");
rimrafSync("./build/types");
async function genDts() {
const dtsContents = [];
const dtsContentsTop = [];
const SyntaxKind = ts.SyntaxKind;
function processTree(sourceFile, rootNode, replacer) {
let code = '';
let cursorPosition = rootNode.pos;
function skip(node) {
cursorPosition = node.end;
}
function readThrough(node) {
code += sourceFile.text.slice(cursorPosition, node.pos);
cursorPosition = node.pos;
}
function visit(node) {
readThrough(node);
const replacement = replacer(node);
if (replacement != null) {
code += replacement;
skip(node);
} else {
ts.forEachChild(node, visit);
}
}
visit(rootNode);
code += sourceFile.text.slice(cursorPosition, rootNode.end);
return code;
}
let files = await matched.promise("./build/temp/**/*.d.ts", {
realpath: true,
nosort: false
});
for (let file of files) {
let inNamespace = !file.endsWith("Laya.d.ts") && !file.endsWith("Laya3D.d.ts");
let code = fs.readFileSync(file, "utf-8");
let declarationFile = ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true);
function visitNode(node) {
if (node.kind == SyntaxKind.ImportDeclaration || node.kind == SyntaxKind.ImportEqualsDeclaration) { //删除所有import语句
return '';
} else if (node.kind == SyntaxKind.ExportDeclaration) { //something like "export xx;"
return '';
} else if (node.kind == SyntaxKind.ExportKeyword) { //删除所有export语句
let code = declarationFile.text.slice(node.pos, node.end);
return code.substring(0, code.length - 6);
} else if ((node.kind == SyntaxKind.DeclareKeyword || node.kind == SyntaxKind.ModuleDeclaration) && inNamespace) { //删除declare
return '';
} else if (node.kind == SyntaxKind.TypeReference) {
let code = declarationFile.text.slice(node.pos, node.end);
code = code.substring(1);
if (!inNamespace && code.indexOf(".") == -1 && !code.startsWith("Promise"))
return " Laya." + code;
else if (code.startsWith("glTF."))
return " " + code.substring(5);
}
//console.log(node.kind, node.parent?.kind, node.text);
}
const content = processTree(declarationFile, declarationFile, visitNode).trimEnd();
if (content.length == 0)
continue;
if (inNamespace) {
let lines = content.split("\n");
dtsContents.push(lines.map(l => " " + l).join("\n"));
} else
dtsContentsTop.push(content);
}
//pretty print
let code = dtsContentsTop.join("\n\n") +
"\n\ndeclare module Laya {\n\n" +
dtsContents.join("\n\n") +
"\n\n}";
let declarationFile = ts.createSourceFile("./build/types/LayaAir.d.ts", code, ts.ScriptTarget.Latest, true);
code = ts.createPrinter().printFile(declarationFile);
fs.writeFileSync("./build/types/LayaAir.d.ts", code);
rimrafSync("./build/temp");
}
const proj = gulpts.createProject("./src/layaAir/tsconfig.json", {
declaration: true,
removeComments: false,
});
return merge(
proj.src().pipe(proj()).dts.pipe(gulp.dest("./build/temp")).on("end", genDts),
gulp.src(['./src/layaAir/tslibs/*.*']).pipe(gulp.dest('./build/types')),
);
});
gulp.task('build',
gulp.series(
'compile',
'buildJs',
'copyJsLibs',
'buildBox2dPhysics',
'buildBox2dWasmPhysics',
'buildBulletWASMPhysics',
'buildBulletPhysics',
'buildPhysXWASMPhysics',
'buildPhysXPhysics',
'buildNavMesh_wasm',
'buildNavMesh',
'genDts',
));
/**
* 主要用来给laya库加上所有的Laya.xx=xx
* 主要用在
* 1. 分包的时候统计laya文件
* 2. 打包的时候导出Laya
* addLayaExpAt:string 打包的最后会替换这个字符串,加上Laya.xx=xx
* layaPath:laya所在目录。这个目录下的是laya文件,可以用来收集laya文件或者判断需要导出的类
* isLayaLib:boolean 当前打包是否是laya目录,是的话表示强制加 Laya.xx 不再判断目录
* gatherExtFiles:string[] 收集用到的laya文件。这表示是分包模式
* baseUrl:string 设置baseurl,只有分包模式用到
*/
function layaExpPlugin(options) {
let dirname = __dirname; //process.cwd();
let opt = options;
let layaPath = null;
let layafiles = null;
let baseUrl = null;
if (opt) {
layafiles = opt.gatherExtFiles;
if (layafiles && !(layafiles instanceof Array)) {
throw 'gatherExtFiles should be an Array';
}
layaPath = options.layaPath;
if (layaPath)
layaPath = path.resolve(dirname, layaPath);
baseUrl = opt.baseUrl;
if (baseUrl) {
baseUrl = path.resolve(dirname, baseUrl);
}
}
function isLayaPath(id) {
if (!layaPath)
return false;
let r = path.relative(layaPath, id);
return !r.startsWith('..');
}
return ({
load(id) { },
resolveId(id, importer) {
if (!importer)
return;
if (!layafiles) // 不收集laya文件,表示是整体打包。不排除laya文件
return;
let importfile;
if (id.startsWith('..') || id.startsWith('.'))
importfile = path.join(path.dirname(importer), id);
else if (baseUrl) {
importfile = path.join(baseUrl, id);
}
if (isLayaPath(importfile)) {
let tsfile = importfile;
tsfile += '.ts';
if (layafiles.indexOf(tsfile) < 0)
layafiles.push(tsfile);
return 'Laya';
} else { }
},
renderChunk(code, chunk, options) {
let replacestr = opt.addLayaExpAt;
let SourceMap = null;
let _code = code;
if (!replacestr)
return {
code: _code,
map: SourceMap
};
let p = code.lastIndexOf(replacestr);
if (p < 0)
return {
code: _code,
map: SourceMap
};
let expstr = 'Laya=window.Laya;\n';
let islayalib = opt.isLayaLib;
for (let mod in chunk.modules) {
if (!islayalib && !isLayaPath(mod))
continue;
// 所有的laya模块都导出
chunk.modules[mod].renderedExports.forEach(m => {
if (m === 'default') return;
if (m === 'Laya') return;
expstr += 'Laya.' + m + '=' + m + '\n';
});
}
// 插入导出的模块
let st = 'window.Laya=window.Laya||{};\n';
_code = st + code.substr(0, p) + expstr + code.substr(p + replacestr.length);
// console.log(_code);
return {
code: _code,
map: SourceMap
}
}
});
}
let baseurl = __dirname;
let layaFiles = [
path.join(baseurl, "./src/", "layaAir", "Laya.ts"),
path.join(baseurl, "./src/", "layaAir", "laya", "net", "HttpRequest.ts"),
path.join(baseurl, "./src/", "layaAir", "laya", "resource", "Resource.ts"),
path.join(baseurl, "./src/", "layaAir", "laya", "resource", "Texture.ts"),
path.join(baseurl, "./src/", "layaAir", "laya", "media", "SoundChannel.ts"),
path.join(baseurl, "./src/", "layaAir", "laya", "events", "EventDispatcher.ts"),
path.join(baseurl, "./src/", "layaAir", "laya", "utils", "Browser.ts"),
path.join(baseurl, "./src/", "layaAir", "laya", "utils", "RunDriver.ts"),
path.join(baseurl, "./src/", "layaAir", "laya", "display", "Input.ts"),
path.join(baseurl, "./src/", "layaAir", "laya", "net", "Loader.ts"),
path.join(baseurl, "./src/", "layaAir", "laya", "net", "LocalStorage.ts"),
path.join(baseurl, "./src/", "layaAir", "Config.ts"),
];
let layaexpreplace = '//__LAYARPLACEMENTHERE__//';
var curPackFiles = null; //当前包的所有的文件
var mentry = 'multientry.ts';
function mySamplesMultiInput(options) {
let packPath = options ? options.path : null; // 除了制定输入以外,这个目录下的也可以认为是内部文件,可以引用
if (packPath && !path.isAbsolute(packPath)) {
packPath = path.join(__dirname, packPath);
}
function pathInPack(p) {
if (!packPath)
return true; // 没有设置,则认为true,
let r = path.relative(packPath, p);
if (r.startsWith('..')) //TODO 如果盘符都变了这样是不对的
return false;
return true;
}
var include = [];
var exclude = [];
function configure(config) {
if (typeof config === 'string') {
include = [config];
} else if (Array.isArray(config)) {
include = config;
} else {
include = config.include || [];
exclude = config.exclude || [];
if (config.exports === false) {
exporter = function exporter(p) {
if (p.substr(p.length - 3) == '.ts') {
p = p.substr(0, p.length - 3);
}
return `import ${JSON.stringify(p)};`;
};
}
}
}
var exporter = function exporter(p) {
if (p.substr(p.length - 3) == '.ts') {
p = p.substr(0, p.length - 3);
}
return `export * from ${JSON.stringify(p)};`;
};
return ({
options(options) {
configure(options.input);
options.input = mentry;
},
resolveId(id, importer) { //entry是个特殊字符串,rollup并不识别,所以假装这里解析一下
if (id === mentry) {
return mentry;
}
if (mentry == importer)
return;
var importfile = path.join(path.dirname(importer), id);
var ext = path.extname(importfile);
if (ext != '.ts' && ext != '.glsl' && ext != '.vs' && ext != '.ps' && ext != '.fs') {
importfile += '.ts';
}
if (importfile.endsWith('.json')) {
console.log('import ', importfile);
}
if (curPackFiles.indexOf(importfile) < 0 && !pathInPack(importfile)) {
//其他包里的文件
// console.log('other pack:',id,'impo rter=', importer);
return 'Laya';
}
},
load(id) {
if (id === mentry) {
if (!include.length) {
return Promise.resolve('');
}
var patterns = include.concat(exclude.map(function (pattern) {
return '!' + pattern;
}));
return matched.promise(patterns, {
realpath: true
}).then(function (paths) {
curPackFiles = paths; // 记录一下所有的文件
return paths.map(exporter).join('\n');
});
} else {
// console.log('load ',id);
}
}
});
}
gulp.task('compileSamples', async (cb) => {
let bundleobj = {
tsconfig: samplesBathURL + '/tsconfig.json',
check: false, //Set to false to avoid doing any diagnostic checks on the code
tsconfigOverride: {
compilerOptions: {
removeComments: true
}
},
include: samplesBathURL + "/**/*.ts"
}
await rollup.rollup({
input: samplesBathURL + '/index.ts',
treeshake: false, //建议忽略
onwarn: (waring, warn) => {
if (ignoreCirclarDependencyWarnings) {
return
} else {
console.log("warnning Circular dependency:");
console.log(waring);
}
},