-
Notifications
You must be signed in to change notification settings - Fork 0
/
EnvironmentGenerator.js
1924 lines (1713 loc) · 80.5 KB
/
EnvironmentGenerator.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
var events = require('events');
var util = require('util');
var Math3D = require('Math3D.js');
var SimplexNoise = require('simplex-noise.js');
var EnvironmentGenerator = module.exports = function(dbClient) {
this.storyGenerator = null;
this.seed = new Date().getTime();
this.simplex = new SimplexNoise();
this.elasticClient = dbClient;
this.requestQueue = [];
this.inQueue = false;
this.waitingToGenerate = [];
this.cachedResponse = null;
this.fertSeed = this.seed + 9;
this.tempSeed = this.seed + 5;
this.civSeed = this.seed - 23;
this.colourSeed = parseInt(this.seed/2);
this.palettes = [];
this.Math3D = new Math3D();
/* Generate Initial JSON chunks ( 500 x 500)
1. Define glyph biomes - for now just divide along x, y axis - TODO - randomize
- Central area is just defined by a distance
*/
// TODO: Find a way to do this asynchronously, as the client is kept waiting on first load
// for awhile for 100 chunks to generate
this.GeneratedWorld = []; // terrain
this.GeneratedObjects = []; // stored for grid pos
this.GeneratedObjectsByID = [];
this.NewObjects = [];
this.lastObjID = 0;
this.cancelQueue = false;
this.glyphBiomes = {};
this.gameStart = false;
//this.generateForPosition({x:0, y:0}, []);
console.log("Environment Generator Initialized");
this.playerPosition = {
x:0,
y:0,
};
};
util.inherits(EnvironmentGenerator, events.EventEmitter);
//EnvironmentGenerator.prototype = new events.EventEmitter();
EnvironmentGenerator.prototype.initialize = function(storyGenerator) {
var self = this;
this.storyGenerator = storyGenerator;
// Add any relevant event listeners
var promise = new Promise(function(resolve, reject) {
// Select palettes from DB and categorize
var msg = {
index: "anotherend-palettes",
body: {
//this time we define a query in the body
from: 0,
size: 100
}
};
self.elasticClient.search(msg).then(
function(response) {
// go through returned palettes
var glyphPalettes = {};
for (var i = 0; i < response.hits.hits.length; i++) {
var p = response.hits.hits[i]._source;
if (p.glyph === "") {
self.palettes[p.slice] = p;
} else {
glyphPalettes[p.glyph] = p;
}
}
resolve({glyphPalettes: glyphPalettes});
}, function(error) {
reject(error);
});
});
return promise;
};
EnvironmentGenerator.prototype.disconnect = function() {
// cancel any queues
this.cancelQueue = true;
// remove any event listeners here
};
EnvironmentGenerator.prototype.addObjectToGenerator = function(gridPos, obj) {
this.GeneratedObjects[gridPos.x][gridPos.y].push(obj);
this.GeneratedObjectsByID[obj.id] = obj;
};
/*
=============== Events from Socket ================
*/
EnvironmentGenerator.prototype.playerMoved = function(newX, newY) {
//console.log("Player Position update to: " + newX + ", " + newY);
this.generateForPosition({x: newX, y: newY});
this.playerPosition.x = newX;
this.playerPosition.y = newY;
};
EnvironmentGenerator.prototype.getTerrainJSON = function(pos, level) {
return this.GeneratedWorld[pos.x][pos.y].terrain[level];
};
EnvironmentGenerator.prototype.getObjectJSON = function(pos, level) {
// This function returns object JSON for a client request. If the objects are not generated,
// the request is added to the queue and will be pushed as soon as it is done.
var self = this;
// FallBack - if not generated yet, add a listener which will send it when it's ready
if (this.GeneratedObjects[pos.x][pos.y].length === 0) {
//console.log("Adding objects to queue for gridPos: [" + pos.x + "," + pos.y + "]");
this.waitingToGenerate.push({pos: pos, level: level});
return false;
}
//console.log("Returning : " + this.GeneratedObjects[pos.x][pos.y].length + " objects for gridPos: [" + pos.x + "," + pos.y + "]");
return this.GeneratedObjects[pos.x][pos.y];
};
EnvironmentGenerator.prototype.checkListeners = function(evt) {
//console.log("Checking object Listeners - evt has " + evt.targets.length + " targets.");
var eventLog = [];
for (var t=0; t < evt.targets.length; t++) {
//console.log("Checking target with id: " + evt.targets[t].id);
var objToCheck = evt.targets[t].id;
var obj = this.GeneratedObjectsByID[objToCheck];
if (!obj.hasOwnProperty("listeners")) {
continue;
}
for (var l=0; l < obj.listeners.length; l++) {
// If power enum matches listener, fire event to story generator
//console.log("Object has a listener for action: " + obj.listeners[l].listener.actionID + " for node: " + obj.listeners[l].nodeID);
if (obj.listeners[l].listener.actionID === "any" || evt.power === obj.listeners[l].listener.actionID) {
eventLog.push({
type: ((obj.type === "Religious" || obj.type === "Human") ? "Ruin" : obj.type),
nodeID: obj.listeners[l].nodeID,
listenerID: obj.listeners[l].listener.id
});
}
}
}
return eventLog;
};
EnvironmentGenerator.prototype.updateObjectState = function(objID, newState) {
var obj = this.GeneratedObjectsByID[objID];
if (obj == undefined) {
console.log("ERROR (UpdateObjectState): Object with id: " + objID + " not found on the server.");
return;
}
obj.state = newState;
//This may not be the right place for this logic....
if (obj.hasOwnProperty("listeners") && obj.listeners.length > 0) {
for (var l=0; l < obj.listeners.length; l++) {
// expire nodes that can no longer have listeners be completed
if (obj.listeners[l].listener.subject.state != null && obj.listeners[l].listener.subject.state != newState) {
this.emit("expireNode", obj.listeners[l].nodeID);
}
}
}
};
EnvironmentGenerator.prototype.voidObject = function(objID) {
// If the object has a listener / node attached, send a flag to expire that node
var obj = this.GeneratedObjectsByID[objID];
if (obj === undefined) {
console.log("ERROR (voidObject): Object with id: " + objID + " not found on the server.");
return;
}
if (obj.hasOwnProperty("listeners") && obj.listeners.length > 0) {
for (var l=0; l < obj.listeners.length; l++) {
this.emit("expireNode", obj.listeners[l].nodeID);
}
}
// delete the object
obj = null;
};
EnvironmentGenerator.prototype.updateObjectScale = function(objID, newScale) {
var obj = this.GeneratedObjectsByID[objID];
if (!obj || !obj.hasOwnProperty("scale")) {
console.log("Cannot update scale on object: " + objID + ", type: " + obj.type);
return;
}
obj.scale.x = newScale;
obj.scale.y = newScale;
obj.scale.z = newScale;
};
EnvironmentGenerator.prototype.updateObjectPosition = function(objID, newPos) {
var obj = this.GeneratedObjectsByID[objID];
obj.position.x = newPos.x;
obj.position.z = newPos.z;
};
EnvironmentGenerator.prototype.duplicateObject = function(objID, newPos, tempID) {
// get gridPos for new position
var gridPos = {x: parseInt(newPos.x / 50), y: parseInt(newPos.z / 50)},
objToCopy = this.GeneratedObjectsByID[objID];
if (objToCopy === undefined) {
console.log("ERROR (duplicateObject): Object with id: " + objID + " not found on the server.");
return;
}
// copy object
var newObj = {
id: this.lastObjID,
name: "DuplicatedObject", // todo - to change?
position: {x:newPos.x , y:0, z:newPos.z },
scale: objToCopy.scale,
alignToTerrainHeight: true,
alignToTerrainNormal: objToCopy.alignToTerrainNormal,
listeners: [],
pieces: objToCopy.pieces,
type: objToCopy.type
};
// add to gridPos / generatedObjectsByID
this.addObjectToGenerator(gridPos, newObj);
this.lastObjID ++;
this.emit("newID", {oldID: tempID, newID: newObj.id});
};
EnvironmentGenerator.prototype.morphObjects = function(targets) {
// array of objects - query db once and assign random responses to each target
var msg = {
index: "anotherend-objects",
body: {
from: 0,
size: 500,
query:{
bool: {
must: [{match: {BaseObject : true}}]
}
}
}
};
var self = this
var newObjs = [];
self.elasticClient.search(msg).then(
function( response )
{
for (var i=0; i < targets.length; i++) {
var oldObj = self.GeneratedObjectsByID[targets[i].id];
if (oldObj === undefined) {
console.log("ERROR (morphObjects): Object with id " + targets[i].id + " was not found on the server.");
return;
}
var objects = {
id: targets[i].id,
name: "MorphedObject", // todo - to change?
position: {x:oldObj.position.x, y:0, z:oldObj.position.z},
scale: {},
rotation: {x:0, y:Math.random()*Math.PI*2, z:0},
alignToTerrainHeight: true,
alignToTerrainNormal: false,
listeners: [],
pieces: []
};
if (oldObj.hasOwnProperty("collider"))
objects.collider = oldObj.collider;
self.createObjectFromResponse(response, objects).then(
function(objResponse) {
newObjs.push(objResponse.objects);
if (newObjs.length === targets.length) {
for (var o=0; i < newObjs.length; o++) {
var gridPos = {x: Math.floor(newObjs[o].position.x / 50), y: Math.floor(newObjs[o].position.z / 50)};
// add object to generatedObjects
if (typeof(self.GeneratedObjects[gridPos.x]) == 'undefined') {
self.GeneratedObjects[gridPos.x] = [];
}
if (typeof(self.GeneratedObjects[gridPos.x][gridPos.y]) == 'undefined') {
self.GeneratedObjects[gridPos.x][gridPos.y] = [];
}
self.addObjectToGenerator(gridPos, newObjs[o]);
}
self.emit("objectUpdate", newObjs);
}
resolve(objResponse);
}, function(error) {
console.log("Morph object DB FAILURE");
console.log(error);
});
}
},
function(error)
{
reject(JSON.stringify(error));
}
);
};
/*
================ Initial Generation =============
*/
EnvironmentGenerator.prototype.generateInitialWorld = function(glyphPalettes) {
console.log("Generating Initial World....");
var self = this;
this.emit("loadingStateUpdate", {message: "Placing Towers..."});
// Start by randomly placing the towers at a distance of 600-1000, and roughly in the 4 cardinal directions.
// For now, we will make that tower appear at the center of its gridsquare, and there will be no other objects
var towers = [],
skies = [];
var entityBiome = {
x: (Math.random()*100 + 275) * ((Math.random() > 0.5) ? 1 : -1),
z: (Math.random()*100 + 275) * ((Math.random() > 0.5) ? 1 : -1)
};
var EntityTower = {
id: this.lastObjID,
name:"entity_tower",
alignToTerrainHeight: false,
alignToTerrainNormal: false,
alwaysActive: true,
position: {x: entityBiome.x, y: 0, z: entityBiome.z},
pieces: [
{
url: {0: "assets/towers/entity_tower.js" },
color1: glyphPalettes["entity"].tower[0],
color2: glyphPalettes["entity"].tower[1]
}
],
collider : {
type: 2,
radius: 100,
url: "assets/towers/entity_collision.js"
},
type: "GlyphTower"
};
this.lastObjID ++;
var EntityPillar = {
id: this.lastObjID,
name:"entity_pillar",
alignToTerrainHeight: false,
alignToTerrainNormal: false,
alwaysActive: true,
position: {x: entityBiome.x, y: 0, z: entityBiome.z},
pieces: [
{
url: {0: "assets/towers/entity_pillar.js" },
color1: glyphPalettes["entity"].tower[0],
color2: glyphPalettes["entity"].tower[1]
}
],
type: "GlyphPillar"
};
this.lastObjID ++;
var EntityGlyph = {
id: this.lastObjID,
name:"entity_glyph",
alignToTerrainHeight: false,
alignToTerrainNormal: false,
alwaysActive: true,
position: {x: entityBiome.x, y: 40, z: entityBiome.z},
pieces: [
{
url: {0: "assets/glyphs/entity_glyph.js" },
color1: glyphPalettes["entity"].essence,
color2: [ 0.371, 0.371, 0.371]
}
],
type: "Glyph"
};
this.lastObjID ++;
this.GeneratedObjects[0] = [];
this.GeneratedObjects[0][-1] = [EntityTower, EntityPillar, EntityGlyph];
this.GeneratedObjectsByID[EntityTower.id] = EntityTower;
this.GeneratedObjectsByID[EntityPillar.id] = EntityPillar;
this.GeneratedObjectsByID[EntityGlyph.id] = EntityGlyph;
towers.push(EntityTower);
towers.push(EntityPillar);
towers.push(EntityGlyph);
var radius = Math.random()*100 + 300;
this.glyphBiomes["entity"] = {
x: entityBiome.x,
y: 37,
z: entityBiome.z,
radius: radius,
palette: glyphPalettes["entity"]
};
//entity sky
var randEntity = Math.floor(Math.random()*glyphPalettes["entity"].skies.length);
var sky = glyphPalettes["entity"].skies[randEntity];
sky.position = EntityTower.position;
sky.radius = radius;
skies.push(sky);
// default sky
glyphPalettes["entity"].skies.splice(randEntity, 1);
randEntity = Math.floor(Math.random()*glyphPalettes["entity"].skies.length);
sky = glyphPalettes["entity"].skies[randEntity];
sky.position = null;
sky.radius = 300;
skies.push(sky);
var towerNames = {"destroyer": 9, "illusionist": 8, "protector": 6, "architect": 6};
for (var glyphName in towerNames) {
// find an acceptable distance that is >600m from any other tower
var towerPos = {x: 0, y: 0};
var foundSpot = false,
attempts =0;
placementLoop:
while(foundSpot === false) {
attempts ++;
if (attempts > 50) { // If I get this, I need to rethink the algorithm
console.log("Tower not placed.. no suitable location found");
break;
}
towerPos.x = (Math.round(Math.random()*300) + 550) * ((Math.random() < 0.5) ? 1 : -1) + entityBiome.x;
towerPos.y = (Math.round(Math.random()*300) + 550) * ((Math.random() < 0.5) ? 1 : -1) + entityBiome.z;
var spotFound = true;
for (var t=0; t < towers.length; t++) {
var dist = distance(towerPos.x, towerPos.y, towers[t].position.x, towers[t].position.z);
//console.log("Distance: " + dist);
if (dist < 700 || distance(towerPos.x, towerPos.y, 0,0) < 450) {
//console.log("failed attempt to place tower");
spotfound = false;
continue placementLoop;
}
}
foundSpot = true;
}
var rotation = {x: 0, y: Math.random()*Math.PI*2, z: 0};
var y = (glyphName === "destroyer") ? 8.5 : 0;
var tower = {
id: this.lastObjID,
name: glyphName + "_tower",
alignToTerrainHeight: false,
alignToTerrainNormal: false,
alwaysActive: true,
position: {x: towerPos.x, y: 0, z: towerPos.y},
rotation: rotation,
pieces: [
{
url: {0: "assets/towers/" + glyphName + "_tower.js"},
color1: glyphPalettes[glyphName].tower[0],
color2: glyphPalettes[glyphName].tower[1]
}
],
collider : {
type: 2,
radius: 100,
url: "assets/towers/" + glyphName + "_tower_collision.js"
},
type: "GlyphTower"
};
towers.push(tower);
this.lastObjID ++;
var pillar = {
id: this.lastObjID,
name: glyphName + "_pillar",
alignToTerrainHeight: false,
alignToTerrainNormal: false,
alwaysActive: true,
position: {x: towerPos.x, y: 0, z: towerPos.y},
rotation: rotation,
pieces: [
{
url: {0: "assets/towers/" + glyphName + "_pillar.js"},
color1: glyphPalettes[glyphName].tower[0],
color2: glyphPalettes[glyphName].tower[1]
}
],
type: "GlyphPillar"
};
towers.push(pillar);
this.lastObjID ++;
var glyph = {
id: this.lastObjID,
name: glyphName + "_glyph",
alignToTerrainHeight: false,
alignToTerrainNormal: false,
alwaysActive: true,
position: {x: towerPos.x, y: towerNames[glyphName], z: towerPos.y},
rotation: rotation,
pieces: [
{
url: {0: "assets/glyphs/" + glyphName + "_glyph.js"},
color1: glyphPalettes[glyphName].essence,
color2: [ 1, 1, 1]
}
],
type: "Glyph"
};
towers.push(glyph);
this.lastObjID ++;
// find gridsquare and set value
var gridSquare = {x: Math.ceil(towerPos.x/50), y: Math.ceil(towerPos.y/50)};
console.log("Tower placed after " + attempts + " attempts at [" + towerPos.x + ", " + towerPos.y + "], gridSquare: [" + gridSquare.x + ", " + gridSquare.y + "]");
this.GeneratedObjects[gridSquare.x] = [];
this.GeneratedObjects[gridSquare.x][gridSquare.y] = [tower, pillar, glyph];
this.GeneratedObjectsByID[tower.id] = tower;
this.GeneratedObjectsByID[pillar.id] = pillar;
this.GeneratedObjectsByID[glyph.id] = glyph;
var biomeRadius = Math.random()*100 + 400;
this.glyphBiomes[glyphName] = {
x: towerPos.x,
y: y,
z: towerPos.y,
radius: biomeRadius,
palette: glyphPalettes[glyphName]
};
var randSky = Math.floor(Math.random()*glyphPalettes[glyphName].skies.length);
sky = glyphPalettes[glyphName].skies[randSky];
sky.position = tower.position;
sky.radius = biomeRadius;
skies.push(sky);
}
this.generateForPosition({x:0, y:0}).then(
function(response) {
console.log("Done Generating Initial world");
self.emit("initialGenerationFinished", { objects: towers, skies: skies});
}, function(error) {
});
};
/*
=============== Terrain Algorithm ===============
*/
EnvironmentGenerator.prototype.generateTerrainJSON = function(gridPos, level) {
// chunks are 50 metres square
// Input: The grid position of the chunk being generated, and the world seed for the current session
// Output: a JSON String containing the terrain mesh JSON for the chunk
//console.log("Generating chunk at grid x: " + gridPos.x + ", y: " + gridPos.y + " at level: " + level);
var JSONobj = {};
JSONobj.metadata = {};
JSONobj.scale = 1;
JSONobj.materials = [ {
"DbgColor" : 15658734,
"DbgIndex" : 0,
"DbgName" : "default",
"vertexColors" : true
}];
JSONobj.vertices = [];
JSONobj.faces = [];
JSONobj.normals = [];
JSONobj.colors = [];
JSONobj.uvs = [[]];
var xstart = gridPos.x * 50;
var ystart = gridPos.y * 50;
// determine density of polygon stepping here
// N.B. Stepping needs to be evenly divisble by 50 to make sure chunks line up
var step;
switch (level) {
case 0:
step = 10;
break;
case 1:
step = 5;
break;
}
// vertices
for (var y = ystart; y < 51 + ystart; y+= step) {
//var array = (vtx.vtxs[y] !== undefined) ? vtx.vtxs[y] : [];
for (var x = xstart; x < 51 + xstart; x+= step) {
var normx = x/51, // normalize to the chunk size
normy = y/51,
value = null;
//add noise to the vertex position
var noiseX = 0, noiseY = 0, noiseZ = 0;
//low poly terrain gets no variance
if( level >= 1 )
{
var posVariance = (level < 1) ? 0 : 5;
var heightVariance = 1;
noiseX = map_range(this.simplex.noise3D( 3*normx, 3*normy, this.seed + 05 ), 0, 1, -posVariance, posVariance);
//remove height noise to make the terrain smoother in the game
noiseY = 0;//map_range(this.simplex.noise3D( 3*normx, 3*normy, this.seed + 10 ), 0, 1, -heightVariance, heightVariance);
noiseZ = map_range(this.simplex.noise3D( 3*normx, 3*normy, this.seed + 15 ), 0, 1, -posVariance, posVariance);
//move based on normal
var normal = this.getTerrainNormal(x + noiseX, y + noiseZ);
var nsAmount = this.simplex.noise3D( 100*normx, 100*normy, this.seed + 08 )*2 - 1;
noiseX += -normal.x * nsAmount;
noiseY += -normal.y * nsAmount;
noiseZ += -normal.z * nsAmount;
}
//First check if we are near enough to a tower that we need to override the noise map
var glyphBiome = null;
for (var i in this.glyphBiomes) {
var distToTower = distance(x + noiseX, y + noiseZ, this.glyphBiomes[i].x, this.glyphBiomes[i].z)
if (distToTower < 150) {
glyphBiome = i;
// if distance < 75, completely flat. If 75 - 150, gradient between flat and natural
if (distToTower < 75) {
value = 0;
} else {
// proportional average between 0 and noise height
var val1 = 0,
val2 = this.getNoiseHeight(normx + noiseX/51, normy + noiseZ/51);
var proportion = map_range(distToTower, 75, 150, 1, 0);
value = (val1*proportion) + (val2*(1-proportion));
}
break;
}
}
// now check if we are near the start - same thing
if (Math.abs(x + noiseX) < 101 && Math.abs(y + noiseZ) < 101) {
var distToOrigin = distance(x + noiseX, y + noiseZ, 0, 0);
if (distToOrigin < 100) {
// if distance < 30, completely flat. If 30-100, gradient between flat and natural
if (distToOrigin < 30) {
value = 0;
} else {
// proportional average between 0 and noise height
var val1 = 0,
val2 = this.getNoiseHeight(normx + noiseX/51, normy + noiseZ/51);
var proportion = map_range(distToOrigin, 30, 100, 1, 0);
value = (val1*proportion) + (val2*(1-proportion));
}
}
}
if (value === null) {
value = this.getNoiseHeight(normx + noiseX/51, normy + noiseZ/51);
}
// Push to String
JSONobj.vertices.push(x - xstart + noiseX);
JSONobj.vertices.push(value + noiseY);
JSONobj.vertices.push(y - ystart + noiseZ);
}
//vtx.vtxs.push(array);
}
// faces
var faceStep = Math.ceil(51/step);
var colorsIndex = 0;
var colors = (level >= 1) ? 'all' : 'average';
var colorAverage = [ 0, 0, 0 ];
var faceCount = 0;
for (var y=0; y < (faceStep - 1) * faceStep; y+= faceStep) {
for (var x=0; x < faceStep - 1; x ++) {
// determine where the face is in the world and colour appropriately
var xcoord = JSONobj.vertices[(x+y)*3] + xstart;//xstart + x;
var ycoord = JSONobj.vertices[(x+y)*3 + 2] + ystart;//ystart + y;
// Get colour for face
// First, define saturation based on temperature = 0 = 0, 1 = 100
var saturation = this.simplex.noise3D( 0.003*xcoord, 0.003*ycoord, this.tempSeed);
// For secondary blending
var fertilityBlend = this.simplex.noise3D( 0.003*xcoord, 0.003*ycoord, this.fertSeed),
civBlend = this.simplex.noise3D( 0.003*xcoord, 0.003*ycoord, this.civSeed);
var colorFace = null; // the final colour
// First check if within a glyph biome
var glyphBiome = this.getGlyphBiome({x:xcoord, y:ycoord});
if (glyphBiome != null) {
var palette,
colorBlend;
palette = this.glyphBiomes[glyphBiome].palette;
var col1Default = HSVtoRGB(palette.default[0]/360,palette.default[1]/100*saturation, palette.default[2]/100),
col1Fert = HSVtoRGB(palette.fertility[0]/360,palette.fertility[1]/100*saturation, palette.fertility[2]/100),
col1Civ = HSVtoRGB(palette.civilization[0]/360,palette.civilization[1]/100*saturation, palette.civilization[2]/100);
// Blend the fert and civ with the default for the final colour
colorBlend = [
(col1Default[0] + (col1Fert[0]*fertilityBlend) + (col1Civ[0]*civBlend)) / (1 + fertilityBlend + civBlend),
(col1Default[1] + (col1Fert[1]*fertilityBlend) + (col1Civ[1]*civBlend)) / (1 + fertilityBlend + civBlend),
(col1Default[2] + (col1Fert[2]*fertilityBlend) + (col1Civ[2]*civBlend)) / (1 + fertilityBlend + civBlend)
];
// Now check if we are at the borders, so we can blend with the regular colour
var borderDist = distance(xcoord, ycoord, this.glyphBiomes[glyphBiome].x, this.glyphBiomes[glyphBiome].z)/this.glyphBiomes[glyphBiome].radius;
if (borderDist > 0.9) {
borderDist = map_range(borderDist, 0.9, 1, 1, 0); // proportion
// blend with colourWheel colour appropriately
var colWheel = this.getColourWheelBlend(xcoord, ycoord, saturation, fertilityBlend, civBlend);
colorFace = [
((colorBlend[0]*borderDist) + (colWheel[0]*(1-borderDist))),
((colorBlend[1]*borderDist) + (colWheel[1]*(1-borderDist))),
((colorBlend[2]*borderDist) + (colWheel[2]*(1-borderDist))),
];
} else {
colorFace = colorBlend;
}
} else {
colorFace = this.getColourWheelBlend(xcoord, ycoord, saturation, fertilityBlend, civBlend);
}
if(colors === 'all')
{
var colorVariance = 0.05;
//put some noise on the color for each triangle
var colorNoise = -1 + 2 * Math.random();
colorNoise *= colorVariance;
//add color to object
JSONobj.colors.push( Math.min( Math.max( colorFace[0] + colorNoise, 0 ), 1) );
JSONobj.colors.push( Math.min( Math.max( colorFace[1] + colorNoise, 0 ), 1) );
JSONobj.colors.push( Math.min( Math.max( colorFace[2] + colorNoise, 0 ), 1) );
}
//console.log("Selected Color: " + color);
// Push the two faces to make up the quad... TODO make it an actual quad?
// Face Bit Type - Triangle with vertex colors
JSONobj.faces.push(128);
// Vertex Indices
JSONobj.faces.push(x+y);
JSONobj.faces.push(x+y+faceStep);
JSONobj.faces.push(x+y+1);
// Vertex Color Indices
JSONobj.faces.push(colorsIndex);
JSONobj.faces.push(colorsIndex);
JSONobj.faces.push(colorsIndex);
faceCount++;
if(colors === 'all')
{
colorsIndex ++;
//put some noise on the color for each triangle
var colorNoise = -1 + 2 * Math.random();
colorNoise *= colorVariance;
//add color to object
JSONobj.colors.push( Math.min( Math.max( colorFace[0] + colorNoise, 0 ), 1) );
JSONobj.colors.push( Math.min( Math.max( colorFace[1] + colorNoise, 0 ), 1) );
JSONobj.colors.push( Math.min( Math.max( colorFace[2] + colorNoise, 0 ), 1) );
}
// Face Bit Type - Triangle with vertex colors
JSONobj.faces.push(128);
// Vertex Indices
JSONobj.faces.push(x+y+faceStep);
JSONobj.faces.push(x+y+faceStep + 1);
JSONobj.faces.push(x+y+1);
// Vertex Color Indices
JSONobj.faces.push(colorsIndex);
JSONobj.faces.push(colorsIndex);
JSONobj.faces.push(colorsIndex);
faceCount++;
if(colors === 'all')
{
colorsIndex ++;
}
//this could just be an else but I find it reads better
else if(colors === 'average')
{
colorAverage[0] += colorFace[0];
colorAverage[1] += colorFace[1];
colorAverage[2] += colorFace[2];
}
}
}
if(colors === 'average')
{
colorAverage[0] /= faceCount;
colorAverage[1] /= faceCount;
colorAverage[2] /= faceCount;
JSONobj.colors.push( colorAverage[0] );
JSONobj.colors.push( colorAverage[1] );
JSONobj.colors.push( colorAverage[2] );
}
//console.log(JSONobj.colors.length + ", " + JSONobj.faces.length);
var JSONstring = JSON.stringify(JSONobj);
//console.log(JSONobj);
//console.log(JSONstring);
return JSONstring;
}
//takes position in GRID UNITS and returns the height of the world
EnvironmentGenerator.prototype.getNoiseHeight = function(xVal, yVal)
{
// Size variable controls "zoom" of noise map - it is itself noise mapped to create more dynamic terrain
var size = map_range(this.simplex.noise3D( 0.03 * xVal, 0.03 * yVal, this.seed - 17 ), 0, 1, 0.005, 0.20),
value;
// Create a smaller-scale noisemap for more jagged terrain
var smoothness = map_range(this.simplex.noise3D( 0.4 * xVal, 0.4 * yVal, this.seed + 1 ), 0, 1, 0, 1),
variance = map_range(this.simplex.noise3D( 1.2 * xVal, 1.2 * yVal, this.seed - 82 ), 0, 1, -5, 5);
value = map_range(this.simplex.noise3D( size*xVal, size*yVal, this.seed ), 0, 1, -80, 50) + (variance * smoothness);
return value;
}
//takes position in METERS and returns the normal of the terrain relative to the global "up y" vector
EnvironmentGenerator.prototype.getTerrainNormal = function(x, y)
{
//get three vectors on terrain
var vec1 = {x: x, y: 0, z:y},
vec2 = {x: x+0.5, y: 0, z:y},
vec3 = {x: x, y: 0, z:y+0.5};
//get height values for them
vec1.y = this.getNoiseHeight( vec1.x / 51, vec1.z / 51 );
vec2.y = this.getNoiseHeight( vec2.x / 51, vec2.z / 51 );
vec3.y = this.getNoiseHeight( vec3.x / 51, vec3.z / 51 );
//turn vertices into edges
var edge1 = {
x: vec2.x - vec1.x,
y: vec2.y - vec1.y,
z: vec2.z - vec1.z
};
var edge2 = {
x: vec3.x - vec1.x,
y: vec3.y - vec1.y,
z: vec3.z - vec1.z
};
//normal is cross product of the two edges
var normal = {
x: edge1.y * edge2.z - edge1.z * edge2.y,
y: edge1.z * edge2.x - edge1.x * edge2.z,
z: edge1.x * edge2.y - edge1.y * edge2.x
};
//normalize
var mag = Math.sqrt( normal.x * normal.x + normal.y * normal.y + normal.z * normal.z );
normal.x /= mag;
normal.y /= mag;
normal.z /= mag;
return normal;
}
//takes position in METERS and returns the angle of the terrain relative to the global "up y" vector
EnvironmentGenerator.prototype.getTerrainAngle = function(x, y)
{
// For some reason, removing the below code and calling this.getTerrainNormal causes an error..
//get three vectors on terrain
var vec1 = {x: x, y: 0, z:y},
vec2 = {x: x+0.5, y: 0, z:y},
vec3 = {x: x, y: 0, z:y+0.5};
//get height values for them
vec1.y = this.getNoiseHeight( vec1.x / 51, vec1.z / 51 );
vec2.y = this.getNoiseHeight( vec2.x / 51, vec2.z / 51 );
vec3.y = this.getNoiseHeight( vec3.x / 51, vec3.z / 51 );
//turn vertices into edges
var edge1 = {
x: vec2.x - vec1.x,
y: vec2.y - vec1.y,
z: vec2.z - vec1.z
};
var edge2 = {
x: vec3.x - vec1.x,
y: vec3.y - vec1.y,
z: vec3.z - vec1.z
};
//normal is cross product of the two edges
var normal = {
x: edge1.y * edge2.z - edge1.z * edge2.y,
y: edge1.z * edge2.x - edge1.x * edge2.z,
z: edge1.x * edge2.y - edge1.y * edge2.x
};
//find angle between normal and UP
//cosAngle = (a dot b) / (magA * magB)
var aDotB = normal.x * 0 + normal.y * 1 + normal.z * 0,
magA = Math.sqrt( edge1.x * edge1.x + edge1.y * edge1.y + edge1.z * edge1.z ),
magB = Math.sqrt( edge2.x * edge2.x + edge2.y * edge2.y + edge2.z * edge2.z )
var theta = Math.acos(aDotB / (magA * magB));
theta = (0.5 * Math.PI) - (theta % (0.5 * Math.PI));
return theta;
}
EnvironmentGenerator.prototype.getColourWheelBlend = function(xcoord, ycoord, saturation, fertilityBlend, civBlend) {
// Get the "Biome" colour from the colour simplex noise map, and map to a degree position on the colour wheel
var colourWheel = map_range(this.simplex.noise3D( 0.0005*xcoord, 0.0005*ycoord, this.colourSeed), 0, 1, 0, 360);
var colours = this.palettes;
var sliceSize = 360 / colours.length;
var slice = Math.floor(colourWheel / sliceSize);
// convert to RGB
var col1Default = HSVtoRGB(colours[slice].default[0]/360,colours[slice].default[1]/100*saturation, colours[slice].default[2]/100),
col1Fert = HSVtoRGB(colours[slice].fertility[0]/360,colours[slice].default[1]/100*saturation, colours[slice].fertility[2]/100),
col1Civ = HSVtoRGB(colours[slice].civilization[0]/360,colours[slice].default[1]/100*saturation, colours[slice].civilization[2]/100);
// Blend the fert and civ with the default for the final colour
var col1 = [
(col1Default[0] + (col1Fert[0]*fertilityBlend) + (col1Civ[0]*civBlend)) / (1 + fertilityBlend + civBlend),
(col1Default[1] + (col1Fert[1]*fertilityBlend) + (col1Civ[1]*civBlend)) / (1 + fertilityBlend + civBlend),
(col1Default[2] + (col1Fert[2]*fertilityBlend) + (col1Civ[2]*civBlend)) / (1 + fertilityBlend + civBlend)
];
// Check if near border, if so blend
var blendSlice,
proportion;
if ((colourWheel % sliceSize) / sliceSize < 0.2) {
// for now do 50%
var blendSlice = (slice === 0) ? colours.length -1 : slice - 1;
var col2Default = HSVtoRGB(colours[blendSlice].default[0]/360,colours[blendSlice].default[1]/100*saturation, colours[blendSlice].default[2]/100),
col2Fert = HSVtoRGB(colours[blendSlice].fertility[0]/360,colours[blendSlice].default[1]/100*saturation, colours[blendSlice].fertility[2]/100),
col2Civ = HSVtoRGB(colours[blendSlice].civilization[0]/360,colours[blendSlice].default[1]/100*saturation, colours[blendSlice].civilization[2]/100);
var col2 = [
(col2Default[0] + (col2Fert[0]*fertilityBlend) + (col2Civ[0]*civBlend)) / (1 + fertilityBlend + civBlend),
(col2Default[1] + (col2Fert[1]*fertilityBlend) + (col2Civ[1]*civBlend)) / (1 + fertilityBlend + civBlend),
(col2Default[2] + (col2Fert[2]*fertilityBlend) + (col2Civ[2]*civBlend)) / (1 + fertilityBlend + civBlend)
];
// convert to RGB
var proportion = map_range(((colourWheel % sliceSize) / sliceSize), 0, 0.2, 0.5, 1);
colorFace = [
((col1[0]*proportion) + (col2[0]*(1-proportion))),
((col1[1]*proportion) + (col2[1]*(1-proportion))),
((col1[2]*proportion) + (col2[2]*(1-proportion))),
];
} else if ((colourWheel % sliceSize) / sliceSize > 0.8) {
var blendSlice = (slice === colours.length-1) ? 0 : slice + 1;
var col2Default = HSVtoRGB(colours[blendSlice].default[0]/360,colours[blendSlice].default[1]/100*saturation, colours[blendSlice].default[2]/100),
col2Fert = HSVtoRGB(colours[blendSlice].fertility[0]/360,colours[blendSlice].default[1]/100*saturation, colours[blendSlice].fertility[2]/100),
col2Civ = HSVtoRGB(colours[blendSlice].civilization[0]/360,colours[blendSlice].default[1]/100*saturation, colours[blendSlice].civilization[2]/100);
var col2 = [
(col2Default[0] + (col2Fert[0]*fertilityBlend) + (col2Civ[0]*civBlend)) / (1 + fertilityBlend + civBlend),
(col2Default[1] + (col2Fert[1]*fertilityBlend) + (col2Civ[1]*civBlend)) / (1 + fertilityBlend + civBlend),
(col2Default[2] + (col2Fert[2]*fertilityBlend) + (col2Civ[2]*civBlend)) / (1 + fertilityBlend + civBlend)
];
var proportion = map_range(((colourWheel % sliceSize) / sliceSize), 0.8, 1, 1, 0.5);
colorFace = [
((col1[0]*proportion) + (col2[0]*(1-proportion))),
((col1[1]*proportion) + (col2[1]*(1-proportion))),
((col1[2]*proportion) + (col2[2]*(1-proportion))),
];
} else {
// no blending required, use original colour
colorFace = col1;
}
return colorFace;
}
EnvironmentGenerator.prototype.generateForPosition = function(pos) {
var self=this;
//console.log("Generating For Position: [" + pos.x + ", " + pos.y + "]");
var promise = new Promise(function(resolve, reject) {
self.generateTerrainForPosition(pos);
self.generateObjectsForPosition(pos).then(
function(response) {
resolve({generationFinished:true});
}, function(error) {
console.log("Erroring out at generateForPosition");
console.log("ERROR: " + JSON.stringify(error));
});
});
return promise;
}
EnvironmentGenerator.prototype.generateTerrainForPosition = function(pos) {
if (!this.gameStart) {