-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathterrain-system.js
4861 lines (4758 loc) · 739 KB
/
terrain-system.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
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
;
(() => {
const defs = {};
const resolved = {};
// save original define and require
window.___amd___OriginalDefine = window.define;
window.___amd___OriginalRequire = window.require;
if (!window.define && !window.require) {
const define = (id, deps, factory) => {
if (defs[id]) {
throw new Error('Duplicate definition for ' + id);
}
defs[id] = [deps, factory];
};
define.amd = {
bundle: true, // this implementation works only with bundled amd modules
dynamic: false, // does not support dynamic or async loading
};
const require = (id) => {
if (id === 'require')
return require;
if (id === 'exports')
return {};
if (resolved[id])
return resolved[id];
if (!defs[id]) {
console.log(defs, id);
throw new Error('No definition for ' + id);
}
const moduleExports = {};
const deps = defs[id][0];
const factory = defs[id][1];
const args = deps.map(dep => {
if (dep === 'exports') {
return moduleExports;
}
return require(dep);
});
factory.apply(null, args);
return resolved[id] = moduleExports;
};
window.define = define;
window.require = require;
}
window.___amd___requireResolver = () => {
for (const id in defs) {
if (defs.hasOwnProperty(id)) {
const deps = defs[id][0];
if (deps) {
deps.map(dep => {
if (dep !== 'require' &&
dep !== 'exports') {
if (!resolved.hasOwnProperty(dep)) {
require(dep);
}
if (!defs.hasOwnProperty(dep) &&
!resolved.hasOwnProperty(dep)) {
throw new Error(`Failed define '${id}' dep not found '${dep}'`);
}
}
});
}
require(id);
delete defs[id];
}
}
// return original define and require
window.define = window.___amd___OriginalDefine;
window.require = window.___amd___OriginalRequire;
// clear
delete window.___amd___requireResolver;
delete window.___amd___OriginalDefine;
delete window.___amd___OriginalRequire;
};
})();
define("src/EditorSystem/KeyboardHandler", ["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeyboardHanlder = void 0;
class KeyboardHanlder {
init() {
}
destroy() {
}
}
exports.KeyboardHanlder = KeyboardHanlder;
exports.default = KeyboardHanlder;
});
define("src/EditorSystem/MouseHandler", ["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MouseHandler = void 0;
class MouseHandler {
get enter() { return this._enter; }
constructor() {
this._enter = false;
this._onWindowEnter = this._onWindowEnter.bind(this);
this._onWindowLeave = this._onWindowLeave.bind(this);
}
init() {
document.addEventListener("mouseenter", this._onWindowEnter);
document.addEventListener("mouseleave", this._onWindowLeave);
}
destroy() {
document.removeEventListener("mouseenter", this._onWindowEnter);
document.removeEventListener("mouseleave", this._onWindowLeave);
}
_onWindowEnter(event) {
if (event.clientY > 0 || event.clientX > 0 || (event.clientX < window.innerWidth || event.clientY < window.innerHeight)) {
console.log('Enter');
this._enter = true;
}
}
_onWindowLeave(event) {
if (event.clientY <= 0 || event.clientX <= 0 || (event.clientX >= window.innerWidth || event.clientY >= window.innerHeight)) {
console.log('Leave');
this._enter = false;
}
}
}
exports.MouseHandler = MouseHandler;
});
define("src/ScriptHelpers/Brush", ["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
});
define("src/ScriptHelpers/ColorPainterShaders", ["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fragmentInvertShader = exports.fragmentShader = exports.factorMethod = exports.vertexShader = void 0;
exports.vertexShader = `
attribute vec3 aPosition;
attribute vec2 aUv0;
uniform mat4 matrix_model;
uniform mat4 matrix_viewProjection;
varying vec2 vUv0;
void main(void)
{
vUv0 = aUv0;
gl_Position = matrix_viewProjection * matrix_model * vec4(aPosition, 1.0);
}
`;
exports.factorMethod = `
varying vec2 vUv0;
uniform sampler2D uHeightMap;
uniform float uBrushOpacity;
uniform vec4 uBrushMask;
float getFactor() {
vec4 heightMap = texture2D(uHeightMap, vUv0);
float height = (heightMap.r + heightMap.g + heightMap.b) / 3.0 / heightMap.a;
float factor = height * uBrushOpacity;
return factor;
}
`;
exports.fragmentShader = `
${exports.factorMethod}
void main(void)
{
float factor = getFactor();
vec4 color = vec4(uBrushMask * factor);
gl_FragColor = color;
}
`;
exports.fragmentInvertShader = `
${exports.factorMethod}
void main(void)
{
float levels = 4.0;
float factor = getFactor();
vec4 color = vec4(factor);
if (uBrushMask.r > 0.0) { color.r = 0.0; levels -= 1.0; }
if (uBrushMask.g > 0.0) { color.g = 0.0; levels -= 1.0; }
if (uBrushMask.b > 0.0) { color.b = 0.0; levels -= 1.0; }
if (uBrushMask.a > 0.0) { color.a = 0.0; levels -= 1.0; }
gl_FragColor = color / levels;
}
`;
});
define("src/ScriptHelpers/Shared", ["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkGDSupportR32F = exports.setPrecision = void 0;
const setPrecision = (graphicsDevice, shaderCode) => {
return "precision " + graphicsDevice.precision + " float;\n" + shaderCode;
};
exports.setPrecision = setPrecision;
const checkGDSupportR32F = (graphicsDevice) => {
// TODO: maybe not support
if (graphicsDevice.isWebGPU) {
return true;
}
let result = false;
if (graphicsDevice.isWebGL2) {
const gl = graphicsDevice.gl;
result = gl.getExtension("EXT_color_buffer_float");
if (result) {
result = gl.getExtension("OES_texture_float");
}
}
//alert(JSON.stringify(result));
return !!result;
};
exports.checkGDSupportR32F = checkGDSupportR32F;
});
define("src/ScriptHelpers/ColorPainter", ["require", "exports", "src/ScriptHelpers/ColorPainterShaders", "src/ScriptHelpers/Shared"], function (require, exports, ColorPainterShaders_mjs_1, Shared_mjs_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.painterLayerName = exports.painterCameraFar = void 0;
exports.painterCameraFar = 10;
exports.painterLayerName = 'TerrainEditor';
class ColorPainter {
get painting() { return this._painting; }
get cameraFar() { return exports.painterCameraFar; }
get background() { return this._buffer; }
constructor(app, buffer) {
this._painting = false;
this._painterMask = new Float32Array(4);
this._buffer = buffer;
this._app = app;
this._initCamera();
this._initShaders();
this._initMaterials();
this._initEntities();
}
_initCamera() {
const painterLayer = this._app.scene.layers.getLayerByName(exports.painterLayerName);
this._painterRenderTarget = new pc.RenderTarget({
colorBuffer: this._buffer,
flipY: this._app.graphicsDevice.isWebGPU,
depth: false,
});
this._painterCameraEntity = new pc.Entity('TerrainPainterCamera');
this._painterCameraEntity.setLocalPosition(0, 0, exports.painterCameraFar);
this._painterCameraEntity.lookAt(0, 0, 0);
this._painterCameraEntity.addComponent('camera', {
projection: pc.PROJECTION_ORTHOGRAPHIC,
clearColorBuffer: false,
clearDepthBuffer: false,
priority: -1,
layers: [painterLayer.id],
nearClip: 0.1,
farClip: exports.painterCameraFar * 2,
renderTarget: this._painterRenderTarget,
});
this._app.root.addChild(this._painterCameraEntity);
this._painterCameraEntity.enabled = false;
this._painterCameraEntity.camera.frustumCulling = false;
this._painterCameraEntity.camera.orthoHeight = exports.painterCameraFar;
}
_initEntities() {
const painterLayer = this._app.scene.layers.getLayerByName(exports.painterLayerName);
painterLayer.transparentSortMode = pc.SORTMODE_MANUAL;
this._painterEntity = new pc.Entity('TerrainBrushPainter');
this._painterEntity.addComponent('render', {
type: 'plane',
layers: [painterLayer.id],
material: this._painterMaterial,
castShadows: false,
castShadowsLightmap: false,
receiveShadows: false
});
this._painterInvertEntity = new pc.Entity('TerrainBrushPainterInvert');
this._painterInvertEntity.addComponent('render', {
type: 'plane',
layers: [painterLayer.id],
material: this._painterInvertMaterial,
castShadows: false,
castShadowsLightmap: false,
receiveShadows: false,
});
this._painterEntity.render.meshInstances[0].drawOrder = 1;
this._painterInvertEntity.render.meshInstances[0].drawOrder = 0;
this._app.root.addChild(this._painterInvertEntity);
this._app.root.addChild(this._painterEntity);
this._painterInvertEntity.setLocalEulerAngles(90, 0, 0);
this._painterEntity.setLocalEulerAngles(90, 0, 0);
this._painterInvertEntity.enabled = false;
this._painterEntity.enabled = false;
}
_initShaders() {
const vertex = ColorPainterShaders_mjs_1.vertexShader;
const fragment = (0, Shared_mjs_1.setPrecision)(this._app.graphicsDevice, ColorPainterShaders_mjs_1.fragmentShader);
const fragmentInvert = (0, Shared_mjs_1.setPrecision)(this._app.graphicsDevice, ColorPainterShaders_mjs_1.fragmentInvertShader);
this._painterShader = pc.createShaderFromCode(this._app.graphicsDevice, vertex, fragment, 'PainterFragmentShader', {
aPosition: pc.SEMANTIC_POSITION,
aUv0: pc.SEMANTIC_TEXCOORD0
});
this._painterInvertShader = pc.createShaderFromCode(this._app.graphicsDevice, vertex, fragmentInvert, 'PainterInvertFragmentShader', {
aPosition: pc.SEMANTIC_POSITION,
aUv0: pc.SEMANTIC_TEXCOORD0
});
}
_initMaterials() {
this._painterMaterial = new pc.Material();
this._painterMaterial.name = 'BrushPainterMaterial';
// @ts-ignore
this._painterMaterial.shader = this._painterShader;
this._painterMaterial.blendType = pc.BLEND_ADDITIVE;
this._painterMaterial.update();
this._painterInvertMaterial = new pc.Material();
this._painterInvertMaterial.name = 'BrushPainterInvertMaterial';
// @ts-ignore
this._painterInvertMaterial.shader = this._painterInvertShader;
this._painterInvertMaterial.blendType = pc.BLEND_SUBTRACTIVE;
this._painterInvertMaterial.update();
}
_updateRuntimeSettings(dt) {
const originalOpacity = this._brushSettings.opacity;
const opacity = originalOpacity;
this._painterMaterial.setParameter('uBrushOpacity', opacity);
this._painterInvertMaterial.setParameter('uBrushOpacity', opacity);
}
_updatePositionAndScale(x, y, scaleWidth, scaleHeight) {
const far = this.cameraFar * 2;
const ration = this.background.width / this.background.height;
x = x * far * ration - this.cameraFar * ration;
y = y * far - this.cameraFar;
scaleWidth = scaleWidth * this.background.width / far / 2.5;
scaleHeight = scaleHeight * this.background.height / far / 2.5;
this._setScale(scaleWidth, scaleHeight);
this._setPosition(x, y);
}
startPaint(dt, x, y, scaleWidth, scaleHeight) {
this._updateRuntimeSettings(dt);
this._updatePositionAndScale(x, y, scaleWidth, scaleHeight);
this._painting = true;
this._painterInvertEntity.enabled = true;
this._painterEntity.enabled = true;
this._painterCameraEntity.enabled = true;
}
stopPaint() {
this._painting = false;
this._painterInvertEntity.enabled = false;
this._painterEntity.enabled = false;
this._painterCameraEntity.enabled = false;
}
_setScale(x, y) {
this._painterEntity.setLocalScale(x, 1, y);
this._painterInvertEntity.setLocalScale(x, 1, y);
}
_setPosition(x, y) {
this._painterEntity.setLocalPosition(x, y, 0);
this._painterInvertEntity.setLocalPosition(x, y, 0);
}
updateSettings(brushSettings, activeLayer) {
this._painterMask.fill(0);
if (activeLayer > 0) {
this._painterMask[activeLayer - 1] = 1;
}
const brushTexture = brushSettings.textures[brushSettings.active].resource;
this._painterMaterial.setParameter('uBrushMask', this._painterMask);
this._painterMaterial.setParameter('uHeightMap', brushTexture);
this._painterInvertMaterial.setParameter('uBrushMask', this._painterMask);
this._painterInvertMaterial.setParameter('uHeightMap', brushTexture);
this._brushSettings = brushSettings;
}
}
exports.default = ColorPainter;
});
define("src/ScriptHelpers/EnumConverter", ["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isNumeric = isNumeric;
exports.mapEnum = mapEnum;
function isNumeric(value) {
return /^-?\d+$/.test(value);
}
function mapEnum(someEnum) {
const result = [];
for (let value in someEnum) {
if (!someEnum.hasOwnProperty(value)) {
continue;
}
const enumEntry = {};
enumEntry[value] = someEnum[value];
result.push(enumEntry);
}
return result;
}
});
define("src/ScriptHelpers/Enum", ["require", "exports", "src/ScriptHelpers/EnumConverter"], function (require, exports, EnumConverter_mjs_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.terrainHeightsCompressAlgoritm = exports.terrainHeightsCompressAlgoritmDefault = exports.terrainPatchSizeEnum = exports.terrainPatchSizeEnumDefault = exports.terrainSizeEnum = exports.terrainSizeEnumDefault = void 0;
exports.terrainSizeEnumDefault = 513;
exports.terrainSizeEnum = (0, EnumConverter_mjs_1.mapEnum)({
'128': 129,
'256': 257,
'512': 513,
'1024': 1025,
'2048': 2049,
'4096': 4097,
'8192': 8193,
'16384': 16385,
'32768': 32769,
});
exports.terrainPatchSizeEnumDefault = 33;
exports.terrainPatchSizeEnum = (0, EnumConverter_mjs_1.mapEnum)({
'16': 17,
'32': 33,
'64': 65,
'128': 129,
'256': 257,
'512': 513,
'1024': 1025,
});
exports.terrainHeightsCompressAlgoritmDefault = 'none';
exports.terrainHeightsCompressAlgoritm = (0, EnumConverter_mjs_1.mapEnum)({
'None': 'none',
'X2': 'x2',
'X4': 'x4'
});
});
define("src/Shared/Types", ["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
});
define("src/TerrainSystem/AbsHeightMapFileIO", ["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AbsHeightMapFileIO = exports.factorSize = exports.heightMapVersion = void 0;
exports.heightMapVersion = 99;
exports.factorSize = 3;
class AbsHeightMapFileIO {
__readHeightFactor(view, headerSize, width, x, z) {
const index = z * width + x;
const r = view.getUint8(headerSize + index * exports.factorSize + 0);
const g = view.getUint8(headerSize + index * exports.factorSize + 1);
const b = view.getUint8(headerSize + index * exports.factorSize + 2);
const scaled = (r << 16) | (g << 8) | b;
const factor = scaled / 16777215;
return factor;
}
__writeHeightFactor(view, headerSize, heightMap, x, z) {
const index = z * heightMap.width + x;
const factor = heightMap.getFactor(x, z);
const scaled = Math.floor(factor * 16777215);
const r = (scaled >> 16) & 0xFF;
const g = (scaled >> 8) & 0xFF;
const b = (scaled & 0xFF);
view.setUint8(headerSize + index * exports.factorSize + 0, r);
view.setUint8(headerSize + index * exports.factorSize + 1, g);
view.setUint8(headerSize + index * exports.factorSize + 2, b);
}
__importFromFile(heightMap, buffer, options) {
return __awaiter(this, void 0, void 0, function* () {
// TODO:
// header version 99
// headerByteSize, version, width, depth, minHeight, maxHeight
const view = new DataView(buffer);
const version = view.getUint32(1, true);
if (version !== exports.heightMapVersion) {
console.warn('Height map version: %f no support.', version);
return null;
}
const headerSize = view.getUint8(0);
const width = view.getUint32(5, true);
const depth = view.getUint32(9, true);
const minHeight = view.getFloat32(13, true);
const maxHeight = view.getFloat32(17, true);
const delta = (options === null || options === void 0 ? void 0 : options.adaptiveMinMaxHeight)
? heightMap.maxHeight - heightMap.minHeight
: maxHeight - minHeight;
const resultMinHeight = (options === null || options === void 0 ? void 0 : options.adaptiveMinMaxHeight) ? heightMap.minHeight : minHeight;
if (heightMap.width !== width ||
heightMap.depth !== depth &&
options &&
options.adaptiveWidthAndDepth) {
// TODO: its work for x^n + 1, z^n + 1
const factorX = (width - 1) / (heightMap.width - 1);
const factorZ = (depth - 1) / (heightMap.depth - 1);
for (let z = 0; z < depth; z += factorZ) {
for (let x = 0; x < width; x += factorX) {
// TODO: smooth for heightMap more import data
const factor = this.__readHeightFactor(view, headerSize, width, x | 0, z | 0);
const height = resultMinHeight + factor * delta;
heightMap.set(x / factorX, z / factorZ, height);
}
}
}
else {
for (let z = 0; (z < depth) && (z < heightMap.depth); z++) {
for (let x = 0; (x < width) && (x < heightMap.width); x++) {
const factor = this.__readHeightFactor(view, headerSize, width, x, z);
const height = resultMinHeight + factor * delta;
heightMap.set(x, z, height);
}
}
}
return {
width,
depth,
minHeight,
maxHeight
};
});
}
__exportToBuffer(heightMap) {
return __awaiter(this, void 0, void 0, function* () {
// TODO:
// header version 99
// headerByteSize, version, width, depth, minHeight, maxHeight
const headerSize = 1 + 4 + 4 + 4 + 4 + 4;
const buffer = new ArrayBuffer(headerSize + exports.factorSize * heightMap.width * heightMap.depth);
const view = new DataView(buffer);
view.setUint8(0, headerSize);
view.setUint32(1, exports.heightMapVersion, true);
view.setUint32(5, heightMap.width, true);
view.setUint32(9, heightMap.depth, true);
view.setFloat32(13, heightMap.minHeight, true);
view.setFloat32(17, heightMap.maxHeight, true);
for (let z = 0; z < heightMap.depth; z++) {
for (let x = 0; x < heightMap.width; x++) {
this.__writeHeightFactor(view, headerSize, heightMap, x, z);
}
}
return buffer;
});
}
}
exports.AbsHeightMapFileIO = AbsHeightMapFileIO;
exports.default = AbsHeightMapFileIO;
});
define("src/TerrainSystem/IZone", ["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
});
define("src/TerrainSystem/AbsHeightMap", ["require", "exports", "src/TerrainSystem/AbsHeightMapFileIO"], function (require, exports, AbsHeightMapFileIO_mjs_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AbsHeightMap = void 0;
AbsHeightMapFileIO_mjs_1 = __importDefault(AbsHeightMapFileIO_mjs_1);
class AbsHeightMap extends AbsHeightMapFileIO_mjs_1.default {
constructor() {
super(...arguments);
this.minX = 0;
this.minZ = 0;
}
get maxX() { return this.width; }
get maxZ() { return this.depth; }
getHeightInterpolated(x, z) {
const intX = x | 0;
const intZ = z | 0;
const x0z0 = this.get(intX, intZ);
if ((intX + 1 >= this.width) ||
(intZ + 1 >= this.depth)) {
return x0z0;
}
const x1z0 = this.get(intX + 1, intZ);
const x0z1 = this.get(intX, intZ + 1);
const x1z1 = this.get(intX + 1, intZ + 1);
const factorX = x - intX;
const interpolatedBottom = (x1z0 - x0z0) * factorX + x0z0;
const interpolatedTop = (x1z1 - x0z1) * factorX + x0z1;
const factorZ = z - intZ;
const finalHeight = (interpolatedTop - interpolatedBottom) * factorZ + interpolatedBottom;
return finalHeight;
}
substract(x, z, value) {
return this.append(x, z, -value);
}
divide(x, z, value, heightIfZero = 0) {
return this.multiply(x, z, 1 / value, heightIfZero);
}
fromFile(buffer, options) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.__importFromFile(this, buffer, options);
});
}
toFile() {
return __awaiter(this, void 0, void 0, function* () {
const buffer = yield this.__exportToBuffer(this);
return new Blob([buffer], { type: "application/octet-stream" });
});
}
toBuffer(buffer) {
const width = this.width;
const delta = this.maxHeight - this.minHeight;
for (let z = 0; z < this.depth; z++) {
for (let x = 0; x < this.width; x++) {
const h = this.get(x, z);
const v = (h - this.minHeight) / delta * 255;
const pos = (x + z * width) * 4;
buffer[pos] = v;
buffer[pos + 1] = v;
buffer[pos + 2] = v;
buffer[pos + 3] = 255;
}
}
}
toCanvas() {
const canvas = document.createElement('canvas');
const width = this.width;
const height = this.depth;
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error('Failed create canvas 2d context');
}
const imageData = ctx.getImageData(0, 0, width, height);
const buffer = imageData.data;
this.toBuffer(buffer);
ctx.putImageData(imageData, 0, 0);
return canvas;
}
/**
* Save height map to image of base64
*/
toImage(type, quality) {
const canvas = this.toCanvas();
return canvas.toDataURL(type, quality);
}
/**
* Load height map from image
* @param img
*/
fromImage(img) {
const bufferWidth = img.width;
const bufferHeight = img.height;
if (bufferWidth % 2 !== 0 || bufferHeight % 2 !== 0) {
throw new Error("Map sizes not divisible by 2 are not supported");
}
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
canvas.width = bufferWidth;
canvas.height = bufferHeight;
context.drawImage(img, 0, 0);
const imageData = context.getImageData(0, 0, bufferWidth, bufferHeight);
const imageBuffer = imageData.data;
const demMinMax = this.maxHeight - this.minHeight;
const maxSegmentX = this.width - 1;
const maxSegmentZ = this.depth - 1;
const factorX = bufferWidth / maxSegmentX;
const factorZ = bufferHeight / maxSegmentZ;
for (let z = 0; z < this.depth; z++) {
for (let x = 0; x < this.width; x++) {
let normalizeX = x === maxSegmentX ? x - 1 : x;
let normalizeZ = z === maxSegmentZ ? z - 1 : z;
const heightMapX = (normalizeX * factorX) | 0;
const heightMapZ = (normalizeZ * factorZ) | 0;
const pos = (heightMapX + heightMapZ * bufferWidth) * 4;
const r = imageBuffer[pos];
const g = imageBuffer[pos + 1];
const b = imageBuffer[pos + 2];
const a = imageBuffer[pos + 3];
const coeff = (r + g + b) / 3 / a;
const height = this.minHeight + demMinMax * coeff;
this.set(x, z, height);
}
}
}
smoothZone(zone, np, radius) {
if (zone.maxX < 0)
return;
if (zone.maxZ < 0)
return;
if (np < 0 || np > 1)
return;
if (radius === 0)
radius = 1;
const minX = Math.max(zone.minX, 0);
const minZ = Math.max(zone.minZ, 0);
const maxX = Math.min(zone.maxX, this.width);
const maxZ = Math.min(zone.maxZ, this.depth);
const cp = 1 - np;
for (let x = minX; x < maxX; x++) {
for (let z = minZ; z < maxZ; z++) {
const prevHeight = this.get(x, z);
let updtHeight;
let neighNumber = 0;
let neighAverage = 0;
for (let rx = -radius; rx <= radius; rx++) {
for (let rz = -radius; rz <= radius; rz++) {
const innerX = (x + rx);
const innerZ = (z + rz);
if (innerX < 0 || innerX >= this.width)
continue;
if (innerZ < 0 || innerZ >= this.depth)
continue;
const height = (innerX === x && innerZ === z)
? prevHeight
: this.get(innerX, innerZ);
neighNumber++;
neighAverage += height;
}
}
neighAverage /= neighNumber;
updtHeight = neighAverage * np + prevHeight * cp;
this.set(x, z, updtHeight);
}
}
}
smooth(np, radius) {
this.smoothZone(this, np, radius);
}
normalize(minHeight, maxHeight) {
if (minHeight > maxHeight) {
return;
}
const minMaxDelta = this.maxHeight - this.minHeight;
const minMaxRange = maxHeight - minHeight;
for (let z = 0; z < this.depth; z++) {
for (let x = 0; x < this.width; x++) {
const currentHeight = this.get(x, z);
const normalizeHeight = ((currentHeight - minHeight) / minMaxDelta) * minMaxRange + maxHeight;
this.set(x, z, normalizeHeight);
}
}
}
combineHeights(type, heightMap, value, zone, heightIfZero = 0, minHeight = null, maxHeight = null) {
if (zone.maxX < 0)
return;
if (zone.maxZ < 0)
return;
const lenX = zone.maxX - zone.minX;
const lenZ = zone.maxZ - zone.minZ;
if (lenX < 1 || lenZ < 1 || value === 0) {
return;
}
const fixedMinX = Math.max(zone.minX, 0);
const fixedMinZ = Math.max(zone.minZ, 0);
const fixedMaxX = Math.min(zone.maxX, this.width);
const fixedMaxZ = Math.min(zone.maxZ, this.depth);
const coeffFactorX = (heightMap.width - 1) / lenX;
const coeffFactorZ = (heightMap.depth - 1) / lenZ;
for (let z = fixedMinZ; z < fixedMaxZ; z++) {
for (let x = fixedMinX; x < fixedMaxX; x++) {
const x2 = (coeffFactorX * (x - zone.minX)) | 0;
const z2 = (coeffFactorZ * (z - zone.minZ)) | 0;
const height = heightMap.get(x2, z2);
const smoothAppendValue = height * value;
const oldHeight = this.get(x, z) || heightIfZero;
let candidate = type === '+' ? oldHeight + smoothAppendValue :
type === '-' ? oldHeight - smoothAppendValue :
type === '*' ? oldHeight * smoothAppendValue :
type === '/' ? oldHeight / smoothAppendValue :
oldHeight;
if (minHeight !== null && candidate < minHeight) {
candidate = minHeight;
}
if (maxHeight !== null && candidate > maxHeight) {
candidate = maxHeight;
}
this.set(x, z, candidate);
}
}
}
}
exports.AbsHeightMap = AbsHeightMap;
exports.default = AbsHeightMap;
});
define("src/TerrainSystem/CoordsBuffer", ["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CoordsBuffer = exports.coordsVertexSize = void 0;
exports.coordsVertexSize = 2;
class CoordsBuffer {
get patchVertexBufferLength() { return this._length; }
get patchVertexBufferData() { return this._data; }
get patchVertexBufferTyped() { return this._dataTyped; }
get width() { return this._width; }
get depth() { return this._depth; }
get patchSize() { return this._patchSize; }
constructor(heightMap, patchSize) {
this.heightMap = heightMap;
// We can use uint8 for patches smaller than 255, but we only use 2 bytes,
// for optimal performance need 4 bytes for the buffer.
this._patchSize = patchSize;
this._width = heightMap.width;
this._depth = heightMap.depth;
this._length = this._patchSize * this._patchSize;
const coordsArrLength = this._length * exports.coordsVertexSize;
const coordsByteLength = coordsArrLength * Uint16Array.BYTES_PER_ELEMENT;
this._data = new ArrayBuffer(coordsByteLength);
this._dataTyped = new Uint16Array(this._data, 0, coordsArrLength);
}
init() {
let index = 0;
for (let z = 0; z < this._patchSize; z++) {
for (let x = 0; x < this._patchSize; x++) {
this._dataTyped[index++] = x;
this._dataTyped[index++] = z;
}
}
}
getPosition(index, buf) {
const x = index % this._width | 0;
const z = index / this._width | 0;
buf.x = x;
buf.y = this.heightMap.get(x, z);
buf.z = z;
return true;
}
getPositionWithHeightByFactor(index, buf) {
const x = index % this._width | 0;
const z = index / this._width | 0;
buf.x = x;
buf.y = this.heightMap.getFactor(x, z);
buf.z = z;
return true;
}
getCoords(index, buf) {
const x = index % this._width | 0;
const z = index / this._width | 0;
buf.x = x;
buf.z = z;
return true;
}
}
exports.CoordsBuffer = CoordsBuffer;
exports.default = CoordsBuffer;
});
define("src/TerrainSystem/HeightMap", ["require", "exports", "src/TerrainSystem/AbsHeightMap"], function (require, exports, AbsHeightMap_mjs_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HeightMap = exports.defaultHeightVertexSize = exports.HeightMapArrType = void 0;
AbsHeightMap_mjs_1 = __importDefault(AbsHeightMap_mjs_1);
exports.HeightMapArrType = Float32Array;
exports.defaultHeightVertexSize = 1;
class HeightMap extends AbsHeightMap_mjs_1.default {
get size() { return this._width * this._depth; }
get width() { return this._width; }
get depth() { return this._depth; }
get data() { return this._data; }
get itemSize() { return this._itemSize; }
get itemHeightIndexOffset() { return this._itemHeightIndexOffset; }
get minHeight() { return this._minHeight; }
get maxHeight() { return this._maxHeight; }
constructor(width, depth, minHeight, maxHeight, buffer, itemSize = exports.defaultHeightVertexSize, itemHeightIndexOffset = 0) {
super();
this._width = 0;
this._depth = 0;
this._minHeight = 0;
this._maxHeight = 0;
this._init(width, depth, minHeight, maxHeight, buffer, itemSize, itemHeightIndexOffset);
}
_init(width, depth, minHeight, maxHeight, buffer, itemSize = exports.defaultHeightVertexSize, itemHeightIndexOffset = 0) {
this._width = width;
this._depth = depth;
this._maxHeight = minHeight;
this._maxHeight = maxHeight;
if (buffer) {
if (itemSize < itemHeightIndexOffset) {
throw new Error("ItemSize can't less or eq ItemHeightIndexOffset");
}
if (buffer.length < (width * depth) * itemSize) {
throw new Error("Buffer has invalid length");
}
this._data = buffer;
this._itemSize = itemSize;
this._itemHeightIndexOffset = itemHeightIndexOffset;
}
else {
// TODO: type checker
this._data = new exports.HeightMapArrType(width * depth * exports.defaultHeightVertexSize);
this._itemSize = exports.defaultHeightVertexSize;
this._itemHeightIndexOffset = 0;
}
}
_encodeHeightFactor(store, index, value) {
store[index] = value;
}
_decodeHeightFactor(store, index) {
return store[index];
}
_decodeHeight(store, index, min, max) {
return this._decodeHeightFactor(store, index) * (max - min) + min;
}
_encodeAndSetHeightFactor(store, index, realHeight, min, max) {
const normalize = Math.max(Math.min(realHeight, max), min);
const factor = (normalize - min) / (max - min);
this._encodeHeightFactor(store, index, factor);
return this._decodeHeightFactor(store, index);
}
getIndex(x, z) {
return (z * this._width + x) * this._itemSize + this._itemHeightIndexOffset;
}
getFactor(x, z) {
const index = this.getIndex(x, z);
return this._decodeHeightFactor(this._data, index);
}
get(x, z) {
const index = this.getIndex(x, z);
return this._decodeHeight(this._data, index, this._minHeight, this._maxHeight);
}
set(x, z, value) {
const index = this.getIndex(x, z);
return this._encodeAndSetHeightFactor(this._data, index, value, this._minHeight, this._maxHeight);
}
setMinMaxHeight(minHeight, maxHeight) {
if (this._minHeight > this._maxHeight) {
return;
}
this._minHeight = minHeight;
this._maxHeight = maxHeight;
}
append(x, z, value) {
const index = this.getIndex(x, z);
const oldValue = this._decodeHeight(this._data, index, this._minHeight, this._maxHeight);
const canValue = oldValue + value;
return this._encodeAndSetHeightFactor(this._data, index, canValue, this._minHeight, this._maxHeight);
}
multiply(x, z, value, heightIfZero = 0) {
const index = this.getIndex(x, z);
const oldValue = this._decodeHeight(this._data, index, this._minHeight, this._maxHeight) || heightIfZero;
const canValue = oldValue * value;
return this._encodeAndSetHeightFactor(this._data, index, canValue, this._minHeight, this._maxHeight);
}
}
exports.HeightMap = HeightMap;
exports.default = HeightMap;
});
define("src/TerrainSystem/AbsPatchedHeightMap", ["require", "exports", "src/TerrainSystem/HeightMap"], function (require, exports, HeightMap_mjs_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AbsPatchedHeightMap = exports.minMaxStackSize = void 0;
exports.getOrThrowDataChunkSize = getOrThrowDataChunkSize;
HeightMap_mjs_1 = __importStar(HeightMap_mjs_1);
exports.minMaxStackSize = 2;
function getOrThrowDataChunkSize(patchSize, dataChunkSize) {
if ((dataChunkSize - 1) % (patchSize - 1) !== 0) {
const recommendedWidth = ((dataChunkSize - 1 + patchSize - 1) / (dataChunkSize - 1)) * (patchSize - 1) + 1;
console.error("DataChunkSize minus 1 (%d) must be divisible by patchSize minus 1 (%d)\n", dataChunkSize, patchSize);
console.error("Try using DataChunkSize = %d\n", recommendedWidth);
throw new Error();
}
return dataChunkSize;
}
class AbsPatchedHeightMap extends HeightMap_mjs_1.default {
get patchSize() { return this._patchSize; }
get numPatchesX() { return this._numPatchesX; }
get numPatchesZ() { return this._numPatchesZ; }
get dataChunkSize() { return this._dataChunkSize; }
get dataNumChunksX() { return this._dataNumChunksX; }
get dataNumChunksZ() { return this._dataNumChunksZ; }
get dataChunkSizeFactor() { return this._dataChunkSizeFactor; }
constructor(width, depth, patchSize, dataChunkSize, minHeight, maxHeight, buffer, itemSize = HeightMap_mjs_1.defaultHeightVertexSize, itemHeightIndexOffset = 0) {
super(width, depth, minHeight, maxHeight, buffer /** TS huck */, itemSize, itemHeightIndexOffset);
this._minHeightCoord = [0, 0];
this._maxHeightCoord = [0, 0];
this._setPatchSize(patchSize);
this._setDataChunkSize(dataChunkSize);
this._clearMinMaxHeightCoords();
}
_setPatchSize(patchSize) {
this._patchSize = patchSize;
this._numPatchesX = ((this.width - 1) / (this._patchSize - 1)) | 0;
this._numPatchesZ = ((this.depth - 1) / (this._patchSize - 1)) | 0;
this._patchesSegmentSize = this._numPatchesX * this._numPatchesZ * exports.minMaxStackSize;
this._minMaxHeightCoords = new Array(this._patchesSegmentSize * 2);
}
_setDataChunkSize(value) {
this._dataChunkSize = getOrThrowDataChunkSize(this._patchSize, value);