-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathasteroid.cpp
996 lines (902 loc) · 28.8 KB
/
asteroid.cpp
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
#include <vector>
#include "uv_mapper.hpp"
#include "FastNoise.h"
#include "asteroid.h"
#include <Urho3D/Urho3DAll.h>
//uncomment this if u want to subdivide more
//#define DETAIL_ASTEROID_MODEL 1
namespace Urho3D
{
struct asteroid_vertex_data_
{
Vector3 position;
Vector3 normal;
Vector4 tangent;
Vector2 uv;
};
#ifdef DETAIL_ASTEROID_MODEL
typedef unsigned IBtype;
#else
typedef unsigned short IBtype;
#endif
static BoundingBox calculateBB(const PODVector<asteroid_vertex_data_> &vd)
{
BoundingBox ret;
for (unsigned ii = 0; ii < vd.Size(); ++ii)
ret.Merge(vd[ii].position);
return ret;
}
class XZplaneIterator{
public:
virtual IBtype iter(unsigned i) const = 0;
virtual ~XZplaneIterator() = default;
};
class TopBottomPlane : public XZplaneIterator
{
public:
TopBottomPlane(IBtype start_offset, const IntVector3 &Segment)
: XZplaneIterator(), off(start_offset), seg(Segment)
{}
IBtype iter(unsigned i) const override
{
if(i < seg.z_)
{
return off + i;
}
else if(i < seg.z_ + seg.x_)
{
unsigned xx = i - seg.z_;
return off + seg.z_ + xx * (seg.z_ + 1);
}
else if(i < seg.z_ + seg.x_ + seg.z_)
{
unsigned zz = seg.z_ + seg.x_ + seg.z_ - i;
return off + seg.x_ * (seg.z_ + 1) + zz;
}
else if(i < 2*seg.x_ + 2*seg.z_)
{
unsigned xx = 2*seg.x_ + 2*seg.z_ - i;
return off + xx * (seg.z_ + 1);
}
else if(i == 2*seg.x_ + 2*seg.z_)
{
return off;
}
else
{
URHO3D_LOGERROR("TopBottomPlane: exceed boundary");
return off;
}
}
private:
const IBtype off;
const IntVector3 seg;
};
class MiddlePlane : public XZplaneIterator
{
public:
MiddlePlane(IBtype start_offset, const IntVector3 &Segment)
: XZplaneIterator(), off(start_offset), seg(Segment)
{}
IBtype iter(unsigned i) const override
{
if(i < 2*seg.x_ + 2*seg.z_)
{
return off + i;
}
else if(i == 2*seg.x_ + 2*seg.z_)
{
return off;
}
else
{
URHO3D_LOGERROR("MiddlePlane: exceed boundary");
return off;
}
}
private:
const IBtype off;
const IntVector3 seg;
};
/*
quad:
i0 i1
i2 i3
*/
static void buildQuadIndex(PODVector<IBtype> &id, IBtype i0, IBtype i1, IBtype i2, IBtype i3, const bool bottom)
{
if (!bottom)
{ //CW
id.Push(i0); id.Push(i1); id.Push(i3);
id.Push(i0); id.Push(i3); id.Push(i2);
}
else
{ //CCW
id.Push(i0); id.Push(i3); id.Push(i1);
id.Push(i0); id.Push(i2); id.Push(i3);
}
}
static IBtype CreateCubeTopBottomPlane(PODVector<asteroid_vertex_data_> &vd, PODVector<IBtype> &id, const Vector3 &Size, const IntVector3 &Segment,
const bool bottom)
{
const unsigned vdStart = vd.Size();
const Vector3 half(Size / 2.0f);
for (unsigned xx = 0; xx < Segment.x_ + 1; ++xx)
{
for (unsigned zz = 0; zz < Segment.z_ + 1; ++zz)
{
asteroid_vertex_data_ data;
data.position = Vector3(-half.x_ + xx * Size.x_ / Segment.x_, bottom ? -half.y_ : half.y_, -half.z_ + zz * Size.z_ / Segment.z_);
vd.Push(data);
}
}
for (unsigned xx = 0; xx < Segment.x_; ++xx)
{
for (unsigned zz = 0; zz < Segment.z_; ++zz)
{
IBtype i0 = vdStart + xx * (Segment.z_ + 1) + 1 + zz;
IBtype i1 = vdStart + (xx + 1) * (Segment.z_ + 1) + 1 + zz;
IBtype i2 = vdStart + xx * (Segment.z_ + 1) + zz;
IBtype i3 = vdStart + (xx + 1) * (Segment.z_ + 1) + zz;
buildQuadIndex(id, i0, i1, i2, i3, bottom);
}
}
return vdStart;
}
static IBtype CreateMiddleXZVertices(PODVector<asteroid_vertex_data_> &vd, const Vector3 &Size, const IntVector3 &Segment, float y)
{
const unsigned vdStart = vd.Size();
const Vector3 half(Size / 2.0f);
for(unsigned zz = 0; zz < Segment.z_ + 1; ++zz)
{
asteroid_vertex_data_ data;
data.position = Vector3(-half.x_, y, -half.z_ + zz * (Size.z_ / Segment.z_));
vd.Push(data);
}
for(unsigned xx = 1; xx < Segment.x_; ++xx)
{
asteroid_vertex_data_ data;
data.position = Vector3(-half.x_ + xx * (Size.x_ / Segment.x_), y, half.z_);
vd.Push(data);
}
for(unsigned zz = 0; zz < Segment.z_ + 1; ++zz)
{
asteroid_vertex_data_ data;
data.position = Vector3(half.x_, y, half.z_ - zz * (Size.z_ / Segment.z_));
vd.Push(data);
}
for(unsigned xx = 1; xx < Segment.x_; ++xx)
{
asteroid_vertex_data_ data;
data.position = Vector3(half.x_ - xx * (Size.x_ / Segment.x_), y, -half.z_);
vd.Push(data);
}
return vdStart;
}
/*create cube without duplicated vertices*/
static void CreateCube(PODVector<asteroid_vertex_data_> &vd, PODVector<IBtype> &id, const Vector3 &Size, const IntVector3 &Segment)
{
if (Segment.x_ <= 0 || Segment.y_ <= 0 || Segment.z_ <= 0 || Size.x_ <= 0.0f || Size.y_ <= 0.0f || Size.z_ <= 0.0f)
{
URHO3D_LOGERROR("CreateCube: size or segment cannot <= 0");
return;
}
const unsigned numVertices = (Segment.x_ + 1) * (Segment.y_ + 1) * 2 + (Segment.y_ + 1)*(Segment.z_ + 1) * 2 + (Segment.x_ + 1)*(Segment.z_ + 1) * 2
- 4 * (Segment.x_ - 1) - 4 * (Segment.y_ - 1) - 4 * (Segment.z_ - 1) - 8 * 2;
const unsigned numIndices = Segment.x_*Segment.y_ * 2 * 3 * 2 + Segment.y_*Segment.z_ * 2 * 3 * 2 + Segment.x_*Segment.z_ * 2 * 3 * 2;
#ifndef DETAIL_ASTEROID_MODEL
if (numVertices > 65535)
{
URHO3D_LOGERROR("CreateCube: index buffer need larger type; plz define DETAIL_ASTEROID_MODEL");
return;
}
#endif
vd.Clear();
vd.Reserve(numVertices);
id.Clear();
id.Reserve(numIndices);
/*bottom xz plane*/
IBtype bottomOff = CreateCubeTopBottomPlane(vd, id, Size, Segment, true);
XZplaneIterator * lastPlane = new TopBottomPlane(bottomOff, Segment);
XZplaneIterator * newPlane = nullptr;
for(unsigned ii=0; ii<Segment.y_-1; ++ii)
{
IBtype middleOff = CreateMiddleXZVertices(vd,Size, Segment, -Size.y_/2.0f + (ii+1)*(Size.y_/Segment.y_));
newPlane = new MiddlePlane(middleOff, Segment);
for(unsigned jj=0; jj<Segment.x_*2 + Segment.z_*2; ++jj)
{
buildQuadIndex(id, newPlane->iter(jj+1), newPlane->iter(jj), lastPlane->iter(jj+1), lastPlane->iter(jj), false);
}
delete lastPlane;
lastPlane = newPlane;
newPlane = nullptr;
}
IBtype topOff = CreateCubeTopBottomPlane(vd, id, Size, Segment, false);
newPlane = new TopBottomPlane(topOff, Segment);
for(unsigned jj=0; jj<Segment.x_*2 + Segment.z_*2; ++jj)
{
buildQuadIndex(id, newPlane->iter(jj+1), newPlane->iter(jj), lastPlane->iter(jj+1), lastPlane->iter(jj), false);
}
delete newPlane;
delete lastPlane;
if(vd.Size() != numVertices)
{
URHO3D_LOGERROR("numVertices calculation error");
}
if(id.Size() != numIndices)
{
URHO3D_LOGERROR("numIndices calculation error");
}
}
/*Create sphere without duplicated vertices, github.com/caosdoar/spheres*/
static void CreateSphere(PODVector<asteroid_vertex_data_> &vd, PODVector<IBtype> &id, const float radius, const unsigned parallels_count, const unsigned meridians_count)
{
if (radius <= 0.0f || parallels_count < 3 || meridians_count < 3)
{
URHO3D_LOGERROR("CreateSphere: parameter error");
return;
}
const unsigned numVertices = 2 + (parallels_count-1) * meridians_count;
const unsigned numIndices = 2 * meridians_count * 3 + (parallels_count - 2) * meridians_count * 6;
#ifndef DETAIL_ASTEROID_MODEL
if (numVertices > 65535)
{
URHO3D_LOGERROR("CreateSphere: index buffer need larger type; plz define DETAIL_ASTEROID_MODEL");
return;
}
#endif
vd.Clear();
vd.Reserve(numVertices);
id.Clear();
id.Reserve(numIndices);
{
asteroid_vertex_data_ north;
north.position = Vector3(0.0f, radius, 0.0f);
vd.Push(north);
}
for(unsigned j=0; j<parallels_count-1; ++j)
{
float const polar = 180.0f * float(j+1) / float(parallels_count);
float const sp = Sin(polar);
float const cp = Cos(polar);
for(unsigned i=0; i<meridians_count; ++i)
{
float const azimuth = 360.0f * float(i) / float(meridians_count);
float const sa = Sin(azimuth);
float const ca = Cos(azimuth);
float const x = sp * ca * radius;
float const y = cp * radius;
float const z = sp * sa * radius;
asteroid_vertex_data_ point;
point.position = Vector3(x, y, z);
vd.Push(point);
}
}
{
asteroid_vertex_data_ south;
south.position = Vector3(0.0f, -radius, 0.0f);
vd.Push(south);
}
for(unsigned i=0; i<meridians_count; ++i)
{
IBtype const a = i + 1;
IBtype const b = (i + 1) % meridians_count + 1;
id.Push(0);
id.Push(b);
id.Push(a);
}
for (unsigned j = 0; j < parallels_count - 2; ++j)
{
IBtype aStart = j * meridians_count + 1;
IBtype bStart = (j + 1) * meridians_count + 1;
for (unsigned i = 0; i < meridians_count; ++i)
{
const IBtype a = aStart + i;
const IBtype a1 = aStart + (i + 1) % meridians_count;
const IBtype b = bStart + i;
const IBtype b1 = bStart + (i + 1) % meridians_count;
id.Push(a);
id.Push(a1);
id.Push(b1);
id.Push(a);
id.Push(b1);
id.Push(b);
}
}
for (unsigned i = 0; i < meridians_count; ++i)
{
IBtype const a = i + meridians_count * (parallels_count - 2) + 1;
IBtype const b = (i + 1) % meridians_count + meridians_count * (parallels_count - 2) + 1;
id.Push(vd.Size()-1);
id.Push(a);
id.Push(b);
}
if(vd.Size() != numVertices)
{
URHO3D_LOGERROR("numVertices calculation error");
}
if(id.Size() != numIndices)
{
URHO3D_LOGERROR("numIndices calculation error");
}
}
/*split mesh to 2 parts by a plane; output 2 index buffers, they use the same vertex buffer*/
static void SplitMesh(const PODVector<asteroid_vertex_data_> &vd, const PODVector<IBtype> &id, const Plane &p,
Vector< PODVector<IBtype> > &parts)
{
if(id.Size() % 3)
{
URHO3D_LOGERROR("SplitCube: size of index buffer mod 3 != 0");
return;
}
const unsigned numTriangles = id.Size() / 3;
parts.Resize(2);
parts[0].Clear();
parts[1].Clear();
for(unsigned ii=0; ii<numTriangles; ++ii)
{
unsigned behindPlane = 0;
for(unsigned jj=0; jj<3; ++jj)
{
if(p.Distance(vd[ id[ii*3 + jj] ].position) < 0.0f)
{
behindPlane += 1;
}
}
if(behindPlane > 2)
{
for(unsigned jj=0; jj<3; ++jj)
{
parts[0].Push(id[ii*3 + jj]);
}
}
else
{
for(unsigned jj=0; jj<3; ++jj)
{
parts[1].Push(id[ii*3 + jj]);
}
}
}
}
static void cutByPlane(PODVector<asteroid_vertex_data_> &vd, const Plane &p)
{
for (unsigned ii = 0; ii < vd.Size(); ++ii)
{
if (p.Distance(vd[ii].position) < 0.0f)
{
vd[ii].position = p.Project(vd[ii].position);
}
}
}
static Vector3 calculateCenter(const PODVector<asteroid_vertex_data_> &vd)
{
Vector3 ret(Vector3::ZERO);
const unsigned sz = vd.Size();
for(unsigned ii=0; ii<sz; ++ii)
{
ret += vd[ii].position;
}
ret /= sz;
return ret;
}
static void calculateNormal(PODVector<asteroid_vertex_data_> &vd, const PODVector<IBtype> &id)
{
if(id.Size() % 3)
{
URHO3D_LOGERROR("calculateNormal: size of index buffer mod 3 != 0");
return;
}
const unsigned numTriangles = id.Size() / 3;
const unsigned numVertices = vd.Size();
for (unsigned ii = 0; ii < numVertices; ++ii)
{
Vector3 n(Vector3::ZERO);
for (unsigned jj = 0; jj < numTriangles; ++jj)
{
bool found = false;
for(unsigned kk=0; kk<3; ++kk)
{
if(id[jj*3 + kk] == ii)
{
found = true;
break;
}
}
if(found)
{
Vector3 triNormal((vd[ id[jj*3+1] ].position - vd[ id[jj*3] ].position).CrossProduct(vd[ id[jj*3+2] ].position - vd[ id[jj*3] ].position));
n += triNormal;
}
}
vd[ii].normal = n.Normalized();
}
}
static unsigned numVerticesBehindPlane(const PODVector<asteroid_vertex_data_> &vd, const Plane &p)
{
unsigned ret = 0;
for (unsigned ii = 0; ii < vd.Size(); ++ii)
{
if (p.Distance(vd[ii].position) < 0.0f)
ret += 1;
}
return ret;
}
static unsigned numCornersBehindPlane(const BoundingBox &bb, const Plane &p)
{
Vector3 bbCorners[8] = {
bb.min_,
bb.max_,
Vector3(bb.min_.x_, bb.min_.y_, bb.max_.z_),
Vector3(bb.min_.x_, bb.max_.y_,bb.min_.z_),
Vector3(bb.max_.x_, bb.min_.y_, bb.min_.z_),
Vector3(bb.max_.x_, bb.max_.y_, bb.min_.z_),
Vector3(bb.max_.x_, bb.min_.y_, bb.max_.z_),
Vector3(bb.min_.x_, bb.max_.y_, bb.max_.z_)
};
unsigned cnt = 0;
for (unsigned ii = 0; ii < 8; ++ii)
{
if (p.Distance(bbCorners[ii]) < 0.0f)
{
cnt += 1;
}
}
return cnt;
}
static void autoUV(const PODVector<asteroid_vertex_data_> &vd, const PODVector<IBtype> &id,
PODVector<asteroid_vertex_data_> &outVd, PODVector<IBtype> &outId)
{
std::vector<float> vertices, outVertices;
std::vector<int> indices, outIndices;
std::vector<float> outUv;
vertices.reserve(vd.Size() * 3);
indices.reserve(id.Size());
for (unsigned ii = 0; ii < vd.Size(); ++ii)
{
vertices.push_back(vd[ii].position.x_);
vertices.push_back(vd[ii].position.y_);
vertices.push_back(vd[ii].position.z_);
}
for (unsigned ii = 0; ii < id.Size(); ++ii)
{
indices.push_back(id[ii]);
}
uvMap(vertices, indices, outVertices, outIndices, outUv, nullptr);
for (unsigned ii = 0; ii < outVertices.size(); ii += 3)
{
asteroid_vertex_data_ v;
v.position = Vector3(outVertices[ii], outVertices[ii + 1], outVertices[ii + 2]);
outVd.Push(v);
}
for (unsigned ii = 0; ii < outVd.Size(); ++ii)
{
outVd[ii].uv = Vector2(outUv[ii * 2], outUv[ii * 2 + 1]);
}
/*recover normal*/
for (unsigned ii = 0; ii < outVd.Size(); ++ii)
{
for (unsigned jj = 0; jj < vd.Size(); ++jj)
{
if (outVd[ii].position == vd[jj].position)
{
outVd[ii].normal = vd[jj].normal;
break;
}
}
}
for (unsigned ii = 0; ii < outIndices.size(); ++ii)
{
outId.Push(outIndices[ii]);
}
}
static Model * CreateMesh(Context* ctx, unsigned edge_division)
{
bool sphereBase = false;
if (Random(1.0f) < 0.5f)
sphereBase = true;
PODVector<asteroid_vertex_data_> vd;
PODVector<IBtype> id;
BoundingBox BB;
const IntVector3 segment(edge_division, edge_division, edge_division);
if(sphereBase)
CreateSphere(vd, id, 0.5f, edge_division/2, edge_division);
else
CreateCube(vd, id, Vector3::ONE, segment);
/*random scale*/
Vector3 scale(Random(0.5f, 1.5f), Random(0.5f, 1.5f), Random(0.5f, 1.5f));
for (unsigned ii = 0; ii < vd.Size(); ++ii)
{
vd[ii].position *= scale;
}
/*random cut with plane*/
const unsigned numCutPlane = 8;
BB = calculateBB(vd);
const float plane_points_x_start[numCutPlane] = { 0, BB.min_.x_ , 0, BB.min_.x_, 0, BB.min_.x_ ,0, BB.min_.x_ };
const float plane_points_x_end[numCutPlane] = { BB.max_.x_, 0, BB.max_.x_ , 0, BB.max_.x_, 0, BB.max_.x_ , 0 };
const float plane_points_y_start[numCutPlane] = { 0, 0, 0, 0, BB.min_.y_ ,BB.min_.y_ ,BB.min_.y_ ,BB.min_.y_ };
const float plane_points_y_end[numCutPlane] = { BB.max_.y_, BB.max_.y_, BB.max_.y_, BB.max_.y_, 0, 0, 0, 0 };
const float plane_points_z_start[numCutPlane] = { 0, 0, BB.min_.z_, BB.min_.z_, 0, 0, BB.min_.z_, BB.min_.z_ };
const float plane_points_z_end[numCutPlane] = { BB.max_.z_, BB.max_.z_, 0, 0, BB.max_.z_, BB.max_.z_, 0, 0 };
for (unsigned ii = 0; ii < numCutPlane; ++ii)
{
while (true)
{
Quaternion q(Random(-30.0f, 30.0f), Random(-30.0f, 30.0f), Random(-30.0f, 30.0f));
Vector3 plane_point(Random(plane_points_x_start[ii], plane_points_x_end[ii]), Random(plane_points_y_start[ii], plane_points_y_end[ii]),
Random(plane_points_z_start[ii], plane_points_z_end[ii]));
Plane plane(-(q * plane_point), plane_point);
if (numCornersBehindPlane(BB, plane) == 1 && numVerticesBehindPlane(vd, plane) > 0)
{
cutByPlane(vd, plane);
break;
}
}
}
calculateNormal(vd, id);
/*displace with noise*/
{
PODVector<float> displacements;
displacements.Reserve(vd.Size());
FastNoise *perlin = new FastNoise(Random(0, M_MAX_UNSIGNED));
perlin->SetFrequency(Random(0.01f, 0.03f));
const float noiseScale = Random(100.0f, 200.0f);
const float noiseFactor = Random(0.05f, 0.2f);
float noiseMax = FLT_MIN, noiseMin = FLT_MAX;
for (unsigned ii = 0; ii < vd.Size(); ++ii)
{
Vector3 p(vd[ii].position * noiseScale);
float noise = perlin->GetPerlinFractal(p.x_, p.y_, p.z_);
if (noise > noiseMax)
noiseMax = noise;
if (noise < noiseMin)
noiseMin = noise;
displacements.Push(noise);
}
delete perlin;
//normalize to [-0.5, 0.5]
for (unsigned ii = 0; ii < displacements.Size(); ++ii)
{
displacements[ii] = (displacements[ii] - noiseMin) / (noiseMax - noiseMin) - 0.5f;
}
for (unsigned ii = 0; ii < vd.Size(); ++ii)
{
//vd[ii].position = vd[ii].position + displacements[ii] * noiseFactor * (center - vd[ii].position).Normalized();
vd[ii].position = vd[ii].position + displacements[ii] * noiseFactor * vd[ii].normal;
}
}
BB = calculateBB(vd);
calculateNormal(vd, id);
Vector3 center = calculateCenter(vd);
Vector< PODVector<IBtype> > parts;
{
Plane split(Vector3::UP, center);
SplitMesh(vd, id, split, parts);
}
Vector< PODVector<asteroid_vertex_data_> > new_parts_vd(parts.Size());
Vector< PODVector<IBtype> > new_parts_id(parts.Size());
for (unsigned ii = 0; ii < parts.Size(); ++ii)
{
autoUV(vd, parts[ii], new_parts_vd[ii], new_parts_id[ii]);
GenerateTangents(new_parts_vd[ii].Buffer(), sizeof(asteroid_vertex_data_), new_parts_id[ii].Buffer(), sizeof(IBtype), 0, new_parts_id[ii].Size(),
offsetof(asteroid_vertex_data_, normal), offsetof(asteroid_vertex_data_, uv), offsetof(asteroid_vertex_data_, tangent));
}
PODVector<Geometry*> geometries;
for (unsigned ii = 0; ii < parts.Size(); ++ii)
{
VertexBuffer * vb(new VertexBuffer(ctx));
IndexBuffer * ib(new IndexBuffer(ctx));
Geometry * geom(new Geometry(ctx));
vb->SetShadowed(true);
PODVector<VertexElement> elements;
elements.Push(VertexElement(TYPE_VECTOR3, SEM_POSITION));
elements.Push(VertexElement(TYPE_VECTOR3, SEM_NORMAL));
elements.Push(VertexElement(TYPE_VECTOR4, SEM_TANGENT));
elements.Push(VertexElement(TYPE_VECTOR2, SEM_TEXCOORD));
vb->SetSize(new_parts_vd[ii].Size(), elements);
vb->SetData(new_parts_vd[ii].Buffer());
ib->SetShadowed(true);
#ifdef DETAIL_ASTEROID_MODEL
bool largeIndices = true;
#else
bool largeIndices = false;
#endif
ib->SetSize(new_parts_id[ii].Size(), largeIndices);
ib->SetData(new_parts_id[ii].Buffer());
geom->SetVertexBuffer(0, vb);
geom->SetIndexBuffer(ib);
geom->SetDrawRange(TRIANGLE_LIST, 0, new_parts_id[ii].Size());
geometries.Push(geom);
}
Model * fromScratchModel(new Model(ctx));
fromScratchModel->SetNumGeometries(geometries.Size());
for (unsigned ii = 0; ii < geometries.Size(); ++ii)
{
fromScratchModel->SetGeometry(ii, 0, geometries[ii]);
}
fromScratchModel->SetBoundingBox(BB);
return fromScratchModel;
}
// github.com/cpetry/NormalMap-Online
static Image * CalculateNormalMapFromHeight(Context* ctx, const Image * heightMap)
{
const int w = heightMap->GetWidth();
const int h = heightMap->GetHeight();
Image * ret = new Image(ctx);
if (ret->SetSize(w, h, 4) == false)
{
URHO3D_LOGERROR("CalculateNormalMapFromHeight: Image::SetSize fail");
delete ret;
return nullptr;
}
const float Strength = 2.5f;
const float Level = 7.0f;
const int type = 0;
//webgl setting default is [1,1,-1]
const float invertR = 1.0f; //-1 or 1
const float invertG = 1.0f; //-1 or 1
const float invertH = -1.0f; //-1 or 1
Vector2 step(-1.0f / w, -1.0f / h);
float dz = (1.0f / Strength) * (1.0f + Pow(2.0f, Level));
for (int x = 0; x < w; ++x)
{
for (int y = 0; y < h; ++y)
{
Vector2 vUv((float)x/w, (float)y/h);
Vector2 tlv = Vector2(vUv.x_ - step.x_, vUv.y_ + step.y_);
Vector2 lv = Vector2(vUv.x_ - step.x_, vUv.y_);
Vector2 blv = Vector2(vUv.x_ - step.x_, vUv.y_ - step.y_);
Vector2 tv = Vector2(vUv.x_, vUv.y_ + step.y_);
Vector2 bv = Vector2(vUv.x_, vUv.y_ - step.y_);
Vector2 trv = Vector2(vUv.x_ + step.x_, vUv.y_ + step.y_);
Vector2 rv = Vector2(vUv.x_ + step.x_, vUv.y_);
Vector2 brv = Vector2(vUv.x_ + step.x_, vUv.y_ - step.y_);
tlv = Vector2(tlv.x_ >= 0.0 ? tlv.x_ : (1.0f + tlv.x_), tlv.y_ >= 0.0f ? tlv.y_ : (1.0f + tlv.y_));
tlv = Vector2(tlv.x_ < 1.0f ? tlv.x_ : (tlv.x_ - 1.0f), tlv.y_ < 1.0f ? tlv.y_ : (tlv.y_ - 1.0f));
lv = Vector2(lv.x_ >= 0.0f ? lv.x_ : (1.0f + lv.x_), lv.y_ >= 0.0f ? lv.y_ : (1.0f + lv.y_));
lv = Vector2(lv.x_ < 1.0f ? lv.x_ : (lv.x_ - 1.0f), lv.y_ < 1.0f ? lv.y_ : (lv.y_ - 1.0f));
blv = Vector2(blv.x_ >= 0.0f ? blv.x_ : (1.0f + blv.x_), blv.y_ >= 0.0f ? blv.y_ : (1.0f + blv.y_));
blv = Vector2(blv.x_ < 1.0f ? blv.x_ : (blv.x_ - 1.0f), blv.y_ < 1.0f ? blv.y_ : (blv.y_ - 1.0f));
tv = Vector2(tv.x_ >= 0.0f ? tv.x_ : (1.0f + tv.x_), tv.y_ >= 0.0f ? tv.y_ : (1.0f + tv.y_));
tv = Vector2(tv.x_ < 1.0f ? tv.x_ : (tv.x_ - 1.0f), tv.y_ < 1.0f ? tv.y_ : (tv.y_ - 1.0f));
bv = Vector2(bv.x_ >= 0.0f ? bv.x_ : (1.0f + bv.x_), bv.y_ >= 0.0f ? bv.y_ : (1.0f + bv.y_));
bv = Vector2(bv.x_ < 1.0f ? bv.x_ : (bv.x_ - 1.0f), bv.y_ < 1.0f ? bv.y_ : (bv.y_ - 1.0f));
trv = Vector2(trv.x_ >= 0.0f ? trv.x_ : (1.0f + trv.x_), trv.y_ >= 0.0f ? trv.y_ : (1.0f + trv.y_));
trv = Vector2(trv.x_ < 1.0f ? trv.x_ : (trv.x_ - 1.0f), trv.y_ < 1.0f ? trv.y_ : (trv.y_ - 1.0f));
rv = Vector2(rv.x_ >= 0.0f ? rv.x_ : (1.0f + rv.x_), rv.y_ >= 0.0f ? rv.y_ : (1.0f + rv.y_));
rv = Vector2(rv.x_ < 1.0f ? rv.x_ : (rv.x_ - 1.0f), rv.y_ < 1.0f ? rv.y_ : (rv.y_ - 1.0f));
brv = Vector2(brv.x_ >= 0.0f ? brv.x_ : (1.0f + brv.x_), brv.y_ >= 0.0f ? brv.y_ : (1.0f + brv.y_));
brv = Vector2(brv.x_ < 1.0f ? brv.x_ : (brv.x_ - 1.0f), brv.y_ < 1.0f ? brv.y_ : (brv.y_ - 1.0f));
float tl = Abs(heightMap->GetPixelBilinear(tlv.x_, tlv.y_).r_);
float l = Abs(heightMap->GetPixelBilinear(lv.x_, lv.y_).r_);
float bl = Abs(heightMap->GetPixelBilinear(blv.x_, blv.y_).r_);
float t = Abs(heightMap->GetPixelBilinear(tv.x_, tv.y_).r_);
float b = Abs(heightMap->GetPixelBilinear(bv.x_, bv.y_).r_);
float tr = Abs(heightMap->GetPixelBilinear(trv.x_, trv.y_).r_);
float r = Abs(heightMap->GetPixelBilinear(rv.x_, rv.y_).r_);
float br = Abs(heightMap->GetPixelBilinear(brv.x_, brv.y_).r_);
float dx = 0.0f, dy = 0.0f;
if (type == 0) { // Sobel
dx = tl + l * 2.0 + bl - tr - r * 2.0 - br;
dy = tl + t * 2.0 + tr - bl - b * 2.0 - br;
}
else { // Scharr
dx = tl * 3.0 + l * 10.0 + bl * 3.0 - tr * 3.0 - r * 10.0 - br * 3.0;
dy = tl * 3.0 + t * 10.0 + tr * 3.0 - bl * 3.0 - b * 10.0 - br * 3.0;
}
Vector4 normal(Vector3(dx * invertR * invertH * 255.0f, dy * invertG * invertH * 255.0f, dz).Normalized(), heightMap->GetPixelBilinear(vUv.x_, vUv.y_).a_);
Color gl_FragColor(normal.x_ * 0.5f + 0.5f, normal.y_ * 0.5f + 0.5f, normal.z_, normal.w_);
ret->SetPixel(x, y, gl_FragColor);
}
}
return ret;
}
static Image * CreateCraterHeightMap(Context* ctx, int size)
{
Image * ret = new Image(ctx);
if (ret->SetSize(size, size, 1) == false)
{
URHO3D_LOGERROR("CreateCraterHeightMap: Image::SetSize fail");
return nullptr;
}
for (unsigned x = 0; x < size; ++x)
{
for (unsigned y = 0; y < size; ++y)
{
ret->SetPixel(x, y, Color(0.5f, 0.5f, 0.5f, 0.5f));
}
}
/*topography height; need to be tile-able
www.gamedev.net/blogs/entry/2138456-seamless-noise/
*/
FastNoise *simplex = new FastNoise(Random(0, M_MAX_UNSIGNED));
simplex->SetFrequency(0.02f);
float **topography = new float *[size];
for (unsigned ii = 0; ii < size; ++ii)
topography[ii] = new float[size];
float max = FLT_MIN, min = FLT_MAX;
const float x1 = Random(500.0f);
const float y1 = Random(500.0f);
const float x2 = x1 + Random(500.0f);
const float y2 = y1 + Random(500.0f);
for (unsigned x = 0; x < size; ++x)
{
for (unsigned y = 0; y < size; ++y)
{
const float dx = x2 - x1;
const float dy = y2 - y1;
float s = (float)x / size;
float t = (float)y / size;
float nx = x1 + Cos(s * 360.0f)*dx / (2 * M_PI);
float ny = y1 + Cos(t * 360.0f)*dy / (2 * M_PI);
float nz = x1 + Sin(s * 360.0f)*dx / (2 * M_PI);
float nw = y1 + Sin(t * 360.0f)*dy / (2 * M_PI);
#if 1
const unsigned octaves = 5;
const float lacunarity = 2.0f;
const float gain = 0.5f;
float amp = 1.0f;
float fbmSum = simplex->GetSimplex(nx, ny, nz, nw);
for (unsigned ii = 0; ii < octaves; ++ii)
{
nx *= lacunarity;
ny *= lacunarity;
nz *= lacunarity;
nw *= lacunarity;
amp *= gain;
fbmSum += simplex->GetSimplex(nx, ny, nz, nw) * amp;
}
topography[x][y] = fbmSum;
#else
topography[x][y] = simplex->GetSimplex(nx, ny, nz, nw);
#endif
if (topography[x][y] > max)
max = topography[x][y];
if (topography[x][y] < min)
min = topography[x][y];
}
}
delete simplex;
/*normalize to [-0.5, 0.5]*/
for (unsigned x = 0; x < size; ++x)
{
for (unsigned y = 0; y < size; ++y)
{
topography[x][y] = (topography[x][y] - min) / (max - min) - 0.5f;
}
}
const float topographyFactor = 0.3f;
for (int x = 0; x < size; ++x)
{
for (int y = 0; y < size; ++y)
{
Color c = ret->GetPixel(x, y);
float h = (topography[x][y] - 0.5f) * topographyFactor;
Color r(h, h, h, h);
c += r;
ret->SetPixel(x, y, c);
}
}
for (unsigned ii = 0; ii < size; ++ii)
delete[] topography[ii];
delete[] topography;
const unsigned numCraters = Random(1, 10);
for (unsigned ii = 0; ii < numCraters; ++ii)
{
int centerX = Random(0, size - 1);
int centerY = Random(0, size - 1);
float radius = Random(5.0f, 30.0f);
while (centerX < radius || centerX + radius > size || centerY < radius || centerY + radius > size)
{
centerX = Random(0, size - 1);
centerY = Random(0, size - 1);
radius = Random(5.0f, 30.0f);
}
for (int x = 0; x < size; ++x)
{
for (int y = 0; y < size; ++y)
{
int sqrX = (x - centerX) * (x - centerX);
int sqrY = (y - centerY) * (y - centerY);
const float ring = 4;
if (sqrX + sqrY <= radius * radius)
{
float cosTheta = Sqrt((float)sqrX + sqrY) / radius;
float sinTheta = Sqrt(1.0f - cosTheta * cosTheta);
float deepness = sinTheta * 0.5f; //radius * sinTheta * 0.5f / radius
ret->SetPixel(x, y, Color(0.5f - deepness, 0.5f - deepness, 0.5f - deepness, 0.5f - deepness));
}
}
}
}
/*add shallow roughness*/
FastNoise *cell = new FastNoise(Random(0, M_MAX_UNSIGNED));
float **Layer = new float *[size];
for (unsigned ii = 0; ii < size; ++ii)
Layer[ii] = new float[size];
max = FLT_MIN, min = FLT_MAX;
for (unsigned x = 0; x < size; ++x)
{
for (unsigned y = 0; y < size; ++y)
{
Layer[x][y] = cell->GetWhiteNoise(x, y);
if (Layer[x][y] > max)
max = Layer[x][y];
if (Layer[x][y] < min)
min = Layer[x][y];
}
}
delete cell;
/*normalize to [-0.5, 0.5]*/
for (unsigned x = 0; x < size; ++x)
{
for (unsigned y = 0; y < size; ++y)
{
Layer[x][y] = (Layer[x][y] - min) / (max - min) - 0.5f;
}
}
const float roughnessFactor = 0.1f;
for (int x = 0; x < size; ++x)
{
for (int y = 0; y < size; ++y)
{
Color c = ret->GetPixel(x, y);
float rough = (Layer[x][y] - 0.5f) * roughnessFactor;
Color r(rough, rough, rough, rough);
c += r;
ret->SetPixel(x, y, c);
}
}
for (unsigned ii = 0; ii < size; ++ii)
delete[] Layer[ii];
delete[] Layer;
return ret;
}
void CreateAsteroidBlob(Context* ctx, Node * node, unsigned textureSize, unsigned subdivision, const Vector<String> &diffusePaths)
{
StaticModelGroup * s = node->CreateComponent<StaticModelGroup>();
Model * model = CreateMesh(ctx, subdivision);
if (model != nullptr)
s->SetModel(model);
SharedPtr<Image> height(CreateCraterHeightMap(ctx, textureSize));
if (height == nullptr)
return;
SharedPtr<Image> normal(CalculateNormalMapFromHeight(ctx, height));
if (normal == nullptr)
return;
height->SaveBMP("height.bmp");
normal->SavePNG("normal.png");
ResourceCache * cache = ctx->GetSubsystem<ResourceCache>();
SharedPtr <Texture2D> diffTex(cache->GetResource<Texture2D>(diffusePaths[Random(0, diffusePaths.Size())]));
if (diffTex == nullptr)
{
URHO3D_LOGERROR(String("diffTex->LoadFile fail"));
return;
}
#if 1
SharedPtr <Texture2D> normalMap(MakeShared<Texture2D>(ctx));
normalMap->SetNumLevels(1);
if (normalMap->SetSize(textureSize, textureSize, Graphics::GetRGBAFormat(), TEXTURE_DYNAMIC) == false)
{
URHO3D_LOGERROR(String("normalMap->SetSize fail"));
return;
}
normalMap->SetData(normal, true);
#else
SharedPtr <Texture2D> normalMap(cache->GetResource<Texture2D>("Textures/NormalMap.png"));
if (diffTex == nullptr)
{
URHO3D_LOGERROR(String("normalMap->LoadFile fail"));
return;
}
#endif
Material * m = new Material(ctx);
m->SetNumTechniques(2);
m->SetTechnique(0, cache->GetResource<Technique>("Techniques/DiffNormal.xml"), QUALITY_MEDIUM);
m->SetTechnique(1, cache->GetResource<Technique>("Techniques/Diff.xml"), QUALITY_LOW);
m->SetTexture(TU_DIFFUSE, diffTex);
m->SetTexture(TU_NORMAL, normalMap);
m->SetShaderParameter("MatSpecColor", Vector4(0.3f, 0.3f, 0.3f, 16.0f));
s->SetMaterial(m);
}
}