-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathengine.cpp
5012 lines (4117 loc) · 181 KB
/
engine.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
997
998
999
1000
/*
* FILE:
* engine.cpp
*
* AUTHORS:
* Sasan Tavakkol <[email protected]> or <[email protected]>
* Stephen Thompson <[email protected]>
*
* LAST UPDATE:
* 26-Aug-2016
* CREATED:
* 24-Oct-2011
*
COPYRIGHT:
* Copyright (C) 2016, Sasan Tavakkol.
* Copyright (C) 2012, Stephen Thompson.
*
* This file is part of Celeris software. Celeris is an interactive
* Boussinesq-type, coastal wave solver and visualizer.
*
* Celeris is free software: you can redistribute it
* and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* The Shallow Water Demo is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the Shallow Water Demo. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "engine.hpp"
#include "settings.hpp"
#include "terrain_heightfield.hpp"
#include "coercri/dx11/core/dx_error.hpp"
#include "coercri/gfx/load_bmp.hpp"
#include "coercri/gfx/pixel_array.hpp"
#include "boost/scoped_array.hpp"
#include "coercri/timer/generic_timer.hpp"
#include <d3d11.h>
#include <d3dx11.h>
#include <d3dcompiler.h>
#include <d3dx10math.h>
#include <xnamath.h>
#include <cmath>
#include <boost/math/special_functions/gamma.hpp>
#include <fstream>
#include <string>
#include <iostream>
#include <sstream>
#include <math.h>
#include <time.h>
#ifdef near
#undef near
#endif
#ifdef far
#undef far
#endif
// Turning off USE_KP07 activates an experimental Lax-Wendroff solver.
// Unfortunately this is buggy and unstable currently, so leaving USE_KP07
// on is recommended.
#define USE_KP07
// Debugging switches
//#define DUMP_TO_FILE
//#define RUN_CHECKS
#if defined(DUMP_TO_FILE) || defined(RUN_CHECKS)
#include <iomanip>
#endif
namespace {
const float PI = 4.0f * std::atan(1.0f);
const float BCOEF=1/15.0f;
float GaussianBrush(float x, float y, float r)
{
const float sigma = 1.0f / 3.0f;
float z = (x*x + y*y) / (r*r);
if (z > 1) return 0;
else return 2 * std::exp(-z/(2*sigma*sigma));
}
void solitaryWave (const float waterDepth, const float param_H, const float theta, const float x_zero, const float y_zero, float x, float y, float *eta, float *hu, float *hv){
const float param_K = sqrt(0.75f * abs(param_H)/pow(waterDepth,3));
const float param_C = sqrt (GetSetting("gravity") * (param_H+waterDepth));
const float temp_eta = param_H * 1.0f/pow(cosh(param_K * ((x - x_zero) * cos(theta) + (y - y_zero) * sin(theta))),2);
*eta = temp_eta; // stillwater elevation is asumed to be zero. this is eta!
*hu = ( param_C * cos(theta) * temp_eta);
*hv = ( param_C * sin(theta) * temp_eta);
}
class MapTexture {
public:
MapTexture(ID3D11DeviceContext &cxt, ID3D11Texture2D & tex)
: context(cxt), texture(tex)
{
HRESULT hr = context.Map(&texture, 0, D3D11_MAP_READ, 0, &msr);
if (FAILED(hr)) {
throw Coercri::DXError("Map failed", hr);
}
}
~MapTexture()
{
context.Unmap(&texture, 0);
}
// allow access to the pointer / pitch values
D3D11_MAPPED_SUBRESOURCE msr;
private:
ID3D11DeviceContext &context;
ID3D11Texture2D &texture; // must be a staging texture
};
// VS input for water/terrain rendering
struct MeshVertex {
int x, y;
};
// Const buffer for water/terrain rendering
struct MyConstBuffer {
XMMATRIX tex_to_clip; // transforms (tex_x, tex_y, world_z, 1) into clip space
XMFLOAT3 light_dir; // in world space
float ambient;
XMFLOAT3 eye_mult;
float pack6;
XMFLOAT3 eye_trans;
float pack7;
XMFLOAT2 terrain_tex_scale;
float pack8, pack9;
XMMATRIX skybox_mtx;
float world_mult_x, world_mult_y, world_trans_x, world_trans_y;
float world_to_grass_tex_x, world_to_grass_tex_y;
float grass_tex_of_origin_x, grass_tex_of_origin_y;
float fresnel_coeff, fresnel_exponent;
float specular_intensity, specular_exponent;
float refractive_index;
float attenuation_1, attenuation_2;
int nx_plus_1, ny_plus_1;
//float dx, dy;
float deep_r, deep_g, deep_b;
float zScale;
float seaLevel;
int water_shading;
int terrain_shading;
float water_colormap_min;
float water_colormap_max;
float terrain_colormap_min;
float terrain_colormap_max;
int isGridOn; //passing bool as integer.
int is_dissipation_threshold_on; //passing bool as integer.
float dissipation_threshold;
float sqrt_sqrt_epsilon;
float drylandDepthOfInundation;
};
// Const buffer used for the simulation
struct SimConstBuffer {
float two_theta;
float two_over_nx_plus_four;
float two_over_ny_plus_four;
float g;
float half_g;
float Bcoef_g;
float g_over_dx;
float g_over_dy;
float one_over_dx;
float one_over_dy;
float dt;
float dt_old;
float dt_old_old;
float epsilon; // usually dx^4
int nx;
int ny;
float friction; // m s^-2
int isManning;
float seaLevel;
float dissipation_threshold; // For visualization purposes, not simulation.
float whiteWaterDecayRate; // For visualization purposes, not simulation.
};
// Const buffer used for boundary conditions
struct BoundaryConstBuffer {
float PI;
float boundary_epsilon;
int boundary_nx, boundary_ny; // number of cells, including ghost zones
float dx, dy;
int reflect_x, reflect_y;
int northBoundaryWidth, eastBoundaryWidth, westBoundaryWidth, southBoundaryWidth;
float northSeaLevel, eastSeaLevel, westSeaLevel, southSeaLevel;
float eastAmplitude_or_eta, eastPeriod_or_hu, eastTheta_or_hv;
float westAmplitude_or_eta, westPeriod_or_hu, westTheta_or_hv;
float northAmplitude_or_eta, northPeriod_or_hu, northTheta_or_hv;
float southAmplitude_or_eta, southPeriod_or_hu, southTheta_or_hv;
int solid_wall_flag;
int inflow_x_min, inflow_x_max;
float sea_level, inflow_height, inflow_speed;
float g;
float boundary_dt;
float total_time;
float sa1, skx1, sky1, so1;
float sa2, skx2, sky2, so2;
float sa3, skx3, sky3, so3;
float sa4, skx4, sky4, so4;
float sdecay;
};
// Const buffer for setting time integration scheme.
struct TimeIntegrationConstBuffer{
int tScheme;
};
struct WaveParam{
float amplitude, period, theta, phase;
};
struct IrregularWavesDataConstBuffer{
WaveParam wavesWest[MAX_NUM_OF_IRREGULAR_WAVES],
wavesEast[MAX_NUM_OF_IRREGULAR_WAVES],
wavesSouth[MAX_NUM_OF_IRREGULAR_WAVES],
wavesNorth[MAX_NUM_OF_IRREGULAR_WAVES];
int numberOfWavesWest, numberOfWavesEast, numberOfWavesSouth, numberOfWavesNorth; // This is the number of sinewaves to be superposed.
};
struct IrregularWavesColumnRowConstBuffer{
int columnNumber;
int rowNumber;
};
// Const buffer for adding solitary wave.
struct SolitaryWaveConstBuffer{
float g;
float dx;
float dy;
float param_H;
float x_zero;
float y_zero;
float theta;
};
struct LeftMouseConstBuffer {
float scale_x, scale_y;
float bias_x, bias_y;
float two_over_nx_plus_four;
float two_over_ny_plus_four;
float disp_A, disp_B;
};
float CalcEpsilon()
{
const float W = GetSetting("valley_width");
const float L = GetSetting("valley_length");
const float nx = GetSetting("mesh_size_x");
const float ny = GetSetting("mesh_size_y");
const float dx = W / (nx-1);
const float dy = L / (ny-1);
return std::min(initSetting.epsilon, std::pow(std::max(dx, dy), 4));
}
float CalcU(float h, float hu)
{
float epsilon = CalcEpsilon();
float h2 = h*h;
float h4 = h2*h2;
float divide_by_h = sqrt(2.0f) * h / sqrt(h4 + std::max(h4, epsilon));
return divide_by_h * hu;
}
void CompileShader(const char *filename,
const char *entry_point,
const char *profile,
Coercri::ComPtrWrapper<ID3DBlob> &compiled_code)
{
DWORD compile_flags = D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_WARNINGS_ARE_ERRORS;
#ifdef _DEBUG
compile_flags |= D3DCOMPILE_DEBUG;
#endif
ID3DBlob *output_blob = 0;
ID3DBlob *error_blob = 0;
HRESULT hr = D3DX11CompileFromFile(filename,
0, // defines
0, // include handler
entry_point,
profile,
compile_flags,
0, // effect flags (ignored)
0, // thread pump
&output_blob,
&error_blob,
0); // used for async compilation only
compiled_code.reset(output_blob);
Coercri::ComPtrWrapper<ID3DBlob> error_sentinel(error_blob);
if (FAILED(hr)) {
std::string msg = "D3DX11CompileFromFile failed";
if (error_blob) {
OutputDebugStringA((char*)error_blob->GetBufferPointer());
msg += "\n\n";
msg += (char*)error_blob->GetBufferPointer();
}
throw Coercri::DXError(msg, hr);
}
}
void CreateVertexShader(ID3D11Device *device,
const char *filename,
const char *entry_point,
Coercri::ComPtrWrapper<ID3DBlob> &bytecode,
Coercri::ComPtrWrapper<ID3D11VertexShader> &output)
{
const char * vs_profile = "vs_4_0";
CompileShader(filename, entry_point, vs_profile, bytecode);
ID3D11VertexShader *vert_shader = 0;
HRESULT hr = device->CreateVertexShader(bytecode->GetBufferPointer(),
bytecode->GetBufferSize(),
0,
&vert_shader);
if (FAILED(hr)) {
throw Coercri::DXError("CreateVertexShader failed", hr);
}
output.reset(vert_shader);
}
void CreatePixelShader(ID3D11Device *device,
const char *filename,
const char *entry_point,
Coercri::ComPtrWrapper<ID3D11PixelShader> &output)
{
const char * ps_profile = "ps_4_0";
Coercri::ComPtrWrapper<ID3DBlob> bytecode;
CompileShader(filename, entry_point, ps_profile, bytecode);
ID3D11PixelShader *pixel_shader = 0;
HRESULT hr = device->CreatePixelShader(bytecode->GetBufferPointer(),
bytecode->GetBufferSize(),
0,
&pixel_shader);
if (FAILED(hr)) {
throw Coercri::DXError("CreatePixelShader failed", hr);
}
output.reset(pixel_shader);
}
void GetTextureSize(ID3D11Texture2D *tex, int &width, int &height)
{
D3D11_TEXTURE2D_DESC td;
tex->GetDesc(&td);
width = td.Width;
height = td.Height;
}
void GetRenderTargetSize(ID3D11RenderTargetView *view, int &width, int &height)
{
ID3D11Resource *resource;
view->GetResource(&resource);
Coercri::ComPtrWrapper<ID3D11Resource> psResource(resource);
ID3D11Texture2D *texture;
resource->QueryInterface(__uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&texture));
Coercri::ComPtrWrapper<ID3D11Texture2D> psTexture(texture);
GetTextureSize(texture, width, height);
}
void CreateTextureImpl(ID3D11Device *device,
const D3D11_TEXTURE2D_DESC &td,
const D3D11_SUBRESOURCE_DATA *srd,
Coercri::ComPtrWrapper<ID3D11Texture2D> &out_tex,
Coercri::ComPtrWrapper<ID3D11ShaderResourceView> *out_srv,
Coercri::ComPtrWrapper<ID3D11RenderTargetView> *out_rtv)
{
ID3D11Texture2D *pTexture;
HRESULT hr = device->CreateTexture2D(&td, srd, &pTexture);
if (FAILED(hr)) {
throw Coercri::DXError("Failed to create texture", hr);
}
out_tex.reset(pTexture);
if (out_srv) {
D3D11_SHADER_RESOURCE_VIEW_DESC sd;
memset(&sd, 0, sizeof(sd));
sd.Format = td.Format;
sd.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
sd.Texture2D.MipLevels = td.MipLevels;
ID3D11ShaderResourceView *pSRV;
hr = device->CreateShaderResourceView(pTexture, &sd, &pSRV);
if (FAILED(hr)) {
throw Coercri::DXError("Failed to create shader resource view for texture", hr);
}
out_srv->reset(pSRV);
}
if (out_rtv) {
D3D11_RENDER_TARGET_VIEW_DESC rd;
memset(&rd, 0, sizeof(rd));
rd.Format = td.Format;
rd.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
ID3D11RenderTargetView *rtv;
HRESULT hr = device->CreateRenderTargetView(pTexture, &rd, &rtv);
if (FAILED(hr)) {
throw Coercri::DXError("Failed to create render target view", hr);
}
out_rtv->reset(rtv);
}
}
// Creates a texture, with optional initial data,
// and creates optional shader resource view, and optional render target view
void CreateTexture(ID3D11Device * device,
int width,
int height,
const D3D11_SUBRESOURCE_DATA *initial_data,
DXGI_FORMAT format,
bool staging,
Coercri::ComPtrWrapper<ID3D11Texture2D> &out_tex,
Coercri::ComPtrWrapper<ID3D11ShaderResourceView> *out_srv,
Coercri::ComPtrWrapper<ID3D11RenderTargetView> *out_rtv)
{
D3D11_TEXTURE2D_DESC td;
memset(&td, 0, sizeof(td));
td.Width = width;
td.Height = height;
td.MipLevels = 1;
td.ArraySize = 1;
td.Format = format;
td.SampleDesc.Count = 1;
td.Usage = D3D11_USAGE_DEFAULT;
if (out_srv) td.BindFlags = D3D11_BIND_SHADER_RESOURCE;
if (out_rtv) td.BindFlags |= D3D11_BIND_RENDER_TARGET;
if (staging) {
td.Usage = D3D11_USAGE_STAGING;
td.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
}
CreateTextureImpl(device, td, initial_data, out_tex, out_srv, out_rtv);
}
int GetNumMipLevels(int width, int height)
{
int num_levels = 1;
while (width > 1 && height > 1) {
width /= 2;
height /= 2;
++num_levels;
}
return num_levels;
}
int TexIndex(int x, int y, int component, int width)
{
return (y * width + x)*4 + component;
}
// creates an IMMUTABLE texture and auto generates the mip maps.
void CreateTextureWithMips(ID3D11Device *device,
int width,
int height,
const unsigned char * initial_data, // 32-bit RGBA (8-bit per channel)
Coercri::ComPtrWrapper<ID3D11Texture2D> &out_tex,
Coercri::ComPtrWrapper<ID3D11ShaderResourceView> &out_view)
{
const int num_mip_levels = GetNumMipLevels(width, height);
D3D11_TEXTURE2D_DESC td;
memset(&td, 0, sizeof(td));
td.Width = width;
td.Height = height;
td.MipLevels = num_mip_levels;
td.ArraySize = 1;
td.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
td.SampleDesc.Count = 1;
td.Usage = D3D11_USAGE_IMMUTABLE;
td.BindFlags = D3D11_BIND_SHADER_RESOURCE;
boost::scoped_array<D3D11_SUBRESOURCE_DATA> srd(new D3D11_SUBRESOURCE_DATA[num_mip_levels]);
boost::scoped_array<std::vector<unsigned char> > pixels(new std::vector<unsigned char>[num_mip_levels]);
srd[0].pSysMem = initial_data;
srd[0].SysMemPitch = width * 4;
for (int level = 1; level < num_mip_levels; ++level) {
const int prev_width = width;
width = std::max(width/2, 1);
height = std::max(height/2, 1);
pixels[level].resize(width*height*4);
unsigned char * out = &pixels[level][0];
const unsigned char * in;
if (level == 1) {
in = initial_data;
} else {
in = &pixels[level-1][0];
}
for (int y = 0; y < height; ++y) {
for (int x = 0; x < height; ++x) {
for (int component = 0; component < 4; ++component) {
const int in1 = in[TexIndex(2*x, 2*y, component, prev_width)];
const int in2 = in[TexIndex(2*x+1, 2*y, component, prev_width)];
const int in3 = in[TexIndex(2*x, 2*y+1, component, prev_width)];
const int in4 = in[TexIndex(2*x+1, 2*y+1, component, prev_width)];
const int avg = (in1 + in2 + in3 + in4 + 2) / 4;
*out++ = avg;
}
}
}
srd[level].pSysMem = &pixels[level][0];
srd[level].SysMemPitch = width * 4;
}
CreateTextureImpl(device, td, &srd[0], out_tex, &out_view, 0);
}
void CreateSimBuffer(ID3D11Device *device, Coercri::ComPtrWrapper<ID3D11Buffer> &vert_buf,
int i_left, int i_top, int i_right, int i_bottom)
{
// assumes viewport of (nx+4) * (ny+4),
// and renders all pixels from (left,top) (inclusive) to (right,bottom) (exclusive).
// the tex coords sent to the pixel shader are e.g. (0.5f, 0.5f) for the top left pixel in the render target.
const float left = float(i_left);
const float right = float(i_right);
const float top = float(i_top);
const float bottom = float(i_bottom);
const float vertices[12] = {
left, top,
right, top,
left, bottom,
right, top,
right, bottom,
left, bottom
};
// create the vertex buffer
D3D11_BUFFER_DESC bd;
memset(&bd, 0, sizeof(bd));
bd.ByteWidth = 12 * sizeof(float);
bd.Usage = D3D11_USAGE_IMMUTABLE;
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
D3D11_SUBRESOURCE_DATA sd;
memset(&sd, 0, sizeof(sd));
sd.pSysMem = &vertices[0];
ID3D11Buffer *pBuffer;
HRESULT hr = device->CreateBuffer(&bd, &sd, &pBuffer);
if (FAILED(hr)) {
throw Coercri::DXError("Failed to create vertex buffer for the simulation", hr);
}
vert_buf.reset(pBuffer);
}
int RoundUpTo16(int x)
{
return (x + 15) & (~15);
}
void setTimeIntegrationScheme(ID3D11DeviceContext *context, TimeIntegrationScheme *ts, ID3D11Buffer *cbuffer){
TimeIntegrationConstBuffer t_cBuffer;
t_cBuffer.tScheme = (int) (*ts);
context->UpdateSubresource(cbuffer, 0, 0, &t_cBuffer, 0, 0);
ID3D11Buffer *t_cst_buf = cbuffer;
context->PSSetConstantBuffers(1, 1, &t_cst_buf);
}
void st_DumpToFile(ID3D11DeviceContext *context, ID3D11Texture2D *staging, ID3D11Texture2D *tex, int nx, int ny, float total_time)
{ // Can get nx and ny using GetTextureSize(...)
std::string timeAxisFileName = initSetting.logPath + "/" + initSetting.timeAxisFilename +".txt";
std::ofstream timeAxisFile;
if (!timeAxisFile.is_open()) {
timeAxisFile.open(timeAxisFileName.c_str(), std::ios::out | std::ios::app);
}
timeAxisFile << total_time << "\n";
std::string elapsedTimeAxisFileName = initSetting.logPath + "/" + initSetting.timeAxisFilename + "-elapsed.txt";
std::ofstream elapsedTimeAxisFile;
if (!elapsedTimeAxisFile.is_open()) {
elapsedTimeAxisFile.open(elapsedTimeAxisFileName.c_str(), std::ios::out | std::ios::app);
}
elapsedTimeAxisFile << GetSetting("elapsed time") << "\n";
context->CopyResource(staging, tex);
MapTexture m(*context, *staging);
for (int r = 0; r < initSetting.countOfRanges; ++r){
std::string fileName = initSetting.logPath + "/" + initSetting.logRange[r].name +".txt";
std::ofstream myfile;
if (!myfile.is_open()){
myfile.open (fileName.c_str(),std::ios::out | std::ios::app);
}
for (int j = initSetting.logRange[r].bottomLeft.y; j <= initSetting.logRange[r].topRight.y; ++j) {
for (int i = initSetting.logRange[r].bottomLeft.x; i <= initSetting.logRange[r].topRight.x; ++i) {
const char *q = reinterpret_cast<const char*>(m.msr.pData) + j * m.msr.RowPitch;
const float *p = reinterpret_cast<const float*>(q) + i * 4;
myfile << i << "\t" << j << "\t" << p[0] << "\t" << p[1] << "\t" << p[2] << "\t" << p[3] << "\n";
}
}
}
std::string fileName = initSetting.logPath + "/" + initSetting.gaugesFilename +".txt";
std::ofstream myfile;
if (!myfile.is_open()){
myfile.open (fileName.c_str(),std::ios::out | std::ios::app);
}
for (int g = 0; g < initSetting.countOfGauges; ++g){
int i = initSetting.logGauges[g].x;
int j = initSetting.logGauges[g].y;
const char *q = reinterpret_cast<const char*>(m.msr.pData) + j * m.msr.RowPitch;
const float *p = reinterpret_cast<const float*>(q) + i * 4;
myfile << i << "\t" << j << "\t" << p[0] << "\t" << p[1] << "\t" << p[2] << "\t" << p[3] << "\n";
}
}
void st_DumpToFileForDebug(ID3D11DeviceContext *context, ID3D11Texture2D *staging, ID3D11Texture2D *tex, int nx, int ny)
{
context->CopyResource(staging, tex);
MapTexture m(*context, *staging);
std::string fileName = initSetting.exePath + "/" + "debug.txt";
std::ofstream myfile;
if (!myfile.is_open()){
myfile.open (fileName.c_str(),std::ios::out | std::ios::app);
}
for (int j = 0; j < ny + 4; ++j) {
for (int i = 0; i < nx + 4; ++i) {
const char *q = reinterpret_cast<const char*>(m.msr.pData) + j * m.msr.RowPitch;
const float *p = reinterpret_cast<const float*>(q) + i * 4;
myfile << i << "\t" << j << "\t" << p[0] << "\t" << p[1] << "\t" << p[2] << "\t" << p[3] << "\n";
}
}
}
void SeaWaveSettings(char c, float &sa, float &skx, float &sky, float &so)
{
using std::string;
sa = GetSetting(string("sa") + c);
float k = GetSetting(string("sk") + c);
float kdir = GetSetting(string("sk") + c + "_dir");
skx = k * std::cos(kdir);
sky = k * std::sin(kdir);
so = GetSetting(string("so") + c);
}
}
ShallowWaterEngine::ShallowWaterEngine(ID3D11Device *device_,
ID3D11DeviceContext *context_)
: device(device_), context(context_), current_timestep(0), old_timestep(0), old_old_timestep(0), total_time(0)
{
// create D3D objects
createShadersAndInputLayout();
createConstantBuffers();
loadGraphics();
//createBlendState();
loadSkybox(2); // 2 is the default skybox.
setupMousePicking();
remesh(R_MESH);
newTerrainSettings();
//moveCamera(0, 0, .5, 0, 0, 100, 100);
}
void ShallowWaterEngine::remesh(ResetType reset_type)
{
createMeshBuffers();
createSimBuffers();
createTerrainTexture();
fillTerrainTextureLite();
//ST_: I added createShadersAndInputLayout to make all the shaders each time we remesh.
createShadersAndInputLayout();
createSimTextures(reset_type);
myTimestep_count = 0;
initSetting.initialized_timesteps = false;
total_time = 0;
}
int ShallowWaterEngine::st_getCountOfMatrices(int n){ //returns the number of matrices for Cyclic Reduction
int countOfMatrices = 1;
while (n > 1) {
n /= 2;
++countOfMatrices;
}
return countOfMatrices;
}
void ShallowWaterEngine::dumpBathymetryToFile()
{
const int nx = GetIntSetting("mesh_size_x");
const int ny = GetIntSetting("mesh_size_y");
time_t timer = time(0);
struct tm * now = localtime(&timer);
std::ostringstream s;
s << now->tm_year + 1900 << "-" << now->tm_mon + 1 << "-" << now->tm_mday << " " << now->tm_hour << "-" << now->tm_min << "-" << now->tm_sec;
std::string fileName = initSetting.logPath + "/" + s.str() +".cbf";
std::ofstream myfile;
if (!myfile.is_open()){
myfile.open (fileName.c_str(),std::ios::out | std::ios::app);
}
myfile << "[nx] " << nx << "\n";
myfile << "[ny] " << ny << "\n";
myfile << "\n" << "\n";
myfile << "====================================" << "\n";
for (int j = 2; j < ny + 2; ++j) {
for (int i = 2; i < nx + 2; ++i) {
float z = g_bottom[(nx+4) * j + i].BA;
myfile << z << "\t" ;
}
myfile << "\n";
}
myfile.close();
}
void ShallowWaterEngine::dumpInundationToFile(ID3D11DeviceContext *context, ID3D11Texture2D *staging, ID3D11Texture2D *tex)
{
const int nx = GetIntSetting("mesh_size_x");
const int ny = GetIntSetting("mesh_size_y");
context->CopyResource(staging, tex);
MapTexture m(*context, *staging);
time_t timer = time(0);
struct tm * now = localtime(&timer);
std::ostringstream s;
s << now->tm_year + 1900 << "-" << now->tm_mon + 1 << "-" << now->tm_mday << " " << now->tm_hour << "-" << now->tm_min << "-" << now->tm_sec;
std::string fileName = initSetting.logPath + "/" + s.str() +"-inundation.txt";
std::ofstream myfile;
if (!myfile.is_open()){
myfile.open (fileName.c_str(),std::ios::out | std::ios::app);
}
myfile << "[nx] " << nx << "\n";
myfile << "[ny] " << ny << "\n";
myfile << "\n" << "\n";
myfile << "# This file contains the maximum depth of inundation on each point, in meters.";
myfile << "\n" << "\n";
myfile << "====================================" << "\n";
for (int j = 2; j < ny + 2; ++j) {
for (int i = 2; i <= nx + 2; ++i) {
const char *q = reinterpret_cast<const char*>(m.msr.pData) + j * m.msr.RowPitch;
const float *p = reinterpret_cast<const float*>(q) + i * 4;
myfile << p[0] << "\t" ;
}
myfile << "\n";
}
}
void ShallowWaterEngine::newTerrainSettings()
{
fillTerrainTexture();
}
void ShallowWaterEngine::moveCamera(float x, float y, float z, float yaw_, float pitch_, int vw, int vh)
{
pitch = pitch_;
yaw = yaw_;
camera_x = x;
camera_y = y;
camera_z = z;
vp_width = vw;
vp_height = vh;
near_plane_dist = std::min(GetSetting("valley_width")/(GetSetting("mesh_size_x")-1)/2.0f, GetSetting("valley_length")/(GetSetting("mesh_size_y")-1)/2.0f);;
far_plane_dist = 5 * std::max(GetSetting("valley_width"), GetSetting("valley_length"));
const float fov = GetSetting("fov"); // x fov in degrees
const float fov_r = fov / 45.0f * std::atan(1.0f);
xpersp = 1.0f / tan(fov_r * 0.5f);
ypersp = float(vw)/float(vh) * xpersp;
//ypersp = 1.0f / tan(fov_r * 0.5f);
//xpersp = float(vw)/float(vh) * ypersp;
fillConstantBuffers();
}
void ShallowWaterEngine::timestep()
{
///// Allow only a certain number of timesteps for debugging
#if 0
static bool debug_flag = true;
if(timestep_count == 0){
debug_flag = true;
}
if (debug_flag) return;
#endif
/////////////////////////////////////
/*
boost::shared_ptr<Coercri::Timer> timer(new Coercri::GenericTimer);
float tr=GetSetting("time_ratio");
float ta=GetSetting("time_acceleration");
float myAlpha=(tr-ta);
if (myAlpha<1){
myAlpha=abs(myAlpha)*myAlpha;
}
myDelay+=myAlpha*(realworld_timestep-myDelay)/100.0f;
if(myDelay<0){
myDelay=0;
}
*/
//timer->sleepMsec(1000.0f*myDelay);
// Get some resource pointers
ID3D11Buffer * cst_buf = m_psSimConstantBuffer.get();
ID3D11ShaderResourceView * bottom_tex = m_psBottomTextureView.get();
ID3D11ShaderResourceView * new_state_or_h_tex = m_psSimTextureView[1 - sim_idx].get();
ID3D11ShaderResourceView * old_state_tex = m_psSimTextureView[sim_idx].get();
ID3D11ShaderResourceView * old_gradients_tex = m_psSimTextureView[old_index].get();
ID3D11ShaderResourceView * old_old_gradients_tex = m_psSimTextureView[old_old_index].get();
ID3D11ShaderResourceView * predicted_gradients_tex = m_psSimTextureView[predicted_index].get();
ID3D11ShaderResourceView * scratch_gradients_tex = m_psSimTextureView[scratch_index].get();
ID3D11ShaderResourceView * F_G_star_old_gradients_tex = m_psSimTextureView[F_G_star_old_index].get();
ID3D11ShaderResourceView * F_G_star_old_old_gradients_tex = m_psSimTextureView[F_G_star_old_old_index].get();
ID3D11ShaderResourceView * F_G_star_scratch_gradients_tex = m_psSimTextureView[F_G_star_scratch_index].get();
ID3D11ShaderResourceView * F_G_star_predicted_gradients_tex = m_psSimTextureView[F_G_star_predicted_index].get();
ID3D11ShaderResourceView * st_RHS_tex = st_psRHSTextureView.get();
ID3D11ShaderResourceView * u_tex = m_psSimTextureView[2].get();
ID3D11ShaderResourceView * v_tex = m_psSimTextureView[3].get();
ID3D11ShaderResourceView * xflux_tex = m_psSimTextureView[4].get();
ID3D11ShaderResourceView * yflux_tex = m_psSimTextureView[5].get();
ID3D11ShaderResourceView * normal_tex = m_psSimTextureView[6].get(); // {nX, nY, nZ, unused}
ID3D11ShaderResourceView * auxiliary1_tex = m_psAuxiliary1TextureView.get();
ID3D11ShaderResourceView * auxiliary2_tex = m_psAuxiliary2TextureView.get();
ID3D11RenderTargetView * new_state_or_h_target = m_psSimRenderTargetView[1 - sim_idx].get();
ID3D11RenderTargetView * old_state_or_h_target = m_psSimRenderTargetView[sim_idx].get();
ID3D11RenderTargetView * old_gradients_target = m_psSimRenderTargetView[old_index].get();
ID3D11RenderTargetView * old_old_gradients_target = m_psSimRenderTargetView[old_old_index].get();
ID3D11RenderTargetView * scratch_gradients_target = m_psSimRenderTargetView[scratch_index].get();
ID3D11RenderTargetView * predicted_gradients_target = m_psSimRenderTargetView[predicted_index].get();
ID3D11RenderTargetView * F_G_star_old_gradients_target = m_psSimRenderTargetView[F_G_star_old_index].get();
ID3D11RenderTargetView * F_G_star_old_old_gradients_target = m_psSimRenderTargetView[F_G_star_old_old_index].get();
ID3D11RenderTargetView * F_G_star_scratch_gradients_target = m_psSimRenderTargetView[F_G_star_scratch_index].get();
ID3D11RenderTargetView * F_G_star_predicted_gradients_target = m_psSimRenderTargetView[F_G_star_predicted_index].get();
ID3D11RenderTargetView * st_RHS_target = st_psRHSRenderTargetView.get();
ID3D11RenderTargetView * u_target = m_psSimRenderTargetView[2].get();
ID3D11RenderTargetView * v_target = m_psSimRenderTargetView[3].get();
ID3D11RenderTargetView * xflux_target = m_psSimRenderTargetView[4].get();
ID3D11RenderTargetView * yflux_target = m_psSimRenderTargetView[5].get();
ID3D11RenderTargetView * normal_target = m_psSimRenderTargetView[6].get();
ID3D11RenderTargetView * auxiliary1_target = m_psAuxiliary1RenderTargetView.get();
ID3D11RenderTargetView * auxiliary2_target = m_psAuxiliary2RenderTargetView.get();
// Common Settings
context->ClearState();
context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
context->IASetInputLayout(m_psSimInputLayout.get());
context->VSSetShader(m_psSimVertexShader.get(), 0, 0);
D3D11_VIEWPORT vp;
memset(&vp, 0, sizeof(vp));
const int nx = GetIntSetting("mesh_size_x");
const int ny = GetIntSetting("mesh_size_y");
vp.Width = float(nx + 4);
vp.Height = float(ny + 4);
vp.MinDepth = 0;
vp.MaxDepth = 1;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
context->RSSetViewports(1, &vp);
context->VSSetConstantBuffers(0, 1, &cst_buf);
context->PSSetConstantBuffers(0, 1, &cst_buf);
setTimeIntegrationScheme(context,&timeScheme,m_psTimeIntegrationConstantBuffer.get());
ID3D11Buffer *vert_buf;
const UINT stride = 8;
const UINT offset = 0;
ID3D11ShaderResourceView *pNULL = 0;
const int countOfMatricesXdirection = st_getCountOfMatrices(nx);
const int countOfMatricesYdirection = st_getCountOfMatrices(ny);
if (bootstrap_needed) {
// Pass 1
// read: old_state; bottom
// write: h, u, v
vert_buf = m_psSimVertexBuffer11.get();
context->IASetVertexBuffers(0, 1, &vert_buf, &stride, &offset);
ID3D11RenderTargetView * p1_tgt[] = {new_state_or_h_target, u_target, v_target, normal_target, auxiliary2_target};
context->OMSetRenderTargets(5, &p1_tgt[0], 0);
context->PSSetShader(m_psSimPixelShader[0].get(), 0, 0);
context->PSSetShaderResources(0, 1, &old_state_tex);
context->PSSetShaderResources(1, 1, &bottom_tex);
context->PSSetShaderResources(3, 1, &auxiliary1_tex);
context->Draw(6, 0);
bootstrap_needed = false;
}
// Pass 2
// read: h, u, v
// write: xflux, yflux
// xflux and yflux are used as scratch texture elsewhere. Here we reset them to (0,0,0,0). Note that D1x[0] and D1y[0] are never used in this code, so they are all (0,0,0,0).
context->CopyResource(m_psSimTexture[4].get(),
st_psTriDigTexture_D1x[0].get());
context->CopyResource(m_psSimTexture[5].get(),
st_psTriDigTexture_D1y[0].get());
vert_buf = m_psSimVertexBuffer10.get();
context->IASetVertexBuffers(0, 1, &vert_buf, &stride, &offset);
context->PSSetShaderResources(0, 1, &new_state_or_h_tex);
context->PSSetShaderResources(1, 1, &u_tex);
context->PSSetShaderResources(2, 1, &v_tex);
context->PSSetShaderResources(3, 1, &normal_tex);
context->PSSetShaderResources(4, 1, &auxiliary2_tex);
ID3D11RenderTargetView * p2_tgt[] = {xflux_target, yflux_target, auxiliary1_target, 0};
context->OMSetRenderTargets(4, &p2_tgt[0], 0);
context->PSSetShader(m_psSimPixelShader[1].get(), 0, 0);
context->Draw(6, 0);