From 0f66037da0dfc085a0abbb44a074cdb498d3d066 Mon Sep 17 00:00:00 2001 From: saschawillems Date: Sat, 18 Jun 2016 19:24:37 +0200 Subject: [PATCH] Started work on dynamic terrain tessellation example --- .../terraintessellation/generate-spirv.bat | 7 + .../terraintessellation/skysphere.frag | 13 + .../terraintessellation/skysphere.frag.spv | Bin 0 -> 796 bytes .../terraintessellation/skysphere.vert | 23 + .../terraintessellation/skysphere.vert.spv | Bin 0 -> 1208 bytes data/shaders/terraintessellation/terrain.frag | 55 ++ .../terraintessellation/terrain.frag.spv | Bin 0 -> 2944 bytes data/shaders/terraintessellation/terrain.tesc | 86 ++ .../terraintessellation/terrain.tesc.spv | Bin 0 -> 6464 bytes data/shaders/terraintessellation/terrain.tese | 51 + .../terraintessellation/terrain.tese.spv | Bin 0 -> 4696 bytes data/shaders/terraintessellation/terrain.vert | 23 + .../terraintessellation/terrain.vert.spv | Bin 0 -> 1028 bytes terraintessellation/terraintessellation.cpp | 874 ++++++++++++++++++ .../terraintessellation.vcxproj | 99 ++ .../terraintessellation.vcxproj.filters | 42 + vulkanExamples.sln | 12 + 17 files changed, 1285 insertions(+) create mode 100644 data/shaders/terraintessellation/generate-spirv.bat create mode 100644 data/shaders/terraintessellation/skysphere.frag create mode 100644 data/shaders/terraintessellation/skysphere.frag.spv create mode 100644 data/shaders/terraintessellation/skysphere.vert create mode 100644 data/shaders/terraintessellation/skysphere.vert.spv create mode 100644 data/shaders/terraintessellation/terrain.frag create mode 100644 data/shaders/terraintessellation/terrain.frag.spv create mode 100644 data/shaders/terraintessellation/terrain.tesc create mode 100644 data/shaders/terraintessellation/terrain.tesc.spv create mode 100644 data/shaders/terraintessellation/terrain.tese create mode 100644 data/shaders/terraintessellation/terrain.tese.spv create mode 100644 data/shaders/terraintessellation/terrain.vert create mode 100644 data/shaders/terraintessellation/terrain.vert.spv create mode 100644 terraintessellation/terraintessellation.cpp create mode 100644 terraintessellation/terraintessellation.vcxproj create mode 100644 terraintessellation/terraintessellation.vcxproj.filters diff --git a/data/shaders/terraintessellation/generate-spirv.bat b/data/shaders/terraintessellation/generate-spirv.bat new file mode 100644 index 00000000..79ab91c1 --- /dev/null +++ b/data/shaders/terraintessellation/generate-spirv.bat @@ -0,0 +1,7 @@ +glslangvalidator -V terrain.vert -o terrain.vert.spv +glslangvalidator -V terrain.frag -o terrain.frag.spv +glslangvalidator -V skysphere.vert -o skysphere.vert.spv +glslangvalidator -V skysphere.frag -o skysphere.frag.spv +glslangvalidator -V terrain.tesc -o terrain.tesc.spv +glslangvalidator -V terrain.tese -o terrain.tese.spv + diff --git a/data/shaders/terraintessellation/skysphere.frag b/data/shaders/terraintessellation/skysphere.frag new file mode 100644 index 00000000..d9c9f92d --- /dev/null +++ b/data/shaders/terraintessellation/skysphere.frag @@ -0,0 +1,13 @@ +#version 450 core + +layout (location = 0) in vec2 inUV; + +layout (set = 0, binding = 1) uniform sampler2D samplerColorMap; + +layout (location = 0) out vec4 outFragColor; + +void main(void) +{ + vec4 color = texture(samplerColorMap, inUV); + outFragColor = vec4(color.rgb, 1.0); +} diff --git a/data/shaders/terraintessellation/skysphere.frag.spv b/data/shaders/terraintessellation/skysphere.frag.spv new file mode 100644 index 0000000000000000000000000000000000000000..b09de25bc22b3db044f6f995199416295ed9d36d GIT binary patch literal 796 zcmYk3%}WAN6vb~&qn71ImS$F{Edyy$5k$2Ja${6PwH_)$P)A1F`?vX5wFx@E*F5ma z^}ciNxnJ{w%u&v4MZdfq+W)CoM%b)iS?7EG=YDrO`{5XXiPLZSc-&OIf&%Es-$+Gpmnmik4*g2<)MGC6WqE4BqX)AS9Pw>=UWs{# zgV_;|dNq0Kfsci`H)Lk>n{$0x`mh@Z&5xK+o?7h6dr|vJn3;<*<^?m;mW+Acl!dM; zLj!-UisZwgCtjDqJ*Yaf?WP<&hrO8T$-TPSp6+Nko@?q3ht_lZDM#+3I??MuMm~Dt P?9EJkA7a0%a3T8xb5JJD literal 0 HcmV?d00001 diff --git a/data/shaders/terraintessellation/skysphere.vert b/data/shaders/terraintessellation/skysphere.vert new file mode 100644 index 00000000..e5bf123b --- /dev/null +++ b/data/shaders/terraintessellation/skysphere.vert @@ -0,0 +1,23 @@ +#version 450 core + +layout (location = 0) in vec3 inPos; +layout (location = 2) in vec2 inUV; + +layout (location = 0) out vec2 outUV; + +layout (set = 0, binding = 0) uniform UBO +{ + mat4 mvp; +} ubo; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main(void) +{ + gl_Position = ubo.mvp * vec4(inPos, 1.0); + outUV = inUV; + outUV.t = 1.0 - outUV.t; +} diff --git a/data/shaders/terraintessellation/skysphere.vert.spv b/data/shaders/terraintessellation/skysphere.vert.spv new file mode 100644 index 0000000000000000000000000000000000000000..de16dbaf696ecfd7adcddfb9bcd45bac3d207103 GIT binary patch literal 1208 zcmYk4%We}v5JfBYI0OO-A>_d;jAPz`hy@@d1PC_HA`(F;*&+}Y8j08_aS%%+zJOoi ztJolMPEU_>|bThu^-Yz4OE;A4jRDda5C1@M=)o=w!Tqkg+o(E zUF+a;cxyGay{DYD7xC(mv$oi~%elXlWAoK{5wA{ryT5|Bue|5Q&PGlx=B{HAKVF*e zOgyU|>y>zOntom4x^`VpygA{D=n-4H#Ox<_)^g6`7QVz>_7~sA>N7>$A-29fpYR{p z*SWal|G@a)yyETMFJR8Yc|Ir8IV@xHV(-0%dFQvBvF@eJ;U?VW%&DWvyOKFI>@g8% zauxHu`R+TrU(|K)8fI^E)aNX(WBv>3d%+FF=Bcg3-^84cd(KhpS?6#UlXE`itNk7( b|1;lZi&zcv&AI!;%{l9e&HKxgpJM+2)0H=e literal 0 HcmV?d00001 diff --git a/data/shaders/terraintessellation/terrain.frag b/data/shaders/terraintessellation/terrain.frag new file mode 100644 index 00000000..4d20d36e --- /dev/null +++ b/data/shaders/terraintessellation/terrain.frag @@ -0,0 +1,55 @@ +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (set = 0, binding = 1) uniform sampler2D displacementMap; +layout (set = 0, binding = 2) uniform sampler2DArray terrainLayers; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inEyePos; +layout (location = 3) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +vec4 sampleTerrainLayer() +{ + // Define some layer ranges for sampling depending on terrain height + vec2 layers[4]; + layers[0] = vec2(0.0, 5.0); + layers[1] = vec2(5.0, 50.0); + layers[2] = vec2(50.0, 120.0); + layers[3] = vec2(120.0, 255.0); + + vec3 color = vec3(0.0); + + // Get height from displacement map + float height = textureLod(displacementMap, inUV, 0.0).r * 255.0; + + for (int i = 0; i < 4; i++) + { + float range = layers[i].y - layers[i].x; + float weight = (range - abs(height - layers[i].y)) / range; + weight = max(0.05, weight); + color += weight * texture(terrainLayers, vec3(inUV * 16.0, i)).rgb; + } + + return vec4(color, 1.0); +} + +void main() +{ +/* todo: no lighting yet + vec3 N = normalize(inNormal); + vec3 L = normalize(vec3(1.0)); + vec3 Eye = normalize(inEyePos); + vec3 Reflected = normalize(reflect(-inLightVec, inNormal)); + + vec4 IAmbient = vec4(vec3(0.15), 1.0); + vec4 IDiffuse = vec4(1.0) * max(dot(inNormal, inLightVec), 0.0); + + outFragColor = vec4((IAmbient + IDiffuse) * vec4(texture(terrainLayers, vec3(inUV, 0.0)).rgb, 1.0)); +*/ + outFragColor = sampleTerrainLayer(); +} \ No newline at end of file diff --git a/data/shaders/terraintessellation/terrain.frag.spv b/data/shaders/terraintessellation/terrain.frag.spv new file mode 100644 index 0000000000000000000000000000000000000000..e4dbed5bc5641b58f299e5d5d5ee772494e5f880 GIT binary patch literal 2944 zcmZ9M+j3Mz6oxxT2}BM80R%Mx3@9;13d+^{+#()oZ$UPxq0hLg?aeOZX~mu3e!U9>TWJ zpUK(ct>SpAy)-^~YQl)^p(hJ8W=Gf>dXZu^snm2B^ch$OUw|*cPI8Q)7+Mb%LimXd zdc#1NEtU#5r%SE0ku;NbT57E%OKG!IzyBaDw_E>@!Bwd(m#Rr^c`aE^OOq!j8cF$K z=wqkO9{Q*>K#f+i+Nh?t(`J+AiphG~Jf6kw#8;KFzqzCEa=lt_BIPe3SJKMzN?YC^ zUV$%FT8(N_PFK@f`)bn2;yi1mHot&?_k=g(ncf=;$R>@ZIe!=VsAJC$;q8vjXeF!V z?CNXn%gtnYCT|IQUpCK5?OMILnp6qNY|gh*yR@Fp)lJWA&YQ#9{6bm|VV3jQ|6v1I zk&mGJ8_GS$^BvsYI^*TW`@0!$kH)*?{??t`zT`39p5)$~-B`7cWH(_mW(d6>+c4P2 ze%=$gzo~IsklOTZL+W#nz3@TgFmRp7`P1m;9^(IYq&eD#;X9D-rQQ5pnSFB>=F6V} zF1fXKXY4<|C*wa{9Ao0{y*H21ZjB+NHT1#d&n^!5*e~A-9`11L8jRKM#KSxj1!zug3f6+Vs1gl%C@rcH^x3fk7;7_9^$h zxZ-b6%GgFB^6WzyHZGXIhR@mCyZLh8SNuIbN4E!m2mSK(+!nd-&6vo2Z}QXJPw$U2 zaJlF2So)A>v0C#H@LPEvuXW{rk$nc3Z;XDI@6i0MNNf3){FcVvy*r~F+&kj8H2VFG z{6wOV>t2IfS9@o_*WvnN-8ppk(mu$EJkt%(1$;C5W9&_I`_LczxP@+C z-{t4Hjc%NF&*5Fx7ULJtwGDDxtaS%i%NfrD{V`8p%)5(jp8Ov2Bj7hi?mhe%On~p{ zL%s;K`Q0(b`;Y) 0.0) + { + gl_TessLevelOuter[0] = screenSpaceTessFactor(gl_in[3].gl_Position, gl_in[0].gl_Position); + gl_TessLevelOuter[1] = screenSpaceTessFactor(gl_in[0].gl_Position, gl_in[1].gl_Position); + gl_TessLevelOuter[2] = screenSpaceTessFactor(gl_in[1].gl_Position, gl_in[2].gl_Position); + gl_TessLevelOuter[3] = screenSpaceTessFactor(gl_in[2].gl_Position, gl_in[3].gl_Position); + gl_TessLevelInner[0] = mix(gl_TessLevelOuter[0], gl_TessLevelOuter[3], 0.5); + gl_TessLevelInner[1] = mix(gl_TessLevelOuter[2], gl_TessLevelOuter[1], 0.5); + } + else + { + // Tessellation factor can be set to zero by example + // to demonstrate a simple passthrough + gl_TessLevelInner[0] = 1.0; + gl_TessLevelInner[1] = 1.0; + gl_TessLevelOuter[0] = 1.0; + gl_TessLevelOuter[1] = 1.0; + gl_TessLevelOuter[2] = 1.0; + gl_TessLevelOuter[3] = 1.0; + } + } + + gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position; + outNormal[gl_InvocationID] = inNormal[gl_InvocationID]; + outUV[gl_InvocationID] = inUV[gl_InvocationID]; +} diff --git a/data/shaders/terraintessellation/terrain.tesc.spv b/data/shaders/terraintessellation/terrain.tesc.spv new file mode 100644 index 0000000000000000000000000000000000000000..da911f5f6dd1da07f485b59d4f760d7760112ffc GIT binary patch literal 6464 zcmZ{miJw(v8OIOIFo2L~f`}m9ffhTv5!xFsGl${AoqMO5J5yO1WQb*% zwrXXOMT_lw*^1d>Wo4F?6zdqX|1HSmvvg!gMXH-+qiY(;?dT?;-wcX0cIx`QD)1s86ekg zWT;weuw=u?wa9+tlgK^DeaQXDL&y>26e5f{6LIb0-$d5CN!FcBrDor%D_8f8=EK#I zYAf#>-BlgPNBWvOcIW-A(Z~8=sx=1t>ea^JSamS(TYCPI;cEY$Y*MNbeND~Vm@$ESiZd`+@7vHAZ}t}rY*-6Fxi}Z_ z&V6G(p4T^zwepb^vyTB^gDgG(_6QEKif`<|w{+mQci?w-;M+U!9Ub`4 zWANnS{?O0Sd2MJkj?U{azS#b6Uh+QL%JY&x(Y&;sXkOY*G%xQqb(&+`2JeUW9I&Z5 zGE}Xj%X#l>jiVGyckvy-Z`=05r@Qzj)EWiE-jh8FKUy6cuID4`bI(6`J#le|JiqJl z47?ERQ|9>K@trvq=ibY4V&hgK5hr&nuASex=(iUMKj$HLbBXiL$$19C&w6sVmN@U2 z+(Bd=lXVZ)SjYYkr}^4_b`|F`>iUh>&u^>w4zv2m`2^QlSHI4>a-DU<&v|&h;+=~Vc1@SRXyatIp z_OS`^-q^=xR{L;o(MJ{C+S+%pY8QunC%UtXzILN$+1?d__q6e9D#X0=`2W?c)|4~PYgpZbym`deCNAP%3pTIuds&T_n~%1SHO|CdbS2_m zhh9O9yN*@gHrJiK9^IVs))nthobkQr*CY03pEo3%wZv~pHhT&G+t8h9)W0)f>wg?w zUpeDH!D?=K>x=y!$hoh>teyKZ&)x9aVt(I2H%8t(;(HQjoqLmRF5`d1>KTjpA1AxK z@nXLf=G6bEtop~?euh2)k=I}Bw?xi*4}XlWvUlA7M3@cn;ryzp(lq^e;bw=i>cW4Eh=Wx8x*eJ@KQ7 zyO7&95xqNM>--bOJE*VUu>**+4}4<>_V1vw-QU16_V1uFzP$tA(SZ*odfWpm^Xv98RM+Q z7gNW6Z$hRc=F;ZgyvH{qesj!YoLJwe^;Y!b)p{GeHe-B`;)r<%x-kooa)0jxYcs}o zEsp-)g>HZ5(iZ*Qif(`AGES^-)Orv4@oK#nUYjwVBXPvM58asCkaBb%!kp9={yr3fzxKpAy#qp_fd5F zGncmL?_=opXD;K!`iA{e=-OirJ?NiCL5xsR`c?IX^U*qDED zFTJzgPw#2e{2F?>Z?S(Hg#GKu9{I#&`!~QbU-vC8+rOFY5ic&=zm@E9zQkqwx05~I zuULC|KkiFB#_IlDonJ5Ocah-|{$9dy7QYYnEXv0jnT-AeM4Nv1vi=b9x7U2}j^*@= zT0cQA*ZO(F&hi2DUm*7*^2T_Ueu>EI^C0W5koypGIZv@ZQRBDhgXmo>!t{D+fu5#n#3XWskfGZk5e-xSu9O8PW(=lwX=_zgT6 z-T8@Uvd$`DSQxIzgJ{8@%`{+^o;}L!2Z%W*0iT7T(KYNmk9H*m~ zbIt~vb2=H__Zf(HYz?BX_8Zbn&P3Nf2Qjz%lXJEUS)Yhh5YM~y=CM8rk&pUMMz^P1 zQom0@*GJx*&PXnDJ`KHs#Q8Mm*@%4PJO|x4v3qzrVsBTZzRyEng7^e?KDwNH4el9< zo5;F_c{t;xi22N6j6T<;-Y-D6wmz|+3(@UQoBQz{%f)^!La!j@{ag%|kNrFoy}Y00 z;PQT+1@7F>C5bEV=hDQL_p<`deC9AlpEyq|(XFjd>}M6a{jEgYk7rcQ{dmULBJR=i z67#<-@v)!FlTXZa9ax{Tc*dOfdPIMHVt#T_Zv(nLlJJ7xrkyCtpC;Q2#?J7jOIU;@=dOLn< zF@x=3Ieoj4Nr>;T3yGQN6Foi;y@Hf`d_Gt{YP_Ps^ThQk3#Qy-ge{nnj literal 0 HcmV?d00001 diff --git a/data/shaders/terraintessellation/terrain.tese b/data/shaders/terraintessellation/terrain.tese new file mode 100644 index 00000000..7f6397bd --- /dev/null +++ b/data/shaders/terraintessellation/terrain.tese @@ -0,0 +1,51 @@ +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (set = 0, binding = 0) uniform UBO +{ + mat4 projection; + mat4 modelview; + vec4 lightPos; + float displacementFactor; + float tessellationFalloff; +} ubo; + +layout (set = 0, binding = 1) uniform sampler2D displacementMap; + +layout(quads, equal_spacing, cw) in; + +layout (location = 0) in vec3 inNormal[]; +layout (location = 1) in vec2 inUV[]; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec2 outUV; +layout (location = 2) out vec3 outEyePos; +layout (location = 3) out vec3 outLightVec; + +void main() +{ + // Interpolate UV coordinates + vec2 uv1 = mix(inUV[0], inUV[1], gl_TessCoord.x); + vec2 uv2 = mix(inUV[3], inUV[2], gl_TessCoord.x); + outUV = mix(uv1, uv2, gl_TessCoord.y); + + // Interpolate normals + vec3 nm1 = mix(inNormal[0], inNormal[1], gl_TessCoord.x); + vec3 nm2 = mix(inNormal[3], inNormal[2], gl_TessCoord.x); + outNormal = mix(nm1, nm2, gl_TessCoord.y); + + // Interpolate positions + vec4 pos1 = mix(gl_in[0].gl_Position, gl_in[1].gl_Position, gl_TessCoord.x); + vec4 pos2 = mix(gl_in[3].gl_Position, gl_in[2].gl_Position, gl_TessCoord.x); + vec4 pos = mix(pos1, pos2, gl_TessCoord.y); + // Displace + pos.y -= textureLod(displacementMap, outUV, 0.0).r * ubo.displacementFactor; + // Perspective projection + gl_Position = ubo.projection * ubo.modelview * pos; + + // Calculate vectors for lighting based on tessellated position + outEyePos = -pos.xyz; + outLightVec = normalize(ubo.lightPos.xyz + outEyePos); +} \ No newline at end of file diff --git a/data/shaders/terraintessellation/terrain.tese.spv b/data/shaders/terraintessellation/terrain.tese.spv new file mode 100644 index 0000000000000000000000000000000000000000..4c5fa6f9b66e65f1fb45e463099340949450828b GIT binary patch literal 4696 zcmZ{mXLnRp6oxNpfS{cbCYBa|K=rsB%SYuq$lacv|XCFrMw-a zU62frpCsFc_YSXawZ~VlTfYW3xi0HvwIo@D*F)O}Cd<`24NQ_O0}p~Hz)RpD_ySx4 zKY{D1VV_$Hw)KKH*2_O@|4E=PnU9XKp*@?%TIp1|S#GCet)u1fv^mx|{AOBdxBi<$ zs9K*GtCi~$)8&bDY~9*5Q{~EANk5f}TKgGeK4VPJJd(xKUajvRrNJM_<}pzl+n2Ul zn;VVhc!%#zN*L2KYqLJivoYPyI$3W$etpt<{n`Ah^_`98WVr?n)0+%sar^dXYeV1J z1oiDBKGkSF(#ao46oZD5v^knK+v#!n0sdto^H`%*ZC4w0*tr?+TH2>kt+)49Po|wd zotSG%Y;&zT^?bF}F4rsRY(LL~vFTcEHl`-`4?f#q{R%!B*V1Hja&q|C1IY~bc(pZE zD_7FVwBFuPp2~9GgWtbt7a0SIw%=5<;qEDYmRI{^V?3?RRMTVFk+1Grb>e7ygn=@C zURFoV#qqY5EA2+pex11c-DU&RTCMCzTg$atZ8_I{8xiZ7=UASNyMSN#gV>## zeY5AHAI^GlPFC1~ugLMB@m|Pv`dOpcPv3sef#@gqZ@*4`wV8JsM4oeyJ6GVGkK9Gz zywn!+@*EZCr9TM#tQlvhxTbM_ifbC@rnshYUW#iPd9L9l#&G{ai)TdNIV^^iAH>tw zz8PzPwgi^a-}TTpR>Gf0D<^Kkzb51Pk8f4(tEB{P$6rWmZinm3&fOe*`3=N9hn`V6 z>n)-!<-Yaw-A6yizk$|VYesxY&Z*bmD)l-a^ZgAmU*7Tby#sQg_f~8_^KYXyW{s#n zh;6;_S7OI{tjc5RvA(`{D)L>Qhk-S%zmC>i^|(Hd<#w#k3FWG~wcF&{Z?WJ`*dB@vNYg|psu|{d5k1=81%e2Nq*8yxb$g4}=cRzF;%57^c z<5$y1*l~;(zwmEk7HtCNsdG9{lC!@4OwPIP);f{gUaO}lEK5}ltHfITloSU)b&GEk74!o1zLvvjBJAnKMIo9>fk`oJ= zt=yep4poO`h4L+icR-CFO1lMk); zW6O!q`T%xlbzJM3r`8g!@fh6q;6BG*@4m5uu+4L?i+Qi(8w=fI*xl>*2Auo|x7ONa@J1KZZtO4! z?P{>T`D*ulG9H@7vDGvPikebT`D(Aw8h5{)=Ol1G;n%Uv2`vq5wLA>W8K9j4@}cGJoRbfPmL^d&P;4tx&|R$o& akzbg<*}r4kZwt5r)bbOp{NF^L0RI4Pe15F} literal 0 HcmV?d00001 diff --git a/data/shaders/terraintessellation/terrain.vert b/data/shaders/terraintessellation/terrain.vert new file mode 100644 index 00000000..3dc0d169 --- /dev/null +++ b/data/shaders/terraintessellation/terrain.vert @@ -0,0 +1,23 @@ +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec3 inPos; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec2 inUV; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec2 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main(void) +{ + gl_Position = vec4(inPos.xyz, 1.0); + outUV = inUV; + outNormal = inNormal; +} \ No newline at end of file diff --git a/data/shaders/terraintessellation/terrain.vert.spv b/data/shaders/terraintessellation/terrain.vert.spv new file mode 100644 index 0000000000000000000000000000000000000000..3dad2d6170c9e5a17343bef8e4b19f8229ad474d GIT binary patch literal 1028 zcmY+BOH1TX5QWQb<8yqC&zbQNbt#ApDuSr!rf1O%&WLV9)X+xTM3M+D{cZj#H-hK8 zeIt59QTLoWw_a&B)(6e{^bOgX_0E(vgv~~6!1-4Dti4%Q*PGirTPVh@>4az|q~i3; z?&CD$J|dft{gf@rR%D^9sjngbqKEx9Y^`>5{Qo2>lZUv7t0XFK;_IY{^2^)gsw%%~ z6iTyB)Qz*wW86ui?cZAu@ztFL%JjK*pq__RqtlH}lj0&Ns^m#fY>($oEHBe4%`?4k zx_;rwMc-+ru*b}hKUU`#9y3pxIVgSLW>frcUfjoBrwQDwY4$-T7W;{p!Q%%dfvohYJC(d4um6x5&%lHrM`cR#K(bEUB aF3Fga82bR%J+A5=%7`&5_)Qb;$=(6U$w@f? literal 0 HcmV?d00001 diff --git a/terraintessellation/terraintessellation.cpp b/terraintessellation/terraintessellation.cpp new file mode 100644 index 00000000..876544c1 --- /dev/null +++ b/terraintessellation/terraintessellation.cpp @@ -0,0 +1,874 @@ +/* +* Vulkan Example - Dynamic terrain tessellation +* +* Copyright (C) 2016 by Sascha Willems - www.saschawillems.de +* +* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) +*/ + +#include +#include +#include +#include +#include + +#define GLM_FORCE_RADIANS +#define GLM_FORCE_DEPTH_ZERO_TO_ONE +#include +#include +#include + +#include +#include "vulkanexamplebase.h" +#include "vulkanMeshLoader.hpp" + +#define VERTEX_BUFFER_BIND_ID 0 +#define ENABLE_VALIDATION false + +// Vertex layout for this example +std::vector vertexLayout = +{ + vkMeshLoader::VERTEX_LAYOUT_POSITION, + vkMeshLoader::VERTEX_LAYOUT_NORMAL, + vkMeshLoader::VERTEX_LAYOUT_UV +}; + +class VulkanExample : public VulkanExampleBase +{ +private: + struct { + vkTools::VulkanTexture heightMap; + vkTools::VulkanTexture skySphere; + vkTools::VulkanTexture terrainArray; + } textures; +public: + bool wireframe = true; + bool tessellation = true; + + struct { + VkPipelineVertexInputStateCreateInfo inputState; + std::vector bindingDescriptions; + std::vector attributeDescriptions; + } vertices; + + struct { + vkMeshLoader::MeshBuffer object; + vkMeshLoader::MeshBuffer skysphere; + } meshes; + + struct { + vkTools::UniformData terrainTessellation; + vkTools::UniformData skysphereVertex; + } uniformData; + + // Shared values for tessellation control and evaluation stages + struct { + glm::mat4 projection; + glm::mat4 modelview; + glm::vec4 lightPos = glm::vec4(0.0f, -2.0f, 0.0f, 0.0f); + float displacementFactor = 16.0f; + float tessellationFactor = 0.75f; + glm::vec2 viewportDim; + // Desired size of tessellated quad patch edge + float tessellatedEdgeSize = 20.0f; + } uboTess; + + // Skysphere vertex shader stage + struct { + glm::mat4 mvp; + } uboVS; + + struct { + VkPipeline terrain; + VkPipeline wireframe; + VkPipeline skysphere; + } pipelines; + + struct { + VkDescriptorSetLayout terrain; + VkDescriptorSetLayout skysphere; + } descriptorSetLayouts; + + struct { + VkPipelineLayout terrain; + VkPipelineLayout skysphere; + } pipelineLayouts; + + struct { + VkDescriptorSet terrain; + VkDescriptorSet skysphere; + } descriptorSets; + + VulkanExample() : VulkanExampleBase(ENABLE_VALIDATION) + { + enableTextOverlay = true; + title = "Vulkan Example - Dynamic terrain tessellation"; + camera.type = Camera::CameraType::firtsperson; + camera.setPerspective(60.0f, (float)width / (float)height, 0.1f, 512.0f); + camera.setRotation(glm::vec3(-22.0f, 135.0f, 0.6f)); + camera.setTranslation(glm::vec3(0.0f, 30.0f, 0.0f)); +// camera.setTranslation(glm::vec3(36.5f, 13.25f, 36.2f)); + camera.movementSpeed = 10.0f; + timerSpeed *= 15.0f; + // Support for tessellation shaders is optional, so check first + //if (!deviceFeatures.tessellationShader) + //{ + // vkTools::exitFatal("Selected GPU does not support tessellation shaders!", "Feature not supported"); + //} + } + + ~VulkanExample() + { + // Clean up used Vulkan resources + // Note : Inherited destructor cleans up resources stored in base class + vkDestroyPipeline(device, pipelines.terrain, nullptr); + vkDestroyPipeline(device, pipelines.wireframe, nullptr); + + vkDestroyPipelineLayout(device, pipelineLayouts.skysphere, nullptr); + vkDestroyPipelineLayout(device, pipelineLayouts.terrain, nullptr); + + vkDestroyDescriptorSetLayout(device, descriptorSetLayouts.terrain, nullptr); + vkDestroyDescriptorSetLayout(device, descriptorSetLayouts.skysphere, nullptr); + + vkMeshLoader::freeMeshBufferResources(device, &meshes.object); + + vkDestroyBuffer(device, uniformData.terrainTessellation.buffer, nullptr); + vkFreeMemory(device, uniformData.terrainTessellation.memory, nullptr); + + vkDestroyBuffer(device, uniformData.skysphereVertex.buffer, nullptr); + vkFreeMemory(device, uniformData.skysphereVertex.memory, nullptr); + + textureLoader->destroyTexture(textures.heightMap); + textureLoader->destroyTexture(textures.skySphere); + textureLoader->destroyTexture(textures.terrainArray); + } + + void loadTextures() + { + textureLoader->loadTexture(getAssetPath() + "textures/skysphere_bc3.ktx", VK_FORMAT_BC3_UNORM_BLOCK, &textures.skySphere); + textureLoader->loadTexture(getAssetPath() + "textures/terrain_desert_heightmap.ktx", VK_FORMAT_R8G8B8A8_UNORM, &textures.heightMap); + + textureLoader->loadTextureArray(getAssetPath() + "textures/terrain_array_bc3.ktx", VK_FORMAT_BC3_UNORM_BLOCK, &textures.terrainArray); + + VkSamplerCreateInfo samplerInfo = vkTools::initializers::samplerCreateInfo(); + + // Setup a mirroring sampler for the height map + vkDestroySampler(device, textures.heightMap.sampler, nullptr); + samplerInfo.magFilter = VK_FILTER_LINEAR; + samplerInfo.minFilter = VK_FILTER_LINEAR; + samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; + samplerInfo.addressModeV = samplerInfo.addressModeU; + samplerInfo.addressModeW = samplerInfo.addressModeU; + samplerInfo.compareOp = VK_COMPARE_OP_NEVER; + samplerInfo.minLod = 0.0f; + samplerInfo.maxLod = (float)textures.heightMap.mipLevels; + samplerInfo.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; + VK_CHECK_RESULT(vkCreateSampler(device, &samplerInfo, nullptr, &textures.heightMap.sampler)); + textures.heightMap.descriptor.sampler = textures.heightMap.sampler; + + // Setup a repeating sampler for the terrain texture layers + vkDestroySampler(device, textures.terrainArray.sampler, nullptr); + samplerInfo = vkTools::initializers::samplerCreateInfo(); + samplerInfo.magFilter = VK_FILTER_LINEAR; + samplerInfo.minFilter = VK_FILTER_LINEAR; + samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; + samplerInfo.addressModeV = samplerInfo.addressModeU; + samplerInfo.addressModeW = samplerInfo.addressModeU; + samplerInfo.compareOp = VK_COMPARE_OP_NEVER; + samplerInfo.minLod = 0.0f; + samplerInfo.maxLod = (float)textures.terrainArray.mipLevels; + samplerInfo.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; + if (deviceFeatures.samplerAnisotropy) + { + samplerInfo.maxAnisotropy = 4.0f; + samplerInfo.anisotropyEnable = VK_TRUE; + } + VK_CHECK_RESULT(vkCreateSampler(device, &samplerInfo, nullptr, &textures.terrainArray.sampler)); + textures.terrainArray.descriptor.sampler = textures.terrainArray.sampler; + } + + void reBuildCommandBuffers() + { + if (!checkCommandBuffers()) + { + destroyCommandBuffers(); + createCommandBuffers(); + } + buildCommandBuffers(); + } + + void buildCommandBuffers() + { + VkCommandBufferBeginInfo cmdBufInfo = vkTools::initializers::commandBufferBeginInfo(); + + VkClearValue clearValues[2]; + clearValues[0].color = defaultClearColor; + clearValues[0].color = { {0.2f, 0.2f, 0.2f, 0.0f} }; + clearValues[1].depthStencil = { 1.0f, 0 }; + + VkRenderPassBeginInfo renderPassBeginInfo = vkTools::initializers::renderPassBeginInfo(); + renderPassBeginInfo.renderPass = renderPass; + renderPassBeginInfo.renderArea.offset.x = 0; + renderPassBeginInfo.renderArea.offset.y = 0; + renderPassBeginInfo.renderArea.extent.width = width; + renderPassBeginInfo.renderArea.extent.height = height; + renderPassBeginInfo.clearValueCount = 2; + renderPassBeginInfo.pClearValues = clearValues; + + for (int32_t i = 0; i < drawCmdBuffers.size(); ++i) + { + renderPassBeginInfo.framebuffer = frameBuffers[i]; + + VK_CHECK_RESULT(vkBeginCommandBuffer(drawCmdBuffers[i], &cmdBufInfo)); + + vkCmdBeginRenderPass(drawCmdBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); + + VkViewport viewport = vkTools::initializers::viewport((float)width, (float)height, 0.0f, 1.0f); + vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport); + + VkRect2D scissor = vkTools::initializers::rect2D(width, height, 0, 0); + vkCmdSetScissor(drawCmdBuffers[i], 0, 1, &scissor); + + vkCmdSetLineWidth(drawCmdBuffers[i], 1.0f); + + VkDeviceSize offsets[1] = { 0 }; + + // Skysphere + vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.skysphere); + vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayouts.skysphere, 0, 1, &descriptorSets.skysphere, 0, NULL); + vkCmdBindVertexBuffers(drawCmdBuffers[i], VERTEX_BUFFER_BIND_ID, 1, &meshes.skysphere.vertices.buf, offsets); + vkCmdBindIndexBuffer(drawCmdBuffers[i], meshes.skysphere.indices.buf, 0, VK_INDEX_TYPE_UINT32); + vkCmdDrawIndexed(drawCmdBuffers[i], meshes.skysphere.indexCount, 1, 0, 0, 0); + + // Terrrain + vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, wireframe ? pipelines.wireframe : pipelines.terrain); + vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayouts.terrain, 0, 1, &descriptorSets.terrain, 0, NULL); + vkCmdBindVertexBuffers(drawCmdBuffers[i], VERTEX_BUFFER_BIND_ID, 1, &meshes.object.vertices.buf, offsets); + vkCmdBindIndexBuffer(drawCmdBuffers[i], meshes.object.indices.buf, 0, VK_INDEX_TYPE_UINT32); + vkCmdDrawIndexed(drawCmdBuffers[i], meshes.object.indexCount, 1, 0, 0, 0); + + vkCmdEndRenderPass(drawCmdBuffers[i]); + + VK_CHECK_RESULT(vkEndCommandBuffer(drawCmdBuffers[i])); + } + } + + void loadMeshes() + { + loadMesh(getAssetPath() + "models/geosphere.obj", &meshes.skysphere, vertexLayout, 1.0f); + } + + // Generate a terrain quad patch for feeding to the tessellation control shader + void generateTerrain() + { + struct Vertex { + glm::vec3 pos; + glm::vec3 normal; + glm::vec2 uv; + }; + + #define PATCH_SIZE 64 + #define UV_SCALE 2.0f + + Vertex *vertices = new Vertex[PATCH_SIZE * PATCH_SIZE * 4]; + + const float wx = 2.0f; + const float wy = 2.0f; + + for (auto x = 0; x < PATCH_SIZE; x++) + { + for (auto y = 0; y < PATCH_SIZE; y++) + { + uint32_t index = (x + y * PATCH_SIZE); + vertices[index].pos[0] = x * wx + wx / 2.0f - (float)PATCH_SIZE * wx / 2.0f; + vertices[index].pos[1] = 0.0f; + vertices[index].pos[2] = y * wy + wy / 2.0f - (float)PATCH_SIZE * wy / 2.0f; + vertices[index].normal = glm::vec3(0.0f, -1.0f, 0.0f); + vertices[index].uv = glm::vec2((float)x / PATCH_SIZE, (float)y / PATCH_SIZE) * UV_SCALE; + } + } + + const uint32_t w = (PATCH_SIZE - 1); + uint32_t *indices = new uint32_t[w * w * 4]; + for (auto x = 0; x < w; x++) + { + for (auto y = 0; y < w; y++) + { + uint32_t index = (x + y * w) * 4; + indices[index] = (x + y * PATCH_SIZE); + indices[index + 1] = indices[index] + PATCH_SIZE; + indices[index + 2] = indices[index + 1] + 1; + indices[index + 3] = indices[index] + 1; + } + } + + meshes.object.indexCount = (PATCH_SIZE - 1) * (PATCH_SIZE - 1) * 4; + + uint32_t vertexBufferSize = (PATCH_SIZE * PATCH_SIZE * 4) * sizeof(Vertex); + uint32_t indexBufferSize = (w * w * 4) * sizeof(uint32_t); + + struct { + VkBuffer buffer; + VkDeviceMemory memory; + } vertexStaging, indexStaging; + + // Create staging buffers + // Vertex data + createBuffer( + VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, + vertexBufferSize, + vertices, + &vertexStaging.buffer, + &vertexStaging.memory); + // Index data + createBuffer( + VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, + indexBufferSize, + indices, + &indexStaging.buffer, + &indexStaging.memory); + + createBuffer( + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + vertexBufferSize, + nullptr, + &meshes.object.vertices.buf, + &meshes.object.vertices.mem); + + createBuffer( + VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + indexBufferSize, + nullptr, + &meshes.object.indices.buf, + &meshes.object.indices.mem); + + // Copy from staging buffers + VkCommandBuffer copyCmd = VulkanExampleBase::createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); + + VkBufferCopy copyRegion = {}; + + copyRegion.size = vertexBufferSize; + vkCmdCopyBuffer( + copyCmd, + vertexStaging.buffer, + meshes.object.vertices.buf, + 1, + ©Region); + + copyRegion.size = indexBufferSize; + vkCmdCopyBuffer( + copyCmd, + indexStaging.buffer, + meshes.object.indices.buf, + 1, + ©Region); + + VulkanExampleBase::flushCommandBuffer(copyCmd, queue, true); + + vkDestroyBuffer(device, vertexStaging.buffer, nullptr); + vkFreeMemory(device, vertexStaging.memory, nullptr); + vkDestroyBuffer(device, indexStaging.buffer, nullptr); + vkFreeMemory(device, indexStaging.memory, nullptr); + + delete[] vertices; + delete[] indices; + } + + void setupVertexDescriptions() + { + // Binding description + vertices.bindingDescriptions.resize(1); + vertices.bindingDescriptions[0] = + vkTools::initializers::vertexInputBindingDescription( + VERTEX_BUFFER_BIND_ID, + vkMeshLoader::vertexSize(vertexLayout), + VK_VERTEX_INPUT_RATE_VERTEX); + + // Attribute descriptions + // Describes memory layout and shader positions + vertices.attributeDescriptions.resize(3); + + // Location 0 : Position + vertices.attributeDescriptions[0] = + vkTools::initializers::vertexInputAttributeDescription( + VERTEX_BUFFER_BIND_ID, + 0, + VK_FORMAT_R32G32B32_SFLOAT, + 0); + + // Location 1 : Normals + vertices.attributeDescriptions[1] = + vkTools::initializers::vertexInputAttributeDescription( + VERTEX_BUFFER_BIND_ID, + 1, + VK_FORMAT_R32G32B32_SFLOAT, + sizeof(float) * 3); + + // Location 2 : Texture coordinates + vertices.attributeDescriptions[2] = + vkTools::initializers::vertexInputAttributeDescription( + VERTEX_BUFFER_BIND_ID, + 2, + VK_FORMAT_R32G32_SFLOAT, + sizeof(float) * 6); + + vertices.inputState = vkTools::initializers::pipelineVertexInputStateCreateInfo(); + vertices.inputState.vertexBindingDescriptionCount = vertices.bindingDescriptions.size(); + vertices.inputState.pVertexBindingDescriptions = vertices.bindingDescriptions.data(); + vertices.inputState.vertexAttributeDescriptionCount = vertices.attributeDescriptions.size(); + vertices.inputState.pVertexAttributeDescriptions = vertices.attributeDescriptions.data(); + } + + void setupDescriptorPool() + { + std::vector poolSizes = + { + vkTools::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 3), + vkTools::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 3) + }; + + VkDescriptorPoolCreateInfo descriptorPoolInfo = + vkTools::initializers::descriptorPoolCreateInfo( + poolSizes.size(), + poolSizes.data(), + 2); + + VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool)); + } + + void setupDescriptorSetLayouts() + { + VkDescriptorSetLayoutCreateInfo descriptorLayout; + VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo; + std::vector setLayoutBindings; + + // Terrain + setLayoutBindings = + { + // Binding 0 : Shared Tessellation shader ubo + vkTools::initializers::descriptorSetLayoutBinding( + VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, + 0), + // Binding 1 : Height map + vkTools::initializers::descriptorSetLayoutBinding( + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, + 1), + // Binding 3 : Terrain texture array layers + vkTools::initializers::descriptorSetLayoutBinding( + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + VK_SHADER_STAGE_FRAGMENT_BIT, + 2), + }; + + descriptorLayout = vkTools::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings.data(), static_cast(setLayoutBindings.size())); + VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayouts.terrain)); + pipelineLayoutCreateInfo = vkTools::initializers::pipelineLayoutCreateInfo(&descriptorSetLayouts.terrain, 1); + VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCreateInfo, nullptr, &pipelineLayouts.terrain)); + + // Skysphere + setLayoutBindings = + { + // Binding 0 : Vertex shader ubo + vkTools::initializers::descriptorSetLayoutBinding( + VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + VK_SHADER_STAGE_VERTEX_BIT, + 0), + // Binding 1 : Color map + vkTools::initializers::descriptorSetLayoutBinding( + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + VK_SHADER_STAGE_FRAGMENT_BIT, + 1), + }; + + descriptorLayout = vkTools::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings.data(), static_cast(setLayoutBindings.size())); + VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayouts.skysphere)); + pipelineLayoutCreateInfo = vkTools::initializers::pipelineLayoutCreateInfo(&descriptorSetLayouts.skysphere, 1); + VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCreateInfo, nullptr, &pipelineLayouts.skysphere)); + } + + void setupDescriptorSets() + { + VkDescriptorSetAllocateInfo allocInfo; + std::vector writeDescriptorSets; + + // Terrain + allocInfo = vkTools::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayouts.terrain, 1); + VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.terrain)); + + writeDescriptorSets = + { + // Binding 0 : Shared tessellation shader ubo + vkTools::initializers::writeDescriptorSet( + descriptorSets.terrain, + VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + 0, + &uniformData.terrainTessellation.descriptor), + // Binding 1 : Displacement map + vkTools::initializers::writeDescriptorSet( + descriptorSets.terrain, + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + 1, + &textures.heightMap.descriptor), + // Binding 2 : Color map (alpha channel) + vkTools::initializers::writeDescriptorSet( + descriptorSets.terrain, + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + 2, + &textures.terrainArray.descriptor), + }; + vkUpdateDescriptorSets(device, writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL); + + // Skysphere + allocInfo = vkTools::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayouts.skysphere, 1); + VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.skysphere)); + + writeDescriptorSets = + { + // Binding 0 : Vertex shader ubo + vkTools::initializers::writeDescriptorSet( + descriptorSets.skysphere, + VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + 0, + &uniformData.skysphereVertex.descriptor), + // Binding 1 : Fragment shader color map + vkTools::initializers::writeDescriptorSet( + descriptorSets.skysphere, + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + 1, + &textures.skySphere.descriptor), + }; + vkUpdateDescriptorSets(device, writeDescriptorSets.size(), writeDescriptorSets.data(), 0, NULL); + } + + void preparePipelines() + { + VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = + vkTools::initializers::pipelineInputAssemblyStateCreateInfo( + VK_PRIMITIVE_TOPOLOGY_PATCH_LIST, + 0, + VK_FALSE); + + VkPipelineRasterizationStateCreateInfo rasterizationState = + vkTools::initializers::pipelineRasterizationStateCreateInfo( + VK_POLYGON_MODE_FILL, + VK_CULL_MODE_BACK_BIT, + VK_FRONT_FACE_COUNTER_CLOCKWISE, + 0); + + VkPipelineColorBlendAttachmentState blendAttachmentState = + vkTools::initializers::pipelineColorBlendAttachmentState( + 0xf, + VK_FALSE); + + VkPipelineColorBlendStateCreateInfo colorBlendState = + vkTools::initializers::pipelineColorBlendStateCreateInfo( + 1, + &blendAttachmentState); + + VkPipelineDepthStencilStateCreateInfo depthStencilState = + vkTools::initializers::pipelineDepthStencilStateCreateInfo( + VK_TRUE, + VK_TRUE, + VK_COMPARE_OP_LESS_OR_EQUAL); + + VkPipelineViewportStateCreateInfo viewportState = + vkTools::initializers::pipelineViewportStateCreateInfo(1, 1, 0); + + VkPipelineMultisampleStateCreateInfo multisampleState = + vkTools::initializers::pipelineMultisampleStateCreateInfo( + VK_SAMPLE_COUNT_1_BIT, + 0); + + std::vector dynamicStateEnables = { + VK_DYNAMIC_STATE_VIEWPORT, + VK_DYNAMIC_STATE_SCISSOR, + VK_DYNAMIC_STATE_LINE_WIDTH + }; + VkPipelineDynamicStateCreateInfo dynamicState = + vkTools::initializers::pipelineDynamicStateCreateInfo( + dynamicStateEnables.data(), + dynamicStateEnables.size(), + 0); + + // We render the terrain as a grid of quad patches + VkPipelineTessellationStateCreateInfo tessellationState = + vkTools::initializers::pipelineTessellationStateCreateInfo(4); + + std::array shaderStages; + + // Terrain tessellation pipeline + shaderStages[0] = loadShader(getAssetPath() + "shaders/terraintessellation/terrain.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); + shaderStages[1] = loadShader(getAssetPath() + "shaders/terraintessellation/terrain.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); + shaderStages[2] = loadShader(getAssetPath() + "shaders/terraintessellation/terrain.tesc.spv", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT); + shaderStages[3] = loadShader(getAssetPath() + "shaders/terraintessellation/terrain.tese.spv", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT); + + VkGraphicsPipelineCreateInfo pipelineCreateInfo = + vkTools::initializers::pipelineCreateInfo( + pipelineLayouts.terrain, + renderPass, + 0); + + pipelineCreateInfo.pVertexInputState = &vertices.inputState; + pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; + pipelineCreateInfo.pRasterizationState = &rasterizationState; + pipelineCreateInfo.pColorBlendState = &colorBlendState; + pipelineCreateInfo.pMultisampleState = &multisampleState; + pipelineCreateInfo.pViewportState = &viewportState; + pipelineCreateInfo.pDepthStencilState = &depthStencilState; + pipelineCreateInfo.pDynamicState = &dynamicState; + pipelineCreateInfo.pTessellationState = &tessellationState; + pipelineCreateInfo.stageCount = static_cast(shaderStages.size()); + pipelineCreateInfo.pStages = shaderStages.data(); + pipelineCreateInfo.renderPass = renderPass; + + VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.terrain)); + + // Terrain wireframe pipeline + rasterizationState.polygonMode = VK_POLYGON_MODE_LINE; + VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.wireframe)); + + // Skysphere pipeline + rasterizationState.polygonMode = VK_POLYGON_MODE_FILL; + // Revert to triangle list topology + inputAssemblyState.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + // Reset tessellation state + pipelineCreateInfo.pTessellationState = nullptr; + // Don't write to depth buffer + depthStencilState.depthWriteEnable = VK_FALSE; + pipelineCreateInfo.stageCount = 2; + pipelineCreateInfo.layout = pipelineLayouts.skysphere; + shaderStages[0] = loadShader(getAssetPath() + "shaders/terraintessellation/skysphere.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); + shaderStages[1] = loadShader(getAssetPath() + "shaders/terraintessellation/skysphere.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); + VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.skysphere)); + } + + // Prepare and initialize uniform buffer containing shader uniforms + void prepareUniformBuffers() + { + // Shared tessellation shader stages uniform buffer + createBuffer( + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + sizeof(uboTess), + nullptr, + &uniformData.terrainTessellation.buffer, + &uniformData.terrainTessellation.memory, + &uniformData.terrainTessellation.descriptor); + + // Skysphere vertex shader uniform buffer + createBuffer( + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + sizeof(uboVS), + nullptr, + &uniformData.skysphereVertex.buffer, + &uniformData.skysphereVertex.memory, + &uniformData.skysphereVertex.descriptor); + + updateUniformBuffers(); + } + + void updateUniformBuffers() + { + // Tessellation + + uboTess.projection = camera.matrices.perspective; + uboTess.modelview = camera.matrices.view * glm::mat4(); + uboTess.lightPos.y = -0.5f - uboTess.displacementFactor; // todo: Not uesed yet + uboTess.viewportDim = glm::vec2((float)width, (float)height); + + float savedFactor = uboTess.tessellationFactor; + if (!tessellation) + { + // Setting this to zero sets all tessellation factors to 1.0 in the shader + uboTess.tessellationFactor = 0.0f; + } + + uint8_t *pData; + VK_CHECK_RESULT(vkMapMemory(device, uniformData.terrainTessellation.memory, 0, sizeof(uboTess), 0, (void **)&pData)); + memcpy(pData, &uboTess, sizeof(uboTess)); + vkUnmapMemory(device, uniformData.terrainTessellation.memory); + + if (!tessellation) + { + uboTess.tessellationFactor = savedFactor; + } + + // Skysphere vertex shader + uboVS.mvp = camera.matrices.perspective * glm::mat4(glm::mat3(camera.matrices.view)); + + VK_CHECK_RESULT(vkMapMemory(device, uniformData.skysphereVertex.memory, 0, sizeof(uboVS), 0, (void **)&pData)); + memcpy(pData, &uboVS, sizeof(uboVS)); + vkUnmapMemory(device, uniformData.skysphereVertex.memory); + } + + void draw() + { + VulkanExampleBase::prepareFrame(); + + // Command buffer to be sumitted to the queue + submitInfo.commandBufferCount = 1; + submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer]; + + // Submit to queue + VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); + + VulkanExampleBase::submitFrame(); + } + + void prepare() + { + VulkanExampleBase::prepare(); + loadMeshes(); + generateTerrain(); + loadTextures(); + setupVertexDescriptions(); + prepareUniformBuffers(); + setupDescriptorSetLayouts(); + preparePipelines(); + setupDescriptorPool(); + setupDescriptorSets(); + buildCommandBuffers(); + prepared = true; + } + + virtual void render() + { + if (!prepared) + return; + draw(); + } + + virtual void viewChanged() + { + updateUniformBuffers(); + } + + void changeTessellationFactor(float delta) + { + uboTess.tessellationFactor += delta; + uboTess.tessellationFactor = fmax(0.25f, fmin(uboTess.tessellationFactor, 4.0f)); + updateUniformBuffers(); + updateTextOverlay(); + } + + void toggleWireframe() + { + wireframe = !wireframe; + reBuildCommandBuffers(); + updateUniformBuffers(); + } + + void toggleTessellation() + { + tessellation = !tessellation; + updateUniformBuffers(); + } + + virtual void keyPressed(uint32_t keyCode) + { + switch (keyCode) + { + case 0x6B: + case GAMEPAD_BUTTON_R1: + changeTessellationFactor(0.05f); + break; + case 0x6D: + case GAMEPAD_BUTTON_L1: + changeTessellationFactor(-0.05f); + break; + case 0x20: + case GAMEPAD_BUTTON_X: + toggleWireframe(); + break; + //case VK_RETURN: + // toggleTessellation(); + // break; + } + } + + virtual void getOverlayText(VulkanTextOverlay *textOverlay) + { + std::stringstream ss; + ss << std::setprecision(2) << std::fixed << uboTess.tessellationFactor; + +#if defined(__ANDROID__) + textOverlay->addText("Tessellation factor: " + ss.str() + " (Buttons L1/R1)", 5.0f, 85.0f, VulkanTextOverlay::alignLeft); +// textOverlay->addText("Press \"Button A\" to toggle displacement", 5.0f, 100.0f, VulkanTextOverlay::alignLeft); +// textOverlay->addText("Press \"Button X\" to toggle splitscreen", 5.0f, 115.0f, VulkanTextOverlay::alignLeft); +#else + textOverlay->addText("Tessellation factor: " + ss.str() + " (numpad +/-)", 5.0f, 85.0f, VulkanTextOverlay::alignLeft); + //textOverlay->addText("Press \"d\" to toggle displacement", 5.0f, 100.0f, VulkanTextOverlay::alignLeft); + //textOverlay->addText("Press \"s\" to toggle splitscreen", 5.0f, 115.0f, VulkanTextOverlay::alignLeft); +#endif + } +}; + +VulkanExample *vulkanExample; + +#if defined(_WIN32) +LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + if (vulkanExample != NULL) + { + vulkanExample->handleMessages(hWnd, uMsg, wParam, lParam); + } + return (DefWindowProc(hWnd, uMsg, wParam, lParam)); +} +#elif defined(__linux__) && !defined(__ANDROID__) +static void handleEvent(const xcb_generic_event_t *event) +{ + if (vulkanExample != NULL) + { + vulkanExample->handleEvent(event); + } +} +#endif + +// Main entry point +#if defined(_WIN32) +// Windows entry point +int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) +#elif defined(__ANDROID__) +// Android entry point +void android_main(android_app* state) +#elif defined(__linux__) +// Linux entry point +int main(const int argc, const char *argv[]) +#endif +{ +#if defined(__ANDROID__) + // Removing this may cause the compiler to omit the main entry point + // which would make the application crash at start + app_dummy(); +#endif + vulkanExample = new VulkanExample(); +#if defined(_WIN32) + vulkanExample->setupWindow(hInstance, WndProc); +#elif defined(__ANDROID__) + // Attach vulkan example to global android application state + state->userData = vulkanExample; + state->onAppCmd = VulkanExample::handleAppCommand; + state->onInputEvent = VulkanExample::handleAppInput; + vulkanExample->androidApp = state; +#elif defined(__linux__) + vulkanExample->setupWindow(); +#endif +#if !defined(__ANDROID__) + vulkanExample->initSwapchain(); + vulkanExample->prepare(); +#endif + vulkanExample->renderLoop(); + delete(vulkanExample); +#if !defined(__ANDROID__) + return 0; +#endif +} \ No newline at end of file diff --git a/terraintessellation/terraintessellation.vcxproj b/terraintessellation/terraintessellation.vcxproj new file mode 100644 index 00000000..3282366b --- /dev/null +++ b/terraintessellation/terraintessellation.vcxproj @@ -0,0 +1,99 @@ + + + + + Debug + x64 + + + Release + x64 + + + + {6C6E48B1-5946-4754-9E31-E1C989EC25FE} + Win32Proj + 8.1 + + + + Application + true + v140 + + + Application + false + v140 + + + + + + + + + + + + + true + $(SolutionDir)\bin\ + $(SolutionDir)\bin\intermediate\$(ProjectName)\$(ConfigurationName) + + + true + $(SolutionDir)\bin\ + $(SolutionDir)\bin\intermediate\$(ProjectName)\$(ConfigurationName) + + + + WIN32;_DEBUG;_WINDOWS;VK_USE_PLATFORM_WIN32_KHR;_USE_MATH_DEFINES;NOMINMAX;%(PreprocessorDefinitions) + MultiThreadedDebugDLL + Level3 + ProgramDatabase + Disabled + ..\base;..\external\glm;..\external\gli;..\external\assimp;..\external;%(AdditionalIncludeDirectories) + + + + + /FS %(AdditionalOptions) + + + true + Windows + ..\libs\vulkan\vulkan-1.lib;..\libs\assimp\assimp.lib;%(AdditionalDependencies) + + + + + WIN32;NDEBUG;_WINDOWS;VK_USE_PLATFORM_WIN32_KHR;_USE_MATH_DEFINES;NOMINMAX;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + MultiThreadedDLL + Level3 + ProgramDatabase + ..\base;..\external\glm;..\external\gli;..\external\assimp;..\external;%(AdditionalIncludeDirectories) + + + true + Windows + true + true + ..\libs\vulkan\vulkan-1.lib;..\libs\assimp\assimp.lib;%(AdditionalDependencies) + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/terraintessellation/terraintessellation.vcxproj.filters b/terraintessellation/terraintessellation.vcxproj.filters new file mode 100644 index 00000000..94d6a250 --- /dev/null +++ b/terraintessellation/terraintessellation.vcxproj.filters @@ -0,0 +1,42 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + \ No newline at end of file diff --git a/vulkanExamples.sln b/vulkanExamples.sln index c8a836f5..43b07762 100644 --- a/vulkanExamples.sln +++ b/vulkanExamples.sln @@ -69,6 +69,10 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "debugmarker", "debugmarker\ EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "scenerendering", "scenerendering\scenerendering.vcxproj", "{D928DFBB-DB07-411E-A650-6D3CE697D7D0}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "descriptorsets", "descriptorsets\descriptorsets.vcxproj", "{0A613401-3099-4657-9F83-EE54FDD29849}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "terraintessellation", "terraintessellation\terraintessellation.vcxproj", "{6C6E48B1-5946-4754-9E31-E1C989EC25FE}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 @@ -207,6 +211,14 @@ Global {D928DFBB-DB07-411E-A650-6D3CE697D7D0}.Debug|x64.Build.0 = Debug|x64 {D928DFBB-DB07-411E-A650-6D3CE697D7D0}.Release|x64.ActiveCfg = Release|x64 {D928DFBB-DB07-411E-A650-6D3CE697D7D0}.Release|x64.Build.0 = Release|x64 + {0A613401-3099-4657-9F83-EE54FDD29849}.Debug|x64.ActiveCfg = Debug|x64 + {0A613401-3099-4657-9F83-EE54FDD29849}.Debug|x64.Build.0 = Debug|x64 + {0A613401-3099-4657-9F83-EE54FDD29849}.Release|x64.ActiveCfg = Release|x64 + {0A613401-3099-4657-9F83-EE54FDD29849}.Release|x64.Build.0 = Release|x64 + {6C6E48B1-5946-4754-9E31-E1C989EC25FE}.Debug|x64.ActiveCfg = Debug|x64 + {6C6E48B1-5946-4754-9E31-E1C989EC25FE}.Debug|x64.Build.0 = Debug|x64 + {6C6E48B1-5946-4754-9E31-E1C989EC25FE}.Release|x64.ActiveCfg = Release|x64 + {6C6E48B1-5946-4754-9E31-E1C989EC25FE}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE