From 5acca023630726877464c1eea36fc104b86e2fad Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Wed, 15 Feb 2023 21:34:22 +0800 Subject: [PATCH 01/15] Implemented different shadow mapping technique --- Assets/Scenes/MainGame.shade | 9 ++++- Assets/Shaders/DeferredComposite_CS.glsl | 21 ++++++++-- Assets/Shaders/DeferredComposite_CS.shshaderb | Bin 8333 -> 9621 bytes Assets/Shaders/ShadowMap_FS.glsl | 4 +- Assets/Shaders/ShadowMap_FS.shshaderb | Bin 365 -> 789 bytes .../MiddleEnd/Interface/SHGraphicsSystem.cpp | 36 ++++++++++-------- .../MiddleEnd/Lights/SHLightingSubSystem.cpp | 16 +++++--- 7 files changed, 58 insertions(+), 28 deletions(-) diff --git a/Assets/Scenes/MainGame.shade b/Assets/Scenes/MainGame.shade index 87343839..438b5a29 100644 --- a/Assets/Scenes/MainGame.shade +++ b/Assets/Scenes/MainGame.shade @@ -8440,6 +8440,11 @@ IsActive: true NumberOfChildren: 0 Components: + Transform Component: + Translate: {x: 0, y: 0, z: 0} + Rotate: {x: 0, y: 0, z: 0} + Scale: {x: 1, y: 1, z: 1} + IsActive: true Light Component: Position: {x: 0, y: 0, z: 0} Type: Directional @@ -8469,14 +8474,14 @@ NumberOfChildren: 0 Components: Transform Component: - Translate: {x: 2, y: 1.5, z: -5.5999999} + Translate: {x: 0.242245644, y: 1.56757355, z: -6.07086945} Rotate: {x: -0, y: 0, z: -0} Scale: {x: 1, y: 1, z: 1} IsActive: true Light Component: Position: {x: 2, y: 1.5, z: -5.5999999} Type: Directional - Direction: {x: -0.245000005, y: 0, z: 0} + Direction: {x: 0, y: 0, z: -1} Color: {x: 0, y: 0, z: 0, w: 1} Layer: 4294967295 Strength: 1 diff --git a/Assets/Shaders/DeferredComposite_CS.glsl b/Assets/Shaders/DeferredComposite_CS.glsl index 50a269ac..745b93e0 100644 --- a/Assets/Shaders/DeferredComposite_CS.glsl +++ b/Assets/Shaders/DeferredComposite_CS.glsl @@ -48,19 +48,34 @@ layout(std430, set = 1, binding = 4) buffer AmbientLightData AmbientLightStruct aLightData[]; } AmbLightData; +float LinStep (float val, float low, float high) +{ + return clamp ((val - low)/(high - low), 0.0f, 1.0f); +} + float CalcShadowValue (sampler2D shadowMap, vec4 worldSpaceFragPos, mat4 lightPV) { + // clip space for fragment from light view space vec4 fragPosLightPOV = lightPV * worldSpaceFragPos; + + // Perform perspective division and convert to 0 to 1 range vec3 converted = (fragPosLightPOV.xyz / fragPosLightPOV.w) * vec3(0.5f) + vec3(0.5f); - float sampledDepth = texture(shadowMap, converted.xy).r; + // float sampledDepth = texture(shadowMap, converted.xy).r; + // float sampledDepth = texture(shadowMap, converted.xy).z; + vec2 moments = texture(shadowMap, converted.xy).xy; if (converted.x < 0.0f || converted.x > 1.0f || converted.y < 0.0f || converted.y > 1.0f) return 1.0f; - if (fragPosLightPOV.z > sampledDepth && fragPosLightPOV.w > 0.0f) + if (fragPosLightPOV.z > moments.x && fragPosLightPOV.w > 0.0f) { - return 0.7f; + float p = step (fragPosLightPOV.z, moments.x); + float variance = max (moments.y - (moments.x * moments.x), 0.00002f); + + float d = fragPosLightPOV.z - moments.x; + float pMax = LinStep (variance / (variance + (d * d)), 0.9f, 1.0f); + return min (max (p, pMax), 1.0f); } else return 1.0f; diff --git a/Assets/Shaders/DeferredComposite_CS.shshaderb b/Assets/Shaders/DeferredComposite_CS.shshaderb index 7f06b4713f034c5c4945e920f736283fcf7fc0df..ff474e272b60daadce873126ae23984c156a834f 100644 GIT binary patch literal 9621 zcmZ{n2bi5z5r+RHTS5pBdJmg~NazFt0Rn_HmcWK21VSg=?B3m6xx07Wy-5H;f{3D0 z6(65R6eAX@f*r9z6hX03#9jh66uVR@zVCm}EI;>wBjbGY&77Gz=RfD{O~(~evwVyh zJ*7R%MrGr&&9c5x4Q|V9G)$JMr=vH`+H$+IYgyNR!}Xs1W*mHgk(*~@RJm^pVp_p1 zNPnp^Aio}&057*?j( zcpSJ|TMKSsy;-)Z(zgnQJucf3J+D;lUbd>#Q(L>dR9#)3HhkdpS!;S{%g>RVD9&V4P}4(KX%>PwbWr!Ct9ySEY1 zmD7vmTeE%PyK4h$%0u;XPnvrKy1&+69;go!F(z}v8#PHX_+@R|K5Go6`i?j z;lP?&cd1^f4J@3W``fac(1Vrp%GLRm-rm*2skfHwR`^nNWx1zjp0?}`<7&edC!gZp z<@4LKJDd4@PaAW-Qt&OWl-FXCt2O&tfp6@4Yj!W(Ky9eMRBc4M<_#m9``Ma3fSrGv zuG0DCp+=1dU&GBW)k}>U55fE0=GCe-LYdu`J%S!N3(4VkdJMjj$Fyd@Mdu%SUTwAC zv5h^HbEIQm8z@!t5PNUqfBLkN1|A`d3ysEF-yG<3{+Z z2QAh2zWf<(P9b(#eQ0$z2g+Rf94S{UH}6ZIeGS)#$^(7%RmRzuynR)M=cHTwDsNxi ztE*h|zD1?sbLpr(`wLvLeq)y#bM!e%`6^=n+p?$Nm{VZ=24k`|8fxtI*la8C{Kiu< zvZt@Etu6PPdt~3i_U}B`)!e_l>nir|9?83|p2iV>%^vA%!8f>OQK>#u$?sp(XoYW_ zmsr=>Y#ZX6doJ#Wen(GX<(|Fm8uJRQ`_Z252H%K1AwT_<3-ad#Ut2a+U!!NXrSS

W zZTH@3i;$2k91b&}P5#@X9Ow6&ub?MaBkoZc@-v9_G? zaubki%1O()=HQ~g z=-D{y7}t@AWYTGt`wiu+`Y!?ntd$#F}5 zuZnB+o=w7s%JX?w^xKd5we>r+PfY&Er>#HYy$j9{zqWpRbbc?k_rl*JTXRC(uSrB3 zFWwFm->!pr*RRM;;{QE!;^5Ug@+)Zb#FPFtBkY~Yy9FNO%W+HMS);S#8I_|M`{Jm!#`E6k5q9gx2up{iH;86wp9I$z! z{zc&1@4IPc*jHlr_V&)U{||vX5a-*+^=P^1b=vHN_ii4sG9PN7x%0 zW*&b(*mb*B`~Ggiuh;h^eAf6L+F`6YwI7sVxOYE9o6mK|S$G&cxgh&c)ieDlGNnnZ z@e?@va!>u9>YpNxiR^;!x;2X8yx+mO$NKF}dm|zjc^(JHcYPxH%wt~Pd;4;qBloUE zKZ&hxBG@-u+j@URn_JF$+P>Rz`kzVIoKgQp@TlZ}Dfz88kypjH)w>h5o#)-wwh!M~ zW9-BCRNFe+qOB=sAKJdDa#44OWE($e#P_QI5IEoUUGN_X_Dx!f7=IMDL*D$_zR8Zr zKLs#3HBSEUF%q5DKQRXt)cC^?$Evk?K|%9oSg}FUt*2oGTa2T=gzz8 zJ1?iWmP1&f@%HKP96Sf(x~<_m;J?W{d)mH(Hx+E()H@2ce*e8xjK8;F-w%GEU>pBX z!8YF`1>1A~Sd;Bzf^9y3Q%1b+|AK-o?{7-=k*v=>`WUhvxe)tC^v4mo zrR<9L?h}bajc}h#9I3J;#QAQ13NcpSQS7YyC}$ntxZ99hlWqL%h%qaf?>YZ8VvPJ^ z?t=H=Gl;z6u%6$~{5PTXNB+-(?@YG&KZg|ae;(Ty`N;nTu)N}k{I1>e`bESTM{r*P z%NZNomlJ1iOW0l4a~I-#o>oD1HO+um~8X^0EztmE%*^) zjJ*5hJ^e8v@33d@h@AK#^uq~zHy%ycd*R=J=Q#mCLwj%4&(Oy&(7!|+`hSJiueMLm z@vjkcc+TzNH;J1=Pfvh}arO>5|mT7;HIXK@?k-^YIJ*2wl7#tai~Tk=C+6ZAgmYnWPh++NZgYH;LN2z z);JyPdk`@PVjCwPF$aN*cWDN;oUyJ|pIofwW_t_uBf%gq1_90?8PFmdlB!~31GQ+zx2sDza8!TP0-F?f?kIBdtCc^ z`aB67f9KuDlT(a*{4QD!mUp;@#b7yecy3Pt%V~T6P6fLMSEV=mG;BHJVh`kuznQo* zz^5ns2JExI>(Pt(4rhYTM&uNS$~V;hS77Lm+UJ0+9le*Ze{b$^}j?nha&!)#Jw1gIL0C~*{gQ+CIvjMfHwvEeKteKUhWJwKI~n< z&bc(@-xX|(e8fxyn=9WDV;+kKkM}5V0 zdM_N?BCc}+db@{;L=3bt_rO?JJ>zPQQ0 ztjWHr$-cVDz9!l3q3?o!2kcwhd$A|tnyzL4wD&@ck@rly9=V9$4=fjN|NdY(#o<1C z*8JP=`VK^lpN_n=75h*g39Mv-*2oh_Fz8Pdj6h> zJ@D_m{9UYdF8UZm&ipsir(7o@@86V#Xor7O_1o7Hw8OsS7b9}^C62yM1l!kAB=%q#SU&dPB(R)& zU|*3(9ete)wzj<*Z;j|{Iat4aor-qYm;5P+oPCL-uhYQIeVq;`ANzF%ST6P}@~ES) zGr`ujSL3Z=A7`T-_F>Ffh@5?heS^%aEgyZAz}}m4kl3%4VEKsY27A`#AraF9mXF@c zVCTu(PaoQ0Kl*wRIqQof_bRaUi}$vIEg!kx43>-U6?xRLFXw`-XPo@pte-u=Vss?{5R!`!q!VMTouE(fXq1 zI&kw|T>>W`F>ePq@71Mn^3lUPz|NDmj(>yXV*lR>wszR>YO*iKc24-;o$Ofmd$5g> zza;I&d%@;u_!|3j1-7;H*~e9AIq}u#D-*s3Jq3y1x7UKlBgPx2-#M3|^+jLr1N;5M qem~fl*!SzevG2y}58nrpZz|e2>wA~wJ;R>m;@$SVzd|;DYy2Olwd-&I literal 8333 zcmZ{n37A%86~`|Ov&bUg3JN$QE~tPaxIqdCI#LiAhE_iDTxLFoFTa^@obMZ4vck}! zO|z^}v$DkuD=k~hvP>=8Y~RbY&8%$CwbXvUd+!;q^E|yi$8*mAocEmbo_pSRJ~}Vy zOtRH7c6NJ`j7i2Plal#ka%^fc79>gJ3*ZxywoLC{y?*ulMzeSRqGOKIbN8f0mf0rb z(~3L}>QAc!;(gE*aIvYGte*R~uy-u-og^AZ_U_diyVtJmUVX~Op25M5jphZl%EnrC zpt7;II#lUtR<~C4>nQnE2YPD5y=8}1Jj(f7iMt0mR;0C_^;^>3`gt4D+Hhq~QLIZuHMLOo%~vE!hivbMCP^gV&0;Ci{W+)Caa!hMJY$Y;RjK2i{2g2Wyqym6gHf7St?;_P$zu zQ(8M?%TOg%1@FlE*jL-wotah*Y_0dC&1!vM)yiU@%^s|tU#YFEZr(iHpi}M}mz)bv zYnv*)^*sJo{pyXXo6q!InO}Qy-e^2KZ@y<+$+n?d(UsV($@UVS_oOx10X9${>Q8IA zr!~A`1Z!mbE=SM$wmQ9_GL+|d+jFp$X*11p>;$)`E9$j6uIz71u7;0%r^3+6EL{s; z&3syu>*3i)SWzDyXg1i@kzv3|F;4Y?w3fM8dmI0`$C)3jR|lGfC2;4oF<1{6@Ak~! z=}-GNRVyPq^15#T&(2unZ^i#6u;nG+_06H-o~F5T8|H`=$Ia?;pLI2wLzRKPd{(SW z+`6ib<;CsD&mnGIJ;ODwPv4rfaSnZJPd))w&YyQV-=ocyX6KInwe;+L ztSzsZw&b7C`_snZN9LFz^sbBt8%&4Ne)gzO9HsB$o<>^d6~o@1OfU44Yr{iBmEKkT zXoTazwq&2*@*(#+v*;`ts=fM!7Iz7GdN_BHe_Wc#n~WiQ*+wcAte+eg{ewY#)? z_sjd$wT~(6-utp$UAy(1Mi%d+Yj(~?F!zi3&BM={#X3rual|G<-9$B>e%9t4HFwma zZf=(`y+YSk&j41B?2i=D17l?achfWqXb7w~c-3`W!V1;|D|bw=w+Oqu(H8?LUWm)@_hJ zai5}A&nnge>F>QNpHtJpUW*%f(?%vF9T<-aMzZ*hiiTN-}L(CuUBYmv)w&qiOkaN$zV zlOlIQ`dh~)xS0N)zX$Gl#I;x8_8`u?8QHz!OR%f=6`1~2WaH`Ycdx@er+doFeDSTk z11^1ysqQ=L3O)M~g>KA?;r}nDc|6B!;VylRp}t*!6}oS$OaIH@p4+pUCsRD}N8C~Ti1QKT_^!JOn{kYL6WqG&^RuyAvNu`VEOz?#-VB-VlW=2; znNQvKS4{iug>1~oe;4wY!hUyQH{UE?0^eKjPULo+oIl{WQ-n;pP;x z4)yyAEb`u8==wiY$mRy0Gq8`NK;NKckp8U}%n~=gx^Jy3_IIGiY)?YA9&2~5 z_SGM`*n*TVeI`TZm{u6|HHW(IvrFCk(G@=EvyttKF|0v(F4z<~*}SX1*J9E#^kX@p z{?_So4ju>b+~(+k_d?E|y6>X@W(wUm)PEa=u6^4meMd?6eqCPD_1{_2jdyiPckZtp zrQci9-Tz=o_Z@z?q#MuQhEd-nbblL$uD`zx)lcMn_Gk;#2VI2jJNAkKJDski$mbLo zED5YuV1!E6;kOCi59zDzBsyy!#mrNO4?*V^y8ir>&3rbo-#O=>IGK<5TBgt094>He zF7x^QjPG~R9`Vmd_Pta${soXVMEnbp^%0NwuS6D?ToK=MIv@9DcB zahElFN5qu9A6FIf)$nTy*?ZyNfG3!M_rkrm@<*xTI{5n`m-Y|9wacw5g?|t-hI4KW zA1bir)U*rvM(75}zYp%w=cADL&G;;Ue++V;_>=gkzYj9M`IKYt$B{i(v z=KC~s3*?!!mGgcEUHd&nzdnm>JniczQCv_0N zCbD&JBVG#s79?i9#?vNNp3mzF+r4o6sO{TuW6Pc0@4~+axwL;Du3a9ve}HU^nB5;D zi^c5z2-(?`>e+M$Z`IOD)-k(C{+5Hu|`D1n;K)w$$pSJs< z*!yeb2cVeU-yj=LJZAT|$l@`(zejdim$u(QV%DV`efR@%)bSAVAEBs2Tb$qT|EIz} zv6!7dqmO}3DQteT2a&~%@1DOvVxj*Pc?WbQ-@Fa}H%K4xiQHqczeC2I1I>fbHdpzwJDSwHdcc@lXi6nE)A$YT1&T@s74{uepUx(oSfD9)dv{pVRwh3Ze#fy*Vq&BpIq48=Wi_a6N;Ibg1kqO&zRcd+e}5)9%MXcZx1kg9N%G2 zbTR#-$6~$_aaOr{+!eXH?}@#TM=$om*IvZ?wKuw0ykFYH-0$1ue%}W7`FG!i7f8&4F2{MGlp|J3t3Fv9vpyd4=yX->`rts{h|kA`q%M0 z5ZQkds8`SrLhggFpuiVd*nV8+1ye49CR^PV22f$aA1cQ*jTXm z?RNy2`}Nnp7+Vi{t=GKTpQ4)MA^%NcFPsuA*IDBq_iMz%?XJNA+^C9=^H~UW>)qk484n zkx-m{A+q?boN)ns5hP~Z8>mn07)abV?>M;2H&6UnNX$7rj3gZd`TosB0av_hl^<{W=|4JoFbKJ8MzrdSrdX z&HZAy%iP+|fW*wD9Jw|io2z^`&qNoG*k>V&#kYw#^60@!kj>*c^f!lfybSKL4t-t< Yy&SR*WqWXTp^KM$;@)StiN2Np1F+75%K!iX diff --git a/Assets/Shaders/ShadowMap_FS.glsl b/Assets/Shaders/ShadowMap_FS.glsl index f514c70b..b19a32a6 100644 --- a/Assets/Shaders/ShadowMap_FS.glsl +++ b/Assets/Shaders/ShadowMap_FS.glsl @@ -3,8 +3,10 @@ #extension GL_ARB_shading_language_420pack : enable #extension GL_EXT_nonuniform_qualifier : require +layout(location = 0) out vec4 shadowMap; void main() { - + // shadowMap = vec4 (0.0f, 0.0f, gl_FragCoord.z, 1.0f); + shadowMap = vec4 (gl_FragCoord.z, gl_FragCoord.z * gl_FragCoord.z, 0.0f, 1.0f); } \ No newline at end of file diff --git a/Assets/Shaders/ShadowMap_FS.shshaderb b/Assets/Shaders/ShadowMap_FS.shshaderb index 453048326bf7f7f05fe7de71024adf6f23d52649..709a2ecc8a2443df79dbbed62ab544a4ac5cc464 100644 GIT binary patch literal 789 zcmZuuO)mpc6unwQ6;|*$iJgr<=2zKBoHLyY ziJRQH@1A?^=TxVPl1Z_!J}xpMWto&?cp{1 zd#`~}fenrFY=Tbq*|1kuC+FF)6ZE~`1P6@Y`#IudJ96ge1meIp z@ntRU$^Ptdkk_l`_>eRE4`&V-@gb-74`&`2@%QWxa6b{|5x>9%c%x+~`!U8nIQt(); - if (lightComps.size() > 2) - { - lightComps[2].SetEnableShadow(true); - } - //for (auto& comp : lightComps) + //if (lightComps.size() > 2) //{ - // comp.SetEnableShadow(true); + // lightComps[2].SetEnableShadow(true); //} + for (auto& comp : lightComps) + { + comp.SetEnableShadow(true); + } } renderGraph->Begin(frameIndex); @@ -779,10 +780,11 @@ namespace SHADE // we need to wait for the device to finish using the graph first device->WaitIdle(); - auto const& EVENT_DATA = reinterpret_cast*>(eventPtr.get())->data; - auto* lightComp = SHComponentManager::GetComponent(EVENT_DATA->lightEntity); - std::string resourceName = "ShadowMap " + std::to_string(EVENT_DATA->lightEntity); - Handle companionSubpass = renderGraph->GetNode(SHGraphicsConstants::RenderGraphEntityNames::GBUFFER_PASS.data())->GetSubpass(SHGraphicsConstants::RenderGraphEntityNames::GBUFFER_WRITE_SUBPASS); + auto const& EVENT_DATA = reinterpret_cast*>(eventPtr.get())->data; + auto* lightComp = SHComponentManager::GetComponent(EVENT_DATA->lightEntity); + std::string depthResourceName = "ShadowMap_Depth " + std::to_string(EVENT_DATA->lightEntity); + std::string shadowMapResourceName = "ShadowMap " + std::to_string(EVENT_DATA->lightEntity); + Handle companionSubpass = renderGraph->GetNode(SHGraphicsConstants::RenderGraphEntityNames::GBUFFER_PASS.data())->GetSubpass(SHGraphicsConstants::RenderGraphEntityNames::GBUFFER_WRITE_SUBPASS); if (EVENT_DATA->generateRenderer) { @@ -795,14 +797,16 @@ namespace SHADE } // Add the shadow map resource to the graph - renderGraph->AddResource(resourceName, {SH_RENDER_GRAPH_RESOURCE_FLAGS::DEPTH, SH_RENDER_GRAPH_RESOURCE_FLAGS::INPUT}, false, SHLightingSubSystem::SHADOW_MAP_WIDTH, SHLightingSubSystem::SHADOW_MAP_HEIGHT, vk::Format::eD32Sfloat); + renderGraph->AddResource(depthResourceName, {SH_RENDER_GRAPH_RESOURCE_FLAGS::DEPTH}, false, SHLightingSubSystem::SHADOW_MAP_WIDTH, SHLightingSubSystem::SHADOW_MAP_HEIGHT, vk::Format::eD32Sfloat); + renderGraph->AddResource(shadowMapResourceName, { SH_RENDER_GRAPH_RESOURCE_FLAGS::COLOR, SH_RENDER_GRAPH_RESOURCE_FLAGS::INPUT }, false, SHLightingSubSystem::SHADOW_MAP_WIDTH, SHLightingSubSystem::SHADOW_MAP_HEIGHT, vk::Format::eR32G32B32A32Sfloat); // link resource to node. This means linking the resource and regenerating the node's renderpass and framebuffer. - auto shadowMapNode = renderGraph->AddNodeAfter(SHGraphicsConstants::RenderGraphEntityNames::SHADOW_MAP_PASS.data() + resourceName, {resourceName.c_str()}, SHGraphicsConstants::RenderGraphEntityNames::GBUFFER_PASS.data()); + auto shadowMapNode = renderGraph->AddNodeAfter(SHGraphicsConstants::RenderGraphEntityNames::SHADOW_MAP_PASS.data() + shadowMapResourceName, {depthResourceName.c_str(), shadowMapResourceName.c_str()}, SHGraphicsConstants::RenderGraphEntityNames::GBUFFER_PASS.data()); // Add a subpass to render to that shadow map - auto newSubpass = shadowMapNode->RuntimeAddSubpass(resourceName + " Subpass", shadowMapViewport, lightComp->GetRenderer()); - newSubpass->AddDepthOutput(resourceName, SH_RENDER_GRAPH_RESOURCE_FLAGS::DEPTH); + auto newSubpass = shadowMapNode->RuntimeAddSubpass(shadowMapResourceName + " Subpass", shadowMapViewport, lightComp->GetRenderer()); + newSubpass->AddColorOutput(shadowMapResourceName); + newSubpass->AddDepthOutput(depthResourceName, SH_RENDER_GRAPH_RESOURCE_FLAGS::DEPTH); // regenerate the node shadowMapNode->RuntimeStandaloneRegenerate(); @@ -828,7 +832,7 @@ namespace SHADE newSubpass->SetCompanionSubpass(companionSubpass, shadowMapPipeline); // set companion subpass and pipeline // add the shadow map to the lighting system - uint32_t const NEW_SHADOW_MAP_INDEX = lightingSubSystem->AddShadowMap(renderGraph->GetRenderGraphResource(resourceName), EVENT_DATA->lightEntity); + uint32_t const NEW_SHADOW_MAP_INDEX = lightingSubSystem->AddShadowMap(renderGraph->GetRenderGraphResource(shadowMapResourceName), EVENT_DATA->lightEntity); auto nodeCompute = renderGraph->GetNode(SHGraphicsConstants::RenderGraphEntityNames::DEFERRED_COMPOSITE_PASS.data())->GetNodeCompute(SHGraphicsConstants::RenderGraphEntityNames::DEFERRED_COMPOSITE_COMPUTE.data()); nodeCompute->ModifyWriteDescImageComputeResource(SHGraphicsConstants::DescriptorSetBindings::SHADOW_MAP_IMAGE_SAMPLER_DATA, lightingSubSystem->GetViewSamplerLayout(NEW_SHADOW_MAP_INDEX), NEW_SHADOW_MAP_INDEX); diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp index 9acdfed0..6f8a9030 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Lights/SHLightingSubSystem.cpp @@ -395,7 +395,11 @@ namespace SHADE switch (lightComp->GetLightData().type) { case SH_LIGHT_TYPE::DIRECTIONAL: - return SHMatrix::Transpose(SHMatrix::LookAtLH(lightComp->GetLightData().position, SHVec3::Normalise (lightComp->GetLightData().direction), SHVec3(0.0f, -1.0f, 0.0f))); + { + SHTransformComponent* transform = SHComponentManager::GetComponent(lightComp->GetEID()); + + return SHMatrix::Transpose(SHMatrix::LookAtLH(transform->GetWorldPosition(), SHVec3::Normalise(lightComp->GetLightData().direction), SHVec3(0.0f, -1.0f, 0.0f))); + } //return SHMatrix::Transpose(SHMatrix::LookAtLH(/*lightComp->GetLightData().position*/SHVec3(1.27862f, 4.78952f, 4.12811f), SHVec3(-0.280564f, -0.66262f, -0.69422f), SHVec3(0.0f, -1.0f, 0.0f))); case SH_LIGHT_TYPE::POINT: return {}; @@ -518,7 +522,7 @@ namespace SHADE if (auto renderer = light.GetRenderer()) { //SHMatrix orthoMatrix = SHMatrix::OrthographicRH() - renderer->UpdateDataManual(frameIndex, GetViewMatrix(&light), SHMatrix::OrthographicLH(10.0f, 10.0f, 1.0f, 50.0f)); + renderer->UpdateDataManual(frameIndex, GetViewMatrix(&light), SHMatrix::OrthographicLH(12.0f, 12.0f, 1.0f, 80.0f)); } auto enumValue = SHUtilities::ConvertEnum(light.GetLightData().type); @@ -627,16 +631,16 @@ namespace SHADE // add to barriers shadowMapMemoryBarriers.push_back (vk::ImageMemoryBarrier { - .srcAccessMask = vk::AccessFlagBits::eDepthStencilAttachmentWrite, + .srcAccessMask = vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead, .dstAccessMask = vk::AccessFlagBits::eShaderRead, - .oldLayout = vk::ImageLayout::eDepthAttachmentOptimal, + .oldLayout = vk::ImageLayout::eColorAttachmentOptimal, .newLayout = vk::ImageLayout::eShaderReadOnlyOptimal, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = newShadowMap->GetImage()->GetVkImage(), .subresourceRange = vk::ImageSubresourceRange { - .aspectMask = vk::ImageAspectFlagBits::eDepth, + .aspectMask = vk::ImageAspectFlagBits::eColor, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, @@ -651,7 +655,7 @@ namespace SHADE void SHLightingSubSystem::PrepareShadowMapsForRead(Handle cmdBuffer) noexcept { // Issue barrier to transition shadow maps for reading in compute shader - cmdBuffer->PipelineBarrier(vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests, vk::PipelineStageFlagBits::eComputeShader, {}, {}, {}, shadowMapMemoryBarriers); + cmdBuffer->PipelineBarrier(vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::PipelineStageFlagBits::eComputeShader, {}, {}, {}, shadowMapMemoryBarriers); } //void SHLightingSubSystem::HandleResize(Handle compute) noexcept From cee45863fafe7f103517f00b1e16850681e10c9c Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Fri, 17 Feb 2023 00:53:45 +0800 Subject: [PATCH 02/15] Trajectory rendering WIP --- Assets/Shaders/Trajectory_FS.glsl | 22 +++ Assets/Shaders/Trajectory_VS.glsl | 36 ++++ .../GlobalData/SHGraphicsPredefinedData.cpp | 12 ++ .../GlobalData/SHGraphicsPredefinedData.h | 1 + .../MiddleEnd/Interface/SHGraphicsConstants.h | 7 + .../MiddleEnd/Interface/SHGraphicsSystem.cpp | 31 +-- .../MiddleEnd/Interface/SHGraphicsSystem.h | 2 + .../SHTrajectoryRenderableComponent.cpp | 91 +++++++++ .../SHTrajectoryRenderableComponent.h | 57 ++++++ .../SHTrajectoryRenderingSubSystem.cpp | 179 ++++++++++++++++++ .../SHTrajectoryRenderingSubSystem.h | 66 +++++++ 11 files changed, 491 insertions(+), 13 deletions(-) create mode 100644 Assets/Shaders/Trajectory_FS.glsl create mode 100644 Assets/Shaders/Trajectory_VS.glsl create mode 100644 SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.cpp create mode 100644 SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.h create mode 100644 SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderingSubSystem.cpp create mode 100644 SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderingSubSystem.h diff --git a/Assets/Shaders/Trajectory_FS.glsl b/Assets/Shaders/Trajectory_FS.glsl new file mode 100644 index 00000000..4e36dfd9 --- /dev/null +++ b/Assets/Shaders/Trajectory_FS.glsl @@ -0,0 +1,22 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable +#extension GL_EXT_nonuniform_qualifier : require + + +layout(location = 0) in struct +{ + vec4 vertPos; // location 0 + vec2 uv; // location = 1 + vec4 color; // location = 2 + +} In; + +layout(location = 0) out vec4 fragColor; + + +void main() +{ + // default red first + fragColor = In.color; +} \ No newline at end of file diff --git a/Assets/Shaders/Trajectory_VS.glsl b/Assets/Shaders/Trajectory_VS.glsl new file mode 100644 index 00000000..6d932734 --- /dev/null +++ b/Assets/Shaders/Trajectory_VS.glsl @@ -0,0 +1,36 @@ +#version 450 +#extension GL_KHR_vulkan_glsl : enable + +// vertex inputs +layout(location = 0) in vec4 aPos; +layout(location = 1) in vec2 aUV; +layout(location = 2) in vec2 aColor; +layout(location = 3) in mat4 aTransform; + +// between shader stages +layout(location = 0) out struct +{ + vec4 vertPos; // location 0 + vec2 uv; // location = 1 + vec4 color; // location = 2 + +} Out; + + +// Camera data +layout(set = 1, binding = 0) uniform CameraData +{ + vec4 position; + mat4 vpMat; + mat4 viewMat; + mat4 projMat; +} cameraData; + + +void main() +{ + Out.uv = aUV; + Out.color = aColor; + + gl_Position = cameraData.projMat * aTransform * vec4(aPos, 1.0f); +} \ No newline at end of file diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/GlobalData/SHGraphicsPredefinedData.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/GlobalData/SHGraphicsPredefinedData.cpp index e65f5c8f..63b39c9f 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/GlobalData/SHGraphicsPredefinedData.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/GlobalData/SHGraphicsPredefinedData.cpp @@ -52,6 +52,12 @@ namespace SHADE {SHPredefinedDescriptorTypes::RENDER_GRAPH_RESOURCE, 3}, {SHPredefinedDescriptorTypes::RENDER_GRAPH_NODE_COMPUTE_RESOURCE, 4}, }); + + perSystemData[SHUtilities::ConvertEnum(SystemType::TRAJECTORY_RENDERING)].descMappings.AddMappings + ({ + {SHPredefinedDescriptorTypes::STATIC_DATA, 0}, + {SHPredefinedDescriptorTypes::CAMERA, 1}, + }); } void SHGraphicsPredefinedData::InitDummyPipelineLayouts(Handle logicalDevice) noexcept @@ -222,6 +228,12 @@ namespace SHADE SHGraphicsPredefinedData::PredefinedDescSetLayoutTypes::CAMERA | SHGraphicsPredefinedData::PredefinedDescSetLayoutTypes::LIGHTS ); + + perSystemData[SHUtilities::ConvertEnum(SystemType::TRAJECTORY_RENDERING)].descSetLayouts = GetPredefinedDescSetLayouts + ( + SHGraphicsPredefinedData::PredefinedDescSetLayoutTypes::STATIC_DATA | + SHGraphicsPredefinedData::PredefinedDescSetLayoutTypes::CAMERA + ); } void SHGraphicsPredefinedData::InitPredefinedVertexInputState(void) noexcept diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/GlobalData/SHGraphicsPredefinedData.h b/SHADE_Engine/src/Graphics/MiddleEnd/GlobalData/SHGraphicsPredefinedData.h index 43a4a55c..77307f57 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/GlobalData/SHGraphicsPredefinedData.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/GlobalData/SHGraphicsPredefinedData.h @@ -38,6 +38,7 @@ namespace SHADE BATCHING_ANIM, TEXT_RENDERING, RENDER_GRAPH_NODE_COMPUTE, + TRAJECTORY_RENDERING, NUM_TYPES }; static constexpr int SYSTEM_TYPE_COUNT = static_cast(SystemType::NUM_TYPES); diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h index fdad3584..569818b9 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h @@ -282,6 +282,13 @@ namespace SHADE */ /***************************************************************************/ static constexpr uint32_t BONE_MATRIX_FIRST_INDEX = 8; + /***************************************************************************/ + /*! + \brief + Vertex buffer bindings for color + */ + /***************************************************************************/ + static constexpr uint32_t TRAJECTORY_COLOR = 2; static constexpr uint32_t CALCULATED_GLYPH_POSITION = 0; static constexpr uint32_t GLYPH_INDEX = 1; diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp index ef68a356..7d783490 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp @@ -433,6 +433,11 @@ namespace SHADE auto uiNode = renderGraph->GetNode(SHGraphicsConstants::RenderGraphEntityNames::SCREEN_SPACE_PASS.data()); textRenderingSubSystem->Init(device, uiNode->GetRenderpass(), uiNode->GetSubpass(SHGraphicsConstants::RenderGraphEntityNames::UI_SUBPASS), descPool, textVS, textFS); + trajectoryRenderingSubSystem = resourceManager.Create(); + + //auto gBufferNode = renderGraph->GetNode(SHGraphicsConstants::RenderGraphEntityNames::SCREEN_SPACE_PASS.data()); + //trajectoryRenderingSubSystem->Init(device, ) + SHGlobalDescriptorSets::SetLightingSubSystem(lightingSubSystem); } @@ -589,19 +594,19 @@ namespace SHADE static bool shadowAdded = false; - if (shadowAdded == false && SHInputManager::GetKey(SHInputManager::SH_KEYCODE::B)) - { - shadowAdded = true; - auto& lightComps = SHComponentManager::GetDense(); - //if (lightComps.size() > 2) - //{ - // lightComps[2].SetEnableShadow(true); - //} - for (auto& comp : lightComps) - { - comp.SetEnableShadow(true); - } - } + //if (shadowAdded == false && SHInputManager::GetKey(SHInputManager::SH_KEYCODE::B)) + //{ + // shadowAdded = true; + // auto& lightComps = SHComponentManager::GetDense(); + // //if (lightComps.size() > 2) + // //{ + // // lightComps[2].SetEnableShadow(true); + // //} + // for (auto& comp : lightComps) + // { + // comp.SetEnableShadow(true); + // } + //} renderGraph->Begin(frameIndex); auto cmdBuffer = renderGraph->GetCommandBuffer(frameIndex); diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h index a35065bd..0576233f 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h @@ -36,6 +36,7 @@ of DigiPen Institute of Technology is prohibited. #include "Graphics/MiddleEnd/TextRendering/SHFontLibrary.h" #include "Graphics/MiddleEnd/Interface/SHRenderer.h" #include "Graphics/Events/SHGraphicsEvents.h" +#include "Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderingSubSystem.h" namespace SHADE { @@ -505,6 +506,7 @@ namespace SHADE Handle postOffscreenRenderSubSystem; Handle lightingSubSystem; Handle textRenderingSubSystem; + Handle trajectoryRenderingSubSystem; Handle ssaoStorage; uint32_t resizeWidth = 1; diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.cpp new file mode 100644 index 00000000..9401d076 --- /dev/null +++ b/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.cpp @@ -0,0 +1,91 @@ +#include "SHpch.h" +#include "SHTrajectoryRenderableComponent.h" + +namespace SHADE +{ + + /***************************************************************************/ + /*! + + \brief + On create the text has nothing. + + */ + /***************************************************************************/ + void SHTrajectoryRenderableComponent::OnCreate(void) + { + } + + void SHTrajectoryRenderableComponent::OnDestroy(void) + { + + } + + + void SHTrajectoryRenderableComponent::ClearPositions(void) noexcept + { + positions.clear(); + } + + bool SHTrajectoryRenderableComponent::HasPositions(void) const noexcept + { + return !positions.empty(); + } + + std::vector SHTrajectoryRenderableComponent::GetPositions(void) const noexcept + { + return positions; + } + + Handle SHTrajectoryRenderableComponent::GetMesh(void) const noexcept + { + return mesh; + } + + SHVec4 const& SHTrajectoryRenderableComponent::GetStartColor(void) const noexcept + { + return startColor; + } + + SHVec4 const& SHTrajectoryRenderableComponent::GetEndColor(void) const noexcept + { + return endColor; + } + + float SHTrajectoryRenderableComponent::GetColorEvolveRate(void) const noexcept + { + return colorEvolveRate; + } + + void SHTrajectoryRenderableComponent::SetMesh(Handle newMesh) noexcept + { + mesh = newMesh; + } + + void SHTrajectoryRenderableComponent::SetStartColor(SHVec4 color) noexcept + { + startColor = color; + } + + void SHTrajectoryRenderableComponent::SetEndColor(SHVec4 color) noexcept + { + endColor = color; + + } + + void SHTrajectoryRenderableComponent::SetColorEvolveRate(float rate) noexcept + { + colorEvolveRate = rate; + } + +} + +namespace rttr +{ + RTTR_REGISTRATION + { + using namespace SHADE; + + registration::class_("Trajectory Renderer Component"); + }; +} diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.h b/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.h new file mode 100644 index 00000000..ac0343d4 --- /dev/null +++ b/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.h @@ -0,0 +1,57 @@ +#pragma once + +#include "Math/Vector/SHVec3.h" +#include "Math/Vector/SHVec4.h" +#include "Resource/SHHandle.h" +#include "ECS_Base/Components/SHComponent.h" +#include + +namespace SHADE +{ + class SHMesh; + + class SHTrajectoryRenderableComponent : public SHComponent + { + private: + + //! Mesh used to render the trajectory + Handle mesh; + + //! positions to plot for rendering. Will be cleared every frame. + std::vector positions; + + //! Starting color of the trajectory + SHVec4 startColor; + + //! Color the trajectory should evolve to the longer it is + SHVec4 endColor; + + //! evolving rate of the color (with respect to dt) + float colorEvolveRate; + + public: + /*-----------------------------------------------------------------------*/ + /* PRIVATE MEMBER FUNCTIONS */ + /*-----------------------------------------------------------------------*/ + void SetMesh(Handle newMesh) noexcept; + void SetStartColor(SHVec4 startColor) noexcept; + void SetEndColor (SHVec4 endColor) noexcept; + void SetColorEvolveRate (float rate) noexcept; + + std::vector GetPositions (void) const noexcept; + Handle GetMesh (void) const noexcept; + SHVec4 const& GetStartColor (void) const noexcept; + SHVec4 const& GetEndColor (void) const noexcept; + float GetColorEvolveRate (void) const noexcept; + + void OnCreate(void) override final; + void OnDestroy(void) override final; + + void ClearPositions(void) noexcept; + bool HasPositions(void) const noexcept; + + + RTTR_ENABLE() + + }; +} diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderingSubSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderingSubSystem.cpp new file mode 100644 index 00000000..9eaca200 --- /dev/null +++ b/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderingSubSystem.cpp @@ -0,0 +1,179 @@ +#include "SHpch.h" +#include "SHTrajectoryRenderingSubSystem.h" +#include "ECS_Base/Managers/SHComponentManager.h" +#include "Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.h" +#include "Graphics/Devices/SHVkLogicalDevice.h" +#include "Math/Transform/SHTransformComponent.h" +#include "Graphics\MiddleEnd\Interface\SHMeshLibrary.h" +#include "Graphics/SHVkUtil.h" +#include "Graphics/MiddleEnd/GlobalData/SHGraphicsPredefinedData.h" +#include "Graphics/Pipeline/SHVkPipeline.h" +#include "Graphics/RenderGraph/SHSubpass.h" +#include "Graphics/MiddleEnd/GlobalData/SHGlobalDescriptorSets.h" +#include "Graphics/MiddleEnd/Interface/SHRenderer.h" + +namespace SHADE +{ + + + void SHTrajectoryRenderingSubSystem::Init(Handle device, Handle compatibleRenderpass, Handle subpass, Handle trajectoryVS, Handle trajectoryFS) noexcept + { + logicalDevice = device; + + SHComponentManager::CreateComponentSparseSet(); + + // prepare pipeline layout params + SHPipelineLayoutParams plParams + { + .shaderModules = {trajectoryVS, trajectoryFS}, + .predefinedDescSetLayouts = SHGraphicsPredefinedData::GetSystemData(SHGraphicsPredefinedData::SystemType::TRAJECTORY_RENDERING).descSetLayouts + }; + + pipelineLayout = logicalDevice->CreatePipelineLayout(plParams); + + // Create pipeline + pipeline = logicalDevice->CreateGraphicsPipeline(pipelineLayout, nullptr, compatibleRenderpass, subpass); + + // vertex input state of the pipeline + SHVertexInputState vertexInputState; + vertexInputState.AddBinding(false, false, { SHVertexAttribute(SHAttribFormat::FLOAT_3D) }); // Attribute positions at binding 0 + vertexInputState.AddBinding(false, false, { SHVertexAttribute(SHAttribFormat::FLOAT_2D) }); // Attribute uv at binding 1 + vertexInputState.AddBinding(true, true, { SHVertexAttribute(SHAttribFormat::FLOAT_4D) }); // Instanced attribute color at binding 2 + vertexInputState.AddBinding(true, true, { SHVertexAttribute(SHAttribFormat::MAT_4D) }); // Instanced Transform at binding 3 - 6 (4 slots) + + pipeline->GetPipelineState().SetVertexInputState(vertexInputState); + + SHColorBlendState colorBlendState{}; + colorBlendState.logic_op_enable = VK_FALSE; + colorBlendState.logic_op = vk::LogicOp::eCopy; + + + auto const& subpassColorReferences = subpass->GetColorAttachmentReferences(); + colorBlendState.attachments.reserve(static_cast(subpassColorReferences.size())); + + for (auto& att : subpassColorReferences) + { + colorBlendState.attachments.push_back(vk::PipelineColorBlendAttachmentState + { + .blendEnable = SHVkUtil::IsBlendCompatible(subpass->GetFormatFromAttachmentReference(att.attachment)) ? true : false, + .srcColorBlendFactor = vk::BlendFactor::eSrcAlpha, + .dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha, + .colorBlendOp = vk::BlendOp::eAdd, + .srcAlphaBlendFactor = vk::BlendFactor::eOne, + .dstAlphaBlendFactor = vk::BlendFactor::eZero, + .alphaBlendOp = vk::BlendOp::eAdd, + .colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA, + } + ); + } + + pipeline->GetPipelineState().SetColorBlenState(colorBlendState); + } + + void SHTrajectoryRenderingSubSystem::Run(uint32_t frameIndex, float dt) noexcept + { + auto& comps = SHComponentManager::GetDense(); + for (auto& comp : comps) + { + // If has positions, feed data to buffer. + if (comp.HasPositions()) + { + SHTransformComponent* transform = SHComponentManager::GetComponent_s(comp.GetEID()); + if (transform) + { + // convenient variable + SHVec4 const& startColor = comp.GetStartColor(); + SHVec4 const& endColor = comp.GetEndColor(); + float colorEvolveRate = comp.GetColorEvolveRate(); + + // trs to be reused + SHMatrix trs = transform->GetTRS(); + + // starting color of trajectory + SHVec4 currentColor = comp.GetStartColor(); + + // Start from 0 and slowly evolve to 1 + float lerpValue = 0.0f; + + // Will be used for baseInstance later + uint32_t oldTransformDataSize = transformData.size(); + + auto meshHandle = comp.GetMesh(); + + auto const& positions = comp.GetPositions(); + for (auto& pos : positions) + { + // modify position and reuse matrix + trs.m[3][0] = pos.x; + trs.m[3][1] = pos.y; + trs.m[3][2] = pos.z; + + transformData.push_back(trs); + colorData.push_back(currentColor); + + // evolve color + currentColor = SHVec4::Lerp(startColor, endColor, lerpValue); + + // evolve lerp value and clamp to 1 + lerpValue = std::max (1.0f, lerpValue + (colorEvolveRate * dt)); + } + + // add draw data for this trajectory + drawData.push_back(vk::DrawIndexedIndirectCommand + { + .indexCount = meshHandle->IndexCount, + .instanceCount = static_cast(transformData.size()) - oldTransformDataSize, + .firstIndex = meshHandle->FirstIndex, + .vertexOffset = meshHandle->FirstVertex, + .firstInstance = oldTransformDataSize + }); + } + } + + // clear at the end of every frame since data is already in buffers + comp.ClearPositions(); + } + + // read transform data to buffer + // read draw data to buffer + SHVkUtil::EnsureBufferAndCopyHostVisibleData(logicalDevice, transformBuffer, transformData.data(), sizeof (SHMatrix) * transformData.size(), vk::BufferUsageFlagBits::eVertexBuffer, "Trajectory System Transform Buffer"); + + SHVkUtil::EnsureBufferAndCopyHostVisibleData(logicalDevice, drawDataBuffer, drawData.data(), sizeof(vk::DrawIndexedIndirectCommand) * drawData.size(), vk::BufferUsageFlagBits::eIndirectBuffer, "Trajectory System Draw Data Buffer"); + + SHVkUtil::EnsureBufferAndCopyHostVisibleData(logicalDevice, colorBuffer, colorData.data(), sizeof(SHVec4) * colorData.size(), vk::BufferUsageFlagBits::eVertexBuffer, "Trajectory System Color Data Buffer"); + + } + + void SHTrajectoryRenderingSubSystem::Render(Handle cmdBuffer, Handle renderer, uint32_t frameIndex) noexcept + { + auto const& mappings = SHGraphicsPredefinedData::GetMappings(SHGraphicsPredefinedData::SystemType::TRAJECTORY_RENDERING); + uint32_t staticGlobalSetIndex = mappings.at(SHPredefinedDescriptorTypes::STATIC_DATA); + uint32_t cameraSetIndex = mappings.at(SHPredefinedDescriptorTypes::CAMERA); + + cmdBuffer->BindPipeline(pipeline); + + // Bind global data + SHGlobalDescriptorSets::BindStaticGlobalData(cmdBuffer, SH_PIPELINE_TYPE::GRAPHICS, staticGlobalSetIndex); + + // Bind camera data + renderer->BindDescriptorSet(cmdBuffer, SH_PIPELINE_TYPE::GRAPHICS, cameraSetIndex, frameIndex); + + // Bind color vertex buffer + cmdBuffer->BindVertexBuffer(SHGraphicsConstants::VertexBufferBindings::TRAJECTORY_COLOR, colorBuffer, 0); + + // call draw call + cmdBuffer->DrawMultiIndirect(drawDataBuffer, drawData.size()); + + // clear CPU transform and draw data + transformData.clear(); + drawData.clear(); + colorData.clear(); + + } + + void SHTrajectoryRenderingSubSystem::Exit(void) noexcept + { + + } + +} \ No newline at end of file diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderingSubSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderingSubSystem.h new file mode 100644 index 00000000..2bba5703 --- /dev/null +++ b/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderingSubSystem.h @@ -0,0 +1,66 @@ +#pragma once + +#include "Resource/SHHandle.h" +#include "Graphics/Pipeline/SHPipelineState.h" +#include "Math/SHMatrix.h" + +namespace SHADE +{ + class SHVkLogicalDevice; + class SHVkDescriptorPool; + class SHVkDescriptorSetGroup; + class SHVkDescriptorSetLayout; + class SHVkBuffer; + class SHLightComponent; + class SHVkCommandBuffer; + class SHVkPipeline; + class SHVkPipelineLayout; + class SHVkRenderpass; + class SHSubpass; + class SHVkShaderModule; + class SHRenderer; + + + + class SHTrajectoryRenderingSubSystem + { + private: + + Handle logicalDevice; + + //! Every trajectory renderable will have one of these + std::vector drawData; + + //! For the MDI call + Handle drawDataBuffer; + + //! matrix data to copy into buffer + std::vector transformData; + + //! All trajectory renderables will use this transform buffer + Handle transformBuffer; + + //! Each object will have their own color data + std::vector colorData; + + //! buffer to hold color data for objects + Handle colorBuffer; + + //! Pipeline for rendering the trajectories + Handle pipeline; + + //! Pipeline layout for the pipeline + Handle pipelineLayout; + + + + public: + void Init (Handle device, Handle compatibleRenderpass, Handle subpass, Handle textVS, Handle textFS) noexcept; + + void Run(uint32_t frameIndex, float dt) noexcept; + + void Render(Handle cmdBuffer, Handle renderer, uint32_t frameIndex) noexcept; + void Exit(void) noexcept; + + }; +} From f1217cc20b9b8e406242d2a41ed52c60a300a6ef Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Fri, 17 Feb 2023 13:48:14 +0800 Subject: [PATCH 03/15] Trajectory Rendering WIP - Trajectory rendering system is all in place. Just requires testing through the component. - Component needs to be reflected in editor - Shaders for trajectory rendering is also in place --- Assets/Shaders/Trajectory_FS.shshaderb | Bin 0 -> 729 bytes Assets/Shaders/Trajectory_FS.shshaderb.shmeta | 3 + Assets/Shaders/Trajectory_VS.glsl | 4 +- Assets/Shaders/Trajectory_VS.shshaderb | Bin 0 -> 1973 bytes Assets/Shaders/Trajectory_VS.shshaderb.shmeta | 3 + .../MiddleEnd/Interface/SHGraphicsConstants.h | 12 ++++ .../MiddleEnd/Interface/SHGraphicsSystem.cpp | 27 ++++++-- .../MiddleEnd/Interface/SHGraphicsSystem.h | 2 + .../SHTrajectoryRenderableComponent.cpp | 5 ++ .../SHTrajectoryRenderableComponent.h | 3 +- .../SHTrajectoryRenderingSubSystem.cpp | 58 +++++++++++------- .../SHTrajectoryRenderingSubSystem.h | 2 +- 12 files changed, 86 insertions(+), 33 deletions(-) create mode 100644 Assets/Shaders/Trajectory_FS.shshaderb create mode 100644 Assets/Shaders/Trajectory_FS.shshaderb.shmeta create mode 100644 Assets/Shaders/Trajectory_VS.shshaderb create mode 100644 Assets/Shaders/Trajectory_VS.shshaderb.shmeta diff --git a/Assets/Shaders/Trajectory_FS.shshaderb b/Assets/Shaders/Trajectory_FS.shshaderb new file mode 100644 index 0000000000000000000000000000000000000000..9e6418664274937ed9d79371b46b6a1a16c80860 GIT binary patch literal 729 zcmY*W+e*Vg5FOj5)p~0!>RYM!D3l^9f+$pxAOtGvgKx{4ZtH4HVlD-L&oA(Ed=We+ zMyv~y**SCO?98O~QIXBvbbcUdO9hC?veXOjdbeIb&BpzM!vQI4QZ1O| ztV=^`@U$0gLnfABtFRV$#PI-bRj7)*qo@Xk>#5<*xk^o}6P+2AKI*YaRP^v<{4D*? zLCS_x73gr9>#0!(`-52f&(K+<&gK1`3ZpO&?IcQG)N8H-JFzA~zRA2h8oA!3^5a;g z*;`;#U_+zEHo;4FX82a2Q}S%+2l;rO;D9kdpCe8&<0R43iztW^%;jLdWq6)CqTl<> zB-wS80;?4mcb3ooINXUpr@_5lVT&&K++!EU!xPxu7cBj~^6!$IM>%e-jZSc8w z#_YX^?;#K-I3G0_voB(sh}YnIWxQ9$>xikz t`c|2v-Vxp)&i;7V$0ra6euyu*Z5Z{baSA5uHekfhP{IBgf1!h8*f&<_RKNfL literal 0 HcmV?d00001 diff --git a/Assets/Shaders/Trajectory_FS.shshaderb.shmeta b/Assets/Shaders/Trajectory_FS.shshaderb.shmeta new file mode 100644 index 00000000..296c38c9 --- /dev/null +++ b/Assets/Shaders/Trajectory_FS.shshaderb.shmeta @@ -0,0 +1,3 @@ +Name: Trajectory_FS +ID: 45635685 +Type: 2 diff --git a/Assets/Shaders/Trajectory_VS.glsl b/Assets/Shaders/Trajectory_VS.glsl index 6d932734..86be6b7e 100644 --- a/Assets/Shaders/Trajectory_VS.glsl +++ b/Assets/Shaders/Trajectory_VS.glsl @@ -2,9 +2,9 @@ #extension GL_KHR_vulkan_glsl : enable // vertex inputs -layout(location = 0) in vec4 aPos; +layout(location = 0) in vec3 aPos; layout(location = 1) in vec2 aUV; -layout(location = 2) in vec2 aColor; +layout(location = 2) in vec4 aColor; layout(location = 3) in mat4 aTransform; // between shader stages diff --git a/Assets/Shaders/Trajectory_VS.shshaderb b/Assets/Shaders/Trajectory_VS.shshaderb new file mode 100644 index 0000000000000000000000000000000000000000..6f509f5c39101e9c796f0e8d0de035a74a9217ec GIT binary patch literal 1973 zcmZ9L+iuf95Qd#LX-lCkrSt%l;SW&fA#Xg3urk@;Z2mgy)p&5=% zEbawq5Jy5M4WGRY9z^L;@J**ACyUXCVtZlG-4A-H7q$IijHwgrhv6_rugsWL(N~q; z^G^K4+xJp0>jjL}wT;MTHsB@6p!>#43m82N0{=6p<*|1+i9dm{&xZVVVIMH=*?X6G zQSU>XoX}6%+`Gr%wd(SjtL+z`+2Yd&zI`+FaG(mzmzBM;5e6R&ZF%H?(W}LNiyz7iLTieEvmy2Mg+mo~nux$6k^(A?-?*#b;l9W{5wP`*7FP zIsY3RaI`DVv^4dIJmM$4P%g5(k zfN`hyq&bVtzn{mzIR`%P20r`2-I6%Y_m{hR1N6ZeSk(9{gg501(T>)(~lnSUwAmEM%V z0f)m`A4oXoTX8t!!yJ$oO%6JU1B>D_J?E7xGS5t Q!u#Ni`0)N|>Q5#A0UK?K#sB~S literal 0 HcmV?d00001 diff --git a/Assets/Shaders/Trajectory_VS.shshaderb.shmeta b/Assets/Shaders/Trajectory_VS.shshaderb.shmeta new file mode 100644 index 00000000..74584b44 --- /dev/null +++ b/Assets/Shaders/Trajectory_VS.shshaderb.shmeta @@ -0,0 +1,3 @@ +Name: Trajectory_VS +ID: 41042628 +Type: 2 diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h index 569818b9..38fe9aa3 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsConstants.h @@ -64,6 +64,17 @@ namespace SHADE /***************************************************************************/ static constexpr std::string_view DEFERRED_COMPOSITE_PASS = "Deferred Comp Pass"; + /***************************************************************************/ + /*! + + \brief + Name of vfx render graph node. + + */ + /***************************************************************************/ + static constexpr std::string_view VFX_PASS = "Vfx Pass"; + + /***************************************************************************/ /*! @@ -117,6 +128,7 @@ namespace SHADE static constexpr std::string_view GBUFFER_WRITE_SUBPASS = "G-Buffer Write"; static constexpr std::string_view UI_SUBPASS = "UI"; + static constexpr std::string_view VFX_SUBPASS = "VFX"; static constexpr std::array USABLE_SUBPASSES = { diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp index 7d783490..976939ce 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp @@ -138,7 +138,8 @@ namespace SHADE //SHAssetManager::CompileAsset("../../Assets/Shaders/UI_VS.glsl", false); //SHAssetManager::CompileAsset("../../Assets/Shaders/UI_FS.glsl", false); //SHAssetManager::CompileAsset("../../Assets/Shaders/Text_VS.glsl", false); - + SHAssetManager::CompileAsset("../../Assets/Shaders/Trajectory_VS.glsl", false); + SHAssetManager::CompileAsset("../../Assets/Shaders/Trajectory_FS.glsl", false); // Load Built In Shaders static constexpr AssetID VS_DEFAULT = 39210065; defaultVertShader = SHResourceManager::LoadOrGet(VS_DEFAULT); @@ -154,8 +155,10 @@ namespace SHADE static constexpr AssetID TEXT_FS = 38024754; textFS = SHResourceManager::LoadOrGet(TEXT_FS); static constexpr AssetID RENDER_SC_VS = 48082949; renderToSwapchainVS = SHResourceManager::LoadOrGet(RENDER_SC_VS); static constexpr AssetID RENDER_SC_FS = 36869006; renderToSwapchainFS = SHResourceManager::LoadOrGet(RENDER_SC_FS); - static constexpr AssetID SHADOW_MAP_VS = 44646107; shadowMapVS = SHResourceManager::LoadOrGet(SHADOW_MAP_VS); - static constexpr AssetID SHADOW_MAP_FS = 45925790; shadowMapFS = SHResourceManager::LoadOrGet(SHADOW_MAP_FS); + static constexpr AssetID SHADOW_MAP_VS = 44646107; shadowMapVS = SHResourceManager::LoadOrGet(SHADOW_MAP_VS); + static constexpr AssetID SHADOW_MAP_FS = 45925790; shadowMapFS = SHResourceManager::LoadOrGet(SHADOW_MAP_FS); + static constexpr AssetID TRAJECTORY_VS = 41042628; trajectoryVS = SHResourceManager::LoadOrGet(TRAJECTORY_VS); + static constexpr AssetID TRAJECTORY_FS = 45635685; trajectoryFS = SHResourceManager::LoadOrGet(TRAJECTORY_FS); } @@ -308,13 +311,24 @@ namespace SHADE lightingSubSystem->PrepareShadowMapsForRead(cmdBuffer); }); + /*-----------------------------------------------------------------------*/ + /* VFX PASS */ + /*-----------------------------------------------------------------------*/ + auto vfxPass = renderGraph->AddNode(SHGraphicsConstants::RenderGraphEntityNames::VFX_PASS.data(), { "Scene", "Depth Buffer" }, { SHGraphicsConstants::RenderGraphEntityNames::GBUFFER_PASS.data(), SHGraphicsConstants::RenderGraphEntityNames::DEFERRED_COMPOSITE_PASS.data() }); + auto vfxSubpass = vfxPass->AddSubpass("Vfx Subpass", worldViewport, worldRenderer); + vfxSubpass->AddColorOutput("Scene"); + vfxSubpass->AddDepthOutput("Depth Buffer"); + vfxSubpass->AddExteriorDrawCalls([=](Handle cmdBuffer, Handle renderer, uint32_t frameIndex) + { + trajectoryRenderingSubSystem->Render(cmdBuffer, renderer, frameIndex); + }); /*-----------------------------------------------------------------------*/ /* DEBUG DRAW PASS INIT */ /*-----------------------------------------------------------------------*/ // Set up Debug Draw Passes // - Depth Tested - auto debugDrawNodeDepth = renderGraph->AddNode(SHGraphicsConstants::RenderGraphEntityNames::DEBUG_DRAW_DEPTH_PASS.data(), {"Scene", "Depth Buffer"}, {SHGraphicsConstants::RenderGraphEntityNames::GBUFFER_PASS.data(), SHGraphicsConstants::RenderGraphEntityNames::DEFERRED_COMPOSITE_PASS.data()}); + auto debugDrawNodeDepth = renderGraph->AddNode(SHGraphicsConstants::RenderGraphEntityNames::DEBUG_DRAW_DEPTH_PASS.data(), {"Scene", "Depth Buffer"}, { SHGraphicsConstants::RenderGraphEntityNames::VFX_PASS.data()/*, SHGraphicsConstants::RenderGraphEntityNames::DEFERRED_COMPOSITE_PASS.data()*/}); auto debugDrawDepthSubpass = debugDrawNodeDepth->AddSubpass("Debug Draw with Depth", worldViewport, worldRenderer); debugDrawDepthSubpass->AddColorOutput("Scene"); debugDrawDepthSubpass->AddDepthOutput("Depth Buffer"); @@ -435,8 +449,8 @@ namespace SHADE trajectoryRenderingSubSystem = resourceManager.Create(); - //auto gBufferNode = renderGraph->GetNode(SHGraphicsConstants::RenderGraphEntityNames::SCREEN_SPACE_PASS.data()); - //trajectoryRenderingSubSystem->Init(device, ) + auto vfxNode = renderGraph->GetNode(SHGraphicsConstants::RenderGraphEntityNames::SCREEN_SPACE_PASS.data()); + trajectoryRenderingSubSystem->Init(device, vfxNode->GetRenderpass(), vfxNode->GetSubpass(SHGraphicsConstants::RenderGraphEntityNames::UI_SUBPASS), trajectoryVS, trajectoryFS); SHGlobalDescriptorSets::SetLightingSubSystem(lightingSubSystem); @@ -572,6 +586,7 @@ namespace SHADE } textRenderingSubSystem->Run(frameIndex); + trajectoryRenderingSubSystem->Run(frameIndex); for (auto renderer : renderers) diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h index 0576233f..21d18be1 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.h @@ -471,6 +471,8 @@ namespace SHADE Handle renderToSwapchainFS; Handle shadowMapVS; Handle shadowMapFS; + Handle trajectoryVS; + Handle trajectoryFS; // Fonts Handle testFont; diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.cpp index 9401d076..77dd66c8 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.cpp @@ -62,6 +62,11 @@ namespace SHADE mesh = newMesh; } + void SHTrajectoryRenderableComponent::SetPositions(std::vector const& inPositions) noexcept + { + positions = inPositions; + } + void SHTrajectoryRenderableComponent::SetStartColor(SHVec4 color) noexcept { startColor = color; diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.h b/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.h index ac0343d4..d6f7be12 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderableComponent.h @@ -26,7 +26,7 @@ namespace SHADE //! Color the trajectory should evolve to the longer it is SHVec4 endColor; - //! evolving rate of the color (with respect to dt) + //! evolving rate of the color float colorEvolveRate; public: @@ -34,6 +34,7 @@ namespace SHADE /* PRIVATE MEMBER FUNCTIONS */ /*-----------------------------------------------------------------------*/ void SetMesh(Handle newMesh) noexcept; + void SetPositions (std::vector const& inPositions) noexcept; void SetStartColor(SHVec4 startColor) noexcept; void SetEndColor (SHVec4 endColor) noexcept; void SetColorEvolveRate (float rate) noexcept; diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderingSubSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderingSubSystem.cpp index 9eaca200..740ffa92 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderingSubSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderingSubSystem.cpp @@ -70,11 +70,17 @@ namespace SHADE pipeline->GetPipelineState().SetColorBlenState(colorBlendState); } - void SHTrajectoryRenderingSubSystem::Run(uint32_t frameIndex, float dt) noexcept + void SHTrajectoryRenderingSubSystem::Run(uint32_t frameIndex) noexcept { auto& comps = SHComponentManager::GetDense(); for (auto& comp : comps) { + comp.SetPositions(std::vector + { + SHVec3 {}, + SHVec3 {} + }); + // If has positions, feed data to buffer. if (comp.HasPositions()) { @@ -115,7 +121,7 @@ namespace SHADE currentColor = SHVec4::Lerp(startColor, endColor, lerpValue); // evolve lerp value and clamp to 1 - lerpValue = std::max (1.0f, lerpValue + (colorEvolveRate * dt)); + lerpValue = std::max (1.0f, lerpValue + colorEvolveRate); } // add draw data for this trajectory @@ -134,40 +140,46 @@ namespace SHADE comp.ClearPositions(); } - // read transform data to buffer - // read draw data to buffer - SHVkUtil::EnsureBufferAndCopyHostVisibleData(logicalDevice, transformBuffer, transformData.data(), sizeof (SHMatrix) * transformData.size(), vk::BufferUsageFlagBits::eVertexBuffer, "Trajectory System Transform Buffer"); + if (!transformData.empty()) + { + // read transform data to buffer + // read draw data to buffer + SHVkUtil::EnsureBufferAndCopyHostVisibleData(logicalDevice, transformBuffer, transformData.data(), sizeof (SHMatrix) * transformData.size(), vk::BufferUsageFlagBits::eVertexBuffer, "Trajectory System Transform Buffer"); - SHVkUtil::EnsureBufferAndCopyHostVisibleData(logicalDevice, drawDataBuffer, drawData.data(), sizeof(vk::DrawIndexedIndirectCommand) * drawData.size(), vk::BufferUsageFlagBits::eIndirectBuffer, "Trajectory System Draw Data Buffer"); + SHVkUtil::EnsureBufferAndCopyHostVisibleData(logicalDevice, drawDataBuffer, drawData.data(), sizeof(vk::DrawIndexedIndirectCommand) * drawData.size(), vk::BufferUsageFlagBits::eIndirectBuffer, "Trajectory System Draw Data Buffer"); - SHVkUtil::EnsureBufferAndCopyHostVisibleData(logicalDevice, colorBuffer, colorData.data(), sizeof(SHVec4) * colorData.size(), vk::BufferUsageFlagBits::eVertexBuffer, "Trajectory System Color Data Buffer"); + SHVkUtil::EnsureBufferAndCopyHostVisibleData(logicalDevice, colorBuffer, colorData.data(), sizeof(SHVec4) * colorData.size(), vk::BufferUsageFlagBits::eVertexBuffer, "Trajectory System Color Data Buffer"); + } } void SHTrajectoryRenderingSubSystem::Render(Handle cmdBuffer, Handle renderer, uint32_t frameIndex) noexcept { - auto const& mappings = SHGraphicsPredefinedData::GetMappings(SHGraphicsPredefinedData::SystemType::TRAJECTORY_RENDERING); - uint32_t staticGlobalSetIndex = mappings.at(SHPredefinedDescriptorTypes::STATIC_DATA); - uint32_t cameraSetIndex = mappings.at(SHPredefinedDescriptorTypes::CAMERA); + if (!transformData.empty()) + { + auto const& mappings = SHGraphicsPredefinedData::GetMappings(SHGraphicsPredefinedData::SystemType::TRAJECTORY_RENDERING); + uint32_t staticGlobalSetIndex = mappings.at(SHPredefinedDescriptorTypes::STATIC_DATA); + uint32_t cameraSetIndex = mappings.at(SHPredefinedDescriptorTypes::CAMERA); - cmdBuffer->BindPipeline(pipeline); + cmdBuffer->BindPipeline(pipeline); - // Bind global data - SHGlobalDescriptorSets::BindStaticGlobalData(cmdBuffer, SH_PIPELINE_TYPE::GRAPHICS, staticGlobalSetIndex); + // Bind global data + SHGlobalDescriptorSets::BindStaticGlobalData(cmdBuffer, SH_PIPELINE_TYPE::GRAPHICS, staticGlobalSetIndex); - // Bind camera data - renderer->BindDescriptorSet(cmdBuffer, SH_PIPELINE_TYPE::GRAPHICS, cameraSetIndex, frameIndex); + // Bind camera data + renderer->BindDescriptorSet(cmdBuffer, SH_PIPELINE_TYPE::GRAPHICS, cameraSetIndex, frameIndex); - // Bind color vertex buffer - cmdBuffer->BindVertexBuffer(SHGraphicsConstants::VertexBufferBindings::TRAJECTORY_COLOR, colorBuffer, 0); + // Bind color vertex buffer + cmdBuffer->BindVertexBuffer(SHGraphicsConstants::VertexBufferBindings::TRAJECTORY_COLOR, colorBuffer, 0); - // call draw call - cmdBuffer->DrawMultiIndirect(drawDataBuffer, drawData.size()); + // call draw call + cmdBuffer->DrawMultiIndirect(drawDataBuffer, drawData.size()); - // clear CPU transform and draw data - transformData.clear(); - drawData.clear(); - colorData.clear(); + // clear CPU transform and draw data + transformData.clear(); + drawData.clear(); + colorData.clear(); + } } diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderingSubSystem.h b/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderingSubSystem.h index 2bba5703..12db99a0 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderingSubSystem.h +++ b/SHADE_Engine/src/Graphics/MiddleEnd/TrajectoryRendering/SHTrajectoryRenderingSubSystem.h @@ -57,7 +57,7 @@ namespace SHADE public: void Init (Handle device, Handle compatibleRenderpass, Handle subpass, Handle textVS, Handle textFS) noexcept; - void Run(uint32_t frameIndex, float dt) noexcept; + void Run(uint32_t frameIndex) noexcept; void Render(Handle cmdBuffer, Handle renderer, uint32_t frameIndex) noexcept; void Exit(void) noexcept; From 19d81b80f6b59fe5bc1bbb59e4d6753ed96a5acd Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Fri, 17 Feb 2023 18:29:44 +0800 Subject: [PATCH 04/15] Base files for particles --- .../MiddleEnd/Particles/SHParticleSubSustem.h | 41 +++++++++++++++++++ .../Particles/SHParticleSubSystem.cpp | 6 +++ 2 files changed, 47 insertions(+) create mode 100644 SHADE_Engine/src/Graphics/MiddleEnd/Particles/SHParticleSubSustem.h create mode 100644 SHADE_Engine/src/Graphics/MiddleEnd/Particles/SHParticleSubSystem.cpp diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Particles/SHParticleSubSustem.h b/SHADE_Engine/src/Graphics/MiddleEnd/Particles/SHParticleSubSustem.h new file mode 100644 index 00000000..da806480 --- /dev/null +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Particles/SHParticleSubSustem.h @@ -0,0 +1,41 @@ +#pragma once + +#include "Resource/SHHandle.h" +#include "Graphics/Pipeline/SHPipelineState.h" +#include "Math/SHMatrix.h" + +namespace SHADE +{ + class SHVkLogicalDevice; + class SHVkDescriptorPool; + class SHVkDescriptorSetGroup; + class SHVkDescriptorSetLayout; + class SHVkBuffer; + class SHLightComponent; + class SHVkCommandBuffer; + class SHVkPipeline; + class SHVkPipelineLayout; + class SHVkRenderpass; + class SHSubpass; + class SHVkShaderModule; + class SHRenderer; + + + + class SHParticleSubSystem + { + private: + + Handle logicalDevice; + + + public: + void Init(Handle device, Handle compatibleRenderpass, Handle subpass) noexcept; + + void Run(uint32_t frameIndex) noexcept; + + void Render(Handle cmdBuffer, Handle renderer, uint32_t frameIndex) noexcept; + void Exit(void) noexcept; + + }; +} diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Particles/SHParticleSubSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Particles/SHParticleSubSystem.cpp new file mode 100644 index 00000000..39bcab5b --- /dev/null +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Particles/SHParticleSubSystem.cpp @@ -0,0 +1,6 @@ +#include "SHParticleSubSustem.h" + +namespace SHADE +{ + +} \ No newline at end of file From dfe4d047e91405069c7e1df3b83fdb057be8791f Mon Sep 17 00:00:00 2001 From: Glence Date: Sat, 18 Feb 2023 22:21:23 +0800 Subject: [PATCH 05/15] added a jumppad to the game --- Assets/Scenes/MainGame.shade | 37 ++++++++++++++++--- .../Gameplay/Player/SC_PlayerController.cs | 14 ++++++- Assets/Scripts/SC_JumpPad.cs | 22 +++++++++++ Assets/Scripts/SC_JumpPad.cs.shmeta | 3 ++ 4 files changed, 69 insertions(+), 7 deletions(-) create mode 100644 Assets/Scripts/SC_JumpPad.cs create mode 100644 Assets/Scripts/SC_JumpPad.cs.shmeta diff --git a/Assets/Scenes/MainGame.shade b/Assets/Scenes/MainGame.shade index 87343839..53b5a0a0 100644 --- a/Assets/Scenes/MainGame.shade +++ b/Assets/Scenes/MainGame.shade @@ -9671,6 +9671,7 @@ maxJumpHeight: 2 maxJumpTime: 0.75 fallMultipler: 3 + jumpPadMultiplayer: 1.20000005 lightMultiper: 0.75 mediumMultiper: 0.5 heavyMultiper: 0.25 @@ -9682,6 +9683,7 @@ aimingLength: 1 throwItem: false rayDistance: 0.75 + rayHeight: 0.100000001 - EID: 3 Name: HoldingPoint IsActive: true @@ -10483,11 +10485,11 @@ Translate: {x: 2.70000005, y: 0.100000001, z: -2} Rotate: {x: -0, y: 0, z: -0} Scale: {x: 1, y: 1, z: 1} - IsActive: true + IsActive: false Renderable Component: Mesh: 140697366 Material: 129495479 - IsActive: true + IsActive: false RigidBody Component: Type: Dynamic Drag: 0.00999999978 @@ -10501,7 +10503,7 @@ Freeze Rotation X: true Freeze Rotation Y: false Freeze Rotation Z: true - IsActive: true + IsActive: false Collider Component: Colliders: - Is Trigger: false @@ -10513,7 +10515,7 @@ Density: 1 Position Offset: {x: 0, y: 0.899999976, z: 0} Rotation Offset: {x: 0, y: 0, z: 0} - IsActive: true + IsActive: false Scripts: - Type: Homeowner1 Enabled: true @@ -10525,4 +10527,29 @@ eyeOffset: [0, 1.64999998, 0] distanceToCapture: 0.5 captureTime: 0.5 - footstepSFXIntervalMultiplier: 0.5 \ No newline at end of file + footstepSFXIntervalMultiplier: 0.5 +- EID: 16 + Name: Default + IsActive: true + NumberOfChildren: 0 + Components: + Transform Component: + Translate: {x: 3.43332767, y: 0.149463654, z: 6.84711409} + Rotate: {x: -0, y: 0, z: -0} + Scale: {x: 1, y: 1, z: 1} + IsActive: true + Collider Component: + Colliders: + - Is Trigger: false + Collision Tag: 0 + Type: Box + Half Extents: {x: 1, y: 0.25, z: 1} + Friction: 0.400000006 + Bounciness: 0 + Density: 1 + Position Offset: {x: 0, y: 0, z: 0} + Rotation Offset: {x: 0, y: 0, z: 0} + IsActive: true + Scripts: + - Type: JumpPad + Enabled: true \ No newline at end of file diff --git a/Assets/Scripts/Gameplay/Player/SC_PlayerController.cs b/Assets/Scripts/Gameplay/Player/SC_PlayerController.cs index d66e7e30..202e587e 100644 --- a/Assets/Scripts/Gameplay/Player/SC_PlayerController.cs +++ b/Assets/Scripts/Gameplay/Player/SC_PlayerController.cs @@ -65,7 +65,7 @@ public class PlayerController : Script //Jumping vars================================================================== [Tooltip("max height of the jump")] public float maxJumpHeight = 1.0f; - [Tooltip("max amt of time it will take for the jump")] + [Tooltip("max amount of time it will take for the jump")] public float maxJumpTime = 0.5f; [Tooltip("increase gravity when falling")] public float fallMultipler = 3.0f; @@ -73,6 +73,9 @@ public class PlayerController : Script private bool isGrounded = true; private float gravity = -9.8f; private float groundGravity = -0.5f; + public bool landedOnJumpPad { get; set; } + [Tooltip("multiply height on Jump Pad ")] + public float jumpPadMultiplayer = 2.0f; //ItemMultipler================================================================== [Tooltip("How light item will affect player jump")] @@ -88,6 +91,7 @@ public class PlayerController : Script isMoveKeyPress = false; holdItem = false; isAiming = false; + landedOnJumpPad = false; //Jump setup float timeToApex = maxJumpTime / 2; @@ -287,7 +291,7 @@ public class PlayerController : Script { if (currentState == RaccoonStates.WALKING || currentState == RaccoonStates.RUNNING || currentState == RaccoonStates.IDLE) { - if (Input.GetKeyDown(Input.KeyCode.Space) && isGrounded && rb != null) + if ( (Input.GetKeyDown(Input.KeyCode.Space) || landedOnJumpPad ) && isGrounded && rb != null) { currentState = RaccoonStates.JUMP; Vector3 v = rb.LinearVelocity; @@ -302,6 +306,12 @@ public class PlayerController : Script if (item != null && item.currCategory == ItemCategory.HEAVY) v.y *= heavyMultiper; } + + if (landedOnJumpPad) + { + v.y *= jumpPadMultiplayer; + landedOnJumpPad = false; + } rb.LinearVelocity = v; } } diff --git a/Assets/Scripts/SC_JumpPad.cs b/Assets/Scripts/SC_JumpPad.cs new file mode 100644 index 00000000..0e331f8c --- /dev/null +++ b/Assets/Scripts/SC_JumpPad.cs @@ -0,0 +1,22 @@ +using SHADE; +using System; + +public class JumpPad : Script +{ + protected override void awake() + { + } + + protected override void update() + { + } + + protected override void onCollisionEnter(CollisionInfo info) + { + if (info.GameObject.GetScript() && info.GameObject.GetScript().currentState == PlayerController.RaccoonStates.FALLING) + { + info.GameObject.GetScript().landedOnJumpPad = true; + } + } + +} diff --git a/Assets/Scripts/SC_JumpPad.cs.shmeta b/Assets/Scripts/SC_JumpPad.cs.shmeta new file mode 100644 index 00000000..62a99f19 --- /dev/null +++ b/Assets/Scripts/SC_JumpPad.cs.shmeta @@ -0,0 +1,3 @@ +Name: SC_JumpPad +ID: 167326885 +Type: 9 From d754a0b5c3836c7a236a7b15f57c5affc48c976d Mon Sep 17 00:00:00 2001 From: Glence Date: Sat, 18 Feb 2023 23:43:43 +0800 Subject: [PATCH 06/15] added targetOffSet to camera position --- SHADE_Engine/src/Camera/SHCameraSystem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SHADE_Engine/src/Camera/SHCameraSystem.cpp b/SHADE_Engine/src/Camera/SHCameraSystem.cpp index 6ebbd078..d508fc09 100644 --- a/SHADE_Engine/src/Camera/SHCameraSystem.cpp +++ b/SHADE_Engine/src/Camera/SHCameraSystem.cpp @@ -265,7 +265,7 @@ namespace SHADE { camera.offset = arm->GetOffset(); if (arm->lookAtCameraOrigin) - CameraLookAt(camera, camera.position); + CameraLookAt(camera, camera.position + arm->GetTargetOffset()); } From 15df08ef67ffe87f0168cff91c90a957afdbba11 Mon Sep 17 00:00:00 2001 From: Brandon Mak Date: Mon, 20 Feb 2023 14:28:23 +0800 Subject: [PATCH 07/15] Implemented events for screen resize --- SHADE_Engine/src/Camera/SHCameraSystem.cpp | 18 ++++++++++++++++++ SHADE_Engine/src/Camera/SHCameraSystem.h | 5 +++++ SHADE_Engine/src/Events/SHEventDefines.h | 1 + .../src/Graphics/Events/SHGraphicsEvents.h | 9 +++++++++ .../MiddleEnd/Interface/SHGraphicsSystem.cpp | 12 ++++++++++-- .../Particles/SHParticleSubSystem.cpp | 1 + 6 files changed, 44 insertions(+), 2 deletions(-) diff --git a/SHADE_Engine/src/Camera/SHCameraSystem.cpp b/SHADE_Engine/src/Camera/SHCameraSystem.cpp index 6ebbd078..d87e428e 100644 --- a/SHADE_Engine/src/Camera/SHCameraSystem.cpp +++ b/SHADE_Engine/src/Camera/SHCameraSystem.cpp @@ -12,6 +12,7 @@ #include "Editor/SHEditor.h" #include "Math/SHRay.h" #include "Physics/System/SHPhysicsSystem.h" +#include "Graphics/Events/SHGraphicsEvents.h" namespace SHADE @@ -122,6 +123,13 @@ namespace SHADE SHComponentManager::CreateComponentSparseSet(); SHComponentManager::CreateComponentSparseSet(); + + std::shared_ptr> thisReceiver + { + std::make_shared>(this, &SHCameraSystem::ReceiveWindowResizeEvent) + }; + ReceiverPtr receiver = std::dynamic_pointer_cast(thisReceiver); + SHEventManager::SubscribeTo(SH_WINDOW_RESIZE_EVENT, receiver); } @@ -130,6 +138,16 @@ namespace SHADE } + SHEventHandle SHCameraSystem::ReceiveWindowResizeEvent(SHEventPtr eventPtr) noexcept + { + auto const& EVENT_DATA = reinterpret_cast*>(eventPtr.get())->data; + + //std::cout << EVENT_DATA->resizeWidth << std::endl; + //std::cout << EVENT_DATA->resizeHeight << std::endl; + + return eventPtr->handle; + } + SHCameraComponent* SHCameraSystem::GetEditorCamera(void) noexcept { return &editorCamera; diff --git a/SHADE_Engine/src/Camera/SHCameraSystem.h b/SHADE_Engine/src/Camera/SHCameraSystem.h index baf0ed09..4d6476bf 100644 --- a/SHADE_Engine/src/Camera/SHCameraSystem.h +++ b/SHADE_Engine/src/Camera/SHCameraSystem.h @@ -46,6 +46,11 @@ namespace SHADE }; friend class CameraSystemUpdate; + /*-----------------------------------------------------------------------*/ + /* Light functions */ + /*-----------------------------------------------------------------------*/ + SHEventHandle ReceiveWindowResizeEvent(SHEventPtr eventPtr) noexcept; + SHCameraComponent* GetEditorCamera (void) noexcept; void GetCameraAxis(SHCameraComponent const& camera, SHVec3& forward, SHVec3& right, SHVec3& up) const noexcept; diff --git a/SHADE_Engine/src/Events/SHEventDefines.h b/SHADE_Engine/src/Events/SHEventDefines.h index e2fcba10..fa5bcafb 100644 --- a/SHADE_Engine/src/Events/SHEventDefines.h +++ b/SHADE_Engine/src/Events/SHEventDefines.h @@ -25,4 +25,5 @@ constexpr SHEventIdentifier SH_SCENE_EXIT_POST { 16 }; constexpr SHEventIdentifier SH_GRAPHICS_LIGHT_ENABLE_SHADOW_EVENT { 17 }; constexpr SHEventIdentifier SH_BUTTON_CLICK_EVENT { 18 }; constexpr SHEventIdentifier SH_PHYSICS_COLLIDER_DRAW_EVENT { 19 }; +constexpr SHEventIdentifier SH_WINDOW_RESIZE_EVENT { 20 }; diff --git a/SHADE_Engine/src/Graphics/Events/SHGraphicsEvents.h b/SHADE_Engine/src/Graphics/Events/SHGraphicsEvents.h index 06c480ef..51cd7aa2 100644 --- a/SHADE_Engine/src/Graphics/Events/SHGraphicsEvents.h +++ b/SHADE_Engine/src/Graphics/Events/SHGraphicsEvents.h @@ -14,4 +14,13 @@ namespace SHADE //! Generate a renderer for the light component bool generateRenderer; }; + + struct SHWindowResizeEvent + { + // New width when window resizes + uint32_t resizeWidth; + + // New height when window resizes + uint32_t resizeHeight; + }; } diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp index 976939ce..297a86ae 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Interface/SHGraphicsSystem.cpp @@ -138,8 +138,8 @@ namespace SHADE //SHAssetManager::CompileAsset("../../Assets/Shaders/UI_VS.glsl", false); //SHAssetManager::CompileAsset("../../Assets/Shaders/UI_FS.glsl", false); //SHAssetManager::CompileAsset("../../Assets/Shaders/Text_VS.glsl", false); - SHAssetManager::CompileAsset("../../Assets/Shaders/Trajectory_VS.glsl", false); - SHAssetManager::CompileAsset("../../Assets/Shaders/Trajectory_FS.glsl", false); + //SHAssetManager::CompileAsset("../../Assets/Shaders/Trajectory_VS.glsl", false); + //SHAssetManager::CompileAsset("../../Assets/Shaders/Trajectory_FS.glsl", false); // Load Built In Shaders static constexpr AssetID VS_DEFAULT = 39210065; defaultVertShader = SHResourceManager::LoadOrGet(VS_DEFAULT); @@ -1178,6 +1178,14 @@ namespace SHADE #ifdef SHEDITOR cameraSystem->GetEditorCamera()->SetWidth(static_cast(resizeWidth)); cameraSystem->GetEditorCamera()->SetHeight(static_cast(resizeHeight)); + + // Create new event and broadcast it + SHWindowResizeEvent newEvent; + newEvent.resizeWidth = resizeWidth; + newEvent.resizeHeight = resizeHeight; + + SHEventManager::BroadcastEvent(newEvent, SH_WINDOW_RESIZE_EVENT); + #else #endif diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/Particles/SHParticleSubSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/Particles/SHParticleSubSystem.cpp index 39bcab5b..eb3c4f1a 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/Particles/SHParticleSubSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/Particles/SHParticleSubSystem.cpp @@ -1,3 +1,4 @@ +#include "SHpch.h" #include "SHParticleSubSustem.h" namespace SHADE From debdba183e2efc8bab5c20581dcc27417b5ac073 Mon Sep 17 00:00:00 2001 From: maverickdgg Date: Mon, 20 Feb 2023 14:39:10 +0800 Subject: [PATCH 08/15] removed some debug code --- SHADE_Engine/src/Camera/SHCameraSystem.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SHADE_Engine/src/Camera/SHCameraSystem.cpp b/SHADE_Engine/src/Camera/SHCameraSystem.cpp index 6ebbd078..dfcfd463 100644 --- a/SHADE_Engine/src/Camera/SHCameraSystem.cpp +++ b/SHADE_Engine/src/Camera/SHCameraSystem.cpp @@ -204,8 +204,8 @@ namespace SHADE //SHLOG_INFO("CAMERA COLLISION HIT, {} armlength: {}, true armlength: {}", hitResult.distance, hitResult.distance, (cameraPos - camera->position).Length()); //SHLOG_INFO("Racoon Position {}, {}, {}, Camera Position: {}, {}, {}, Distance {}", cameraTarget.x, cameraTarget.y, cameraTarget.z, cameraPos.x, cameraPos.y, cameraPos.z, SHVec3::Distance(cameraTarget, cameraPos)); //SHLOG_INFO("Camera Position: {}, {}, {}", cameraPos.x, cameraPos.y, cameraPos.z); - auto otherTransform = SHComponentManager::GetComponent_s(hitResult.entityHit); - SHVec3 otherPos = hitResult.position; + //auto otherTransform = SHComponentManager::GetComponent_s(hitResult.entityHit); + //SHVec3 otherPos = hitResult.position; From c9e9a30c3fc43964aa99441346e37629ca14bd35 Mon Sep 17 00:00:00 2001 From: maverickdgg Date: Mon, 20 Feb 2023 14:52:01 +0800 Subject: [PATCH 09/15] Exposed FOV to editor. Adjust AR for game camera --- SHADE_Engine/src/Camera/SHCameraComponent.cpp | 3 ++- SHADE_Engine/src/Camera/SHCameraSystem.cpp | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/SHADE_Engine/src/Camera/SHCameraComponent.cpp b/SHADE_Engine/src/Camera/SHCameraComponent.cpp index 8b2f50d9..17378d79 100644 --- a/SHADE_Engine/src/Camera/SHCameraComponent.cpp +++ b/SHADE_Engine/src/Camera/SHCameraComponent.cpp @@ -254,7 +254,8 @@ RTTR_REGISTRATION .property("Height", &SHCameraComponent::GetHeight, &SHCameraComponent::SetHeight) .property("Near", &SHCameraComponent::GetNear, &SHCameraComponent::SetNear) .property("Far", &SHCameraComponent::GetFar, &SHCameraComponent::SetFar) - .property("Perspective", &SHCameraComponent::GetIsPerspective, &SHCameraComponent::SetIsPerspective); + .property("Perspective", &SHCameraComponent::GetIsPerspective, &SHCameraComponent::SetIsPerspective) + .property("FOV",&SHCameraComponent::GetFOV, &SHCameraComponent::SetFOV); } diff --git a/SHADE_Engine/src/Camera/SHCameraSystem.cpp b/SHADE_Engine/src/Camera/SHCameraSystem.cpp index 9b5c1a47..6154c104 100644 --- a/SHADE_Engine/src/Camera/SHCameraSystem.cpp +++ b/SHADE_Engine/src/Camera/SHCameraSystem.cpp @@ -145,6 +145,19 @@ namespace SHADE //std::cout << EVENT_DATA->resizeWidth << std::endl; //std::cout << EVENT_DATA->resizeHeight << std::endl; + + for (auto director : directorHandleList) + { + auto camera = SHComponentManager::GetComponent_s(director->mainCameraEID); + if (camera) + { + camera->SetWidth(EVENT_DATA->resizeWidth); + camera->SetHeight(EVENT_DATA->resizeHeight); + } + + } + + return eventPtr->handle; } From 09d88b5a70d75974ae64265867daa119a20f8579 Mon Sep 17 00:00:00 2001 From: Glence Date: Mon, 20 Feb 2023 19:53:22 +0800 Subject: [PATCH 10/15] small bug fixes for text and serialization and added game pause --- Assets/Scenes/MainGame.shade | 137 +++++++++++++++--- Assets/Scripts/Audio/AudioHandler.cs | 8 + .../Gameplay/Player/SC_PickAndThrow.cs | 15 +- .../Gameplay/Player/SC_ThirdPersonCamera.cs | 16 +- Assets/Scripts/Gameplay/SC_GameManager.cs | 26 +++- .../SHTextRenderingSubSystem.cpp | 4 + .../src/Serialization/SHSerialization.cpp | 7 + 7 files changed, 183 insertions(+), 30 deletions(-) diff --git a/Assets/Scenes/MainGame.shade b/Assets/Scenes/MainGame.shade index f1b16c1b..5e30379e 100644 --- a/Assets/Scenes/MainGame.shade +++ b/Assets/Scenes/MainGame.shade @@ -9563,6 +9563,7 @@ timer: 200 scoreText: 237 timeText: 206 + gamePauseText: 11 multiplierText: 139 maxMultiplierDuration: 5 maxMultiplierCombo: 10 @@ -9570,7 +9571,7 @@ - EID: 199 Name: =====Text==== IsActive: true - NumberOfChildren: 3 + NumberOfChildren: 4 Components: ~ Scripts: ~ - EID: 237 @@ -9618,6 +9619,21 @@ Font: 176667660 IsActive: true Scripts: ~ +- EID: 11 + Name: GamePause + IsActive: true + NumberOfChildren: 0 + Components: + Transform Component: + Translate: {x: -145, y: 200, z: 0} + Rotate: {x: 0, y: 0, z: 0} + Scale: {x: 60, y: 60, z: 60} + IsActive: true + Text Renderer Component: + Text: Game Pause + Font: 176667660 + IsActive: true + Scripts: ~ - EID: 198 Name: ====Raccoon==== IsActive: true @@ -9677,18 +9693,20 @@ maxJumpTime: 0.75 fallMultipler: 3 jumpPadMultiplayer: 1.20000005 - lightMultiper: 0.75 - mediumMultiper: 0.5 - heavyMultiper: 0.25 + lightMultiper: 0.899999976 + mediumMultiper: 0.699999988 + heavyMultiper: 0.5 - Type: PickAndThrow Enabled: true throwForce: [10, 8, 10] - cameraArmOffSet: [0, 0.25, 0] + cameraArmOffSet: [0.25, 0.600000024, 0.200000003] delayTimer: 1 aimingLength: 1 throwItem: false rayDistance: 0.75 rayHeight: 0.100000001 + aimingFOV: 50 + defaultFOV: 45 - EID: 3 Name: HoldingPoint IsActive: true @@ -9715,30 +9733,31 @@ Pitch: 0 Yaw: 360 Roll: 1.28065994e-06 - Width: 1920 - Height: 1080 + Width: 1055 + Height: 604 Near: 0.00999999978 Far: 10000 Perspective: true + FOV: 45 IsActive: true Camera Arm Component: Arm Pitch: 0 Arm Yaw: 0 Arm Length: 3 Look At Camera Origin: true - Target Offset: {x: 0, y: 0, z: 0} + Target Offset: {x: 0, y: 0.75, z: 0} Camera Collision: true IsActive: true Scripts: - Type: SHADE_Scripting.ThirdPersonCamera Enabled: true armLength: 3 - turnSpeedPitch: 0.300000012 - turnSpeedYaw: 0.5 - pitchClamp: 45 + turnSpeedPitch: 0.200000003 + turnSpeedYaw: 0.400000006 inverseXControls: false - inverseYControls: true - lowerClamp: 5 + inverseYControls: false + pitchUpperClamp: 45 + pitchLowerClamp: 5 - EID: 9 Name: PlayerBag IsActive: true @@ -10533,28 +10552,108 @@ distanceToCapture: 0.5 captureTime: 0.5 footstepSFXIntervalMultiplier: 0.5 -- EID: 16 - Name: Default +- EID: 12 + Name: Mesh_Meat IsActive: true NumberOfChildren: 0 Components: Transform Component: - Translate: {x: 3.43332767, y: 0.149463654, z: 6.84711409} + Translate: {x: 2.30459714, y: 0.209537908, z: 6.371418} Rotate: {x: -0, y: 0, z: -0} Scale: {x: 1, y: 1, z: 1} IsActive: true + Renderable Component: + Mesh: 136892700 + Material: 131956078 + IsActive: true + RigidBody Component: + Type: Dynamic + Drag: 0.00999999978 + Angular Drag: 0.100000001 + Use Gravity: true + Interpolate: false + Sleeping Enabled: true + Freeze Position X: false + Freeze Position Y: false + Freeze Position Z: false + Freeze Rotation X: false + Freeze Rotation Y: false + Freeze Rotation Z: false + IsActive: true Collider Component: Colliders: - Is Trigger: false - Collision Tag: 0 + Collision Tag: 2 Type: Box - Half Extents: {x: 1, y: 0.25, z: 1} + Half Extents: {x: 0.300000012, y: 0.300000012, z: 0.300000012} Friction: 0.400000006 Bounciness: 0 Density: 1 Position Offset: {x: 0, y: 0, z: 0} Rotation Offset: {x: 0, y: 0, z: 0} IsActive: true + Scripts: + - Type: Item + Enabled: true + Score: 50 + currCategory: 1 + density: 1 + dontReturn: false +- EID: 16 + Name: JumpPad + IsActive: false + NumberOfChildren: 0 + Components: + Transform Component: + Translate: {x: 3.43332767, y: 0.149463654, z: 6.84711409} + Rotate: {x: -0, y: 0, z: -0} + Scale: {x: 1, y: 1, z: 1} + IsActive: false + Collider Component: + Colliders: + - Is Trigger: false + Collision Tag: 1 + Type: Box + Half Extents: {x: 1, y: 0.25, z: 1} + Friction: 0.400000006 + Bounciness: 0 + Density: 1 + Position Offset: {x: 0, y: 0, z: 0} + Rotation Offset: {x: 0, y: 0, z: 0} + IsActive: false Scripts: - Type: JumpPad - Enabled: true \ No newline at end of file + Enabled: true +- EID: 10 + Name: Canvas + IsActive: false + NumberOfChildren: 1 + Components: + Canvas Component: + Canvas Width: 1920 + Canvas Height: 1080 + IsActive: false + Scripts: ~ +- EID: 8 + Name: Default + IsActive: true + NumberOfChildren: 0 + Components: + Transform Component: + Translate: {x: 0, y: 0, z: 0} + Rotate: {x: 0, y: 0, z: 0} + Scale: {x: 300, y: 200, z: 500} + IsActive: true + Renderable Component: + Mesh: 141771688 + Material: 129340704 + IsActive: true + Button Component: + Default Texture: 52901020 + Hovered Texture: 62235279 + Clicked Texture: 64722619 + IsActive: true + UI Component: + Canvas ID: 10 + IsActive: true + Scripts: ~ \ No newline at end of file diff --git a/Assets/Scripts/Audio/AudioHandler.cs b/Assets/Scripts/Audio/AudioHandler.cs index f2e552c1..c6067819 100644 --- a/Assets/Scripts/Audio/AudioHandler.cs +++ b/Assets/Scripts/Audio/AudioHandler.cs @@ -19,5 +19,13 @@ namespace SHADE_Scripting.Audio h.Value.Stop(fadeOut); } } + + public static void pauseAllSounds(bool pause) + { + foreach (KeyValuePair h in audioClipHandlers) + { + h.Value.SetPause(pause); + } + } } } diff --git a/Assets/Scripts/Gameplay/Player/SC_PickAndThrow.cs b/Assets/Scripts/Gameplay/Player/SC_PickAndThrow.cs index a2f1ddb8..d5046db1 100644 --- a/Assets/Scripts/Gameplay/Player/SC_PickAndThrow.cs +++ b/Assets/Scripts/Gameplay/Player/SC_PickAndThrow.cs @@ -8,7 +8,7 @@ using static Item; public class PickAndThrow : Script { - public Vector3 throwForce = new Vector3(100.0f, 200.0f, 100.0f); + public Vector3 throwForce = new Vector3(10.0f, 8.0f, 10.0f); public Vector3 cameraArmOffSet = new Vector3(0.0f, 0.25f, 0.0f); public GameObject item { get; set; } public float delayTimer = 1.0f; @@ -33,6 +33,9 @@ public class PickAndThrow : Script [Tooltip("Height of ray")] public float rayHeight = 0.1f; + public float aimingFOV = 50; + public float defaultFOV = 45; + protected override void awake() { pc = GetScript(); @@ -74,6 +77,7 @@ public class PickAndThrow : Script pc.isAiming = true; pc.camArm.ArmLength = aimingLength; pc.camArm.TargetOffset = cameraArmOffSet; + pc.cam.FOV = aimingFOV; } if (Input.GetMouseButtonUp(Input.MouseCode.LeftButton) && pc.isAiming) @@ -83,6 +87,7 @@ public class PickAndThrow : Script itemCollider.GetCollisionShape(0).IsTrigger = false; pc.isAiming = false; pc.camArm.TargetOffset = Vector3.Zero; + pc.cam.FOV = defaultFOV; if (tpc) pc.camArm.ArmLength = tpc.armLength; pc.holdItem = false; @@ -103,6 +108,7 @@ public class PickAndThrow : Script if (Input.GetMouseButtonDown(Input.MouseCode.RightButton) && pc.isAiming) { pc.isAiming = false; + pc.cam.FOV = defaultFOV; pc.camArm.TargetOffset = Vector3.Zero; if (tpc) pc.camArm.ArmLength = tpc.armLength; @@ -132,7 +138,7 @@ public class PickAndThrow : Script { if (itemScript) { - Vector3 vec = new Vector3(throwForce.x * lastXDir, throwForce.y, throwForce.z * lastZDir); + Vector3 vec = new Vector3(throwForce.x * lastXDir, throwForce.y + (throwForce.y * GetPitchRatioRange()), throwForce.z * lastZDir); if (itemScript.currCategory == ItemCategory.LIGHT) itemRidigBody.AddForce(vec * 0.2f); if (itemScript.currCategory == ItemCategory.MEDIUM) @@ -254,5 +260,10 @@ public class PickAndThrow : Script return false; } + private float GetPitchRatioRange() + { + return (pc.camArm.Pitch - tpc.pitchUpperClamp) / (tpc.pitchLowerClamp - tpc.pitchUpperClamp); + } + } \ No newline at end of file diff --git a/Assets/Scripts/Gameplay/Player/SC_ThirdPersonCamera.cs b/Assets/Scripts/Gameplay/Player/SC_ThirdPersonCamera.cs index b03dbf2f..c3026ce6 100644 --- a/Assets/Scripts/Gameplay/Player/SC_ThirdPersonCamera.cs +++ b/Assets/Scripts/Gameplay/Player/SC_ThirdPersonCamera.cs @@ -14,10 +14,10 @@ namespace SHADE_Scripting public float armLength = 2.0f; public float turnSpeedPitch = 0.3f; public float turnSpeedYaw = 0.5f; - public float pitchClamp = 45.0f; public bool inverseXControls = false; public bool inverseYControls = false; - public float lowerClamp = 5.0f; + public float pitchUpperClamp = 45.0f; + public float pitchLowerClamp = 5.0f; protected override void awake() { @@ -51,17 +51,17 @@ namespace SHADE_Scripting arm.Pitch += vel.y * turnSpeedPitch * Time.DeltaTimeF; if (inverseXControls) - arm.Yaw -= vel.x * turnSpeedYaw * Time.DeltaTimeF; - else arm.Yaw += vel.x * turnSpeedYaw * Time.DeltaTimeF; + else + arm.Yaw -= vel.x * turnSpeedYaw * Time.DeltaTimeF; - if (arm.Pitch > pitchClamp) + if (arm.Pitch > pitchUpperClamp) { - arm.Pitch = pitchClamp; + arm.Pitch = pitchUpperClamp; } - else if (arm.Pitch < lowerClamp) + else if (arm.Pitch < pitchLowerClamp) { - arm.Pitch = lowerClamp; + arm.Pitch = pitchLowerClamp; } } } diff --git a/Assets/Scripts/Gameplay/SC_GameManager.cs b/Assets/Scripts/Gameplay/SC_GameManager.cs index 83b0747a..24a7012b 100644 --- a/Assets/Scripts/Gameplay/SC_GameManager.cs +++ b/Assets/Scripts/Gameplay/SC_GameManager.cs @@ -26,6 +26,7 @@ public class GameManager : Script public GameObject scoreText; public GameObject timeText; + public GameObject gamePauseText; //mulitpler info public GameObject multiplierText; @@ -38,6 +39,9 @@ public class GameManager : Script private Vector3 fontScalar; public static GameManager Instance { get; private set; } + //public static int highScore { get; private set; } maybe need + + public bool GamePause { get; set; } protected override void start() { @@ -76,6 +80,7 @@ public class GameManager : Script currMultiplierCombo = 1; currMultiplierDuration = 0; fontScalar = new Vector3(multiplierFont / maxMultiplierDuration, multiplierFont / maxMultiplierDuration , multiplierFont / maxMultiplierDuration); + GamePause = false; AudioHandler.audioClipHandlers["BGMWin"] = Audio.CreateAudioClip("event:/Music/stingers/game_win"); AudioHandler.audioClipHandlers["BGMLose"] = Audio.CreateAudioClip("event:/Music/stingers/game_lose"); @@ -83,7 +88,26 @@ public class GameManager : Script protected override void update() { - Cheats(); + if (GamePause) + { + if (Input.GetKeyDown(Input.KeyCode.Escape) && GamePause) + { + GamePause = false; + AudioHandler.pauseAllSounds(false); + gamePauseText.GetComponent().Enabled = false; + } + return; + } + + //Cheats(); + + if (Input.GetKeyDown(Input.KeyCode.Escape) && !GamePause) + { + GamePause = true; + AudioHandler.pauseAllSounds(true); + gamePauseText.GetComponent().Enabled = true; + } + if (currGameState == GameState.START) { timer -= Time.DeltaTimeF; diff --git a/SHADE_Engine/src/Graphics/MiddleEnd/TextRendering/SHTextRenderingSubSystem.cpp b/SHADE_Engine/src/Graphics/MiddleEnd/TextRendering/SHTextRenderingSubSystem.cpp index ffd5ac96..e1935634 100644 --- a/SHADE_Engine/src/Graphics/MiddleEnd/TextRendering/SHTextRenderingSubSystem.cpp +++ b/SHADE_Engine/src/Graphics/MiddleEnd/TextRendering/SHTextRenderingSubSystem.cpp @@ -13,6 +13,7 @@ #include "Math/Transform/SHTransformComponent.h" #include "Graphics/MiddleEnd/GlobalData/SHGlobalDescriptorSets.h" #include "Graphics/MiddleEnd/Interface/SHRenderer.h" +#include "Scene/SHSceneManager.h" namespace SHADE { @@ -184,6 +185,9 @@ namespace SHADE for (auto& comp : textRendererComps) { + if (!SHSceneManager::CheckNodeAndComponentsActive(comp.GetEID())) + continue; + auto* transform = SHComponentManager::GetComponent(comp.GetEID()); Handle fontHandle = comp.fontHandle; diff --git a/SHADE_Engine/src/Serialization/SHSerialization.cpp b/SHADE_Engine/src/Serialization/SHSerialization.cpp index bb0f4a43..febca024 100644 --- a/SHADE_Engine/src/Serialization/SHSerialization.cpp +++ b/SHADE_Engine/src/Serialization/SHSerialization.cpp @@ -70,6 +70,7 @@ namespace SHADE //Compile component IDs const auto componentIDList = SHSerialization::GetComponentIDList(node[ComponentsNode]); eid = SHEntityManager::CreateEntity(componentIDList, eid, name, parentEID); + createdEntities[oldEID] = eid; //createdEntities.push_back(eid); if (node[NumberOfChildrenNode]) @@ -90,6 +91,12 @@ namespace SHADE if (node[ScriptsNode]) SHSystemManager::GetSystem()->DeserialiseScripts(eid, node[ScriptsNode]); + auto& sceneGraph = SHSceneManager::GetCurrentSceneGraph(); + if (node[IsActiveNode]) + { + sceneGraph.SetActive(eid, node[IsActiveNode].as()); + } + return eid; } From d7725f4e26f1c8e03c171d2bb6834585a8b3e28b Mon Sep 17 00:00:00 2001 From: Glence Date: Tue, 21 Feb 2023 00:47:20 +0800 Subject: [PATCH 11/15] Pause is done --- Assets/Scenes/MainGame.shade | 70 ++++++++++++-- Assets/Scripts/Gameplay/SC_GameManager.cs | 26 ------ Assets/Scripts/UI/SC_PauseMenu.cs | 106 ++++++++++++++++++++++ Assets/Scripts/UI/SC_PauseMenu.cs.shmeta | 3 + 4 files changed, 170 insertions(+), 35 deletions(-) create mode 100644 Assets/Scripts/UI/SC_PauseMenu.cs create mode 100644 Assets/Scripts/UI/SC_PauseMenu.cs.shmeta diff --git a/Assets/Scenes/MainGame.shade b/Assets/Scenes/MainGame.shade index 5e30379e..591c386f 100644 --- a/Assets/Scenes/MainGame.shade +++ b/Assets/Scenes/MainGame.shade @@ -9563,11 +9563,17 @@ timer: 200 scoreText: 237 timeText: 206 - gamePauseText: 11 multiplierText: 139 maxMultiplierDuration: 5 maxMultiplierCombo: 10 multiplierFont: 60 + - Type: PauseMenu + Enabled: true + resumeBtn: 8 + retryBtn: 461 + quitBtn: 0 + gamePauseText: 11 + canvas: 10 - EID: 199 Name: =====Text==== IsActive: true @@ -9625,14 +9631,14 @@ NumberOfChildren: 0 Components: Transform Component: - Translate: {x: -145, y: 200, z: 0} + Translate: {x: -250, y: 300, z: 0} Rotate: {x: 0, y: 0, z: 0} - Scale: {x: 60, y: 60, z: 60} + Scale: {x: 100, y: 100, z: 100} IsActive: true Text Renderer Component: Text: Game Pause Font: 176667660 - IsActive: true + IsActive: false Scripts: ~ - EID: 198 Name: ====Raccoon==== @@ -9733,8 +9739,8 @@ Pitch: 0 Yaw: 360 Roll: 1.28065994e-06 - Width: 1055 - Height: 604 + Width: 2560 + Height: 1369 Near: 0.00999999978 Far: 10000 Perspective: true @@ -10627,7 +10633,7 @@ - EID: 10 Name: Canvas IsActive: false - NumberOfChildren: 1 + NumberOfChildren: 3 Components: Canvas Component: Canvas Width: 1920 @@ -10635,12 +10641,12 @@ IsActive: false Scripts: ~ - EID: 8 - Name: Default + Name: ResumeButton IsActive: true NumberOfChildren: 0 Components: Transform Component: - Translate: {x: 0, y: 0, z: 0} + Translate: {x: 0, y: 100, z: 0} Rotate: {x: 0, y: 0, z: 0} Scale: {x: 300, y: 200, z: 500} IsActive: true @@ -10656,4 +10662,50 @@ UI Component: Canvas ID: 10 IsActive: true + Scripts: ~ +- EID: 0 + Name: QuitButton + IsActive: true + NumberOfChildren: 0 + Components: + Transform Component: + Translate: {x: 0, y: -300, z: 0} + Rotate: {x: 0, y: 0, z: 0} + Scale: {x: 300, y: 200, z: 500} + IsActive: true + Renderable Component: + Mesh: 141771688 + Material: 129340704 + IsActive: true + Button Component: + Default Texture: 66477839 + Hovered Texture: 65045286 + Clicked Texture: 58607560 + IsActive: true + UI Component: + Canvas ID: 10 + IsActive: true + Scripts: ~ +- EID: 461 + Name: RetryButton + IsActive: true + NumberOfChildren: 0 + Components: + Transform Component: + Translate: {x: 0, y: -100, z: 0} + Rotate: {x: 0, y: 0, z: 0} + Scale: {x: 300, y: 200, z: 500} + IsActive: true + Renderable Component: + Mesh: 141771688 + Material: 129340704 + IsActive: true + Button Component: + Default Texture: 55782622 + Hovered Texture: 58972174 + Clicked Texture: 55224464 + IsActive: true + UI Component: + Canvas ID: 10 + IsActive: true Scripts: ~ \ No newline at end of file diff --git a/Assets/Scripts/Gameplay/SC_GameManager.cs b/Assets/Scripts/Gameplay/SC_GameManager.cs index 24a7012b..6478b5ea 100644 --- a/Assets/Scripts/Gameplay/SC_GameManager.cs +++ b/Assets/Scripts/Gameplay/SC_GameManager.cs @@ -26,7 +26,6 @@ public class GameManager : Script public GameObject scoreText; public GameObject timeText; - public GameObject gamePauseText; //mulitpler info public GameObject multiplierText; @@ -80,7 +79,6 @@ public class GameManager : Script currMultiplierCombo = 1; currMultiplierDuration = 0; fontScalar = new Vector3(multiplierFont / maxMultiplierDuration, multiplierFont / maxMultiplierDuration , multiplierFont / maxMultiplierDuration); - GamePause = false; AudioHandler.audioClipHandlers["BGMWin"] = Audio.CreateAudioClip("event:/Music/stingers/game_win"); AudioHandler.audioClipHandlers["BGMLose"] = Audio.CreateAudioClip("event:/Music/stingers/game_lose"); @@ -90,24 +88,9 @@ public class GameManager : Script { if (GamePause) { - if (Input.GetKeyDown(Input.KeyCode.Escape) && GamePause) - { - GamePause = false; - AudioHandler.pauseAllSounds(false); - gamePauseText.GetComponent().Enabled = false; - } return; } - //Cheats(); - - if (Input.GetKeyDown(Input.KeyCode.Escape) && !GamePause) - { - GamePause = true; - AudioHandler.pauseAllSounds(true); - gamePauseText.GetComponent().Enabled = true; - } - if (currGameState == GameState.START) { timer -= Time.DeltaTimeF; @@ -164,15 +147,6 @@ public class GameManager : Script Instance = null; } - private void Cheats() - { - if (Input.GetKeyDown(Input.KeyCode.Escape)) - { - Audio.StopAllSounds(); - SceneManager.ChangeScene(97158628); - } - } - public void ItemScored() { totalItemCount -= 1; diff --git a/Assets/Scripts/UI/SC_PauseMenu.cs b/Assets/Scripts/UI/SC_PauseMenu.cs new file mode 100644 index 00000000..eae7aa91 --- /dev/null +++ b/Assets/Scripts/UI/SC_PauseMenu.cs @@ -0,0 +1,106 @@ +using System; +using SHADE; +using SHADE_Scripting.Audio; + +public class PauseMenu : Script +{ + public GameObject resumeBtn; + public GameObject retryBtn; + public GameObject quitBtn; + + public GameObject gamePauseText; + public GameObject canvas; + + protected override void awake() + { + GameManager.Instance.GamePause = false; + if (gamePauseText) + gamePauseText.GetComponent().Enabled = false; + if (canvas) + canvas.SetActive(false); + + if (!resumeBtn) + Debug.LogError("Resume Btn missing"); + + if (!retryBtn) + Debug.LogError("Retry Btn missing"); + + if (!quitBtn) + Debug.LogError("Quit Btn missing"); + } + protected override void start() + { + //resume + UIElement resume = resumeBtn.GetComponent(); + if (resume != null) + { + resume.OnClick.RegisterAction(() => + { + if (GameManager.Instance.GamePause) + { + GameManager.Instance.GamePause = false; + AudioHandler.pauseAllSounds(false); + if (gamePauseText) + gamePauseText.GetComponent().Enabled = false; + if (canvas) + canvas.SetActive(false); + } + }); + } + else + { + Debug.LogError("Failed to register resume button."); + } + + //retry + UIElement retry = retryBtn.GetComponent(); + if (retry != null) + { + retry.OnClick.RegisterAction(() => + { + Audio.StopAllSounds(); + //get curr scene + //SceneManager.ChangeScene(); + }); + } + else + { + Debug.LogError("Failed to register retry button."); + } + + UIElement quit = quitBtn.GetComponent(); + if (quit != null) + { + quit.OnClick.RegisterAction(() => + { + Audio.StopAllSounds(); + //go to main menu + SceneManager.ChangeScene(97158628); + }); + } + else + { + Debug.LogError("Failed to register quit button."); + } + } + + protected override void update() + { + if (GameManager.Instance.GamePause) + { + return; + } + + if (Input.GetKeyDown(Input.KeyCode.Escape) && !GameManager.Instance.GamePause) + { + GameManager.Instance.GamePause = true; + AudioHandler.pauseAllSounds(true); + if (gamePauseText) + gamePauseText.GetComponent().Enabled = true; + if (canvas) + canvas.SetActive(true); + } + + } +} + diff --git a/Assets/Scripts/UI/SC_PauseMenu.cs.shmeta b/Assets/Scripts/UI/SC_PauseMenu.cs.shmeta new file mode 100644 index 00000000..0ddcf762 --- /dev/null +++ b/Assets/Scripts/UI/SC_PauseMenu.cs.shmeta @@ -0,0 +1,3 @@ +Name: SC_PauseMenu +ID: 151952680 +Type: 9 From febe22e4871b11012233d6ab1505f5415b9e1687 Mon Sep 17 00:00:00 2001 From: maverickdgg Date: Tue, 21 Feb 2023 09:52:23 +0800 Subject: [PATCH 12/15] Added new button events --- Assets/Editor/Editor.SHConfig | 2 +- SHADE_Engine/src/Events/SHEventDefines.h | 3 + SHADE_Engine/src/UI/SHUISystem.cpp | 233 ++++++++++------------- SHADE_Engine/src/UI/SHUISystem.h | 5 + 4 files changed, 110 insertions(+), 133 deletions(-) diff --git a/Assets/Editor/Editor.SHConfig b/Assets/Editor/Editor.SHConfig index 9bd51ca8..37edf50c 100644 --- a/Assets/Editor/Editor.SHConfig +++ b/Assets/Editor/Editor.SHConfig @@ -1,4 +1,4 @@ Start Maximized: true -Working Scene ID: 86098106 +Working Scene ID: 97158628 Window Size: {x: 1920, y: 1013} Style: 0 \ No newline at end of file diff --git a/SHADE_Engine/src/Events/SHEventDefines.h b/SHADE_Engine/src/Events/SHEventDefines.h index fa5bcafb..fffe8b5f 100644 --- a/SHADE_Engine/src/Events/SHEventDefines.h +++ b/SHADE_Engine/src/Events/SHEventDefines.h @@ -26,4 +26,7 @@ constexpr SHEventIdentifier SH_GRAPHICS_LIGHT_ENABLE_SHADOW_EVENT { 17 }; constexpr SHEventIdentifier SH_BUTTON_CLICK_EVENT { 18 }; constexpr SHEventIdentifier SH_PHYSICS_COLLIDER_DRAW_EVENT { 19 }; constexpr SHEventIdentifier SH_WINDOW_RESIZE_EVENT { 20 }; +constexpr SHEventIdentifier SH_BUTTON_RELEASE_EVENT { 21 }; +constexpr SHEventIdentifier SH_BUTTON_HOVER_ENTER_EVENT { 22 }; +constexpr SHEventIdentifier SH_BUTTON_HOVER_EXIT_EVENT { 23 }; diff --git a/SHADE_Engine/src/UI/SHUISystem.cpp b/SHADE_Engine/src/UI/SHUISystem.cpp index 92a754bf..3ddff353 100644 --- a/SHADE_Engine/src/UI/SHUISystem.cpp +++ b/SHADE_Engine/src/UI/SHUISystem.cpp @@ -146,6 +146,105 @@ namespace SHADE } } + bool SHUISystem::CheckButtonHoveredOrClicked(EntityID eid, SHVec2 topExtent, SHVec2 btmExtent, bool& isHovered, bool& isClicked) noexcept + { + + auto cameraSystem = SHSystemManager::GetSystem(); + SHVec2 mousePos; + SHVec2 windowSize; +#ifdef SHEDITOR + windowSize = SHEditorWindowManager::GetEditorWindow()->beginContentRegionAvailable; + mousePos = SHEditorWindowManager::GetEditorWindow()->viewportMousePos; + //mousePos.y = windowSize.y - mousePos.y; + //SHLOG_INFO("mouse pos: {}, {}", mousePos.x, mousePos.y) + mousePos /= windowSize; + //SHLOG_INFO("mouse pos normalized: {}, {}", mousePos.x, mousePos.y) + + + +#else + + int x, y; + SHInputManager::GetMouseScreenPosition(&x, &y); + mousePos.x = x; + mousePos.y = y; + auto ws = SHSystemManager::GetSystem()->GetWindow()->GetWindowSize(); + windowSize = { static_cast(ws.first), static_cast(ws.second) }; + mousePos /= windowSize; +#endif + + SHVec2 camSize{ cameraSystem->GetCameraWidthHeight(0) }; + //SHLOG_INFO("TopExtent: {}, {}", topExtent.x, topExtent.y) + + topExtent = CanvasToScreenPoint(topExtent, true); + btmExtent = CanvasToScreenPoint(btmExtent, true); + //SHLOG_INFO("TopExtent: {}, {} Btm Extent: {}, {}", topExtent.x, topExtent.y, btmExtent.x, btmExtent.y) + + + //comp.isClicked = false; + if (mousePos.x >= topExtent.x && mousePos.x <= btmExtent.x + && mousePos.y >= topExtent.y && mousePos.y <= btmExtent.y) + { + if (isHovered == false) + { + SHButtonClickEvent clickEvent; + clickEvent.EID = eid; + SHEventManager::BroadcastEvent(clickEvent, SH_BUTTON_HOVER_ENTER_EVENT); + } + isHovered = true; + + + +#ifdef SHEDITOR + //if (SHSystemManager::GetSystem()->editorState == SHEditor::State::PLAY) + { + if (SHInputManager::GetKeyDown(SHInputManager::SH_KEYCODE::LMB)) + { + isClicked = true; + SHButtonClickEvent clickEvent; + clickEvent.EID = eid; + SHEventManager::BroadcastEvent(clickEvent, SH_BUTTON_CLICK_EVENT); + } + } +#else + if (SHInputManager::GetKeyDown(SHInputManager::SH_KEYCODE::LMB)) + { + comp.isClicked = true; + SHButtonClickEvent clickEvent; + clickEvent.EID = eid; + SHEventManager::BroadcastEvent(clickEvent, SH_BUTTON_CLICK_EVENT); + } +#endif + + //SHLOG_INFO("HOVERED") + } + else + { + if (isHovered == true) + { + SHButtonClickEvent clickEvent; + clickEvent.EID = eid; + SHEventManager::BroadcastEvent(clickEvent, SH_BUTTON_HOVER_EXIT_EVENT); + } + + isHovered = false; + //SHLOG_INFO("NOT HOVERED") + } + if (isClicked && SHInputManager::GetKeyUp(SHInputManager::SH_KEYCODE::LMB)) + { + isClicked = false; + SHButtonClickEvent clickEvent; + clickEvent.EID = eid; + SHEventManager::BroadcastEvent(clickEvent, SH_BUTTON_RELEASE_EVENT); + + return true; + } + + + return false; + + } + void SHUISystem::UpdateButtonComponent(SHButtonComponent& comp) noexcept { @@ -164,72 +263,7 @@ namespace SHADE SHVec2 topExtent{ topExtent4.x,topExtent4.y }; SHVec2 btmExtent{ btmExtent4.x,btmExtent4.y }; - - SHVec2 mousePos; - SHVec2 windowSize; -#ifdef SHEDITOR - windowSize = SHEditorWindowManager::GetEditorWindow()->beginContentRegionAvailable; - mousePos = SHEditorWindowManager::GetEditorWindow()->viewportMousePos; - //mousePos.y = windowSize.y - mousePos.y; - //SHLOG_INFO("mouse pos: {}, {}", mousePos.x, mousePos.y) - mousePos /= windowSize; - //SHLOG_INFO("mouse pos normalized: {}, {}", mousePos.x, mousePos.y) - - - -#else - - int x, y; - SHInputManager::GetMouseScreenPosition(&x, &y); - mousePos.x = x; - mousePos.y = y; - auto ws = SHSystemManager::GetSystem()->GetWindow()->GetWindowSize(); - windowSize = { static_cast(ws.first), static_cast(ws.second) }; - mousePos /= windowSize; -#endif - - SHVec2 camSize{ cameraSystem->GetCameraWidthHeight(0)}; - //SHLOG_INFO("TopExtent: {}, {}", topExtent.x, topExtent.y) - - topExtent = CanvasToScreenPoint(topExtent,true); - btmExtent = CanvasToScreenPoint(btmExtent,true); - //SHLOG_INFO("TopExtent: {}, {} Btm Extent: {}, {}", topExtent.x, topExtent.y, btmExtent.x, btmExtent.y) - - - //comp.isClicked = false; - if (mousePos.x >= topExtent.x && mousePos.x <= btmExtent.x - && mousePos.y >= topExtent.y && mousePos.y <= btmExtent.y) - { - comp.isHovered = true; - #ifdef SHEDITOR - //if (SHSystemManager::GetSystem()->editorState == SHEditor::State::PLAY) - { - if (SHInputManager::GetKeyDown(SHInputManager::SH_KEYCODE::LMB)) - { - comp.isClicked = true; - } - } - #else - if (SHInputManager::GetKeyDown(SHInputManager::SH_KEYCODE::LMB)) - { - comp.isClicked = true; - } - #endif - - //SHLOG_INFO("HOVERED") - } - else - { - comp.isHovered = false; - //SHLOG_INFO("NOT HOVERED") - } - if (comp.isClicked && SHInputManager::GetKeyUp(SHInputManager::SH_KEYCODE::LMB)) - { - comp.isClicked = false; - SHButtonClickEvent clickEvent; - clickEvent.EID = comp.GetEID(); - SHEventManager::BroadcastEvent(clickEvent, SH_BUTTON_CLICK_EVENT); - } + CheckButtonHoveredOrClicked(comp.GetEID(), topExtent, btmExtent, comp.isHovered, comp.isClicked); if (SHComponentManager::HasComponent(comp.GetEID())) { @@ -295,73 +329,8 @@ namespace SHADE SHVec2 topExtent{ topExtent4.x,topExtent4.y }; SHVec2 btmExtent{ btmExtent4.x,btmExtent4.y }; - - SHVec2 mousePos; - SHVec2 windowSize; -#ifdef SHEDITOR - windowSize = SHEditorWindowManager::GetEditorWindow()->beginContentRegionAvailable; - mousePos = SHEditorWindowManager::GetEditorWindow()->viewportMousePos; - //mousePos.y = windowSize.y - mousePos.y; - //SHLOG_INFO("mouse pos: {}, {}", mousePos.x, mousePos.y) - mousePos /= windowSize; - //SHLOG_INFO("mouse pos normalized: {}, {}", mousePos.x, mousePos.y) - - - -#else - - int x, y; - SHInputManager::GetMouseScreenPosition(&x, &y); - mousePos.x = x; - mousePos.y = y; - auto ws = SHSystemManager::GetSystem()->GetWindow()->GetWindowSize(); - windowSize = { static_cast(ws.first), static_cast(ws.second) }; - mousePos /= windowSize; -#endif - - SHVec2 camSize{ cameraSystem->GetCameraWidthHeight(0) }; - //SHLOG_INFO("TopExtent: {}, {}", topExtent.x, topExtent.y) - - topExtent = CanvasToScreenPoint(topExtent, true); - btmExtent = CanvasToScreenPoint(btmExtent, true); - //SHLOG_INFO("TopExtent: {}, {} Btm Extent: {}, {}", topExtent.x, topExtent.y, btmExtent.x, btmExtent.y) - - - //comp.isClicked = false; - if (mousePos.x >= topExtent.x && mousePos.x <= btmExtent.x - && mousePos.y >= topExtent.y && mousePos.y <= btmExtent.y) - { - comp.isHovered = true; -#ifdef SHEDITOR - //if (SHSystemManager::GetSystem()->editorState == SHEditor::State::PLAY) - { - if (SHInputManager::GetKeyDown(SHInputManager::SH_KEYCODE::LMB)) - { - comp.isClicked = true; - } - } -#else - if (SHInputManager::GetKeyDown(SHInputManager::SH_KEYCODE::LMB)) - { - comp.isClicked = true; - } -#endif - - //SHLOG_INFO("HOVERED") - } - else - { - comp.isHovered = false; - //SHLOG_INFO("NOT HOVERED") - } - if (comp.isClicked && SHInputManager::GetKeyUp(SHInputManager::SH_KEYCODE::LMB)) - { - comp.isClicked = false; + if (CheckButtonHoveredOrClicked(comp.GetEID(), topExtent, btmExtent, comp.isHovered, comp.isClicked)) comp.value = !comp.value; - SHButtonClickEvent clickEvent; - clickEvent.EID = comp.GetEID(); - SHEventManager::BroadcastEvent(clickEvent, SH_BUTTON_CLICK_EVENT); - } if (SHComponentManager::HasComponent(comp.GetEID())) { diff --git a/SHADE_Engine/src/UI/SHUISystem.h b/SHADE_Engine/src/UI/SHUISystem.h index ae1091ec..1eaf883e 100644 --- a/SHADE_Engine/src/UI/SHUISystem.h +++ b/SHADE_Engine/src/UI/SHUISystem.h @@ -72,6 +72,11 @@ namespace SHADE void UpdateButtonComponent(SHButtonComponent& comp) noexcept; void UpdateToggleButtonComponent(SHToggleButtonComponent& comp) noexcept; void UpdateCanvasComponent(SHCanvasComponent& comp) noexcept; + + //returns true on button release. + bool CheckButtonHoveredOrClicked(EntityID eid, SHVec2 topExtent, SHVec2 btmExtent, bool& isHovered, bool& isClicked) noexcept; + + SHVec2 CanvasToScreenPoint(SHVec2& const canvasPoint, bool normalized) noexcept; From 51909071e69fa1677dba73f68a5cc4ba9d75aa83 Mon Sep 17 00:00:00 2001 From: maverickdgg Date: Tue, 21 Feb 2023 10:09:58 +0800 Subject: [PATCH 13/15] Change isHovered and isClicked to be stored in UIComponent instead and made a helper function to check for clicks and hovered --- SHADE_Engine/src/UI/SHButtonComponent.cpp | 6 ++- SHADE_Engine/src/UI/SHButtonComponent.h | 8 +-- .../src/UI/SHToggleButtonComponent.cpp | 3 +- SHADE_Engine/src/UI/SHToggleButtonComponent.h | 8 +-- SHADE_Engine/src/UI/SHUIComponent.cpp | 17 +++++++ SHADE_Engine/src/UI/SHUIComponent.h | 16 ++++++ SHADE_Engine/src/UI/SHUISystem.cpp | 51 +++++++++---------- SHADE_Engine/src/UI/SHUISystem.h | 2 +- 8 files changed, 64 insertions(+), 47 deletions(-) diff --git a/SHADE_Engine/src/UI/SHButtonComponent.cpp b/SHADE_Engine/src/UI/SHButtonComponent.cpp index 35b6b3bc..cbc36ce3 100644 --- a/SHADE_Engine/src/UI/SHButtonComponent.cpp +++ b/SHADE_Engine/src/UI/SHButtonComponent.cpp @@ -6,8 +6,7 @@ namespace SHADE { SHButtonComponent::SHButtonComponent() - :size(1.0f), isHovered(false), isClicked(false), - defaultTexture(0), hoveredTexture(0), clickedTexture(0), currentTexture(0) + : defaultTexture(0), hoveredTexture(0), clickedTexture(0), currentTexture(0) { } @@ -41,6 +40,9 @@ namespace SHADE clickedTexture = texture; } + + + } diff --git a/SHADE_Engine/src/UI/SHButtonComponent.h b/SHADE_Engine/src/UI/SHButtonComponent.h index bb66d224..a89a4b9e 100644 --- a/SHADE_Engine/src/UI/SHButtonComponent.h +++ b/SHADE_Engine/src/UI/SHButtonComponent.h @@ -17,8 +17,6 @@ namespace SHADE SHButtonComponent(); virtual ~SHButtonComponent() = default; - SHVec2 size; - AssetID GetClickedTexture() const noexcept; AssetID GetDefaultTexture() const noexcept; AssetID GetHoveredTexture() const noexcept; @@ -32,11 +30,7 @@ namespace SHADE friend class SHUISystem; private: - //Set to true when mouse is hovering over the button. - bool isHovered; - //This is set to true when the mouse clicks down, and set back to false when mouse releases. - //The event for the button click will be broadcasted when mouse release. - bool isClicked; + AssetID defaultTexture; AssetID hoveredTexture; AssetID clickedTexture; diff --git a/SHADE_Engine/src/UI/SHToggleButtonComponent.cpp b/SHADE_Engine/src/UI/SHToggleButtonComponent.cpp index 47df669c..1ae0e9e0 100644 --- a/SHADE_Engine/src/UI/SHToggleButtonComponent.cpp +++ b/SHADE_Engine/src/UI/SHToggleButtonComponent.cpp @@ -5,8 +5,7 @@ namespace SHADE { SHToggleButtonComponent::SHToggleButtonComponent() - :size(1.0f), isHovered(false), isClicked(false), value(false), - defaultTexture(0), toggledTexture(0), currentTexture(0) + :value(false), defaultTexture(0), toggledTexture(0), currentTexture(0) { } diff --git a/SHADE_Engine/src/UI/SHToggleButtonComponent.h b/SHADE_Engine/src/UI/SHToggleButtonComponent.h index dc678fe9..1903df93 100644 --- a/SHADE_Engine/src/UI/SHToggleButtonComponent.h +++ b/SHADE_Engine/src/UI/SHToggleButtonComponent.h @@ -17,8 +17,6 @@ namespace SHADE SHToggleButtonComponent(); virtual ~SHToggleButtonComponent() = default; - SHVec2 size; - AssetID GetToggledTexture() const noexcept; AssetID GetDefaultTexture() const noexcept; bool GetValue() const noexcept; @@ -33,11 +31,7 @@ namespace SHADE friend class SHUISystem; private: - //Set to true when mouse is hovering over the button. - bool isHovered; - //This is set to true when the mouse clicks down, and set back to false when mouse releases. - //The event for the button click will be broadcasted when mouse release. - bool isClicked; + bool value; AssetID defaultTexture; AssetID toggledTexture; diff --git a/SHADE_Engine/src/UI/SHUIComponent.cpp b/SHADE_Engine/src/UI/SHUIComponent.cpp index 8131d081..95b93375 100644 --- a/SHADE_Engine/src/UI/SHUIComponent.cpp +++ b/SHADE_Engine/src/UI/SHUIComponent.cpp @@ -7,6 +7,7 @@ namespace SHADE { SHUIComponent::SHUIComponent() + :size(1.0f), isHovered(false), isClicked(false) { } @@ -27,6 +28,20 @@ namespace SHADE (void)id; } + bool SHUIComponent::GetIsHovered() const noexcept + { + return isHovered; + } + + bool SHUIComponent::GetIsClicked() const noexcept + { + return isClicked; + } + + void SHUIComponent::SetEmptyHoveredClick(bool value) noexcept + { + (void)value; + } } @@ -37,6 +52,8 @@ RTTR_REGISTRATION registration::class_("UI Component") .property("Canvas ID", &SHUIComponent::GetCanvasID, &SHUIComponent::SetCanvasID) + .property("Hovered", &SHUIComponent::GetIsHovered, &SHUIComponent::SetEmptyHoveredClick) + .property("Clicked", &SHUIComponent::GetIsClicked, &SHUIComponent::SetEmptyHoveredClick) ; diff --git a/SHADE_Engine/src/UI/SHUIComponent.h b/SHADE_Engine/src/UI/SHUIComponent.h index 5a9290cc..dd5bb664 100644 --- a/SHADE_Engine/src/UI/SHUIComponent.h +++ b/SHADE_Engine/src/UI/SHUIComponent.h @@ -5,6 +5,7 @@ #include "SH_API.h" #include "ECS_Base/Components/SHComponent.h" #include "Math/SHMatrix.h" +#include "Math/Vector/SHVec2.h" namespace SHADE @@ -17,14 +18,29 @@ namespace SHADE SHUIComponent(); ~SHUIComponent() = default; + + SHVec2 size; + + SHMatrix const& GetMatrix() const noexcept; EntityID GetCanvasID() const noexcept; void SetCanvasID(EntityID id) noexcept; + bool GetIsHovered() const noexcept; + bool GetIsClicked() const noexcept; + + void SetEmptyHoveredClick(bool value)noexcept; + + private: SHMatrix localToCanvasMatrix; EntityID canvasID; + //Set to true when mouse is hovering over the button. Only set if there is a Button/Slider/ToggleButton comp. + bool isHovered; + //This is set to true when the mouse clicks down, and set back to false when mouse releases. Only set if there is a Button/Slider/ToggleButton comp. + bool isClicked; + RTTR_ENABLE() }; diff --git a/SHADE_Engine/src/UI/SHUISystem.cpp b/SHADE_Engine/src/UI/SHUISystem.cpp index 3ddff353..69481b5e 100644 --- a/SHADE_Engine/src/UI/SHUISystem.cpp +++ b/SHADE_Engine/src/UI/SHUISystem.cpp @@ -146,9 +146,14 @@ namespace SHADE } } - bool SHUISystem::CheckButtonHoveredOrClicked(EntityID eid, SHVec2 topExtent, SHVec2 btmExtent, bool& isHovered, bool& isClicked) noexcept + bool SHUISystem::CheckButtonHoveredOrClicked(SHUIComponent& comp) noexcept { + SHVec4 topExtent4 = SHMatrix::Translate(-comp.size.x * 0.5f, comp.size.y * 0.5f, 0.0f) * comp.GetMatrix() * SHVec4(0.0f, 0.0f, 0.0f, 1.0f); + SHVec4 btmExtent4 = SHMatrix::Translate(comp.size.x * 0.5f, -comp.size.y * 0.5f, 0.0f) * comp.GetMatrix() * SHVec4(0.0f, 0.0f, 0.0f, 1.0f); + + SHVec2 topExtent{ topExtent4.x,topExtent4.y }; + SHVec2 btmExtent{ btmExtent4.x,btmExtent4.y }; auto cameraSystem = SHSystemManager::GetSystem(); SHVec2 mousePos; SHVec2 windowSize; @@ -185,13 +190,13 @@ namespace SHADE if (mousePos.x >= topExtent.x && mousePos.x <= btmExtent.x && mousePos.y >= topExtent.y && mousePos.y <= btmExtent.y) { - if (isHovered == false) + if (comp.isHovered == false) { SHButtonClickEvent clickEvent; - clickEvent.EID = eid; + clickEvent.EID = comp.GetEID(); SHEventManager::BroadcastEvent(clickEvent, SH_BUTTON_HOVER_ENTER_EVENT); } - isHovered = true; + comp.isHovered = true; @@ -200,9 +205,9 @@ namespace SHADE { if (SHInputManager::GetKeyDown(SHInputManager::SH_KEYCODE::LMB)) { - isClicked = true; + comp.isClicked = true; SHButtonClickEvent clickEvent; - clickEvent.EID = eid; + clickEvent.EID = comp.GetEID(); SHEventManager::BroadcastEvent(clickEvent, SH_BUTTON_CLICK_EVENT); } } @@ -211,7 +216,7 @@ namespace SHADE { comp.isClicked = true; SHButtonClickEvent clickEvent; - clickEvent.EID = eid; + clickEvent.EID = comp.GetEID(); SHEventManager::BroadcastEvent(clickEvent, SH_BUTTON_CLICK_EVENT); } #endif @@ -220,21 +225,21 @@ namespace SHADE } else { - if (isHovered == true) + if (comp.isHovered == true) { SHButtonClickEvent clickEvent; - clickEvent.EID = eid; + clickEvent.EID = comp.GetEID(); SHEventManager::BroadcastEvent(clickEvent, SH_BUTTON_HOVER_EXIT_EVENT); } - isHovered = false; + comp.isHovered = false; //SHLOG_INFO("NOT HOVERED") } - if (isClicked && SHInputManager::GetKeyUp(SHInputManager::SH_KEYCODE::LMB)) + if (comp.isClicked && SHInputManager::GetKeyUp(SHInputManager::SH_KEYCODE::LMB)) { - isClicked = false; + comp.isClicked = false; SHButtonClickEvent clickEvent; - clickEvent.EID = eid; + clickEvent.EID = comp.GetEID(); SHEventManager::BroadcastEvent(clickEvent, SH_BUTTON_RELEASE_EVENT); return true; @@ -256,14 +261,9 @@ namespace SHADE auto uiComp = SHComponentManager::GetComponent(comp.GetEID()); //auto canvasComp = SHComponentManager::GetComponent_s(uiComp->canvasID); - SHVec4 topExtent4 = SHMatrix::Translate(-comp.size.x * 0.5f, comp.size.y * 0.5f, 0.0f) * uiComp->GetMatrix() * SHVec4(0.0f, 0.0f, 0.0f, 1.0f); - SHVec4 btmExtent4 = SHMatrix::Translate(comp.size.x * 0.5f, -comp.size.y * 0.5f, 0.0f) * uiComp->GetMatrix() * SHVec4(0.0f,0.0f, 0.0f,1.0f); - - SHVec2 topExtent{ topExtent4.x,topExtent4.y }; - SHVec2 btmExtent{ btmExtent4.x,btmExtent4.y }; - CheckButtonHoveredOrClicked(comp.GetEID(), topExtent, btmExtent, comp.isHovered, comp.isClicked); + CheckButtonHoveredOrClicked(*uiComp); if (SHComponentManager::HasComponent(comp.GetEID())) { @@ -272,7 +272,7 @@ namespace SHADE AssetID textureID = 0; - if (!comp.isHovered && !comp.isClicked) + if (!uiComp->isHovered && !uiComp->isClicked) { if (comp.GetDefaultTexture() != 0 && SHAssetManager::GetType(comp.GetDefaultTexture()) == AssetType::TEXTURE) { @@ -281,7 +281,7 @@ namespace SHADE //SHLOG_INFO("SETTING DEFAULT TEXTURE") } } - else if (comp.isClicked) + else if (uiComp->isClicked) { if (comp.GetClickedTexture() != 0 && SHAssetManager::GetType(comp.GetClickedTexture()) == AssetType::TEXTURE) { @@ -322,14 +322,9 @@ namespace SHADE auto uiComp = SHComponentManager::GetComponent(comp.GetEID()); //auto canvasComp = SHComponentManager::GetComponent_s(uiComp->canvasID); - SHVec4 topExtent4 = SHMatrix::Translate(-comp.size.x * 0.5f, comp.size.y * 0.5f, 0.0f) * uiComp->GetMatrix() * SHVec4(0.0f, 0.0f, 0.0f, 1.0f); - SHVec4 btmExtent4 = SHMatrix::Translate(comp.size.x * 0.5f, -comp.size.y * 0.5f, 0.0f) * uiComp->GetMatrix() * SHVec4(0.0f, 0.0f, 0.0f, 1.0f); + - - SHVec2 topExtent{ topExtent4.x,topExtent4.y }; - SHVec2 btmExtent{ btmExtent4.x,btmExtent4.y }; - - if (CheckButtonHoveredOrClicked(comp.GetEID(), topExtent, btmExtent, comp.isHovered, comp.isClicked)) + if (CheckButtonHoveredOrClicked(*uiComp)) comp.value = !comp.value; if (SHComponentManager::HasComponent(comp.GetEID())) diff --git a/SHADE_Engine/src/UI/SHUISystem.h b/SHADE_Engine/src/UI/SHUISystem.h index 1eaf883e..3b2bb2cf 100644 --- a/SHADE_Engine/src/UI/SHUISystem.h +++ b/SHADE_Engine/src/UI/SHUISystem.h @@ -74,7 +74,7 @@ namespace SHADE void UpdateCanvasComponent(SHCanvasComponent& comp) noexcept; //returns true on button release. - bool CheckButtonHoveredOrClicked(EntityID eid, SHVec2 topExtent, SHVec2 btmExtent, bool& isHovered, bool& isClicked) noexcept; + bool CheckButtonHoveredOrClicked(SHUIComponent& comp) noexcept; From a3112f9c60d1cb8232bf9ec4ef437c219ac7a8b5 Mon Sep 17 00:00:00 2001 From: maverickdgg Date: Tue, 21 Feb 2023 10:48:07 +0800 Subject: [PATCH 14/15] Fixed Canvas Scaler to keep AR of the UI Elements --- Assets/Scenes/MainMenu.shade | 12 ++++++++++-- SHADE_Engine/src/UI/SHCanvasComponent.cpp | 7 ++++++- SHADE_Engine/src/UI/SHCanvasComponent.h | 5 ++++- SHADE_Engine/src/UI/SHUISystem.cpp | 13 +++++++++++-- 4 files changed, 31 insertions(+), 6 deletions(-) diff --git a/Assets/Scenes/MainMenu.shade b/Assets/Scenes/MainMenu.shade index 54208e8b..30ef368a 100644 --- a/Assets/Scenes/MainMenu.shade +++ b/Assets/Scenes/MainMenu.shade @@ -6,6 +6,7 @@ Canvas Component: Canvas Width: 1920 Canvas Height: 1080 + Scale by canvas width: false IsActive: true Scripts: ~ - EID: 1 @@ -24,6 +25,8 @@ IsActive: true UI Component: Canvas ID: 0 + Hovered: false + Clicked: false IsActive: true Scripts: ~ - EID: 5 @@ -47,6 +50,8 @@ IsActive: true UI Component: Canvas ID: 0 + Hovered: false + Clicked: false IsActive: true Scripts: - Type: ChangeSceneButton @@ -73,6 +78,8 @@ IsActive: true UI Component: Canvas ID: 0 + Hovered: false + Clicked: false IsActive: true Scripts: - Type: QuitButton @@ -106,11 +113,12 @@ Pitch: 0 Yaw: 0 Roll: 0 - Width: 1920 - Height: 1080 + Width: 1319 + Height: 622 Near: 0.00999999978 Far: 10000 Perspective: true + FOV: 90 IsActive: true Scripts: ~ - EID: 4 diff --git a/SHADE_Engine/src/UI/SHCanvasComponent.cpp b/SHADE_Engine/src/UI/SHCanvasComponent.cpp index 1ffc7a19..5ee93bc1 100644 --- a/SHADE_Engine/src/UI/SHCanvasComponent.cpp +++ b/SHADE_Engine/src/UI/SHCanvasComponent.cpp @@ -6,7 +6,7 @@ namespace SHADE { SHCanvasComponent::SHCanvasComponent() - :width(1),height(1), dirtyMatrix(false), canvasMatrix() + :width(1), height(1), dirtyMatrix(false), canvasMatrix(), scaleByCanvasWidth(false) { } @@ -27,6 +27,8 @@ namespace SHADE height = val; } + + SHCanvasComponent::CanvasSizeType SHCanvasComponent::GetCanvasWidth() const noexcept { @@ -43,6 +45,8 @@ namespace SHADE return canvasMatrix; } + + } @@ -54,6 +58,7 @@ RTTR_REGISTRATION registration::class_("Canvas Component") .property("Canvas Width", &SHCanvasComponent::GetCanvasWidth, &SHCanvasComponent::SetCanvasWidth) .property("Canvas Height", &SHCanvasComponent::GetCanvasHeight, &SHCanvasComponent::SetCanvasHeight) + .property("Scale by canvas width", &SHCanvasComponent::scaleByCanvasWidth) ; diff --git a/SHADE_Engine/src/UI/SHCanvasComponent.h b/SHADE_Engine/src/UI/SHCanvasComponent.h index 145b3cb3..5b6c1781 100644 --- a/SHADE_Engine/src/UI/SHCanvasComponent.h +++ b/SHADE_Engine/src/UI/SHCanvasComponent.h @@ -21,21 +21,24 @@ namespace SHADE SHCanvasComponent(); ~SHCanvasComponent() = default; + bool scaleByCanvasWidth; void SetCanvasSize(CanvasSizeType width, CanvasSizeType height) noexcept; void SetCanvasWidth(CanvasSizeType width) noexcept; void SetCanvasHeight(CanvasSizeType height) noexcept; + CanvasSizeType GetCanvasWidth() const noexcept; CanvasSizeType GetCanvasHeight() const noexcept; SHMatrix const& GetMatrix() const noexcept; + private: CanvasSizeType width; CanvasSizeType height; bool dirtyMatrix; SHMatrix canvasMatrix; - + RTTR_ENABLE() }; diff --git a/SHADE_Engine/src/UI/SHUISystem.cpp b/SHADE_Engine/src/UI/SHUISystem.cpp index 69481b5e..3552e47b 100644 --- a/SHADE_Engine/src/UI/SHUISystem.cpp +++ b/SHADE_Engine/src/UI/SHUISystem.cpp @@ -131,8 +131,17 @@ namespace SHADE auto cameraSystem = SHSystemManager::GetSystem(); SHVec2 camSize = cameraSystem->GetCameraWidthHeight(0); comp.canvasMatrix = SHMatrix::Identity; - comp.canvasMatrix(0, 0) = camSize.x * 0.5f / (comp.GetCanvasWidth() * 0.5f); - comp.canvasMatrix(1, 1) = camSize.y * 0.5f / (comp.GetCanvasHeight() * 0.5f); + float scale = camSize.y / comp.GetCanvasHeight(); + if (comp.scaleByCanvasWidth) + { + scale = camSize.x / comp.GetCanvasWidth(); + } + + comp.canvasMatrix(0, 0) = scale; + comp.canvasMatrix(1, 1) = scale; + + //comp.canvasMatrix(0, 0) = camSize.x * 0.5f / (comp.GetCanvasWidth() * 0.5f); + //comp.canvasMatrix(1, 1) = camSize.y * 0.5f / (comp.GetCanvasHeight() * 0.5f); } void SHUISystem::UpdateCanvasMatrixRoutine::Execute(double dt) noexcept From 9a7c0d0bf6513dc42e0bc6b08df89f81e7e1154c Mon Sep 17 00:00:00 2001 From: Kah Wei Date: Tue, 21 Feb 2023 17:30:43 +0800 Subject: [PATCH 15/15] Added SharedMaterial for Renderable --- SHADE_Managed/src/Components/Renderable.cxx | 7 ++++++- SHADE_Managed/src/Components/Renderable.hxx | 12 +++++++++++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/SHADE_Managed/src/Components/Renderable.cxx b/SHADE_Managed/src/Components/Renderable.cxx index 1aa83637..929b0006 100644 --- a/SHADE_Managed/src/Components/Renderable.cxx +++ b/SHADE_Managed/src/Components/Renderable.cxx @@ -47,11 +47,16 @@ namespace SHADE } } SHADE::Material Renderable::Material::get() + { + auto mat = GetNativeComponent()->GetModifiableMaterial(); + return mat ? SHADE::Material(mat) : SHADE::Material(); + } + SHADE::Material Renderable::SharedMaterial::get() { auto mat = GetNativeComponent()->GetMaterial(); return mat ? SHADE::Material(mat) : SHADE::Material(); } - void Renderable::Material::set(SHADE::Material value) + void Renderable::SharedMaterial::set(SHADE::Material value) { if (value) { diff --git a/SHADE_Managed/src/Components/Renderable.hxx b/SHADE_Managed/src/Components/Renderable.hxx index b0786035..a4417166 100644 --- a/SHADE_Managed/src/Components/Renderable.hxx +++ b/SHADE_Managed/src/Components/Renderable.hxx @@ -55,9 +55,19 @@ namespace SHADE void set(MeshAsset value); } ///

- /// Material used to render this Renderable. + /// Special instance of the shared Material for this Renderable. When accessing + /// this property, a new instance of the shared Material is created and assigned + /// to this Renderable. Hence, changes will only affect this Renderable. /// property SHADE::Material Material + { + SHADE::Material get(); + } + /// + /// The shared Material used to render this Renderable and other Renderables + /// using the same base Material. + /// + property SHADE::Material SharedMaterial { SHADE::Material get(); void set(SHADE::Material value);