diff options
author | Brad Davis <[email protected]> | 2014-05-23 01:49:32 -0700 |
---|---|---|
committer | Brad Davis <[email protected]> | 2014-05-23 01:49:32 -0700 |
commit | 46acc0e194ff3c1f120199eeca8324b4502118e9 (patch) | |
tree | b1030198d3ee4698445d1fc5161cebe4158e45d1 /Samples/CommonSrc | |
parent | 07d0f4d0bbf3477ac6a9584f726e8ec6ab285707 (diff) |
Updating to 0.3.2 (windows version)
Diffstat (limited to 'Samples/CommonSrc')
-rw-r--r-- | Samples/CommonSrc/Platform/Win32_Platform.h | 7 | ||||
-rw-r--r-- | Samples/CommonSrc/Render/Render_D3D1X_Device.cpp | 344 | ||||
-rw-r--r-- | Samples/CommonSrc/Render/Render_D3D1X_Device.h | 3 | ||||
-rw-r--r-- | Samples/CommonSrc/Render/Render_Device.cpp | 535 | ||||
-rw-r--r-- | Samples/CommonSrc/Render/Render_Device.h | 67 | ||||
-rw-r--r-- | Samples/CommonSrc/Render/Render_FontEmbed_DejaVu48.h | 2 | ||||
-rw-r--r-- | Samples/CommonSrc/Render/Render_GL_Device.cpp | 593 | ||||
-rw-r--r-- | Samples/CommonSrc/Render/Render_GL_Device.h | 72 | ||||
-rw-r--r-- | Samples/CommonSrc/Render/Render_GL_Win32_Device.cpp | 143 | ||||
-rw-r--r-- | Samples/CommonSrc/Render/Render_GL_Win32_Device.h | 3 | ||||
-rw-r--r-- | Samples/CommonSrc/Render/Render_LoadTextureDDS.cpp | 41 | ||||
-rw-r--r-- | Samples/CommonSrc/Util/OptionMenu.cpp | 899 | ||||
-rw-r--r-- | Samples/CommonSrc/Util/OptionMenu.h | 445 | ||||
-rw-r--r-- | Samples/CommonSrc/Util/RenderProfiler.cpp | 99 | ||||
-rw-r--r-- | Samples/CommonSrc/Util/RenderProfiler.h | 71 |
15 files changed, 2727 insertions, 597 deletions
diff --git a/Samples/CommonSrc/Platform/Win32_Platform.h b/Samples/CommonSrc/Platform/Win32_Platform.h index 23f0b70..a450cb4 100644 --- a/Samples/CommonSrc/Platform/Win32_Platform.h +++ b/Samples/CommonSrc/Platform/Win32_Platform.h @@ -61,7 +61,12 @@ public: bool SetupWindow(int w, int h); void DestroyWindow(); void ShowWindow(bool visible); - void Exit(int exitcode) { Quit = 1; ExitCode = exitcode; } + void Exit(int exitcode) + { + for (MSG msg; PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); ) + ; + Quit = 1; ExitCode = exitcode; + } RenderDevice* SetupGraphics(const SetupGraphicsDeviceSet& setupGraphicsDesc, const char* type, diff --git a/Samples/CommonSrc/Render/Render_D3D1X_Device.cpp b/Samples/CommonSrc/Render/Render_D3D1X_Device.cpp index d7c606f..5476a6f 100644 --- a/Samples/CommonSrc/Render/Render_D3D1X_Device.cpp +++ b/Samples/CommonSrc/Render/Render_D3D1X_Device.cpp @@ -50,6 +50,7 @@ static D3D1x_(INPUT_ELEMENT_DESC) ModelVertexDesc[] = {"Normal", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(Vertex, Norm), D3D1x_(INPUT_PER_VERTEX_DATA), 0}, }; +#pragma region Geometry shaders static const char* StdVertexShaderSrc = "float4x4 Proj;\n" "float4x4 View;\n" @@ -95,7 +96,10 @@ static const char* SolidPixelShaderSrc = "};\n" "float4 main(in Varyings ov) : SV_Target\n" "{\n" - " return Color;\n" + " float4 finalColor = ov.Color;" + // blend state expects premultiplied alpha + " finalColor.rgb *= finalColor.a;\n" + " return finalColor;\n" "}\n"; static const char* GouraudPixelShaderSrc = @@ -107,7 +111,10 @@ static const char* GouraudPixelShaderSrc = "};\n" "float4 main(in Varyings ov) : SV_Target\n" "{\n" - " return ov.Color;\n" + " float4 finalColor = ov.Color;" + // blend state expects premultiplied alpha + " finalColor.rgb *= finalColor.a;\n" + " return finalColor;\n" "}\n"; static const char* TexturePixelShaderSrc = @@ -213,11 +220,14 @@ static const char* AlphaTexturePixelShaderSrc = "float4 main(in Varyings ov) : SV_Target\n" "{\n" " float4 finalColor = ov.Color;\n" - " finalColor.a *= Texture.Sample(Linear, ov.TexCoord).r;\n" + " finalColor.a *= Texture.Sample(Linear, ov.TexCoord).r;\n" + // blend state expects premultiplied alpha + " finalColor.rgb *= finalColor.a;\n" " return finalColor;\n" "}\n"; +#pragma endregion - +#pragma region Distortion shaders // ***** PostProcess Shader static const char* PostProcessVertexShaderSrc = @@ -280,11 +290,12 @@ static const char* PostProcessPixelShaderWithChromAbSrc = " EdgeFadeIn = saturate ( EdgeFadeIn );\n" // Actually do the lookups. - " float ResultR = Texture.Sample(Linear, SourceCoordR).r;\n" - " float ResultG = Texture.Sample(Linear, SourceCoordG).g;\n" - " float ResultB = Texture.Sample(Linear, SourceCoordB).b;\n" - - " return float4(ResultR * EdgeFadeIn, ResultG * EdgeFadeIn, ResultB * EdgeFadeIn, 1.0);\n" + " float4 Result = float4(0,0,0,1);\n" + " Result.r = Texture.Sample(Linear, SourceCoordR).r;\n" + " Result.g = Texture.Sample(Linear, SourceCoordG).g;\n" + " Result.b = Texture.Sample(Linear, SourceCoordB).b;\n" + " Result.rgb *= EdgeFadeIn;\n" + " return Result;\n" "}\n"; //---------------------------------------------------------------------------- @@ -310,7 +321,6 @@ static D3D1x_(INPUT_ELEMENT_DESC) DistortionVertexDesc[] = {"Color", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 8+8+8+8, D3D1x_(INPUT_PER_VERTEX_DATA), 0}, }; - //---------------------------------------------------------------------------- // Simple distortion shader that does three texture reads. // Used for mesh-based distortion without timewarp. @@ -334,16 +344,33 @@ static const char* PostProcessMeshVertexShaderSrc = "}\n"; static const char* PostProcessMeshPixelShaderSrc = - "Texture2D Texture : register(t0);\n" + "Texture2D HmdSpcTexture : register(t0);\n" + "Texture2D OverlayTexture : register(t1);\n" "SamplerState Linear : register(s0);\n" + "float UseOverlay = 1;\n" "\n" "float4 main(in float4 oPosition : SV_Position, in float4 oColor : COLOR,\n" " in float2 oTexCoord0 : TEXCOORD0, in float2 oTexCoord1 : TEXCOORD1, in float2 oTexCoord2 : TEXCOORD2) : SV_Target\n" "{\n" - " float ResultR = Texture.Sample(Linear, oTexCoord0).r;\n" - " float ResultG = Texture.Sample(Linear, oTexCoord1).g;\n" - " float ResultB = Texture.Sample(Linear, oTexCoord2).b;\n" - " return float4(ResultR * oColor.r, ResultG * oColor.g, ResultB * oColor.b, 1.0);\n" + " float4 finalColor = float4(0,0,0,1);\n" + " finalColor.r = HmdSpcTexture.Sample(Linear, oTexCoord0).r;\n" + " finalColor.g = HmdSpcTexture.Sample(Linear, oTexCoord1).g;\n" + " finalColor.b = HmdSpcTexture.Sample(Linear, oTexCoord2).b;\n" + + " if(UseOverlay > 0)\n" + " {\n" + " float2 overlayColorR = OverlayTexture.Sample(Linear, oTexCoord0).ra;\n" + " float2 overlayColorG = OverlayTexture.Sample(Linear, oTexCoord1).ga;\n" + " float2 overlayColorB = OverlayTexture.Sample(Linear, oTexCoord2).ba;\n" + + // do premultiplied alpha blending - overlayColorX.x is color, overlayColorX.y is alpha + " finalColor.r = finalColor.r * saturate(1-overlayColorR.y) + overlayColorR.x;\n" + " finalColor.g = finalColor.g * saturate(1-overlayColorG.y) + overlayColorG.x;\n" + " finalColor.b = finalColor.b * saturate(1-overlayColorB.y) + overlayColorB.x;\n" + " }\n" + + " finalColor.rgb = saturate(finalColor.rgb * oColor.rgb);\n" + " return finalColor;\n" "}\n"; @@ -357,8 +384,11 @@ static const char* PostProcessMeshTimewarpVertexShaderSrc = "float2 EyeToSourceUVOffset;\n" "float3x3 EyeRotationStart;\n" "float3x3 EyeRotationEnd;\n" - "void main(in float2 Position : POSITION, in float4 Color : COLOR0, in float2 TexCoord0 : TEXCOORD0, in float2 TexCoord1 : TEXCOORD1, in float2 TexCoord2 : TEXCOORD2,\n" - " out float4 oPosition : SV_Position, out float4 oColor : COLOR, out float2 oTexCoord0 : TEXCOORD0, out float2 oTexCoord1 : TEXCOORD1, out float2 oTexCoord2 : TEXCOORD2)\n" + "void main(in float2 Position : POSITION, in float4 Color : COLOR0,\n" + " in float2 TexCoord0 : TEXCOORD0, in float2 TexCoord1 : TEXCOORD1, in float2 TexCoord2 : TEXCOORD2,\n" + " out float4 oPosition : SV_Position, out float4 oColor : COLOR,\n" + " out float2 oHmdSpcTexCoordR : TEXCOORD0, out float2 oHmdSpcTexCoordG : TEXCOORD1, out float2 oHmdSpcTexCoordB : TEXCOORD2," + " out float2 oOverlayTexCoordR : TEXCOORD3, out float2 oOverlayTexCoordG : TEXCOORD4, out float2 oOverlayTexCoordB : TEXCOORD5)\n" "{\n" " oPosition.x = Position.x;\n" " oPosition.y = Position.y;\n" @@ -401,51 +431,73 @@ static const char* PostProcessMeshTimewarpVertexShaderSrc = // These are now still in TanEyeAngle space. // Scale them into the correct [0-1],[0-1] UV lookup space (depending on eye) - " float2 SrcCoordR = FlattenedR * EyeToSourceUVScale + EyeToSourceUVOffset;\n" - " float2 SrcCoordG = FlattenedG * EyeToSourceUVScale + EyeToSourceUVOffset;\n" - " float2 SrcCoordB = FlattenedB * EyeToSourceUVScale + EyeToSourceUVOffset;\n" - " oTexCoord0 = SrcCoordR;\n" - " oTexCoord1 = SrcCoordG;\n" - " oTexCoord2 = SrcCoordB;\n" + " oHmdSpcTexCoordR = FlattenedR * EyeToSourceUVScale + EyeToSourceUVOffset;\n" + " oHmdSpcTexCoordG = FlattenedG * EyeToSourceUVScale + EyeToSourceUVOffset;\n" + " oHmdSpcTexCoordB = FlattenedB * EyeToSourceUVScale + EyeToSourceUVOffset;\n" + + // Static layer texcoords don't get any time warp offset + " oOverlayTexCoordR = TexCoord0 * EyeToSourceUVScale + EyeToSourceUVOffset;\n" + " oOverlayTexCoordG = TexCoord1 * EyeToSourceUVScale + EyeToSourceUVOffset;\n" + " oOverlayTexCoordB = TexCoord2 * EyeToSourceUVScale + EyeToSourceUVOffset;\n" + " oColor = Color.r;\n" // Used for vignette fade. "}\n"; static const char* PostProcessMeshTimewarpPixelShaderSrc = - "Texture2D Texture : register(t0);\n" + "Texture2D HmdSpcTexture : register(t0);\n" + "Texture2D OverlayTexture : register(t1);\n" "SamplerState Linear : register(s0);\n" + "float UseOverlay = 1;\n" "\n" "float4 main(in float4 oPosition : SV_Position, in float4 oColor : COLOR,\n" - " in float2 oTexCoord0 : TEXCOORD0, in float2 oTexCoord1 : TEXCOORD1, in float2 oTexCoord2 : TEXCOORD2) : SV_Target\n" + " in float2 oHmdSpcTexCoordR : TEXCOORD0, in float2 oHmdSpcTexCoordG : TEXCOORD1, in float2 oHmdSpcTexCoordB : TEXCOORD2," + " in float2 oOverlayTexCoordR : TEXCOORD3, in float2 oOverlayTexCoordG : TEXCOORD4, in float2 oOverlayTexCoordB : TEXCOORD5) : SV_Target\n" "{\n" - " float ResultR = Texture.Sample(Linear, oTexCoord0).r;\n" - " float ResultG = Texture.Sample(Linear, oTexCoord1).g;\n" - " float ResultB = Texture.Sample(Linear, oTexCoord2).b;\n" - " return float4(ResultR * oColor.r, ResultG * oColor.g, ResultB * oColor.b, 1.0);\n" + " float4 finalColor = float4(0,0,0,1);\n" + " finalColor.r = HmdSpcTexture.Sample(Linear, oHmdSpcTexCoordR).r;\n" + " finalColor.g = HmdSpcTexture.Sample(Linear, oHmdSpcTexCoordG).g;\n" + " finalColor.b = HmdSpcTexture.Sample(Linear, oHmdSpcTexCoordB).b;\n" + + " if(UseOverlay > 0)\n" + " {\n" + " float2 overlayColorR = OverlayTexture.Sample(Linear, oOverlayTexCoordR).ra;\n" + " float2 overlayColorG = OverlayTexture.Sample(Linear, oOverlayTexCoordG).ga;\n" + " float2 overlayColorB = OverlayTexture.Sample(Linear, oOverlayTexCoordB).ba;\n" + + // do premultiplied alpha blending - overlayColorX.x is color, overlayColorX.y is alpha + " finalColor.r = finalColor.r * saturate(1-overlayColorR.y) + overlayColorR.x;\n" + " finalColor.g = finalColor.g * saturate(1-overlayColorG.y) + overlayColorG.x;\n" + " finalColor.b = finalColor.b * saturate(1-overlayColorB.y) + overlayColorB.x;\n" + " }\n" + + " finalColor.rgb = saturate(finalColor.rgb * oColor.rgb);\n" + " return finalColor;\n" "}\n"; + //---------------------------------------------------------------------------- // Pixel shader is very simple - does three texture reads. // Vertex shader does all the hard work. // Used for mesh-based distortion with positional timewarp. static const char* PostProcessMeshPositionalTimewarpVertexShaderSrc = - "Texture2DMS<float,4> DepthTexture : register(t0);\n" + "Texture2DMS<float,4> DepthTexture : register(t0);\n" // Padding because we are uploading "standard uniform buffer" constants "float4x4 Padding1;\n" "float4x4 Padding2;\n" "float2 EyeToSourceUVScale;\n" "float2 EyeToSourceUVOffset;\n" - "float2 DepthProjector;\n" - "float2 DepthDimSize;\n" - "float4x4 EyeRotationStart;\n" + "float2 DepthProjector;\n" + "float2 DepthDimSize;\n" + "float4x4 EyeRotationStart;\n" "float4x4 EyeRotationEnd;\n" "float4 PositionFromDepth(float2 inTexCoord)\n" "{\n" " float2 eyeToSourceTexCoord = inTexCoord * EyeToSourceUVScale + EyeToSourceUVOffset;\n" - " float depth = DepthTexture.Load(int2(eyeToSourceTexCoord * DepthDimSize), 0).x;\n" - " float linearDepth = DepthProjector.y / (depth - DepthProjector.x);\n" - " float4 retVal = float4(inTexCoord, 1, 1);\n" + " float depth = DepthTexture.Load(int2(eyeToSourceTexCoord * DepthDimSize), 0).x;\n" + " float linearDepth = DepthProjector.y / (depth - DepthProjector.x);\n" + " float4 retVal = float4(inTexCoord, 1, 1);\n" " retVal.xyz *= linearDepth;\n" " return retVal;\n" "}\n" @@ -465,10 +517,11 @@ static const char* PostProcessMeshPositionalTimewarpVertexShaderSrc = " return noDepthUV.xy;\n" "}\n" - "void main( in float2 Position : POSITION, in float4 Color : COLOR0, in float2 TexCoord0 : TEXCOORD0,\n" - " in float2 TexCoord1 : TEXCOORD1, in float2 TexCoord2 : TEXCOORD2,\n" - " out float4 oPosition : SV_Position, out float4 oColor : COLOR,\n" - " out float2 oTexCoord0 : TEXCOORD0, out float2 oTexCoord1 : TEXCOORD1, out float2 oTexCoord2 : TEXCOORD2)\n" + "void main(in float2 Position : POSITION, in float4 Color : COLOR0, in float2 TexCoord0 : TEXCOORD0,\n" + " in float2 TexCoord1 : TEXCOORD1, in float2 TexCoord2 : TEXCOORD2,\n" + " out float4 oPosition : SV_Position, out float4 oColor : COLOR,\n" + " out float2 oHmdSpcTexCoordR : TEXCOORD0, out float2 oHmdSpcTexCoordG : TEXCOORD1, out float2 oHmdSpcTexCoordB : TEXCOORD2," + " out float2 oOverlayTexCoordR : TEXCOORD3, out float2 oOverlayTexCoordG : TEXCOORD4, out float2 oOverlayTexCoordB : TEXCOORD5)\n" "{\n" " oPosition.x = Position.x;\n" " oPosition.y = Position.y;\n" @@ -480,28 +533,118 @@ static const char* PostProcessMeshPositionalTimewarpVertexShaderSrc = //" float4x4 lerpedEyeRot = EyeRotationStart;\n" // warped positions are a bit more involved, hence a separate function - " oTexCoord0 = TimewarpTexCoordToWarpedPos(TexCoord0, lerpedEyeRot);\n" - " oTexCoord1 = TimewarpTexCoordToWarpedPos(TexCoord1, lerpedEyeRot);\n" - " oTexCoord2 = TimewarpTexCoordToWarpedPos(TexCoord2, lerpedEyeRot);\n" + " oHmdSpcTexCoordR = TimewarpTexCoordToWarpedPos(TexCoord0, lerpedEyeRot);\n" + " oHmdSpcTexCoordG = TimewarpTexCoordToWarpedPos(TexCoord1, lerpedEyeRot);\n" + " oHmdSpcTexCoordB = TimewarpTexCoordToWarpedPos(TexCoord2, lerpedEyeRot);\n" + + " oOverlayTexCoordR = TexCoord0 * EyeToSourceUVScale + EyeToSourceUVOffset;\n" + " oOverlayTexCoordG = TexCoord1 * EyeToSourceUVScale + EyeToSourceUVOffset;\n" + " oOverlayTexCoordB = TexCoord2 * EyeToSourceUVScale + EyeToSourceUVOffset;\n" " oColor = Color.r; // Used for vignette fade.\n" "}\n"; static const char* PostProcessMeshPositionalTimewarpPixelShaderSrc = - "Texture2D Texture : register(t0);\n" + "Texture2D HmdSpcTexture : register(t0);\n" + "Texture2D OverlayTexture : register(t1);\n" "SamplerState Linear : register(s0);\n" + "float2 DepthDimSize;\n" + "float UseOverlay = 1;\n" + "\n" + "float4 main(in float4 oPosition : SV_Position, in float4 oColor : COLOR,\n" + " in float2 oHmdSpcTexCoordR : TEXCOORD0, in float2 oHmdSpcTexCoordG : TEXCOORD1, in float2 oHmdSpcTexCoordB : TEXCOORD2," + " in float2 oOverlayTexCoordR : TEXCOORD3, in float2 oOverlayTexCoordG : TEXCOORD4, in float2 oOverlayTexCoordB : TEXCOORD5) : SV_Target\n" + "{\n" + " float4 finalColor = float4(0,0,0,1);\n" + " finalColor.r = HmdSpcTexture.Sample(Linear, oHmdSpcTexCoordR).r;\n" + " finalColor.g = HmdSpcTexture.Sample(Linear, oHmdSpcTexCoordG).g;\n" + " finalColor.b = HmdSpcTexture.Sample(Linear, oHmdSpcTexCoordB).b;\n" + + " if(UseOverlay > 0)\n" + " {\n" + " float2 overlayColorR = OverlayTexture.Sample(Linear, oOverlayTexCoordR).ra;\n" + " float2 overlayColorG = OverlayTexture.Sample(Linear, oOverlayTexCoordG).ga;\n" + " float2 overlayColorB = OverlayTexture.Sample(Linear, oOverlayTexCoordB).ba;\n" + + // do premultiplied alpha blending - overlayColorX.x is color, overlayColorX.y is alpha + " finalColor.r = finalColor.r * saturate(1-overlayColorR.y) + overlayColorR.x;\n" + " finalColor.g = finalColor.g * saturate(1-overlayColorG.y) + overlayColorG.x;\n" + " finalColor.b = finalColor.b * saturate(1-overlayColorB.y) + overlayColorB.x;\n" + " }\n" + + " finalColor.rgb = saturate(finalColor.rgb * oColor.rgb);\n" + " return finalColor;\n" + "}\n"; + +//---------------------------------------------------------------------------- +// Pixel shader is very simple - does three texture reads. +// Vertex shader does all the hard work. +// Used for mesh-based heightmap reprojection for positional timewarp. + +static D3D1x_(INPUT_ELEMENT_DESC) HeightmapVertexDesc[] = +{ + {"Position", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D1x_(INPUT_PER_VERTEX_DATA), 0}, + {"TexCoord", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 8, D3D1x_(INPUT_PER_VERTEX_DATA), 0}, +}; + +static const char* PostProcessHeightmapTimewarpVertexShaderSrc = + "Texture2DMS<float,4> DepthTexture : register(t0);\n" + // Padding because we are uploading "standard uniform buffer" constants + "float4x4 Padding1;\n" + "float4x4 Padding2;\n" + "float2 EyeToSourceUVScale;\n" + "float2 EyeToSourceUVOffset;\n" "float2 DepthDimSize;\n" + "float4x4 EyeXformStart;\n" + "float4x4 EyeXformEnd;\n" + //"float4x4 Projection;\n" + "float4x4 InvProjection;\n" + + "float4 PositionFromDepth(float2 position, float2 inTexCoord)\n" + "{\n" + " float depth = DepthTexture.Load(int2(inTexCoord * DepthDimSize), 0).x;\n" + " float4 retVal = float4(position, depth, 1);\n" + " return retVal;\n" + "}\n" + + "float4 TimewarpPos(float2 position, float2 inTexCoord, float4x4 rotMat)\n" + "{\n" + // Apply the 4x4 timewarp rotation to these vectors. + " float4 transformed = PositionFromDepth(position, inTexCoord);\n" + // TODO: Precombining InvProjection in rotMat causes loss of precision flickering + " transformed = mul ( InvProjection, transformed );\n" + " transformed = mul ( rotMat, transformed );\n" + // Commented out as Projection is currently contained in rotMat + //" transformed = mul ( Projection, transformed );\n" + " return transformed;\n" + "}\n" + + "void main( in float2 Position : POSITION, in float3 TexCoord0 : TEXCOORD0,\n" + " out float4 oPosition : SV_Position, out float2 oTexCoord0 : TEXCOORD0)\n" + "{\n" + " float2 eyeToSrcTexCoord = TexCoord0.xy * EyeToSourceUVScale + EyeToSourceUVOffset;\n" + " oTexCoord0 = eyeToSrcTexCoord;\n" + + " float timewarpLerpFactor = TexCoord0.z;\n" + " float4x4 lerpedEyeRot = lerp(EyeXformStart, EyeXformEnd, timewarpLerpFactor);\n" + //" float4x4 lerpedEyeRot = EyeXformStart;\n" + + " oPosition = TimewarpPos(Position.xy, oTexCoord0, lerpedEyeRot);\n" + "}\n"; + +static const char* PostProcessHeightmapTimewarpPixelShaderSrc = + "Texture2D Texture : register(t0);\n" + "SamplerState Linear : register(s0);\n" "\n" - "float4 main(in float4 oPosition : SV_Position, in float4 oColor : COLOR,\n" - " in float2 oTexCoord0 : TEXCOORD0, in float2 oTexCoord1 : TEXCOORD1, in float2 oTexCoord2 : TEXCOORD2) : SV_Target\n" + "float4 main(in float4 oPosition : SV_Position, in float2 oTexCoord0 : TEXCOORD0) : SV_Target\n" "{\n" " float3 result;\n" - " result.r = Texture.Sample(Linear, oTexCoord0).r;\n" - " result.g = Texture.Sample(Linear, oTexCoord1).g;\n" - " result.b = Texture.Sample(Linear, oTexCoord2).b;\n" - " return float4(result * oColor, 1.0);\n" + " result = Texture.Sample(Linear, oTexCoord0);\n" + " return float4(result, 1.0);\n" "}\n"; +#pragma endregion + //---------------------------------------------------------------------------- static const char* VShaderSrcs[VShader_Count] = @@ -511,7 +654,8 @@ static const char* VShaderSrcs[VShader_Count] = PostProcessVertexShaderSrc, PostProcessMeshVertexShaderSrc, PostProcessMeshTimewarpVertexShaderSrc, - PostProcessMeshPositionalTimewarpVertexShaderSrc + PostProcessMeshPositionalTimewarpVertexShaderSrc, + PostProcessHeightmapTimewarpVertexShaderSrc }; static const char* FShaderSrcs[FShader_Count] = { @@ -525,7 +669,8 @@ static const char* FShaderSrcs[FShader_Count] = MultiTexturePixelShaderSrc, PostProcessMeshPixelShaderSrc, PostProcessMeshTimewarpPixelShaderSrc, - PostProcessMeshPositionalTimewarpPixelShaderSrc + PostProcessMeshPositionalTimewarpPixelShaderSrc, + PostProcessHeightmapTimewarpPixelShaderSrc }; RenderDevice::RenderDevice(const RendererParams& p, HWND window) @@ -630,12 +775,23 @@ RenderDevice::RenderDevice(const RendererParams& p, HWND window) HRESULT validate = Device->CreateInputLayout(ModelVertexDesc, sizeof(ModelVertexDesc)/sizeof(ModelVertexDesc[0]), buffer, bufferSize, objRef); OVR_UNUSED(validate); - ID3D10Blob* vsData2 = CompileShader("vs_4_1", PostProcessMeshVertexShaderSrc); - SPInt bufferSize2 = vsData2->GetBufferSize(); - const void* buffer2 = vsData2->GetBufferPointer(); - ID3D1xInputLayout** objRef2 = &DistortionVertexIL.GetRawRef(); - HRESULT validate2 = Device->CreateInputLayout(DistortionVertexDesc, sizeof(DistortionVertexDesc)/sizeof(DistortionVertexDesc[0]), buffer2, bufferSize2, objRef2); - OVR_UNUSED(validate2); + { + ID3D10Blob* vsData2 = CompileShader("vs_4_1", PostProcessMeshVertexShaderSrc); + SPInt bufferSize2 = vsData2->GetBufferSize(); + const void* buffer2 = vsData2->GetBufferPointer(); + ID3D1xInputLayout** objRef2 = &DistortionVertexIL.GetRawRef(); + HRESULT validate2 = Device->CreateInputLayout(DistortionVertexDesc, sizeof(DistortionVertexDesc)/sizeof(DistortionVertexDesc[0]), buffer2, bufferSize2, objRef2); + OVR_UNUSED(validate2); + } + + { + ID3D10Blob* vsData2 = CompileShader("vs_4_1", PostProcessHeightmapTimewarpVertexShaderSrc); + SPInt bufferSize2 = vsData2->GetBufferSize(); + const void* buffer2 = vsData2->GetBufferPointer(); + ID3D1xInputLayout** objRef2 = &HeightmapVertexIL.GetRawRef(); + HRESULT validate2 = Device->CreateInputLayout(HeightmapVertexDesc, sizeof(HeightmapVertexDesc)/sizeof(HeightmapVertexDesc[0]), buffer2, bufferSize2, objRef2); + OVR_UNUSED(validate2); + } Ptr<ShaderSet> gouraudShaders = *new ShaderSet(); gouraudShaders->SetShader(VertexShaders[VShader_MVP]); @@ -647,7 +803,7 @@ RenderDevice::RenderDevice(const RendererParams& p, HWND window) memset(&bm, 0, sizeof(bm)); bm.BlendEnable[0] = true; bm.BlendOp = bm.BlendOpAlpha = D3D1x_(BLEND_OP_ADD); - bm.SrcBlend = bm.SrcBlendAlpha = D3D1x_(BLEND_SRC_ALPHA); + bm.SrcBlend = bm.SrcBlendAlpha = D3D1x_(BLEND_ONE); //premultiplied alpha bm.DestBlend = bm.DestBlendAlpha = D3D1x_(BLEND_INV_SRC_ALPHA); bm.RenderTargetWriteMask[0] = D3D1x_(COLOR_WRITE_ENABLE_ALL); Device->CreateBlendState(&bm, &BlendState.GetRawRef()); @@ -656,7 +812,7 @@ RenderDevice::RenderDevice(const RendererParams& p, HWND window) memset(&bm, 0, sizeof(bm)); bm.RenderTarget[0].BlendEnable = true; bm.RenderTarget[0].BlendOp = bm.RenderTarget[0].BlendOpAlpha = D3D1x_(BLEND_OP_ADD); - bm.RenderTarget[0].SrcBlend = bm.RenderTarget[0].SrcBlendAlpha = D3D1x_(BLEND_SRC_ALPHA); + bm.RenderTarget[0].SrcBlend = bm.RenderTarget[0].SrcBlendAlpha = D3D1x_(BLEND_ONE); //premultiplied alpha bm.RenderTarget[0].DestBlend = bm.RenderTarget[0].DestBlendAlpha = D3D1x_(BLEND_INV_SRC_ALPHA); bm.RenderTarget[0].RenderTargetWriteMask = D3D1x_(COLOR_WRITE_ENABLE_ALL); Device->CreateBlendState(&bm, &BlendState.GetRawRef()); @@ -675,7 +831,7 @@ RenderDevice::RenderDevice(const RendererParams& p, HWND window) const Render::Vertex QuadVertices[] = { Vertex(Vector3f(0, 1, 0)), Vertex(Vector3f(1, 1, 0)), Vertex(Vector3f(0, 0, 0)), Vertex(Vector3f(1, 0, 0)) }; - QuadVertexBuffer->Data(Buffer_Vertex, QuadVertices, sizeof(QuadVertices)); + QuadVertexBuffer->Data(Buffer_Vertex | Buffer_ReadOnly, QuadVertices, sizeof(QuadVertices)); SetDepthMode(0, 0); } @@ -802,6 +958,7 @@ bool RenderDevice::RecreateSwapChain() scDesc.BufferDesc.Width = WindowWidth; scDesc.BufferDesc.Height = WindowHeight; scDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + //scDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; // Use default refresh rate; switching rate on CC prototype can cause screen lockup. scDesc.BufferDesc.RefreshRate.Numerator = 0; scDesc.BufferDesc.RefreshRate.Denominator = 1; @@ -1486,7 +1643,7 @@ ID3D1xSamplerState* RenderDevice::GetSamplerState(int sm) else if (sm & Sample_Anisotropic) { ss.Filter = D3D1x_(FILTER_ANISOTROPIC); - ss.MaxAnisotropy = 8; + ss.MaxAnisotropy = 4; } else { @@ -1573,10 +1730,14 @@ void RenderDevice::GenerateSubresourceData( { bytesPerBlock = 8; } - else if (format == DXGI_FORMAT_BC3_UNORM) - { - bytesPerBlock = 16; - } + else if (format == DXGI_FORMAT_BC2_UNORM) + { + bytesPerBlock = 16; + } + else if (format == DXGI_FORMAT_BC3_UNORM) + { + bytesPerBlock = 16; + } unsigned blockWidth = 0; blockWidth = (subresWidth + 3) / 4; @@ -1659,9 +1820,21 @@ Texture* RenderDevice::CreateTexture(int format, int width, int height, const vo imageDimUpperLimit = 1024; } - if (format == Texture_DXT1 || format == Texture_DXT5) + if (format == Texture_DXT1 || format == Texture_DXT3 || format == Texture_DXT5) { - int convertedFormat = (format == Texture_DXT1) ? DXGI_FORMAT_BC1_UNORM : DXGI_FORMAT_BC3_UNORM; + int convertedFormat; + switch (format) { + case Texture_DXT1: + convertedFormat = DXGI_FORMAT_BC1_UNORM; + break; + case Texture_DXT3: + convertedFormat = DXGI_FORMAT_BC2_UNORM; + break; + case Texture_DXT5: + default: + convertedFormat = DXGI_FORMAT_BC3_UNORM; + break; + } unsigned largestMipWidth = 0; unsigned largestMipHeight = 0; unsigned effectiveMipCount = mipcount; @@ -1670,7 +1843,7 @@ Texture* RenderDevice::CreateTexture(int format, int width, int height, const vo #ifdef OVR_DEFINE_NEW #undef new #endif - + D3D1x_(SUBRESOURCE_DATA)* subresData = (D3D1x_(SUBRESOURCE_DATA)*) OVR_ALLOC(sizeof(D3D1x_(SUBRESOURCE_DATA)) * mipcount); GenerateSubresourceData(width, height, convertedFormat, imageDimUpperLimit, data, subresData, largestMipWidth, @@ -1923,7 +2096,6 @@ void RenderDevice::SetRenderTarget(Render::Texture* color, Render::Texture* dept Context->OMSetRenderTargets(1, &((Texture*)color)->TexRtv.GetRawRef(), ((Texture*)depth)->TexDsv); } - void RenderDevice::SetWorldUniforms(const Matrix4f& proj) { StdUniforms.Proj = proj.Transposed(); @@ -1937,13 +2109,13 @@ void RenderDevice::Render(const Matrix4f& matrix, Model* model) if (!model->VertexBuffer) { Ptr<Buffer> vb = *CreateBuffer(); - vb->Data(Buffer_Vertex, &model->Vertices[0], model->Vertices.GetSize() * sizeof(Vertex)); + vb->Data(Buffer_Vertex | Buffer_ReadOnly, &model->Vertices[0], model->Vertices.GetSize() * sizeof(Vertex)); model->VertexBuffer = vb; } if (!model->IndexBuffer) { Ptr<Buffer> ib = *CreateBuffer(); - ib->Data(Buffer_Index, &model->Indices[0], model->Indices.GetSize() * 2); + ib->Data(Buffer_Index | Buffer_ReadOnly, &model->Indices[0], model->Indices.GetSize() * 2); model->IndexBuffer = ib; } @@ -1961,21 +2133,28 @@ void RenderDevice::RenderWithAlpha( const Fill* fill, Render::Buffer* vertices, } void RenderDevice::Render(const Fill* fill, Render::Buffer* vertices, Render::Buffer* indices, - const Matrix4f& matrix, int offset, int count, PrimitiveType rprim, bool useDistortionVertex/* = false*/) + const Matrix4f& matrix, int offset, int count, PrimitiveType rprim, MeshType meshType/* = Mesh_Scene*/) { ID3D1xBuffer* vertexBuffer = ((Buffer*)vertices)->GetBuffer(); UINT vertexOffset = offset; UINT vertexStride = sizeof(Vertex); - if ( useDistortionVertex ) - { - Context->IASetInputLayout(DistortionVertexIL); - vertexStride = sizeof(DistortionVertex); - } - else + switch(meshType) { + case Mesh_Scene: Context->IASetInputLayout(ModelVertexIL); vertexStride = sizeof(Vertex); + break; + case Mesh_Distortion: + Context->IASetInputLayout(DistortionVertexIL); + vertexStride = sizeof(DistortionVertex); + break; + case Mesh_Heightmap: + Context->IASetInputLayout(HeightmapVertexIL); + vertexStride = sizeof(HeightmapVertex); + break; + default: OVR_ASSERT(false); } + Context->IASetVertexBuffers(0, 1, &vertexBuffer, &vertexStride, &vertexOffset); if (indices) @@ -2058,9 +2237,12 @@ UPInt RenderDevice::QueryGPUMemorySize() void RenderDevice::Present ( bool withVsync ) { - if( OVR::Util::ImageWindow::GlobalWindow() ) + for( int i = 0; i < 4; ++i ) { - OVR::Util::ImageWindow::GlobalWindow()->Process(); + if( OVR::Util::ImageWindow::GlobalWindow( i ) ) + { + OVR::Util::ImageWindow::GlobalWindow( i )->Process(); + } } if ( withVsync ) diff --git a/Samples/CommonSrc/Render/Render_D3D1X_Device.h b/Samples/CommonSrc/Render/Render_D3D1X_Device.h index e06bcda..bd733cc 100644 --- a/Samples/CommonSrc/Render/Render_D3D1X_Device.h +++ b/Samples/CommonSrc/Render/Render_D3D1X_Device.h @@ -265,6 +265,7 @@ public: Ptr<ID3D1xDepthStencilState> CurDepthState; Ptr<ID3D1xInputLayout> ModelVertexIL; Ptr<ID3D1xInputLayout> DistortionVertexIL; + Ptr<ID3D1xInputLayout> HeightmapVertexIL; Ptr<ID3D1xSamplerState> SamplerStates[Sample_Count]; @@ -351,7 +352,7 @@ public: virtual void Render(const Matrix4f& matrix, Model* model); virtual void Render(const Fill* fill, Render::Buffer* vertices, Render::Buffer* indices, - const Matrix4f& matrix, int offset, int count, PrimitiveType prim = Prim_Triangles, bool useDistortionVertex = false); + const Matrix4f& matrix, int offset, int count, PrimitiveType prim = Prim_Triangles, MeshType meshType = Mesh_Scene); virtual void RenderWithAlpha( const Fill* fill, Render::Buffer* vertices, Render::Buffer* indices, const Matrix4f& matrix, int offset, int count, PrimitiveType prim = Prim_Triangles); diff --git a/Samples/CommonSrc/Render/Render_Device.cpp b/Samples/CommonSrc/Render/Render_Device.cpp index e917fb0..88e611a 100644 --- a/Samples/CommonSrc/Render/Render_Device.cpp +++ b/Samples/CommonSrc/Render/Render_Device.cpp @@ -206,35 +206,35 @@ namespace OVR { namespace Render { // Cube vertices and their normals. Vector3f CubeVertices[][3] = { - Vector3f(x1, y2, z1), Vector3f(z1, x1), Vector3f(0.0f, 1.0f, 0.0f), - Vector3f(x2, y2, z1), Vector3f(z1, x2), Vector3f(0.0f, 1.0f, 0.0f), - Vector3f(x2, y2, z2), Vector3f(z2, x2), Vector3f(0.0f, 1.0f, 0.0f), - Vector3f(x1, y2, z2), Vector3f(z2, x1), Vector3f(0.0f, 1.0f, 0.0f), - - Vector3f(x1, y1, z1), Vector3f(z1, x1), Vector3f(0.0f, -1.0f, 0.0f), - Vector3f(x2, y1, z1), Vector3f(z1, x2), Vector3f(0.0f, -1.0f, 0.0f), - Vector3f(x2, y1, z2), Vector3f(z2, x2), Vector3f(0.0f, -1.0f, 0.0f), - Vector3f(x1, y1, z2), Vector3f(z2, x1), Vector3f(0.0f, -1.0f, 0.0f), - - Vector3f(x1, y1, z2), Vector3f(z2, y1), Vector3f(-1.0f, 0.0f, 0.0f), - Vector3f(x1, y1, z1), Vector3f(z1, y1), Vector3f(-1.0f, 0.0f, 0.0f), - Vector3f(x1, y2, z1), Vector3f(z1, y2), Vector3f(-1.0f, 0.0f, 0.0f), - Vector3f(x1, y2, z2), Vector3f(z2, y2), Vector3f(-1.0f, 0.0f, 0.0f), - - Vector3f(x2, y1, z2), Vector3f(z2, y1), Vector3f(1.0f, 0.0f, 0.0f), - Vector3f(x2, y1, z1), Vector3f(z1, y1), Vector3f(1.0f, 0.0f, 0.0f), - Vector3f(x2, y2, z1), Vector3f(z1, y2), Vector3f(1.0f, 0.0f, 0.0f), - Vector3f(x2, y2, z2), Vector3f(z2, y2), Vector3f(1.0f, 0.0f, 0.0f), - - Vector3f(x1, y1, z1), Vector3f(x1, y1), Vector3f(0.0f, 0.0f, -1.0f), - Vector3f(x2, y1, z1), Vector3f(x2, y1), Vector3f(0.0f, 0.0f, -1.0f), - Vector3f(x2, y2, z1), Vector3f(x2, y2), Vector3f(0.0f, 0.0f, -1.0f), - Vector3f(x1, y2, z1), Vector3f(x1, y2), Vector3f(0.0f, 0.0f, -1.0f), - - Vector3f(x1, y1, z2), Vector3f(x1, y1), Vector3f(0.0f, 0.0f, 1.0f), - Vector3f(x2, y1, z2), Vector3f(x2, y1), Vector3f(0.0f, 0.0f, 1.0f), - Vector3f(x2, y2, z2), Vector3f(x2, y2), Vector3f(0.0f, 0.0f, 1.0f), - Vector3f(x1, y2, z2), Vector3f(x1, y2), Vector3f(0.0f, 0.0f, 1.0f) + { Vector3f(x1, y2, z1), Vector3f(z1, x1), Vector3f(0.0f, 1.0f, 0.0f) }, + { Vector3f(x2, y2, z1), Vector3f(z1, x2), Vector3f(0.0f, 1.0f, 0.0f) }, + { Vector3f(x2, y2, z2), Vector3f(z2, x2), Vector3f(0.0f, 1.0f, 0.0f) }, + { Vector3f(x1, y2, z2), Vector3f(z2, x1), Vector3f(0.0f, 1.0f, 0.0f) }, + + { Vector3f(x1, y1, z1), Vector3f(z1, x1), Vector3f(0.0f, -1.0f, 0.0f) }, + { Vector3f(x2, y1, z1), Vector3f(z1, x2), Vector3f(0.0f, -1.0f, 0.0f) }, + { Vector3f(x2, y1, z2), Vector3f(z2, x2), Vector3f(0.0f, -1.0f, 0.0f) }, + { Vector3f(x1, y1, z2), Vector3f(z2, x1), Vector3f(0.0f, -1.0f, 0.0f) }, + + { Vector3f(x1, y1, z2), Vector3f(z2, y1), Vector3f(-1.0f, 0.0f, 0.0f) }, + { Vector3f(x1, y1, z1), Vector3f(z1, y1), Vector3f(-1.0f, 0.0f, 0.0f) }, + { Vector3f(x1, y2, z1), Vector3f(z1, y2), Vector3f(-1.0f, 0.0f, 0.0f) }, + { Vector3f(x1, y2, z2), Vector3f(z2, y2), Vector3f(-1.0f, 0.0f, 0.0f) }, + + { Vector3f(x2, y1, z2), Vector3f(z2, y1), Vector3f(1.0f, 0.0f, 0.0f) }, + { Vector3f(x2, y1, z1), Vector3f(z1, y1), Vector3f(1.0f, 0.0f, 0.0f) }, + { Vector3f(x2, y2, z1), Vector3f(z1, y2), Vector3f(1.0f, 0.0f, 0.0f) }, + { Vector3f(x2, y2, z2), Vector3f(z2, y2), Vector3f(1.0f, 0.0f, 0.0f) }, + + { Vector3f(x1, y1, z1), Vector3f(x1, y1), Vector3f(0.0f, 0.0f, -1.0f) }, + { Vector3f(x2, y1, z1), Vector3f(x2, y1), Vector3f(0.0f, 0.0f, -1.0f) }, + { Vector3f(x2, y2, z1), Vector3f(x2, y2), Vector3f(0.0f, 0.0f, -1.0f) }, + { Vector3f(x1, y2, z1), Vector3f(x1, y2), Vector3f(0.0f, 0.0f, -1.0f) }, + + { Vector3f(x1, y1, z2), Vector3f(x1, y1), Vector3f(0.0f, 0.0f, 1.0f) }, + { Vector3f(x2, y1, z2), Vector3f(x2, y1), Vector3f(0.0f, 0.0f, 1.0f) }, + { Vector3f(x2, y2, z2), Vector3f(x2, y2), Vector3f(0.0f, 0.0f, 1.0f) }, + { Vector3f(x1, y2, z2), Vector3f(x1, y2), Vector3f(0.0f, 0.0f, 1.0f) } }; @@ -899,7 +899,8 @@ namespace OVR { namespace Render { ppfs = LoadBuiltinShader(Shader_Fragment, FShader_PostProcessWithChromAb); vs = LoadBuiltinShader(Shader_Vertex, VShader_PostProcess); } - else if (PostProcessShaderActive == PostProcessShader_MeshDistortionAndChromAb) + else if (PostProcessShaderActive == PostProcessShader_MeshDistortionAndChromAb || + PostProcessShaderActive == PostProcessShader_MeshDistortionAndChromAbHeightmapTimewarp) { ppfs = LoadBuiltinShader(Shader_Fragment, FShader_PostProcessMeshWithChromAb); vs = LoadBuiltinShader(Shader_Vertex, VShader_PostProcessMesh); @@ -909,11 +910,11 @@ namespace OVR { namespace Render { ppfs = LoadBuiltinShader(Shader_Fragment, FShader_PostProcessMeshWithChromAbTimewarp); vs = LoadBuiltinShader(Shader_Vertex, VShader_PostProcessMeshTimewarp); } - else if (PostProcessShaderActive == PostProcessShader_MeshDistortionAndChromAbPositionalTimewarp) - { - ppfs = LoadBuiltinShader(Shader_Fragment, FShader_PostProcessMeshWithChromAbPositionalTimewarp); - vs = LoadBuiltinShader(Shader_Vertex, VShader_PostProcessMeshPositionalTimewarp); - } + else if (PostProcessShaderActive == PostProcessShader_MeshDistortionAndChromAbPositionalTimewarp) + { + ppfs = LoadBuiltinShader(Shader_Fragment, FShader_PostProcessMeshWithChromAbPositionalTimewarp); + vs = LoadBuiltinShader(Shader_Vertex, VShader_PostProcessMeshPositionalTimewarp); + } else { OVR_ASSERT(false); @@ -926,6 +927,23 @@ namespace OVR { namespace Render { pPostProcessShader->SetShader(ppfs); } + // Heightmap method does the timewarp on the first pass + if (!pPostProcessHeightmapShader && + PostProcessShaderActive == PostProcessShader_MeshDistortionAndChromAbHeightmapTimewarp) + { + Shader *vs = NULL; + Shader *ppfs = NULL; + + ppfs = LoadBuiltinShader(Shader_Fragment, FShader_PostProcessHeightmapTimewarp); + vs = LoadBuiltinShader(Shader_Vertex, VShader_PostProcessHeightmapTimewarp); + + OVR_ASSERT(ppfs); // Means the shader failed to compile - look in the debug spew. + OVR_ASSERT(vs); + + pPostProcessHeightmapShader = *CreateShaderSet(); + pPostProcessHeightmapShader->SetShader(vs); + pPostProcessHeightmapShader->SetShader(ppfs); + } if(!pFullScreenVertexBuffer) { @@ -937,7 +955,7 @@ namespace OVR { namespace Render { Vertex(Vector3f(0, 0, 0), Color(1, 1, 1, 1), 0, 1), Vertex(Vector3f(1, 0, 0), Color(1, 1, 1, 1), 1, 1) }; - pFullScreenVertexBuffer->Data(Buffer_Vertex, QuadVertices, sizeof(QuadVertices)); + pFullScreenVertexBuffer->Data(Buffer_Vertex | Buffer_ReadOnly, QuadVertices, sizeof(QuadVertices)); } return true; } @@ -960,7 +978,7 @@ namespace OVR { namespace Render { void RenderDevice::FinishScene() { SetExtraShaders(0); - SetRenderTarget(0); + SetDefaultRenderTarget(); } @@ -971,9 +989,10 @@ namespace OVR { namespace Render { { PostProcessingType = pptype; - if ( ( pptype == PostProcess_MeshDistortion ) || + if (( pptype == PostProcess_MeshDistortion ) || ( pptype == PostProcess_MeshDistortionTimewarp ) || - ( pptype == PostProcess_MeshDistortionPositionalTimewarp ) ) + ( pptype == PostProcess_MeshDistortionPositionalTimewarp ) || + ( pptype == PostProcess_MeshDistortionHeightmapTimewarp)) { for ( int eyeNum = 0; eyeNum < 2; eyeNum++ ) { @@ -1009,13 +1028,55 @@ namespace OVR { namespace Render { DistortionMeshNumTris[eyeNum] = numTris; pDistortionMeshVertexBuffer[eyeNum] = *CreateBuffer(); - pDistortionMeshVertexBuffer[eyeNum]->Data ( Buffer_Vertex, pVerts, sizeof(DistortionVertex) * numVerts ); + pDistortionMeshVertexBuffer[eyeNum]->Data ( Buffer_Vertex | Buffer_ReadOnly, pVerts, sizeof(DistortionVertex) * numVerts ); pDistortionMeshIndexBuffer[eyeNum] = *CreateBuffer(); - pDistortionMeshIndexBuffer[eyeNum]->Data ( Buffer_Index, pIndices, ( sizeof(UInt16) * numIndices ) ); + pDistortionMeshIndexBuffer[eyeNum]->Data ( Buffer_Index | Buffer_ReadOnly, pIndices, ( sizeof(UInt16) * numIndices ) ); DistortionMeshDestroy ( pRawVerts, pIndices ); OVR_FREE ( pVerts ); } + + if(pptype == PostProcess_MeshDistortionHeightmapTimewarp) + { + // Create the positional timewarp rectangular heightmap mesh + for ( int eyeNum = 0; eyeNum < 2; eyeNum++ ) + { + const StereoEyeParams &stereoParams = ( eyeNum == 0 ) ? stereoParamsLeft : stereoParamsRight; + + // Get the mesh data. + int numVerts = 0; + int numTris = 0; + HeightmapMeshVertexData *pRawVerts = NULL; + UInt16 *pIndices = NULL; + HeightmapMeshCreate ( &pRawVerts, &pIndices, &numVerts, &numTris, stereoParams, hmdRenderInfo ); + int numIndices = numTris * 3; + + // Convert to final vertex data. + HeightmapVertex *pVerts = (HeightmapVertex*)OVR_ALLOC ( sizeof(HeightmapVertex) * numVerts ); + HeightmapVertex *pCurVert = pVerts; + HeightmapMeshVertexData *pCurRawVert = pRawVerts; + for ( int vertNum = 0; vertNum < numVerts; vertNum++ ) + { + pCurVert->Pos.x = pCurRawVert->ScreenPosNDC.x; + pCurVert->Pos.y = pCurRawVert->ScreenPosNDC.y; + Vector2f texCoord = pCurRawVert->TanEyeAngles; + pCurVert->Tex.x = texCoord.x; + pCurVert->Tex.y = texCoord.y; + pCurVert->Tex.z = (OVR::UByte)( floorf ( pCurRawVert->TimewarpLerp * 255.999f ) ); + pCurRawVert++; + pCurVert++; + } + + HeightmapMeshNumTris[eyeNum] = numTris; + pHeightmapMeshVertexBuffer[eyeNum] = *CreateBuffer(); + pHeightmapMeshVertexBuffer[eyeNum]->Data ( Buffer_Vertex, pVerts, sizeof(HeightmapVertex) * numVerts ); + pHeightmapMeshIndexBuffer[eyeNum] = *CreateBuffer(); + pHeightmapMeshIndexBuffer[eyeNum]->Data ( Buffer_Index, pIndices, ( sizeof(UInt16) * numIndices ) ); + + HeightmapMeshDestroy ( pRawVerts, pIndices ); + OVR_FREE ( pVerts ); + } + } } else { @@ -1025,117 +1086,265 @@ namespace OVR { namespace Render { void RenderDevice::ApplyPostProcess(Matrix4f const &matNowFromWorldStart, Matrix4f const &matNowFromWorldEnd, - Matrix4f const &matRenderFromWorldLeft, Matrix4f const &matRenderFromWorldRight, - StereoEyeParams const &stereoParamsLeft, StereoEyeParams const &stereoParamsRight, - Ptr<Texture> pSourceTextureLeftOrOnly, - Ptr<Texture> pSourceTextureRight, - Ptr<Texture> pSourceTextureLeftOrOnlyDepth, - Ptr<Texture> pSourceTextureRightDepth) + Matrix4f const &matRenderFromWorldLeft, Matrix4f const &matRenderFromWorldRight, + StereoEyeParams const &stereoParamsLeft, StereoEyeParams const &stereoParamsRight, + RenderTarget* pHmdSpaceLayerRenderTargetLeftOrBothEyes, + RenderTarget* pHmdSpaceLayerRenderTargetRight, + RenderTarget* pOverlayLayerRenderTargetLeftOrBothEyes, + RenderTarget* pOverlayLayerRenderTargetRight) { SetExtraShaders(0); - if ( PostProcessingType == PostProcess_MeshDistortion ) - { - Recti vp ( 0, 0, WindowWidth, WindowHeight ); - SetViewport(vp); - float r, g, b, a; - DistortionClearColor.GetRGBA(&r, &g, &b, &a); - Clear(r, g, b, a); - - Matrix4f dummy; - ShaderFill fill(pPostProcessShader); - - fill.SetTexture ( 0, pSourceTextureLeftOrOnly ); - pPostProcessShader->SetUniform2f("EyeToSourceUVScale", stereoParamsLeft.EyeToSourceUV.Scale.x, stereoParamsLeft.EyeToSourceUV.Scale.y ); - pPostProcessShader->SetUniform2f("EyeToSourceUVOffset", stereoParamsLeft.EyeToSourceUV.Offset.x, stereoParamsLeft.EyeToSourceUV.Offset.y ); - Render(&fill, pDistortionMeshVertexBuffer[0], pDistortionMeshIndexBuffer[0], dummy, 0, DistortionMeshNumTris[0] * 3, Prim_Triangles, true); - - if ( pSourceTextureRight != NULL ) - { - fill.SetTexture ( 0, pSourceTextureRight ); - } - pPostProcessShader->SetUniform2f("EyeToSourceUVScale", stereoParamsRight.EyeToSourceUV.Scale.x, stereoParamsRight.EyeToSourceUV.Scale.y ); - pPostProcessShader->SetUniform2f("EyeToSourceUVOffset", stereoParamsRight.EyeToSourceUV.Offset.x, stereoParamsRight.EyeToSourceUV.Offset.y ); - Render(&fill, pDistortionMeshVertexBuffer[1], pDistortionMeshIndexBuffer[1], dummy, 0, DistortionMeshNumTris[1] * 3, Prim_Triangles, true); - } - else if ( PostProcessingType == PostProcess_MeshDistortionTimewarp ) - { - Recti vp ( 0, 0, WindowWidth, WindowHeight ); - SetViewport(vp); - float r, g, b, a; - DistortionClearColor.GetRGBA(&r, &g, &b, &a); - Clear(r, g, b, a); - - ShaderFill fill(pPostProcessShader); - fill.SetTexture ( 0, pSourceTextureLeftOrOnly ); - - for ( int eyeNum = 0; eyeNum < 2; eyeNum++ ) - { - Matrix4f const &matRenderFromWorld = ( eyeNum == 0 ) ? matRenderFromWorldLeft : matRenderFromWorldRight; - const StereoEyeParams &stereoParams = ( eyeNum == 0 ) ? stereoParamsLeft : stereoParamsRight; - - Matrix4f matRenderFromNowStart = TimewarpComputePoseDelta ( matRenderFromWorld, matNowFromWorldStart ); - Matrix4f matRenderFromNowEnd = TimewarpComputePoseDelta ( matRenderFromWorld, matNowFromWorldEnd ); - - pPostProcessShader->SetUniform2f("EyeToSourceUVScale", stereoParams.EyeToSourceUV.Scale.x, stereoParams.EyeToSourceUV.Scale.y ); - pPostProcessShader->SetUniform2f("EyeToSourceUVOffset", stereoParams.EyeToSourceUV.Offset.x, stereoParams.EyeToSourceUV.Offset.y ); - pPostProcessShader->SetUniform3x3f("EyeRotationStart", matRenderFromNowStart); - pPostProcessShader->SetUniform3x3f("EyeRotationEnd", matRenderFromNowEnd); - - Matrix4f dummy; - if ( ( pSourceTextureRight != NULL ) && ( eyeNum == 1 ) ) - { - fill.SetTexture ( 0, pSourceTextureRight ); - } - Render(&fill, pDistortionMeshVertexBuffer[eyeNum], pDistortionMeshIndexBuffer[eyeNum], dummy, 0, DistortionMeshNumTris[eyeNum] * 3, Prim_Triangles, true); - } - } - else if ( PostProcessingType == PostProcess_MeshDistortionPositionalTimewarp ) - { - Recti vp( 0, 0, WindowWidth, WindowHeight ); - SetViewport(vp); - float r, g, b, a; - DistortionClearColor.GetRGBA(&r, &g, &b, &a); - Clear(r, g, b, a); - - ShaderFill fill(pPostProcessShader); - fill.SetTexture ( 0, pSourceTextureLeftOrOnly ); - fill.SetTexture ( 0, pSourceTextureLeftOrOnlyDepth, Shader_Vertex ); - - for ( int eyeNum = 0; eyeNum < 2; eyeNum++ ) - { - Matrix4f const &matRenderFromWorld = ( eyeNum == 0 ) ? matRenderFromWorldLeft : matRenderFromWorldRight; - const StereoEyeParams &stereoParams = ( eyeNum == 0 ) ? stereoParamsLeft : stereoParamsRight; - - Matrix4f matRenderFromNowStart = TimewarpComputePoseDelta ( matRenderFromWorld, matNowFromWorldStart ); - Matrix4f matRenderFromNowEnd = TimewarpComputePoseDelta ( matRenderFromWorld, matNowFromWorldEnd ); - - pPostProcessShader->SetUniform2f("EyeToSourceUVScale", stereoParams.EyeToSourceUV.Scale.x, stereoParams.EyeToSourceUV.Scale.y ); - pPostProcessShader->SetUniform2f("EyeToSourceUVOffset", stereoParams.EyeToSourceUV.Offset.x, stereoParams.EyeToSourceUV.Offset.y ); - - // DepthProjector values can also be calculated as: - // float DepthProjectorX = FarClip / (FarClip - NearClip); - // float DepthProjectorY = (-FarClip * NearClip) / (FarClip - NearClip); - pPostProcessShader->SetUniform2f("DepthProjector", -stereoParams.RenderedProjection.M[2][2], stereoParams.RenderedProjection.M[2][3]); - pPostProcessShader->SetUniform2f("DepthDimSize", (float)pSourceTextureLeftOrOnlyDepth->GetWidth(), (float)pSourceTextureLeftOrOnlyDepth->GetHeight()); - pPostProcessShader->SetUniform4x4f("EyeRotationStart", matRenderFromNowStart); - pPostProcessShader->SetUniform4x4f("EyeRotationEnd", matRenderFromNowEnd); - - - Matrix4f dummy; - if ( ( pSourceTextureRight != NULL ) && ( eyeNum == 1 ) ) - { - OVR_ASSERT(pSourceTextureRightDepth != NULL); - fill.SetTexture ( 0, pSourceTextureRight ); - fill.SetTexture ( 0, pSourceTextureRightDepth, Shader_Vertex ); - } - - Render(&fill, pDistortionMeshVertexBuffer[eyeNum], pDistortionMeshIndexBuffer[eyeNum], dummy, 0, DistortionMeshNumTris[eyeNum] * 3, Prim_Triangles, true); - } - } - else - { - if ( PostProcessingType == PostProcess_PixelDistortion ) + bool usingOverlay = pOverlayLayerRenderTargetLeftOrBothEyes != NULL; + + switch( PostProcessingType ) + { + case PostProcess_MeshDistortion: + { + Recti vp ( 0, 0, WindowWidth, WindowHeight ); + SetViewport(vp); + float r, g, b, a; + DistortionClearColor.GetRGBA(&r, &g, &b, &a); + Clear(r, g, b, a); + + Matrix4f dummy; + ShaderFill fill(pPostProcessShader); + + fill.SetTexture ( 0, pHmdSpaceLayerRenderTargetLeftOrBothEyes->pColorTex ); + fill.SetTexture ( 1, (usingOverlay ? pOverlayLayerRenderTargetLeftOrBothEyes->pColorTex : NULL)); + pPostProcessShader->SetUniform1f("UseOverlay", usingOverlay ? 1.0f : 0.0f); + pPostProcessShader->SetUniform2f("EyeToSourceUVScale", stereoParamsLeft.EyeToSourceUV.Scale.x, stereoParamsLeft.EyeToSourceUV.Scale.y ); + pPostProcessShader->SetUniform2f("EyeToSourceUVOffset", stereoParamsLeft.EyeToSourceUV.Offset.x, stereoParamsLeft.EyeToSourceUV.Offset.y ); + Render(&fill, pDistortionMeshVertexBuffer[0], pDistortionMeshIndexBuffer[0], dummy, 0, DistortionMeshNumTris[0] * 3, Prim_Triangles, Mesh_Distortion); + + if ( pHmdSpaceLayerRenderTargetRight != NULL ) + { + fill.SetTexture ( 0, pHmdSpaceLayerRenderTargetRight->pColorTex ); + fill.SetTexture ( 1, (usingOverlay ? pOverlayLayerRenderTargetRight->pColorTex : NULL)); + } + pPostProcessShader->SetUniform2f("EyeToSourceUVScale", stereoParamsRight.EyeToSourceUV.Scale.x, stereoParamsRight.EyeToSourceUV.Scale.y ); + pPostProcessShader->SetUniform2f("EyeToSourceUVOffset", stereoParamsRight.EyeToSourceUV.Offset.x, stereoParamsRight.EyeToSourceUV.Offset.y ); + Render(&fill, pDistortionMeshVertexBuffer[1], pDistortionMeshIndexBuffer[1], dummy, 0, DistortionMeshNumTris[1] * 3, Prim_Triangles, Mesh_Distortion); + } + break; + + case PostProcess_MeshDistortionTimewarp: + { + Recti vp ( 0, 0, WindowWidth, WindowHeight ); + SetViewport(vp); + float r, g, b, a; + DistortionClearColor.GetRGBA(&r, &g, &b, &a); + Clear(r, g, b, a); + + ShaderFill fill(pPostProcessShader); + fill.SetTexture ( 0, pHmdSpaceLayerRenderTargetLeftOrBothEyes->pColorTex ); + fill.SetTexture ( 1, (usingOverlay ? pOverlayLayerRenderTargetLeftOrBothEyes->pColorTex : NULL)); + pPostProcessShader->SetUniform1f("UseOverlay", usingOverlay ? 1.0f : 0.0f); + + for ( int eyeNum = 0; eyeNum < 2; eyeNum++ ) + { + Matrix4f const &matRenderFromWorld = ( eyeNum == 0 ) ? matRenderFromWorldLeft : matRenderFromWorldRight; + const StereoEyeParams &stereoParams = ( eyeNum == 0 ) ? stereoParamsLeft : stereoParamsRight; + + Matrix4f matRenderFromNowStart = TimewarpComputePoseDelta ( matRenderFromWorld, matNowFromWorldStart, stereoParams.ViewAdjust ); + Matrix4f matRenderFromNowEnd = TimewarpComputePoseDelta ( matRenderFromWorld, matNowFromWorldEnd, stereoParams.ViewAdjust ); + + pPostProcessShader->SetUniform2f("EyeToSourceUVScale", stereoParams.EyeToSourceUV.Scale.x, stereoParams.EyeToSourceUV.Scale.y ); + pPostProcessShader->SetUniform2f("EyeToSourceUVOffset", stereoParams.EyeToSourceUV.Offset.x, stereoParams.EyeToSourceUV.Offset.y ); + pPostProcessShader->SetUniform3x3f("EyeRotationStart", matRenderFromNowStart); + pPostProcessShader->SetUniform3x3f("EyeRotationEnd", matRenderFromNowEnd); + + Matrix4f dummy; + if ( ( pHmdSpaceLayerRenderTargetRight != NULL ) && ( eyeNum == 1 ) ) + { + fill.SetTexture ( 0, pHmdSpaceLayerRenderTargetRight->pColorTex ); + fill.SetTexture ( 1, (usingOverlay ? pOverlayLayerRenderTargetRight->pColorTex : NULL)); + } + Render(&fill, pDistortionMeshVertexBuffer[eyeNum], pDistortionMeshIndexBuffer[eyeNum], dummy, 0, DistortionMeshNumTris[eyeNum] * 3, Prim_Triangles, Mesh_Distortion); + } + } + break; + + case PostProcess_MeshDistortionPositionalTimewarp: + { + Recti vp( 0, 0, WindowWidth, WindowHeight ); + SetViewport(vp); + float r, g, b, a; + DistortionClearColor.GetRGBA(&r, &g, &b, &a); + Clear(r, g, b, a); + + ShaderFill fill(pPostProcessShader); + fill.SetTexture ( 0, pHmdSpaceLayerRenderTargetLeftOrBothEyes->pColorTex ); + fill.SetTexture ( 0, pHmdSpaceLayerRenderTargetLeftOrBothEyes->pDepthTex, Shader_Vertex ); + fill.SetTexture ( 1, (usingOverlay ? pOverlayLayerRenderTargetLeftOrBothEyes->pColorTex : NULL)); + pPostProcessShader->SetUniform1f("UseOverlay", usingOverlay ? 1.0f : 0.0f); + + for ( int eyeNum = 0; eyeNum < 2; eyeNum++ ) + { + Matrix4f const &matRenderFromWorld = ( eyeNum == 0 ) ? matRenderFromWorldLeft : matRenderFromWorldRight; + const StereoEyeParams &stereoParams = ( eyeNum == 0 ) ? stereoParamsLeft : stereoParamsRight; + + Matrix4f matRenderFromNowStart = TimewarpComputePoseDelta ( matRenderFromWorld, matNowFromWorldStart, stereoParams.ViewAdjust ); + Matrix4f matRenderFromNowEnd = TimewarpComputePoseDelta ( matRenderFromWorld, matNowFromWorldEnd, stereoParams.ViewAdjust ); + + pPostProcessShader->SetUniform2f("EyeToSourceUVScale", stereoParams.EyeToSourceUV.Scale.x, stereoParams.EyeToSourceUV.Scale.y ); + pPostProcessShader->SetUniform2f("EyeToSourceUVOffset", stereoParams.EyeToSourceUV.Offset.x, stereoParams.EyeToSourceUV.Offset.y ); + + // DepthProjector values can also be calculated as: + // float DepthProjectorX = FarClip / (FarClip - NearClip); + // float DepthProjectorY = (-FarClip * NearClip) / (FarClip - NearClip); + pPostProcessShader->SetUniform2f("DepthProjector", -stereoParams.RenderedProjection.M[2][2], stereoParams.RenderedProjection.M[2][3]); + pPostProcessShader->SetUniform2f("DepthDimSize", (float)pHmdSpaceLayerRenderTargetLeftOrBothEyes->Size.w, (float)pHmdSpaceLayerRenderTargetLeftOrBothEyes->Size.h); + pPostProcessShader->SetUniform4x4f("EyeRotationStart", matRenderFromNowStart); + pPostProcessShader->SetUniform4x4f("EyeRotationEnd", matRenderFromNowEnd); + + + Matrix4f dummy; + if ( ( pHmdSpaceLayerRenderTargetRight != NULL ) && ( eyeNum == 1 ) ) + { + OVR_ASSERT(pHmdSpaceLayerRenderTargetRight->pDepthTex != NULL); + fill.SetTexture ( 0, pHmdSpaceLayerRenderTargetRight->pColorTex ); + fill.SetTexture ( 0, pHmdSpaceLayerRenderTargetRight->pDepthTex, Shader_Vertex ); + fill.SetTexture ( 1, (usingOverlay ? pOverlayLayerRenderTargetRight->pColorTex : NULL)); + } + + Render(&fill, pDistortionMeshVertexBuffer[eyeNum], pDistortionMeshIndexBuffer[eyeNum], dummy, 0, DistortionMeshNumTris[eyeNum] * 3, Prim_Triangles, Mesh_Distortion); + } + } + break; + + case PostProcess_MeshDistortionHeightmapTimewarp: + { + // Create pass1 textures if not already done + for ( int eyeNum = 0; eyeNum < 2; eyeNum++ ) + { + Texture* templateTexture = NULL; + switch(eyeNum) + { + case 0: templateTexture = pHmdSpaceLayerRenderTargetLeftOrBothEyes->pColorTex; break; + case 1: templateTexture = pHmdSpaceLayerRenderTargetRight->pColorTex; break; + default: OVR_ASSERT(false); + } + + if( templateTexture == NULL) + { + if(HeightmapTimewarpRTs[eyeNum].pColorTex != NULL) + { + HeightmapTimewarpRTs[eyeNum].pColorTex = NULL; + HeightmapTimewarpRTs[eyeNum].pDepthTex = NULL; + } + } + else if( HeightmapTimewarpRTs[eyeNum].pColorTex == NULL || + HeightmapTimewarpRTs[eyeNum].Size.w != templateTexture->GetWidth() || + HeightmapTimewarpRTs[eyeNum].Size.h != templateTexture->GetHeight()) + { + HeightmapTimewarpRTs[eyeNum].Size.w = templateTexture->GetWidth(); + HeightmapTimewarpRTs[eyeNum].Size.h = templateTexture->GetHeight(); + + HeightmapTimewarpRTs[eyeNum].pColorTex = *CreateTexture(Texture_RGBA | Texture_RenderTarget | templateTexture->GetSamples(), + HeightmapTimewarpRTs[eyeNum].Size.w, HeightmapTimewarpRTs[eyeNum].Size.h, NULL); + + HeightmapTimewarpRTs[eyeNum].pColorTex->SetSampleMode ( Sample_ClampBorder | Sample_Linear); + + HeightmapTimewarpRTs[eyeNum].pDepthTex = *CreateTexture(Texture_Depth | Texture_RenderTarget | Texture_SampleDepth | templateTexture->GetSamples(), + HeightmapTimewarpRTs[eyeNum].Size.w, HeightmapTimewarpRTs[eyeNum].Size.h, NULL); + } + } + + Matrix4f identity; + + // Pass 1 - do heightmap-based positional time warp + { + SetDepthMode(true, true); + + ShaderFill heightmapFill(pPostProcessHeightmapShader); + + for ( int eyeNum = 0; eyeNum < 2; eyeNum++ ) + { + const StereoEyeParams &stereoParams = ( eyeNum == 0 ) ? stereoParamsLeft : stereoParamsRight; + + switch(eyeNum) + { + case 0: + { + heightmapFill.SetTexture ( 0, pHmdSpaceLayerRenderTargetLeftOrBothEyes->pColorTex ); + heightmapFill.SetTexture ( 0, pHmdSpaceLayerRenderTargetLeftOrBothEyes->pDepthTex, Shader_Vertex ); + SetRenderTarget(HeightmapTimewarpRTs[eyeNum]); // output to temp buffers + } + break; + case 1: + if ( ( pHmdSpaceLayerRenderTargetRight != NULL ) ) + { + heightmapFill.SetTexture ( 0, pHmdSpaceLayerRenderTargetRight->pColorTex ); + heightmapFill.SetTexture ( 0, pHmdSpaceLayerRenderTargetRight->pDepthTex, Shader_Vertex ); + SetRenderTarget(HeightmapTimewarpRTs[eyeNum]); // output to temp buffers + } + break; + default: OVR_ASSERT(false); + } + + SetViewport(stereoParams.RenderedViewport); + Clear(); + + Matrix4f const &matRenderFromWorld = ( eyeNum == 0 ) ? matRenderFromWorldLeft : matRenderFromWorldRight; + + Matrix4f matRenderFromNowStart = TimewarpComputePoseDeltaPosition ( matRenderFromWorld, matNowFromWorldStart, stereoParams.ViewAdjust ); + Matrix4f matRenderFromNowEnd = TimewarpComputePoseDeltaPosition ( matRenderFromWorld, matNowFromWorldEnd, stereoParams.ViewAdjust ); + + pPostProcessHeightmapShader->SetUniform2f("EyeToSourceUVScale", stereoParams.EyeToSourceUV.Scale.x, stereoParams.EyeToSourceUV.Scale.y ); + pPostProcessHeightmapShader->SetUniform2f("EyeToSourceUVOffset", stereoParams.EyeToSourceUV.Offset.x, stereoParams.EyeToSourceUV.Offset.y ); + + pPostProcessHeightmapShader->SetUniform2f("DepthDimSize", (float)pHmdSpaceLayerRenderTargetLeftOrBothEyes->Size.w, (float)pHmdSpaceLayerRenderTargetLeftOrBothEyes->Size.h); + + // TODO: Combining "proj * xform * invProj" leads to artifacts due to precision loss with the inversion + pPostProcessHeightmapShader->SetUniform4x4f("EyeXformStart", stereoParams.RenderedProjection * matRenderFromNowStart); + pPostProcessHeightmapShader->SetUniform4x4f("EyeXformEnd", stereoParams.RenderedProjection * matRenderFromNowEnd); + //pPostProcessHeightmapShader->SetUniform4x4f("EyeXformStart", stereoParams.RenderedProjection * matRenderFromNowStart * stereoParams.RenderedProjection.Inverted()); + //pPostProcessHeightmapShader->SetUniform4x4f("EyeXformEnd", stereoParams.RenderedProjection * matRenderFromNowEnd * stereoParams.RenderedProjection.Inverted()); + //pPostProcessHeightmapShader->SetUniform4x4f("Projection", stereoParams.RenderedProjection); + pPostProcessHeightmapShader->SetUniform4x4f("InvProjection", stereoParams.RenderedProjection.Inverted()); + + Render(&heightmapFill, pHeightmapMeshVertexBuffer[eyeNum], pHeightmapMeshIndexBuffer[eyeNum], identity, 0, HeightmapMeshNumTris[eyeNum] * 3, Prim_Triangles, Mesh_Heightmap); + } + } + + // Pass 2 - do distortion + { + SetDefaultRenderTarget(); + SetDepthMode(false, false); + + Recti vp( 0, 0, WindowWidth, WindowHeight ); + SetViewport(vp); + float r, g, b, a; + DistortionClearColor.GetRGBA(&r, &g, &b, &a); + Clear(r, g, b, a); + + ShaderFill fill(pPostProcessShader); + fill.SetTexture ( 0, HeightmapTimewarpRTs[0].pColorTex ); + fill.SetTexture ( 1, (usingOverlay ? pOverlayLayerRenderTargetLeftOrBothEyes->pColorTex : NULL)); + pPostProcessShader->SetUniform1f("UseOverlay", usingOverlay ? 1.0f : 0.0f); + + for ( int eyeNum = 0; eyeNum < 2; eyeNum++ ) + { + const StereoEyeParams &stereoParams = ( eyeNum == 0 ) ? stereoParamsLeft : stereoParamsRight; + + // TODO: Could avoid the need for these vars since the mesh doesn't actually to time warping + pPostProcessShader->SetUniform2f("EyeToSourceUVScale", stereoParams.EyeToSourceUV.Scale.x, stereoParams.EyeToSourceUV.Scale.y ); + pPostProcessShader->SetUniform2f("EyeToSourceUVOffset", stereoParams.EyeToSourceUV.Offset.x, stereoParams.EyeToSourceUV.Offset.y ); + + if ( ( HeightmapTimewarpRTs[1].pColorTex != NULL ) && ( eyeNum == 1 ) ) + { + fill.SetTexture ( 0, HeightmapTimewarpRTs[1].pColorTex ); + fill.SetTexture ( 1, (usingOverlay ? pOverlayLayerRenderTargetRight->pColorTex : NULL)); + } + + Render(&fill, pDistortionMeshVertexBuffer[eyeNum], pDistortionMeshIndexBuffer[eyeNum], identity, 0, DistortionMeshNumTris[eyeNum] * 3, Prim_Triangles, Mesh_Distortion); + } + } + } + break; + + case PostProcess_PixelDistortion: { float r, g, b, a; DistortionClearColor.GetRGBA(&r, &g, &b, &a); @@ -1201,18 +1410,20 @@ namespace OVR { namespace Render { 0, 0, 0, 1); ShaderFill fill(pPostProcessShader); - if ( ( pSourceTextureRight != NULL ) && ( eyeNum == 1 ) ) + if ( ( pHmdSpaceLayerRenderTargetRight != NULL ) && ( eyeNum == 1 ) ) { - fill.SetTexture ( 0, pSourceTextureRight ); + fill.SetTexture ( 0, pHmdSpaceLayerRenderTargetRight->pColorTex ); } else { - fill.SetTexture ( 0, pSourceTextureLeftOrOnly ); + fill.SetTexture ( 0, pHmdSpaceLayerRenderTargetLeftOrBothEyes->pColorTex ); } Render(&fill, pFullScreenVertexBuffer, NULL, view, 0, 4, Prim_TriangleStrip); } } - else if ( PostProcessingType == PostProcess_NoDistortion ) + break; + + case PostProcess_NoDistortion: { // Just splat the thing on the framebuffer with no distortion. Clear ( 0.0f, 0.4f, 0.0f, 1.0f, 1.0f ); @@ -1225,8 +1436,8 @@ namespace OVR { namespace Render { ortho.M[1][3] = 0.0f; ortho.M[2][2] = 0; SetProjection(ortho); - int rtWidth = pSourceTextureLeftOrOnly->GetWidth(); - int rtHeight = pSourceTextureLeftOrOnly->GetHeight(); + int rtWidth = pHmdSpaceLayerRenderTargetLeftOrBothEyes->pColorTex->GetWidth(); + int rtHeight = pHmdSpaceLayerRenderTargetLeftOrBothEyes->pColorTex->GetHeight(); for ( int eyeNum = 0; eyeNum < 2; eyeNum++ ) { @@ -1234,13 +1445,13 @@ namespace OVR { namespace Render { SetViewport ( stereoParams.DistortionViewport ); Ptr<Texture> pTex; - if ( ( pSourceTextureRight != NULL ) && ( eyeNum == 1 ) ) + if ( ( pHmdSpaceLayerRenderTargetRight != NULL ) && ( eyeNum == 1 ) ) { - pTex = pSourceTextureRight; + pTex = pHmdSpaceLayerRenderTargetRight->pColorTex; } else { - pTex = pSourceTextureLeftOrOnly; + pTex = pHmdSpaceLayerRenderTargetLeftOrBothEyes->pColorTex; } float ul = (float)( stereoParams.RenderedViewport.x ) / (float)rtWidth; @@ -1253,10 +1464,10 @@ namespace OVR { namespace Render { Color(255,255,255,255), pTex ); } } - else - { - OVR_ASSERT ( !"Unknown distortion type" ); - } + break; + + default: + OVR_ASSERT ( !"Unknown distortion type" ); } } diff --git a/Samples/CommonSrc/Render/Render_Device.h b/Samples/CommonSrc/Render/Render_Device.h index f8a6dff..eea352e 100644 --- a/Samples/CommonSrc/Render/Render_Device.h +++ b/Samples/CommonSrc/Render/Render_Device.h @@ -83,6 +83,7 @@ enum BuiltinShaders VShader_PostProcessMesh , VShader_PostProcessMeshTimewarp , VShader_PostProcessMeshPositionalTimewarp , + VShader_PostProcessHeightmapTimewarp , VShader_Count , FShader_Solid = 0, @@ -96,6 +97,7 @@ enum BuiltinShaders FShader_PostProcessMeshWithChromAb , FShader_PostProcessMeshWithChromAbTimewarp , FShader_PostProcessMeshWithChromAbPositionalTimewarp , + FShader_PostProcessHeightmapTimewarp , FShader_Count , }; @@ -151,6 +153,12 @@ enum SampleMode Sample_Count =13, }; +enum MeshType +{ + Mesh_Scene, + Mesh_Distortion, + Mesh_Heightmap, +}; struct Color4f { @@ -354,7 +362,12 @@ public: virtual void* GetInternalImplementation() { return NULL; }; }; - +struct RenderTarget +{ + Ptr<Texture> pColorTex; + Ptr<Texture> pDepthTex; + Sizei Size; +}; //----------------------------------------------------------------------------------- @@ -438,7 +451,7 @@ struct Vertex Vertex (const Vector3f& p, const Color& c = Color(64,0,0,255), float u = 0, float v = 0, Vector3f n = Vector3f(1,0,0)) - : Pos(p), C(c), U(u), V(v), Norm(n), U2(u), V2(v) {} + : Pos(p), C(c), U(u), V(v), U2(u), V2(v), Norm(n) {} Vertex(float x, float y, float z, const Color& c = Color(64,0,0,255), float u = 0, float v = 0) : Pos(x,y,z), C(c), U(u), V(v), U2(u), V2(v) { } @@ -461,6 +474,12 @@ struct DistortionVertex Color Col; }; +struct HeightmapVertex +{ + Vector2f Pos; + Vector3f Tex; +}; + // this is stored in a uniform buffer, don't change it without fixing all renderers struct LightingParams { @@ -685,6 +704,7 @@ enum PostProcessType PostProcess_MeshDistortion, PostProcess_MeshDistortionTimewarp, PostProcess_MeshDistortionPositionalTimewarp, + PostProcess_MeshDistortionHeightmapTimewarp, PostProcess_NoDistortion, }; @@ -701,11 +721,11 @@ struct DisplayId String MonitorName; // Monitor name for fullscreen mode // MacOS - long CgDisplayId; // CGDirectDisplayID + int CgDisplayId; // CGDirectDisplayID DisplayId() : CgDisplayId(0) {} - DisplayId(long id) : CgDisplayId(id) {} - DisplayId(String m, long id=0) : MonitorName(m), CgDisplayId(id) {} + DisplayId(int id) : CgDisplayId(id) {} + DisplayId(String m, int id=0) : MonitorName(m), CgDisplayId(id) {} operator bool () const { @@ -754,6 +774,7 @@ protected: PostProcessType PostProcessingType; Ptr<ShaderSet> pPostProcessShader; + Ptr<ShaderSet> pPostProcessHeightmapShader; Ptr<Buffer> pFullScreenVertexBuffer; Color DistortionClearColor; UPInt TotalTextureMemoryUsage; @@ -763,9 +784,15 @@ protected: Ptr<Buffer> pDistortionMeshVertexBuffer[2]; Ptr<Buffer> pDistortionMeshIndexBuffer[2]; + int HeightmapMeshNumTris[2]; + Ptr<Buffer> pHeightmapMeshVertexBuffer[2]; + Ptr<Buffer> pHeightmapMeshIndexBuffer[2]; + // For lighting on platforms with uniform buffers Ptr<Buffer> LightingBuffer; + RenderTarget HeightmapTimewarpRTs[2]; // one for each eye + public: enum CompareFunc { @@ -784,7 +811,11 @@ public: virtual void Init() {} virtual void Shutdown(); - virtual bool SetParams(const RendererParams&) { return 0; } + virtual bool SetParams(const RendererParams& rp) + { + Params = rp; + return true; + } const RendererParams& GetParams() const { return Params; } @@ -859,10 +890,11 @@ public: virtual void ApplyPostProcess(Matrix4f const &matNowFromWorldStart, Matrix4f const &matNowFromWorldEnd, Matrix4f const &matRenderFromWorldLeft, Matrix4f const &matRenderFromWorldRight, StereoEyeParams const &stereoParamsLeft, StereoEyeParams const &stereoParamsRight, - Ptr<Texture> pSourceTextureLeftOrOnly, - Ptr<Texture> pSourceTextureRight, - Ptr<Texture> pSourceTextureLeftOrOnlyDepth, - Ptr<Texture> pSourceTextureRightDepth); + RenderTarget* pHmdSpaceLayerRenderTargetLeftOrBothEyes, + RenderTarget* pHmdSpaceLayerRenderTargetRight, + RenderTarget* pStaticLayerRenderTargetLeftOrBothEyes, + RenderTarget* pStaticLayerRenderTargetRight); + // Finish scene. virtual void FinishScene(); @@ -870,6 +902,12 @@ public: // NULL depth buffer means use an internal, temporary one. virtual void SetRenderTarget(Texture* color, Texture* depth = NULL, Texture* stencil = NULL) { OVR_UNUSED3(color, depth, stencil); } + void SetRenderTarget(const RenderTarget& renderTarget) + { + SetRenderTarget(renderTarget.pColorTex, renderTarget.pDepthTex); + } + // go to back buffer + void SetDefaultRenderTarget() { SetRenderTarget(NULL, NULL); } virtual void SetDepthMode(bool enable, bool write, CompareFunc func = Compare_Less) = 0; virtual void SetProjection(const Matrix4f& proj); virtual void SetWorldUniforms(const Matrix4f& proj) = 0; @@ -887,7 +925,7 @@ public: virtual void Render(const Matrix4f& matrix, Model* model) = 0; // offset is in bytes; indices can be null. virtual void Render(const Fill* fill, Buffer* vertices, Buffer* indices, - const Matrix4f& matrix, int offset, int count, PrimitiveType prim = Prim_Triangles, bool useDistortionVertex = false) = 0; + const Matrix4f& matrix, int offset, int count, PrimitiveType prim = Prim_Triangles, MeshType meshType = Mesh_Scene) = 0; virtual void RenderWithAlpha(const Fill* fill, Render::Buffer* vertices, Render::Buffer* indices, const Matrix4f& matrix, int offset, int count, PrimitiveType prim = Prim_Triangles) = 0; @@ -913,7 +951,11 @@ public: } // Don't call these directly, use App/Platform instead - virtual bool SetFullscreen(DisplayMode fullscreen) { OVR_UNUSED(fullscreen); return false; } + virtual bool SetFullscreen(DisplayMode fullscreen) + { + Params.Fullscreen = fullscreen; + return true; + } virtual void SetWindowSize(int w, int h) { WindowWidth = w; @@ -932,6 +974,7 @@ public: PostProcessShader_MeshDistortionAndChromAb, PostProcessShader_MeshDistortionAndChromAbTimewarp, PostProcessShader_MeshDistortionAndChromAbPositionalTimewarp, + PostProcessShader_MeshDistortionAndChromAbHeightmapTimewarp, PostProcessShader_Count }; diff --git a/Samples/CommonSrc/Render/Render_FontEmbed_DejaVu48.h b/Samples/CommonSrc/Render/Render_FontEmbed_DejaVu48.h index 2428ddd..2683244 100644 --- a/Samples/CommonSrc/Render/Render_FontEmbed_DejaVu48.h +++ b/Samples/CommonSrc/Render/Render_FontEmbed_DejaVu48.h @@ -9457,7 +9457,7 @@ const unsigned char DejaVu_tex[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; -Font DejaVu = {56, 45, -11, DejaVu_chars, DejaVu_kern, 1016, 141, DejaVu_tex}; +Font DejaVu = {56, 45, -11, DejaVu_chars, DejaVu_kern, 1016, 141, DejaVu_tex, 0}; }} diff --git a/Samples/CommonSrc/Render/Render_GL_Device.cpp b/Samples/CommonSrc/Render/Render_GL_Device.cpp index 4b3ddec..774af07 100644 --- a/Samples/CommonSrc/Render/Render_GL_Device.cpp +++ b/Samples/CommonSrc/Render/Render_GL_Device.cpp @@ -26,19 +26,40 @@ limitations under the License. #include "OVR_CAPI_GL.h" namespace OVR { namespace Render { namespace GL { + +#if !defined(OVR_OS_MAC) // GL Hooks for PC. #if defined(OVR_OS_WIN32) +PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB; +PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB; PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT; PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT; -PFNGLGENFRAMEBUFFERSEXTPROC glGenFramebuffersEXT; -PFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffersEXT; + +void* GetFunction(const char* functionName) +{ + return wglGetProcAddress(functionName); +} + +#else + +PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT; + +void (*GetFunction(const char *functionName))( void ) +{ + return glXGetProcAddress((GLubyte*)functionName); +} + +#endif + +PFNGLGENFRAMEBUFFERSPROC glGenFramebuffers; +PFNGLDELETEFRAMEBUFFERSPROC glDeleteFramebuffers; PFNGLDELETESHADERPROC glDeleteShader; -PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glCheckFramebufferStatusEXT; -PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC glFramebufferRenderbufferEXT; -PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2DEXT; -PFNGLBINDFRAMEBUFFEREXTPROC glBindFramebufferEXT; +PFNGLCHECKFRAMEBUFFERSTATUSPROC glCheckFramebufferStatus; +PFNGLFRAMEBUFFERRENDERBUFFERPROC glFramebufferRenderbuffer; +PFNGLFRAMEBUFFERTEXTURE2DPROC glFramebufferTexture2D; +PFNGLBINDFRAMEBUFFERPROC glBindFramebuffer; PFNGLACTIVETEXTUREPROC glActiveTexture; PFNGLDISABLEVERTEXATTRIBARRAYPROC glDisableVertexAttribArray; PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer; @@ -73,87 +94,96 @@ PFNGLUNIFORM3FVPROC glUniform3fv; PFNGLUNIFORM2FVPROC glUniform2fv; PFNGLUNIFORM1FVPROC glUniform1fv; PFNGLCOMPRESSEDTEXIMAGE2DPROC glCompressedTexImage2D; -PFNGLRENDERBUFFERSTORAGEEXTPROC glRenderbufferStorageEXT; -PFNGLBINDRENDERBUFFEREXTPROC glBindRenderbufferEXT; -PFNGLGENRENDERBUFFERSEXTPROC glGenRenderbuffersEXT; -PFNGLDELETERENDERBUFFERSEXTPROC glDeleteRenderbuffersEXT; - +PFNGLRENDERBUFFERSTORAGEPROC glRenderbufferStorage; +PFNGLBINDRENDERBUFFERPROC glBindRenderbuffer; +PFNGLGENRENDERBUFFERSPROC glGenRenderbuffers; +PFNGLDELETERENDERBUFFERSPROC glDeleteRenderbuffers; PFNGLGENVERTEXARRAYSPROC glGenVertexArrays; +PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays; +PFNGLBINDVERTEXARRAYPROC glBindVertexArray; void InitGLExtensions() { - if (glGenFramebuffersEXT) + if (glGenFramebuffers) return; - - - wglGetSwapIntervalEXT = (PFNWGLGETSWAPINTERVALEXTPROC) wglGetProcAddress("wglGetSwapIntervalEXT"); - wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT"); - glGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC) wglGetProcAddress("glGenFramebuffersEXT"); - glDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC) wglGetProcAddress("glDeleteFramebuffersEXT"); - glDeleteShader = (PFNGLDELETESHADERPROC) wglGetProcAddress("glDeleteShader"); - glCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) wglGetProcAddress("glCheckFramebufferStatusEXT"); - glFramebufferRenderbufferEXT = (PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC) wglGetProcAddress("glFramebufferRenderbufferEXT"); - glFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) wglGetProcAddress("glFramebufferTexture2DEXT"); - glBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC) wglGetProcAddress("glBindFramebufferEXT"); - glActiveTexture = (PFNGLACTIVETEXTUREPROC) wglGetProcAddress("glActiveTexture"); - glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC) wglGetProcAddress("glDisableVertexAttribArray"); - glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC) wglGetProcAddress("glVertexAttribPointer"); - glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC) wglGetProcAddress("glEnableVertexAttribArray"); - glBindBuffer = (PFNGLBINDBUFFERPROC) wglGetProcAddress("glBindBuffer"); - glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC) wglGetProcAddress("glUniformMatrix3fv"); - glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC) wglGetProcAddress("glUniformMatrix4fv"); - glDeleteBuffers = (PFNGLDELETEBUFFERSPROC) wglGetProcAddress("glDeleteBuffers"); - glBufferData = (PFNGLBUFFERDATAPROC) wglGetProcAddress("glBufferData"); - glGenBuffers = (PFNGLGENBUFFERSPROC) wglGetProcAddress("glGenBuffers"); - glMapBuffer = (PFNGLMAPBUFFERPROC) wglGetProcAddress("glMapBuffer"); - glUnmapBuffer = (PFNGLUNMAPBUFFERPROC) wglGetProcAddress("glUnmapBuffer"); - glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC) wglGetProcAddress("glGetShaderInfoLog"); - glGetShaderiv = (PFNGLGETSHADERIVPROC) wglGetProcAddress("glGetShaderiv"); - glCompileShader = (PFNGLCOMPILESHADERPROC) wglGetProcAddress("glCompileShader"); - glShaderSource = (PFNGLSHADERSOURCEPROC) wglGetProcAddress("glShaderSource"); - glCreateShader = (PFNGLCREATESHADERPROC) wglGetProcAddress("glCreateShader"); - glCreateProgram = (PFNGLCREATEPROGRAMPROC) wglGetProcAddress("glCreateProgram"); - glAttachShader = (PFNGLATTACHSHADERPROC) wglGetProcAddress("glAttachShader"); - glDetachShader = (PFNGLDETACHSHADERPROC) wglGetProcAddress("glDetachShader"); - glDeleteProgram = (PFNGLDELETEPROGRAMPROC) wglGetProcAddress("glDeleteProgram"); - glUniform1i = (PFNGLUNIFORM1IPROC) wglGetProcAddress("glUniform1i"); - glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC) wglGetProcAddress("glGetUniformLocation"); - glGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC) wglGetProcAddress("glGetActiveUniform"); - glUseProgram = (PFNGLUSEPROGRAMPROC) wglGetProcAddress("glUseProgram"); - glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC) wglGetProcAddress("glGetProgramInfoLog"); - glGetProgramiv = (PFNGLGETPROGRAMIVPROC) wglGetProcAddress("glGetProgramiv"); - glLinkProgram = (PFNGLLINKPROGRAMPROC) wglGetProcAddress("glLinkProgram"); - glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC) wglGetProcAddress("glBindAttribLocation"); - glUniform4fv = (PFNGLUNIFORM4FVPROC) wglGetProcAddress("glUniform4fv"); - glUniform3fv = (PFNGLUNIFORM3FVPROC) wglGetProcAddress("glUniform3fv"); - glUniform2fv = (PFNGLUNIFORM2FVPROC) wglGetProcAddress("glUniform2fv"); - glUniform1fv = (PFNGLUNIFORM1FVPROC) wglGetProcAddress("glUniform1fv"); - glCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC) wglGetProcAddress("glCompressedTexImage2D"); - glRenderbufferStorageEXT = (PFNGLRENDERBUFFERSTORAGEEXTPROC) wglGetProcAddress("glRenderbufferStorageEXT"); - glBindRenderbufferEXT = (PFNGLBINDRENDERBUFFEREXTPROC) wglGetProcAddress("glBindRenderbufferEXT"); - glGenRenderbuffersEXT = (PFNGLGENRENDERBUFFERSEXTPROC) wglGetProcAddress("glGenRenderbuffersEXT"); - glDeleteRenderbuffersEXT = (PFNGLDELETERENDERBUFFERSEXTPROC) wglGetProcAddress("glDeleteRenderbuffersEXT"); - - - glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC) wglGetProcAddress("glGenVertexArrays"); -} +#if defined(OVR_OS_WIN32) + wglGetSwapIntervalEXT = (PFNWGLGETSWAPINTERVALEXTPROC) GetFunction("wglGetSwapIntervalEXT"); + wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) GetFunction("wglSwapIntervalEXT"); +#else + glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC) GetFunction("glXSwapIntervalEXT"); #endif + glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC) GetFunction("glGenFramebuffersEXT"); + glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC) GetFunction("glDeleteFramebuffersEXT"); + glDeleteShader = (PFNGLDELETESHADERPROC) GetFunction("glDeleteShader"); + glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC) GetFunction("glCheckFramebufferStatusEXT"); + glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC) GetFunction("glFramebufferRenderbufferEXT"); + glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC) GetFunction("glFramebufferTexture2DEXT"); + glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC) GetFunction("glBindFramebufferEXT"); + glActiveTexture = (PFNGLACTIVETEXTUREPROC) GetFunction("glActiveTexture"); + glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC) GetFunction("glDisableVertexAttribArray"); + glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC) GetFunction("glVertexAttribPointer"); + glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC) GetFunction("glEnableVertexAttribArray"); + glBindBuffer = (PFNGLBINDBUFFERPROC) GetFunction("glBindBuffer"); + glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC) GetFunction("glUniformMatrix3fv"); + glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC) GetFunction("glUniformMatrix4fv"); + glDeleteBuffers = (PFNGLDELETEBUFFERSPROC) GetFunction("glDeleteBuffers"); + glBufferData = (PFNGLBUFFERDATAPROC) GetFunction("glBufferData"); + glGenBuffers = (PFNGLGENBUFFERSPROC) GetFunction("glGenBuffers"); + glMapBuffer = (PFNGLMAPBUFFERPROC) GetFunction("glMapBuffer"); + glUnmapBuffer = (PFNGLUNMAPBUFFERPROC) GetFunction("glUnmapBuffer"); + glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC) GetFunction("glGetShaderInfoLog"); + glGetShaderiv = (PFNGLGETSHADERIVPROC) GetFunction("glGetShaderiv"); + glCompileShader = (PFNGLCOMPILESHADERPROC) GetFunction("glCompileShader"); + glShaderSource = (PFNGLSHADERSOURCEPROC) GetFunction("glShaderSource"); + glCreateShader = (PFNGLCREATESHADERPROC) GetFunction("glCreateShader"); + glCreateProgram = (PFNGLCREATEPROGRAMPROC) GetFunction("glCreateProgram"); + glAttachShader = (PFNGLATTACHSHADERPROC) GetFunction("glAttachShader"); + glDetachShader = (PFNGLDETACHSHADERPROC) GetFunction("glDetachShader"); + glDeleteProgram = (PFNGLDELETEPROGRAMPROC) GetFunction("glDeleteProgram"); + glUniform1i = (PFNGLUNIFORM1IPROC) GetFunction("glUniform1i"); + glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC) GetFunction("glGetUniformLocation"); + glGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC) GetFunction("glGetActiveUniform"); + glUseProgram = (PFNGLUSEPROGRAMPROC) GetFunction("glUseProgram"); + glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC) GetFunction("glGetProgramInfoLog"); + glGetProgramiv = (PFNGLGETPROGRAMIVPROC) GetFunction("glGetProgramiv"); + glLinkProgram = (PFNGLLINKPROGRAMPROC) GetFunction("glLinkProgram"); + glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC) GetFunction("glBindAttribLocation"); + glUniform4fv = (PFNGLUNIFORM4FVPROC) GetFunction("glUniform4fv"); + glUniform3fv = (PFNGLUNIFORM3FVPROC) GetFunction("glUniform3fv"); + glUniform2fv = (PFNGLUNIFORM2FVPROC) GetFunction("glUniform2fv"); + glUniform1fv = (PFNGLUNIFORM1FVPROC) GetFunction("glUniform1fv"); + glCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC) GetFunction("glCompressedTexImage2D"); + glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC) GetFunction("glRenderbufferStorageEXT"); + glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC) GetFunction("glBindRenderbufferEXT"); + glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC) GetFunction("glGenRenderbuffersEXT"); + glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC) GetFunction("glDeleteRenderbuffersEXT"); + glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC) GetFunction("glGenVertexArrays"); + glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC) GetFunction("glDeleteVertexArrays"); + glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC) GetFunction("glBindVertexArray"); +} + +#endif static const char* StdVertexShaderSrc = + "#version 110\n" + "uniform mat4 Proj;\n" "uniform mat4 View;\n" + "attribute vec4 Position;\n" "attribute vec4 Color;\n" "attribute vec2 TexCoord;\n" "attribute vec2 TexCoord1;\n" "attribute vec3 Normal;\n" - "varying vec4 oColor;\n" - "varying vec2 oTexCoord;\n" - "varying vec2 oTexCoord1;\n" - "varying vec3 oNormal;\n" - "varying vec3 oVPos;\n" + + "varying vec4 oColor;\n" + "varying vec2 oTexCoord;\n" + "varying vec2 oTexCoord1;\n" + "varying vec3 oNormal;\n" + "varying vec3 oVPos;\n" + "void main()\n" "{\n" " gl_Position = Proj * (View * Position);\n" @@ -165,14 +195,19 @@ static const char* StdVertexShaderSrc = "}\n"; static const char* DirectVertexShaderSrc = + "#version 110\n" + "uniform mat4 View;\n" + "attribute vec4 Position;\n" "attribute vec4 Color;\n" "attribute vec2 TexCoord;\n" "attribute vec3 Normal;\n" - "varying vec4 oColor;\n" - "varying vec2 oTexCoord;\n" - "varying vec3 oNormal;\n" + + "varying vec4 oColor;\n" + "varying vec2 oTexCoord;\n" + "varying vec3 oNormal;\n" + "void main()\n" "{\n" " gl_Position = View * Position;\n" @@ -182,23 +217,33 @@ static const char* DirectVertexShaderSrc = "}\n"; static const char* SolidFragShaderSrc = + "#version 110\n" + "uniform vec4 Color;\n" + "void main()\n" "{\n" " gl_FragColor = Color;\n" "}\n"; static const char* GouraudFragShaderSrc = + "#version 110\n" + "varying vec4 oColor;\n" + "void main()\n" "{\n" " gl_FragColor = oColor;\n" "}\n"; static const char* TextureFragShaderSrc = + "#version 110\n" + "uniform sampler2D Texture0;\n" + "varying vec4 oColor;\n" "varying vec2 oTexCoord;\n" + "void main()\n" "{\n" " gl_FragColor = oColor * texture2D(Texture0, oTexCoord);\n" @@ -207,6 +252,7 @@ static const char* TextureFragShaderSrc = "}\n"; #define LIGHTING_COMMON \ + "#version 110\n" \ "uniform vec3 Ambient;\n" \ "uniform vec4 LightPos[8];\n" \ "uniform vec4 LightColor[8];\n" \ @@ -231,98 +277,91 @@ static const char* TextureFragShaderSrc = static const char* LitSolidFragShaderSrc = LIGHTING_COMMON + "void main()\n" "{\n" " gl_FragColor = DoLight() * oColor;\n" "}\n"; static const char* LitTextureFragShaderSrc = - "uniform sampler2D Texture0;\n" LIGHTING_COMMON + + "uniform sampler2D Texture0;\n" + "void main()\n" "{\n" " gl_FragColor = DoLight() * texture2D(Texture0, oTexCoord);\n" "}\n"; static const char* AlphaTextureFragShaderSrc = + "#version 110\n" + "uniform sampler2D Texture0;\n" + "varying vec4 oColor;\n" "varying vec2 oTexCoord;\n" + "void main()\n" "{\n" - " gl_FragColor = oColor * vec4(1,1,1,texture2D(Texture0, oTexCoord).a);\n" + " gl_FragColor = oColor * vec4(1,1,1,texture2D(Texture0, oTexCoord).r);\n" "}\n"; static const char* MultiTextureFragShaderSrc = + "#version 110\n" + "uniform sampler2D Texture0;\n" "uniform sampler2D Texture1;\n" + "varying vec4 oColor;\n" "varying vec2 oTexCoord;\n" "varying vec2 oTexCoord1;\n" + "void main()\n" "{\n" - " vec4 color1 = texture2D(Texture0, oTexCoord);\n" - " vec4 color2 = texture2D(Texture1, oTexCoord1);\n" - " color2.rgb = color2.rgb * mix(1.9, 1.2, clamp(length(color2.rgb),0.0,1.0));\n" - " color2 = color1 * color2;\n" - " if (color2.a <= 0.6)\n" + " vec4 color = texture2D(Texture0, oTexCoord);\n" + + " gl_FragColor = texture2D(Texture1, oTexCoord1);\n" + " gl_FragColor.rgb = gl_FragColor.rgb * mix(1.9, 1.2, clamp(length(gl_FragColor.rgb),0.0,1.0));\n" + + " gl_FragColor = color * gl_FragColor;\n" + + " if (gl_FragColor.a <= 0.6)\n" " discard;\n" - " gl_FragColor = color2;\n" "}\n"; static const char* PostProcessMeshFragShaderSrc = + "#version 110\n" + "uniform sampler2D Texture;\n" + "varying vec4 oColor;\n" "varying vec2 oTexCoord0;\n" "varying vec2 oTexCoord1;\n" "varying vec2 oTexCoord2;\n" - "\n" - "void main()\n" - "{\n" - " float ResultR = texture2D(Texture, oTexCoord0).r;\n" - " float ResultG = texture2D(Texture, oTexCoord1).g;\n" - " float ResultB = texture2D(Texture, oTexCoord2).b;\n" - " gl_FragColor = vec4(ResultR * oColor.r, ResultG * oColor.g, ResultB * oColor.b, 1.0);\n" - "}\n"; - -static const char* PostProcessMeshTimewarpFragShaderSrc = - "uniform sampler2D Texture;\n" - "varying vec4 oColor;\n" - "varying vec2 oTexCoord0;\n" - "varying vec2 oTexCoord1;\n" - "varying vec2 oTexCoord2;\n" - "\n" - "void main()\n" - "{\n" - " float ResultR = texture2D(Texture, oTexCoord0).r;\n" - " float ResultG = texture2D(Texture, oTexCoord1).g;\n" - " float ResultB = texture2D(Texture, oTexCoord2).b;\n" - " gl_FragColor = vec4(ResultR * oColor.r, ResultG * oColor.g, ResultB * oColor.b, 1.0);\n" - "}\n"; - -static const char* PostProcessMeshPositionalTimewarpFragShaderSrc = - "uniform sampler2D Texture0;\n" - "uniform sampler2D Texture1;\n" - "varying vec4 oColor;\n" - "varying vec2 oTexCoord0;\n" - "varying vec2 oTexCoord1;\n" - "varying vec2 oTexCoord2;\n" - "\n" + "void main()\n" "{\n" - " gl_FragColor.r = oColor.r * texture2D(Texture1, oTexCoord0).r;\n" - " gl_FragColor.g = oColor.g * texture2D(Texture1, oTexCoord1).g;\n" - " gl_FragColor.b = oColor.b * texture2D(Texture1, oTexCoord2).b;\n" + " gl_FragColor.r = oColor.r * texture2D(Texture, oTexCoord0).r;\n" + " gl_FragColor.g = oColor.g * texture2D(Texture, oTexCoord1).g;\n" + " gl_FragColor.b = oColor.b * texture2D(Texture, oTexCoord2).b;\n" " gl_FragColor.a = 1.0;\n" "}\n"; +static const char* PostProcessMeshTimewarpFragShaderSrc = PostProcessMeshFragShaderSrc; +static const char* PostProcessMeshPositionalTimewarpFragShaderSrc = PostProcessMeshFragShaderSrc; +static const char* PostProcessHeightmapTimewarpFragShaderSrc = PostProcessMeshFragShaderSrc; static const char* PostProcessVertexShaderSrc = + "#version 110\n" + "uniform mat4 View;\n" "uniform mat4 Texm;\n" + "attribute vec4 Position;\n" "attribute vec2 TexCoord;\n" - "varying vec2 oTexCoord;\n" + + "varying vec2 oTexCoord;\n" + "void main()\n" "{\n" " gl_Position = View * Position;\n" @@ -330,6 +369,8 @@ static const char* PostProcessVertexShaderSrc = "}\n"; static const char* PostProcessMeshVertexShaderSrc = + "#version 110\n" + "uniform vec2 EyeToSourceUVScale;\n" "uniform vec2 EyeToSourceUVOffset;\n" @@ -353,15 +394,17 @@ static const char* PostProcessMeshVertexShaderSrc = // Vertex inputs are in TanEyeAngle space for the R,G,B channels (i.e. after chromatic aberration and distortion). // Scale them into the correct [0-1],[0-1] UV lookup space (depending on eye) " oTexCoord0 = TexCoord0 * EyeToSourceUVScale + EyeToSourceUVOffset;\n" - " oTexCoord0.y = 1-oTexCoord0.y;\n" + " oTexCoord0.y = 1.0-oTexCoord0.y;\n" " oTexCoord1 = TexCoord1 * EyeToSourceUVScale + EyeToSourceUVOffset;\n" - " oTexCoord1.y = 1-oTexCoord1.y;\n" + " oTexCoord1.y = 1.0-oTexCoord1.y;\n" " oTexCoord2 = TexCoord2 * EyeToSourceUVScale + EyeToSourceUVOffset;\n" - " oTexCoord2.y = 1-oTexCoord2.y;\n" + " oTexCoord2.y = 1.0-oTexCoord2.y;\n" " oColor = Color;\n" // Used for vignette fade. "}\n"; static const char* PostProcessMeshTimewarpVertexShaderSrc = + "#version 110\n" + "uniform vec2 EyeToSourceUVScale;\n" "uniform vec2 EyeToSourceUVOffset;\n" "uniform mat4 EyeRotationStart;\n" @@ -392,7 +435,7 @@ static const char* PostProcessMeshTimewarpVertexShaderSrc = " vec3 TanEyeAngleB = vec3 ( TexCoord2.x, TexCoord2.y, 1.0 );\n" // Accurate time warp lerp vs. faster -#if 1 +#if 0 // Apply the two 3x3 timewarp rotations to these vectors. " vec3 TransformedRStart = (EyeRotationStart * vec4(TanEyeAngleR, 0)).xyz;\n" " vec3 TransformedGStart = (EyeRotationStart * vec4(TanEyeAngleG, 0)).xyz;\n" @@ -405,7 +448,10 @@ static const char* PostProcessMeshTimewarpVertexShaderSrc = " vec3 TransformedG = mix ( TransformedGStart, TransformedGEnd, Color.a );\n" " vec3 TransformedB = mix ( TransformedBStart, TransformedBEnd, Color.a );\n" #else - " mat3 EyeRotation = mix ( EyeRotationStart, EyeRotationEnd, Color.a );\n" + " mat3 EyeRotation;\n" + " EyeRotation[0] = mix ( EyeRotationStart[0], EyeRotationEnd[0], Color.a ).xyz;\n" + " EyeRotation[1] = mix ( EyeRotationStart[1], EyeRotationEnd[1], Color.a ).xyz;\n" + " EyeRotation[2] = mix ( EyeRotationStart[2], EyeRotationEnd[2], Color.a ).xyz;\n" " vec3 TransformedR = EyeRotation * TanEyeAngleR;\n" " vec3 TransformedG = EyeRotation * TanEyeAngleG;\n" " vec3 TransformedB = EyeRotation * TanEyeAngleB;\n" @@ -425,42 +471,46 @@ static const char* PostProcessMeshTimewarpVertexShaderSrc = " vec2 SrcCoordG = FlattenedG * EyeToSourceUVScale + EyeToSourceUVOffset;\n" " vec2 SrcCoordB = FlattenedB * EyeToSourceUVScale + EyeToSourceUVOffset;\n" " oTexCoord0 = SrcCoordR;\n" - " oTexCoord0.y = 1-oTexCoord0.y;\n" + " oTexCoord0.y = 1.0-oTexCoord0.y;\n" " oTexCoord1 = SrcCoordG;\n" - " oTexCoord1.y = 1-oTexCoord1.y;\n" + " oTexCoord1.y = 1.0-oTexCoord1.y;\n" " oTexCoord2 = SrcCoordB;\n" - " oTexCoord2.y = 1-oTexCoord2.y;\n" - " oColor = Color.r;\n" // Used for vignette fade. + " oTexCoord2.y = 1.0-oTexCoord2.y;\n" + " oColor = vec4(Color.r, Color.r, Color.r, Color.r);\n" // Used for vignette fade. "}\n"; static const char* PostProcessMeshPositionalTimewarpVertexShaderSrc = +#if 1 //TODO: Disabled until we fix positional timewarp and layering on GL. +PostProcessMeshTimewarpVertexShaderSrc; +#else "#version 150\n" - "uniform sampler2D Texture0;\n" + + "uniform sampler2D Texture0;\n" "uniform vec2 EyeToSourceUVScale;\n" "uniform vec2 EyeToSourceUVOffset;\n" - "uniform vec2 DepthProjector;\n" - "uniform vec2 DepthDimSize;\n" - "uniform mat4 EyeRotationStart;\n" + "uniform vec2 DepthProjector;\n" + "uniform vec2 DepthDimSize;\n" + "uniform mat4 EyeRotationStart;\n" "uniform mat4 EyeRotationEnd;\n" - "in vec2 Position;\n" - "in vec4 Color;\n" - "in vec2 TexCoord0;\n" - "in vec2 TexCoord1;\n" - "in vec2 TexCoord2;\n" + "attribute vec2 Position;\n" + "attribute vec4 Color;\n" + "attribute vec2 TexCoord0;\n" + "attribute vec2 TexCoord1;\n" + "attribute vec2 TexCoord2;\n" - "out vec4 oColor;\n" - "out vec2 oTexCoord0;\n" - "out vec2 oTexCoord1;\n" - "out vec2 oTexCoord2;\n" + "varying vec4 oColor;\n" + "varying vec2 oTexCoord0;\n" + "varying vec2 oTexCoord1;\n" + "varying vec2 oTexCoord2;\n" "vec4 PositionFromDepth(vec2 inTexCoord)\n" "{\n" " vec2 eyeToSourceTexCoord = inTexCoord * EyeToSourceUVScale + EyeToSourceUVOffset;\n" - " eyeToSourceTexCoord.y = 1 - eyeToSourceTexCoord.y;\n" - " float depth = texelFetch(Texture0, ivec2(eyeToSourceTexCoord * DepthDimSize), 0).x;\n" - " float linearDepth = DepthProjector.y / (depth - DepthProjector.x);\n" - " vec4 retVal = vec4(inTexCoord, 1, 1);\n" + " eyeToSourceTexCoord.y = 1.0 - eyeToSourceTexCoord.y;\n" + " float depth = texelFetch(Texture0, ivec2(eyeToSourceTexCoord * DepthDimSize), 0).x;\n" //FIXME: Use Texture2DLod for #version 110 support. + " float linearDepth = DepthProjector.y / (depth - DepthProjector.x);\n" + " vec4 retVal = vec4(inTexCoord, 1, 1);\n" " retVal.xyz *= linearDepth;\n" " return retVal;\n" "}\n" @@ -468,7 +518,7 @@ static const char* PostProcessMeshPositionalTimewarpVertexShaderSrc = "vec2 TimewarpTexCoordToWarpedPos(vec2 inTexCoord, float a)\n" "{\n" // Vertex inputs are in TanEyeAngle space for the R,G,B channels (i.e. after chromatic aberration and distortion). - // These are now "real world" vectors in direction (x,y,1) relative to the eye of the HMD. + // These are now "real world" vectors in direction (x,y,1) relative to the eye of the HMD. // Apply the 4x4 timewarp rotation to these vectors. " vec4 inputPos = PositionFromDepth(inTexCoord);\n" " vec3 transformed = mix ( EyeRotationStart * inputPos, EyeRotationEnd * inputPos, a ).xyz;\n" @@ -476,7 +526,7 @@ static const char* PostProcessMeshPositionalTimewarpVertexShaderSrc = " vec2 flattened = transformed.xy / transformed.z;\n" // Scale them into ([0,0.5],[0,1]) or ([0.5,0],[0,1]) UV lookup space (depending on eye) " vec2 noDepthUV = flattened * EyeToSourceUVScale + EyeToSourceUVOffset;\n" - //" float depth = texture2DLod(Texture0, noDepthUV, 0).r;\n" + //" float depth = texture2D(Texture0, noDepthUV).r;\n" " return noDepthUV.xy;\n" "}\n" @@ -489,45 +539,76 @@ static const char* PostProcessMeshPositionalTimewarpVertexShaderSrc = // warped positions are a bit more involved, hence a separate function " oTexCoord0 = TimewarpTexCoordToWarpedPos(TexCoord0, Color.a);\n" - " oTexCoord0.y = 1-oTexCoord0.y;\n" + " oTexCoord0.y = 1.0 - oTexCoord0.y;\n" " oTexCoord1 = TimewarpTexCoordToWarpedPos(TexCoord1, Color.a);\n" - " oTexCoord1.y = 1-oTexCoord1.y;\n" + " oTexCoord1.y = 1.0 - oTexCoord1.y;\n" " oTexCoord2 = TimewarpTexCoordToWarpedPos(TexCoord2, Color.a);\n" - " oTexCoord2.y = 1-oTexCoord2.y;\n" + " oTexCoord2.y = 1.0 - oTexCoord2.y;\n" - " oColor = vec4(Color.r); // Used for vignette fade.\n" + " oColor = vec4(Color.r, Color.r, Color.r, Color.r); // Used for vignette fade.\n" "}\n"; +#endif -static const char* PostProcessFragShaderSrc = - "uniform vec2 LensCenter;\n" - "uniform vec2 ScreenCenter;\n" + +static const char* PostProcessHeightmapTimewarpVertexShaderSrc = +#if 1 //TODO: Disabled until we fix positional timewarp and layering on GL. +PostProcessMeshTimewarpVertexShaderSrc; +#else + "#version 150\n" + + "uniform sampler2D Texture0;\n" "uniform vec2 EyeToSourceUVScale;\n" - "uniform vec2 EyeToSourceNDCScale;\n" - "uniform vec4 HmdWarpParam;\n" - "uniform sampler2D Texture1;\n" + "uniform vec2 EyeToSourceUVOffset;\n" + "uniform vec2 DepthDimSize;\n" + "uniform mat4 EyeXformStart;\n" + "uniform mat4 EyeXformEnd;\n" + //"uniform mat4 Projection;\n" + "uniform mat4 InvProjection;\n" - "varying vec2 oTexCoord;\n" + "attribute vec2 Position;\n" + "attribute vec3 TexCoord0;\n" + + "varying vec2 oTexCoord0;\n" + + "vec4 PositionFromDepth(vec2 position, vec2 inTexCoord)\n" + "{\n" + " float depth = texelFetch(Texture0, ivec2(inTexCoord * DepthDimSize), 0).x;\n" //FIXME: Use Texture2DLod for #version 110 support. + " vec4 retVal = vec4(position, depth, 1);\n" + " return retVal;\n" + "}\n" - "vec2 HmdWarp(vec2 in01)\n" + "vec4 TimewarpPos(vec2 position, vec2 inTexCoord, mat4 rotMat)\n" "{\n" - " vec2 theta = (in01 - LensCenter) * EyeToSourceNDCScale;\n" // Scales to [-1, 1] - " float rSq = theta.x * theta.x + theta.y * theta.y;\n" - " vec2 theta1 = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + " - " HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\n" - " return LensCenter + EyeToSourceUVScale * theta1;\n" + // Apply the 4x4 timewarp rotation to these vectors. + " vec4 transformed = PositionFromDepth(position, inTexCoord);\n" + " transformed = InvProjection * transformed;\n" + " transformed = rotMat * transformed;\n" + //" transformed = mul ( Projection, transformed );\n" + " return transformed;\n" "}\n" "void main()\n" "{\n" - " vec2 tc = HmdWarp(oTexCoord);\n" - " if (!all(equal(clamp(tc, ScreenCenter-vec2(0.25,0.5), ScreenCenter+vec2(0.25,0.5)), tc)))\n" - " gl_FragColor = vec4(0);\n" - " else\n" - " gl_FragColor = texture2D(Texture1, tc);\n" - "}\n"; + " vec2 eyeToSrcTexCoord = TexCoord0.xy * EyeToSourceUVScale + EyeToSourceUVOffset;\n" + " oTexCoord0 = eyeToSrcTexCoord;\n" + + " float timewarpLerpFactor = TexCoord0.z;\n" + " mat4 lerpedEyeRot; // GL cannot mix() matrices :-( \n" + " lerpedEyeRot[0] = mix(EyeXformStart[0], EyeXformEnd[0], timewarpLerpFactor);\n" + " lerpedEyeRot[1] = mix(EyeXformStart[1], EyeXformEnd[1], timewarpLerpFactor);\n" + " lerpedEyeRot[2] = mix(EyeXformStart[2], EyeXformEnd[2], timewarpLerpFactor);\n" + " lerpedEyeRot[3] = mix(EyeXformStart[3], EyeXformEnd[3], timewarpLerpFactor);\n" + //" float4x4 lerpedEyeRot = EyeXformStart;\n" + // warped positions are a bit more involved, hence a separate function + " gl_Position = TimewarpPos(Position.xy, oTexCoord0, lerpedEyeRot);\n" + "}\n"; +#endif + // Shader with lens distortion and chromatic aberration correction. static const char* PostProcessFragShaderWithChromAbSrc = + "#version 110\n" + "uniform sampler2D Texture;\n" "uniform vec3 DistortionClearColor;\n" "uniform float EdgeFadeScale;\n" @@ -562,19 +643,19 @@ static const char* PostProcessFragShaderWithChromAbSrc = // Scale them into ([0,0.5],[0,1]) or ([0.5,0],[0,1]) UV lookup space (depending on eye) " vec2 SourceCoordR = TanEyeAngleR * EyeToSourceUVScale + EyeToSourceUVOffset;\n" - " SourceCoordR.y = 1 - SourceCoordR.y;\n" + " SourceCoordR.y = 1.0 - SourceCoordR.y;\n" " vec2 SourceCoordG = TanEyeAngleG * EyeToSourceUVScale + EyeToSourceUVOffset;\n" - " SourceCoordG.y = 1 - SourceCoordG.y;\n" + " SourceCoordG.y = 1.0 - SourceCoordG.y;\n" " vec2 SourceCoordB = TanEyeAngleB * EyeToSourceUVScale + EyeToSourceUVOffset;\n" - " SourceCoordB.y = 1 - SourceCoordB.y;\n" + " SourceCoordB.y = 1.0 - SourceCoordB.y;\n" // Find the distance to the nearest edge. " vec2 NDCCoord = TanEyeAngleG * EyeToSourceNDCScale + EyeToSourceNDCOffset;\n" - " float EdgeFadeIn = clamp ( EdgeFadeScale, 0, 1e5 ) * ( 1.0 - max ( abs ( NDCCoord.x ), abs ( NDCCoord.y ) ) );\n" + " float EdgeFadeIn = clamp ( EdgeFadeScale, 0.0, 1e5 ) * ( 1.0 - max ( abs ( NDCCoord.x ), abs ( NDCCoord.y ) ) );\n" " if ( EdgeFadeIn < 0.0 )\n" " {\n" " gl_FragColor = vec4(DistortionClearColor.r, DistortionClearColor.g, DistortionClearColor.b, 1.0);\n" - " return;\n" + " return;\n" " }\n" " EdgeFadeIn = clamp ( EdgeFadeIn, 0.0, 1.0 );\n" @@ -583,7 +664,7 @@ static const char* PostProcessFragShaderWithChromAbSrc = " float ResultG = texture2D(Texture, SourceCoordG).g;\n" " float ResultB = texture2D(Texture, SourceCoordB).b;\n" - " gl_FragColor = vec4(ResultR * EdgeFadeIn, ResultG * EdgeFadeIn, ResultB * EdgeFadeIn, 1.0);\n" + " gl_FragColor = vec4(ResultR * EdgeFadeIn, ResultG * EdgeFadeIn, ResultB * EdgeFadeIn, 1.0);\n" "}\n"; @@ -595,7 +676,8 @@ static const char* VShaderSrcs[VShader_Count] = PostProcessVertexShaderSrc, PostProcessMeshVertexShaderSrc, PostProcessMeshTimewarpVertexShaderSrc, - PostProcessMeshPositionalTimewarpVertexShaderSrc + PostProcessMeshPositionalTimewarpVertexShaderSrc, + PostProcessHeightmapTimewarpVertexShaderSrc, }; static const char* FShaderSrcs[FShader_Count] = { @@ -609,24 +691,71 @@ static const char* FShaderSrcs[FShader_Count] = MultiTextureFragShaderSrc, PostProcessMeshFragShaderSrc, PostProcessMeshTimewarpFragShaderSrc, - PostProcessMeshPositionalTimewarpFragShaderSrc + PostProcessMeshPositionalTimewarpFragShaderSrc, + PostProcessHeightmapTimewarpFragShaderSrc }; RenderDevice::RenderDevice(const RendererParams&) { + int GlMajorVersion = 0; + int GlMinorVersion = 0; + + const char* glVersionString = (const char*)glGetString(GL_VERSION); + char prefix[64]; + bool foundVersion = false; + + for (int i = 10; i < 30; ++i) + { + int major = i / 10; + int minor = i % 10; + OVR_sprintf(prefix, 64, "%d.%d", major, minor); + if (strstr(glVersionString, prefix) == glVersionString) + { + GlMajorVersion = major; + GlMinorVersion = minor; + foundVersion = true; + break; + } + } + + if (!foundVersion) + { + glGetIntegerv(GL_MAJOR_VERSION, &GlMajorVersion); + glGetIntegerv(GL_MAJOR_VERSION, &GlMinorVersion); + } + + if (GlMajorVersion >= 3) + { + SupportsVao = true; + } + else + { + const char* extensions = (const char*)glGetString(GL_EXTENSIONS); + SupportsVao = (strstr("GL_ARB_vertex_array_object", extensions) != NULL); + } + for (int i = 0; i < VShader_Count; i++) + { + OVR_ASSERT ( VShaderSrcs[i] != NULL ); // You forgot a shader! VertexShaders[i] = *new Shader(this, Shader_Vertex, VShaderSrcs[i]); + } for (int i = 0; i < FShader_Count; i++) + { + OVR_ASSERT ( FShaderSrcs[i] != NULL ); // You forgot a shader! FragShaders[i] = *new Shader(this, Shader_Fragment, FShaderSrcs[i]); + } Ptr<ShaderSet> gouraudShaders = *new ShaderSet(); gouraudShaders->SetShader(VertexShaders[VShader_MVP]); gouraudShaders->SetShader(FragShaders[FShader_Gouraud]); DefaultFill = *new ShaderFill(gouraudShaders); - glGenFramebuffersEXT(1, &CurrentFbo); + glGenFramebuffers(1, &CurrentFbo); + + if (SupportsVao) + glGenVertexArrays(1, &Vao); } RenderDevice::~RenderDevice() @@ -641,7 +770,10 @@ void RenderDevice::Shutdown() // This runs before the subclass's Shutdown(), where the context, etc, may be deleted. - glDeleteFramebuffersEXT(1, &CurrentFbo); + glDeleteFramebuffers(1, &CurrentFbo); + + if (SupportsVao) + glDeleteVertexArrays(1, &Vao); for (int i = 0; i < VShader_Count; ++i) VertexShaders[i].Clear(); @@ -674,17 +806,14 @@ Shader *RenderDevice::LoadBuiltinShader(ShaderStage stage, int shader) void RenderDevice::BeginRendering() { + //glEnable(GL_FRAMEBUFFER_SRGB); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glFrontFace(GL_CW); - glLineWidth(3.0f); glEnable(GL_LINE_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); } void RenderDevice::SetDepthMode(bool enable, bool write, CompareFunc func) @@ -707,15 +836,12 @@ void RenderDevice::SetDepthMode(bool enable, bool write, CompareFunc func) void RenderDevice::SetViewport(const Recti& vp) { - int wh; - if (CurRenderTarget) - wh = CurRenderTarget->Height; - else - wh = WindowHeight; - glViewport(vp.x, wh-vp.y-vp.h, vp.w, vp.h); - - //glEnable(GL_SCISSOR_TEST); - //glScissor(vp.x, wh-vp.y-vp.h, vp.w, vp.h); + int wh; + if (CurRenderTarget) + wh = CurRenderTarget->Height; + else + wh = WindowHeight; + glViewport(vp.x, wh - vp.y - vp.h, vp.w, vp.h); } void RenderDevice::WaitUntilGpuIdle() @@ -752,22 +878,22 @@ void RenderDevice::SetRenderTarget(Render::Texture* color, Render::Texture* dept CurRenderTarget = (Texture*)color; if (color == NULL) { - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); + glBindFramebuffer(GL_FRAMEBUFFER, 0); return; } if (depth == NULL) depth = GetDepthBuffer(color->GetWidth(), color->GetHeight(), CurRenderTarget->GetSamples()); - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, CurrentFbo); - glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, ((Texture*)color)->TexId, 0); + glBindFramebuffer(GL_FRAMEBUFFER, CurrentFbo); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, ((Texture*)color)->TexId, 0); if (depth) - glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, ((Texture*)depth)->TexId, 0); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, ((Texture*)depth)->TexId, 0); else - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0); - GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); - if (status != GL_FRAMEBUFFER_COMPLETE_EXT) + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + if (status != GL_FRAMEBUFFER_COMPLETE) OVR_DEBUG_LOG(("framebuffer not complete: %x", status)); } @@ -781,7 +907,6 @@ void RenderDevice::SetTexture(Render::ShaderStage, int slot, const Texture* t) { glActiveTexture(GL_TEXTURE0 + slot); glBindTexture(GL_TEXTURE_2D, ((Texture*)t)->TexId); - glActiveTexture(GL_TEXTURE0); } Buffer* RenderDevice::CreateBuffer() @@ -797,17 +922,20 @@ Fill* RenderDevice::CreateSimpleFill(int flags) void RenderDevice::Render(const Matrix4f& matrix, Model* model) { + if (SupportsVao) + glBindVertexArray(Vao); + // Store data in buffers if not already if (!model->VertexBuffer) { Ptr<Render::Buffer> vb = *CreateBuffer(); - vb->Data(Buffer_Vertex, &model->Vertices[0], model->Vertices.GetSize() * sizeof(Vertex)); + vb->Data(Buffer_Vertex | Buffer_ReadOnly, &model->Vertices[0], model->Vertices.GetSize() * sizeof(Vertex)); model->VertexBuffer = vb; } if (!model->IndexBuffer) { Ptr<Render::Buffer> ib = *CreateBuffer(); - ib->Data(Buffer_Index, &model->Indices[0], model->Indices.GetSize() * 2); + ib->Data(Buffer_Index | Buffer_ReadOnly, &model->Indices[0], model->Indices.GetSize() * 2); model->IndexBuffer = ib; } @@ -817,7 +945,7 @@ void RenderDevice::Render(const Matrix4f& matrix, Model* model) } void RenderDevice::Render(const Fill* fill, Render::Buffer* vertices, Render::Buffer* indices, - const Matrix4f& matrix, int offset, int count, PrimitiveType rprim, bool useDistortionVertex/* = false*/) + const Matrix4f& matrix, int offset, int count, PrimitiveType rprim, MeshType meshType /*= Mesh_Scene*/) { ShaderSet* shaders = (ShaderSet*) ((ShaderFill*)fill)->GetShaders(); @@ -854,28 +982,33 @@ void RenderDevice::Render(const Fill* fill, Render::Buffer* vertices, Render::Bu for (int i = 0; i < 5; i++) glEnableVertexAttribArray(i); - if (useDistortionVertex) - { - glVertexAttribPointer(0, 2, GL_FLOAT, false, sizeof(DistortionVertex), (char*)offset + offsetof(DistortionVertex, Pos)); - glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, true, sizeof(DistortionVertex), (char*)offset + offsetof(DistortionVertex, Col)); - glVertexAttribPointer(2, 2, GL_FLOAT, false, sizeof(DistortionVertex), (char*)offset + offsetof(DistortionVertex, TexR)); - glVertexAttribPointer(3, 2, GL_FLOAT, false, sizeof(DistortionVertex), (char*)offset + offsetof(DistortionVertex, TexG)); - glVertexAttribPointer(4, 2, GL_FLOAT, false, sizeof(DistortionVertex), (char*)offset + offsetof(DistortionVertex, TexB)); - } - else - { - glVertexAttribPointer(0, 3, GL_FLOAT, false, sizeof(Vertex), (char*)offset + offsetof(Vertex, Pos)); - glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, true, sizeof(Vertex), (char*)offset + offsetof(Vertex, C)); - glVertexAttribPointer(2, 2, GL_FLOAT, false, sizeof(Vertex), (char*)offset + offsetof(Vertex, U)); - glVertexAttribPointer(3, 2, GL_FLOAT, false, sizeof(Vertex), (char*)offset + offsetof(Vertex, U2)); - glVertexAttribPointer(4, 3, GL_FLOAT, false, sizeof(Vertex), (char*)offset + offsetof(Vertex, Norm)); - } + switch (meshType) + { + case Mesh_Distortion: + glVertexAttribPointer(0, 2, GL_FLOAT, false, sizeof(DistortionVertex), reinterpret_cast<char*>(offset) + offsetof(DistortionVertex, Pos)); + glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, true, sizeof(DistortionVertex), reinterpret_cast<char*>(offset) + offsetof(DistortionVertex, Col)); + glVertexAttribPointer(2, 2, GL_FLOAT, false, sizeof(DistortionVertex), reinterpret_cast<char*>(offset) + offsetof(DistortionVertex, TexR)); + glVertexAttribPointer(3, 2, GL_FLOAT, false, sizeof(DistortionVertex), reinterpret_cast<char*>(offset) + offsetof(DistortionVertex, TexG)); + glVertexAttribPointer(4, 2, GL_FLOAT, false, sizeof(DistortionVertex), reinterpret_cast<char*>(offset) + offsetof(DistortionVertex, TexB)); + break; + + case Mesh_Heightmap: + glVertexAttribPointer(0, 2, GL_FLOAT, false, sizeof(HeightmapVertex), reinterpret_cast<char*>(offset) + offsetof(HeightmapVertex, Pos)); + glVertexAttribPointer(1, 2, GL_FLOAT, false, sizeof(HeightmapVertex), reinterpret_cast<char*>(offset) + offsetof(HeightmapVertex, Tex)); + break; + + default: + glVertexAttribPointer(0, 3, GL_FLOAT, false, sizeof(Vertex), reinterpret_cast<char*>(offset) + offsetof(Vertex, Pos)); + glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, true, sizeof(Vertex), reinterpret_cast<char*>(offset) + offsetof(Vertex, C)); + glVertexAttribPointer(2, 2, GL_FLOAT, false, sizeof(Vertex), reinterpret_cast<char*>(offset) + offsetof(Vertex, U)); + glVertexAttribPointer(3, 2, GL_FLOAT, false, sizeof(Vertex), reinterpret_cast<char*>(offset) + offsetof(Vertex, U2)); + glVertexAttribPointer(4, 3, GL_FLOAT, false, sizeof(Vertex), reinterpret_cast<char*>(offset) + offsetof(Vertex, Norm)); + } if (indices) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ((Buffer*)indices)->GLBuffer); glDrawElements(prim, count, GL_UNSIGNED_SHORT, NULL); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } else { @@ -922,7 +1055,6 @@ bool Buffer::Data(int use, const void* buffer, size_t size) glBindBuffer(Use, GLBuffer); glBufferData(Use, size, buffer, mode); - glBindBuffer(Use, 0); return 1; } @@ -934,7 +1066,6 @@ void* Buffer::Map(size_t, size_t, int) glBindBuffer(Use, GLBuffer); void* v = glMapBuffer(Use, mode); - glBindBuffer(Use, 0); return v; } @@ -942,7 +1073,6 @@ bool Buffer::Unmap(void*) { glBindBuffer(Use, GLBuffer); int r = glUnmapBuffer(Use); - glBindBuffer(Use, 0); return r != 0; } @@ -997,7 +1127,6 @@ void ShaderSet::UnsetShader(int stage) if (gls) glDetachShader(Prog, gls->GLShader); Shaders[stage] = NULL; - Link(); } bool ShaderSet::Link() @@ -1160,7 +1289,7 @@ void Texture::SetSampleMode(int sm) case Sample_Anisotropic: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 8); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 4); break; case Sample_Nearest: @@ -1187,7 +1316,6 @@ void Texture::SetSampleMode(int sm) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); break; } - glBindTexture(GL_TEXTURE_2D, 0); } ovrTexture Texture::Get_ovrTexture() @@ -1210,7 +1338,7 @@ Texture* RenderDevice::CreateTexture(int format, int width, int height, const vo switch(format & Texture_TypeMask) { case Texture_RGBA: glformat = GL_RGBA; break; - case Texture_R: glformat = GL_ALPHA; break; + case Texture_R: glformat = GL_RED; break; case Texture_Depth: glformat = GL_DEPTH_COMPONENT32F; gltype = GL_FLOAT; break; case Texture_DXT1: glformat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; break; case Texture_DXT3: glformat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; break; @@ -1220,7 +1348,7 @@ Texture* RenderDevice::CreateTexture(int format, int width, int height, const vo } Texture* NewTex = new Texture(this, width, height); glBindTexture(GL_TEXTURE_2D, NewTex->TexId); - OVR_ASSERT(!glGetError()); + OVR_ASSERT(!glGetError()); if (format & Texture_Compressed) { @@ -1275,7 +1403,6 @@ Texture* RenderDevice::CreateTexture(int format, int width, int height, const vo } OVR_ASSERT(!glGetError()); - glBindTexture(GL_TEXTURE_2D, 0); return NewTex; } @@ -1283,16 +1410,16 @@ RBuffer::RBuffer(GLenum format, GLint w, GLint h) { Width = w; Height = h; - glGenRenderbuffersEXT(1, &BufId); - glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, BufId); - glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, format, w, h); - glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0); + glGenRenderbuffers(1, &BufId); + glBindRenderbuffer(GL_RENDERBUFFER, BufId); + glRenderbufferStorage(GL_RENDERBUFFER, format, w, h); + glBindRenderbuffer(GL_RENDERBUFFER, 0); } RBuffer::~RBuffer() { if (BufId) - glDeleteRenderbuffersEXT(1, &BufId); + glDeleteRenderbuffers(1, &BufId); } }}} diff --git a/Samples/CommonSrc/Render/Render_GL_Device.h b/Samples/CommonSrc/Render/Render_GL_Device.h index 5d97eef..563c87b 100644 --- a/Samples/CommonSrc/Render/Render_GL_Device.h +++ b/Samples/CommonSrc/Render/Render_GL_Device.h @@ -3,7 +3,7 @@ Filename : Render_GL_Device.h Content : RenderDevice implementation header for OpenGL Created : September 10, 2012 -Authors : Andrew Reisse +Authors : Andrew Reisse, David Borel Copyright : Copyright 2012 Oculus VR, Inc. All Rights reserved. @@ -27,37 +27,45 @@ limitations under the License. #include "../Render/Render_Device.h" #if defined(OVR_OS_WIN32) -#include <Windows.h> -#endif - -#if defined(OVR_OS_MAC) -#include <OpenGL/gl.h> -#include <OpenGL/glext.h> + #include <Windows.h> + #include <GL/gl.h> + #include <GL/glext.h> + #include <GL/wglext.h> +#elif defined(OVR_OS_MAC) + #include <OpenGL/gl3.h> + #include <OpenGL/gl3ext.h> #else -#ifndef GL_GLEXT_PROTOTYPES -#define GL_GLEXT_PROTOTYPES -#endif -#include <GL/gl.h> -#include <GL/glext.h> -#if defined(OVR_OS_WIN32) -#include <GL/wglext.h> -#endif + #include <GL/gl.h> + #include <GL/glext.h> + #include <GL/glx.h> #endif + namespace OVR { namespace Render { namespace GL { + +#if !defined(OVR_OS_MAC) // GL extension Hooks for PC. #if defined(OVR_OS_WIN32) - + extern PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT; extern PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT; -extern PFNGLGENFRAMEBUFFERSEXTPROC glGenFramebuffersEXT; -extern PFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffersEXT; +extern PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB; +extern PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB; + +#elif defined(OVR_OS_LINUX) + +extern PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT; + +#endif + +extern PFNGLGENFRAMEBUFFERSPROC glGenFramebuffers; +extern PFNGLDELETEFRAMEBUFFERSPROC glDeleteFramebuffers; extern PFNGLDELETESHADERPROC glDeleteShader; -extern PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glCheckFramebufferStatusEXT; -extern PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC glFramebufferRenderbufferEXT; -extern PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2DEXT; -extern PFNGLBINDFRAMEBUFFEREXTPROC glBindFramebufferEXT; +extern PFNGLCHECKFRAMEBUFFERSTATUSPROC glCheckFramebufferStatus; +extern PFNGLFRAMEBUFFERRENDERBUFFERPROC glFramebufferRenderbuffer; +extern PFNGLFRAMEBUFFERTEXTURE2DPROC glFramebufferTexture2D; +extern PFNGLBINDFRAMEBUFFEREXTPROC glBindFramebuffer; extern PFNGLACTIVETEXTUREPROC glActiveTexture; extern PFNGLDISABLEVERTEXATTRIBARRAYPROC glDisableVertexAttribArray; extern PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer; @@ -91,19 +99,18 @@ extern PFNGLUNIFORM3FVPROC glUniform3fv; extern PFNGLUNIFORM2FVPROC glUniform2fv; extern PFNGLUNIFORM1FVPROC glUniform1fv; extern PFNGLCOMPRESSEDTEXIMAGE2DPROC glCompressedTexImage2D; -extern PFNGLRENDERBUFFERSTORAGEEXTPROC glRenderbufferStorageEXT; -extern PFNGLBINDRENDERBUFFEREXTPROC glBindRenderbufferEXT; -extern PFNGLGENRENDERBUFFERSEXTPROC glGenRenderbuffersEXT; -extern PFNGLDELETERENDERBUFFERSEXTPROC glDeleteRenderbuffersEXT; - -// For testing +extern PFNGLRENDERBUFFERSTORAGEPROC glRenderbufferStorage; +extern PFNGLBINDRENDERBUFFERPROC glBindRenderbuffer; +extern PFNGLGENRENDERBUFFERSPROC glGenRenderbuffers; +extern PFNGLDELETERENDERBUFFERSPROC glDeleteRenderbuffers; extern PFNGLGENVERTEXARRAYSPROC glGenVertexArrays; +extern PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays; +extern PFNGLBINDVERTEXARRAYPROC glBindVertexArray; extern void InitGLExtensions(); #endif - class RenderDevice; class Buffer : public Render::Buffer @@ -227,12 +234,15 @@ class RenderDevice : public Render::RenderDevice Matrix4f Proj; + GLuint Vao; + protected: Ptr<Texture> CurRenderTarget; Array<Ptr<Texture> > DepthBuffers; GLuint CurrentFbo; const LightingParams* Lighting; + bool SupportsVao; public: RenderDevice(const RendererParams& p); @@ -243,8 +253,6 @@ public: virtual void FillTexturedRect(float left, float top, float right, float bottom, float ul, float vt, float ur, float vb, Color c, Ptr<OVR::Render::Texture> tex); virtual void SetViewport(const Recti& vp); - - //virtual void SetScissor(int x, int y, int w, int h); virtual void WaitUntilGpuIdle(); @@ -266,7 +274,7 @@ public: virtual void Render(const Matrix4f& matrix, Model* model); virtual void Render(const Fill* fill, Render::Buffer* vertices, Render::Buffer* indices, - const Matrix4f& matrix, int offset, int count, PrimitiveType prim = Prim_Triangles, bool useDistortionVertex = false); + const Matrix4f& matrix, int offset, int count, PrimitiveType prim = Prim_Triangles, MeshType meshType = Mesh_Scene); virtual void RenderWithAlpha(const Fill* fill, Render::Buffer* vertices, Render::Buffer* indices, const Matrix4f& matrix, int offset, int count, PrimitiveType prim = Prim_Triangles); diff --git a/Samples/CommonSrc/Render/Render_GL_Win32_Device.cpp b/Samples/CommonSrc/Render/Render_GL_Win32_Device.cpp index 1065c98..9bfcec9 100644 --- a/Samples/CommonSrc/Render/Render_GL_Win32_Device.cpp +++ b/Samples/CommonSrc/Render/Render_GL_Win32_Device.cpp @@ -36,11 +36,10 @@ PFNDWMENABLECOMPOSITIONPROC DwmEnableComposition; // ***** GL::Win32::RenderDevice -RenderDevice::RenderDevice(const Render::RendererParams& p, HWND win, HDC dc, HGLRC gl) +RenderDevice::RenderDevice(const Render::RendererParams& p, HWND win, HGLRC gl) : GL::RenderDevice(p) , Window(win) , WglContext(gl) - , GdiDc(dc) , PreFullscreen(0, 0, 0, 0) , HMonitor(0) , FSDesktop(0, 0, 0, 0) @@ -52,6 +51,7 @@ RenderDevice::RenderDevice(const Render::RendererParams& p, HWND win, HDC dc, HG Render::RenderDevice* RenderDevice::CreateDevice(const RendererParams& rp, void* oswnd) { HWND hwnd = (HWND)oswnd; + HDC dc = GetDC(hwnd); if (!DwmEnableComposition) { @@ -62,40 +62,93 @@ Render::RenderDevice* RenderDevice::CreateDevice(const RendererParams& rp, void* } DwmEnableComposition(DWM_EC_DISABLECOMPOSITION); + { + PIXELFORMATDESCRIPTOR pfd; + memset(&pfd, 0, sizeof(pfd)); + + pfd.nSize = sizeof(pfd); + pfd.nVersion = 1; + pfd.iPixelType = PFD_TYPE_RGBA; + pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER; + pfd.cColorBits = 32; + pfd.cDepthBits = 16; + + int pf = ChoosePixelFormat(dc, &pfd); + if (!pf) + { + ReleaseDC(hwnd, dc); + return NULL; + } + + if (!SetPixelFormat(dc, pf, &pfd)) + { + ReleaseDC(hwnd, dc); + return NULL; + } + + HGLRC context = wglCreateContext(dc); + if (!wglMakeCurrent(dc, context)) + { + wglDeleteContext(context); + ReleaseDC(hwnd, dc); + return NULL; + } + + wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); + wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); + + wglDeleteContext(context); + } - PIXELFORMATDESCRIPTOR pfd; - memset(&pfd, 0, sizeof(pfd)); - pfd.nSize = sizeof(pfd); - pfd.nVersion = 1; - pfd.iPixelType = PFD_TYPE_RGBA; - pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER; - pfd.cColorBits = 32; - pfd.cDepthBits = 16; + int iAttributes[] = { + //WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, + WGL_SUPPORT_OPENGL_ARB, GL_TRUE, + WGL_COLOR_BITS_ARB, 32, + WGL_DEPTH_BITS_ARB, 16, + WGL_DOUBLE_BUFFER_ARB, GL_TRUE, + WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB, GL_TRUE, + 0, 0}; + + float fAttributes[] = {0,0}; + + int pf = 0; + UINT numFormats = 0; - HDC dc = GetDC(hwnd); - int pf = ChoosePixelFormat(dc, &pfd); - if (!pf) + if (!wglChoosePixelFormatARB(dc, iAttributes, fAttributes, 1, &pf, &numFormats)) { ReleaseDC(hwnd, dc); return NULL; } + + PIXELFORMATDESCRIPTOR pfd; + memset(&pfd, 0, sizeof(pfd)); + if (!SetPixelFormat(dc, pf, &pfd)) { ReleaseDC(hwnd, dc); return NULL; } - HGLRC context = wglCreateContext(dc); - if (!wglMakeCurrent(dc, context)) - { - wglDeleteContext(context); - ReleaseDC(hwnd, dc); - return NULL; - } + + GLint attribs[] = + { + WGL_CONTEXT_MAJOR_VERSION_ARB, 2, + WGL_CONTEXT_MINOR_VERSION_ARB, 1, + WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, + 0 + }; + + HGLRC context = wglCreateContextAttribsARB(dc, 0, attribs); + if (!wglMakeCurrent(dc, context)) + { + wglDeleteContext(context); + ReleaseDC(hwnd, dc); + return NULL; + } InitGLExtensions(); - return new RenderDevice(rp, hwnd, dc, context); + return new RenderDevice(rp, hwnd, context); } ovrRenderAPIConfig RenderDevice::Get_ovrRenderAPIConfig() const @@ -104,9 +157,7 @@ ovrRenderAPIConfig RenderDevice::Get_ovrRenderAPIConfig() const cfg.OGL.Header.API = ovrRenderAPI_OpenGL; cfg.OGL.Header.RTSize = Sizei(WindowWidth, WindowHeight); cfg.OGL.Header.Multisample = Params.Multisample; - cfg.OGL.WglContext = WglContext; cfg.OGL.Window = Window; - cfg.OGL.GdiDc = GdiDc; return cfg.Config; } @@ -118,7 +169,10 @@ void RenderDevice::Present(bool useVsync) if (wglGetSwapIntervalEXT() != swapInterval) wglSwapIntervalEXT(swapInterval); - success = SwapBuffers(GdiDc); + HDC dc = GetDC(Window); + success = SwapBuffers(dc); + ReleaseDC(Window, dc); + OVR_ASSERT(success); } @@ -131,9 +185,7 @@ void RenderDevice::Shutdown() { wglMakeCurrent(NULL,NULL); wglDeleteContext(WglContext); - ReleaseDC(Window, GdiDc); WglContext = NULL; - GdiDc = NULL; Window = NULL; } } @@ -263,25 +315,6 @@ bool RenderDevice::SetFullscreen(DisplayMode fullscreen) monInfo.cbSize = sizeof(MONITORINFOEX); GetMonitorInfo(HMonitor, &monInfo); - // Find the requested device mode - DEVMODE dmode; - bool foundMode = false; - memset(&dmode, 0, sizeof(DEVMODE)); - dmode.dmSize = sizeof(DEVMODE); - Recti vp = VP; - for(int i=0 ; EnumDisplaySettings(monInfo.szDevice, i, &dmode); ++i) - { - foundMode = (dmode.dmPelsWidth==(DWORD)vp.w) && - (dmode.dmPelsHeight==(DWORD)vp.h) && - (dmode.dmBitsPerPel==(DWORD)32); - if (foundMode) - break; - } - if(!foundMode) - return false; - - dmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; - // Save the current window position/size RECT rect; GetWindowRect(Window, &rect); @@ -296,26 +329,20 @@ bool RenderDevice::SetFullscreen(DisplayMode fullscreen) SetWindowLongPtr(Window, GWL_STYLE, style & (~WS_OVERLAPPEDWINDOW)); SetWindowLongPtr(Window, GWL_EXSTYLE, exstyle | WS_EX_APPWINDOW | WS_EX_TOPMOST); - // Attempt to change the resolution - LONG ret = ChangeDisplaySettingsEx(monInfo.szDevice, &dmode, NULL, CDS_FULLSCREEN, NULL); - //LONG ret = ChangeDisplaySettings(&dmode, CDS_FULLSCREEN); - - // If it failed, clean up and return. - if (ret != DISP_CHANGE_SUCCESSFUL) - { - SetWindowLongPtr(Window, GWL_STYLE, style); - SetWindowLongPtr(Window, GWL_EXSTYLE, exstyle); - return false; - } + ChangeDisplaySettingsEx(monInfo.szDevice, NULL, NULL, CDS_FULLSCREEN, NULL); // We need to call GetMonitorInfo() again becase // details may have changed with the resolution GetMonitorInfo(HMonitor, &monInfo); + int x = monInfo.rcMonitor.left; + int y = monInfo.rcMonitor.top; + int w = monInfo.rcMonitor.right - monInfo.rcMonitor.left; + int h = monInfo.rcMonitor.bottom - monInfo.rcMonitor.top; + // Set the window's size and position so // that it covers the entire screen - SetWindowPos(Window, HWND_TOPMOST, monInfo.rcMonitor.left, monInfo.rcMonitor.top, vp.w, vp.h, - SWP_SHOWWINDOW | SWP_NOZORDER | SWP_FRAMECHANGED); + SetWindowPos(Window, HWND_TOPMOST, x, y, w, h, SWP_SHOWWINDOW | SWP_NOZORDER | SWP_FRAMECHANGED); } Params.Fullscreen = fullscreen; diff --git a/Samples/CommonSrc/Render/Render_GL_Win32_Device.h b/Samples/CommonSrc/Render/Render_GL_Win32_Device.h index de81a80..273e997 100644 --- a/Samples/CommonSrc/Render/Render_GL_Win32_Device.h +++ b/Samples/CommonSrc/Render/Render_GL_Win32_Device.h @@ -42,13 +42,12 @@ class RenderDevice : public GL::RenderDevice HWND Window; HGLRC WglContext; - HDC GdiDc; Recti PreFullscreen; Recti FSDesktop; HMONITOR HMonitor; public: - RenderDevice(const Render::RendererParams& p, HWND win, HDC dc, HGLRC gl); + RenderDevice(const Render::RendererParams& p, HWND win, HGLRC gl); virtual ~RenderDevice() { Shutdown(); } // Implement static initializer function to create this class. diff --git a/Samples/CommonSrc/Render/Render_LoadTextureDDS.cpp b/Samples/CommonSrc/Render/Render_LoadTextureDDS.cpp index 5bbdb21..cf20cdd 100644 --- a/Samples/CommonSrc/Render/Render_LoadTextureDDS.cpp +++ b/Samples/CommonSrc/Render/Render_LoadTextureDDS.cpp @@ -29,8 +29,11 @@ limitations under the License. namespace OVR { namespace Render { static const UPInt OVR_DDS_PF_FOURCC = 0x4; -static const UInt32 OVR_DTX1_MAGIC_NUMBER = 827611204; -static const UInt32 OVR_DTX5_MAGIC_NUMBER = 894720068; +static const UInt32 OVR_DXT1_MAGIC_NUMBER = 0x31545844; // "DXT1" +static const UInt32 OVR_DXT2_MAGIC_NUMBER = 0x32545844; // "DXT2" +static const UInt32 OVR_DXT3_MAGIC_NUMBER = 0x33545844; // "DXT3" +static const UInt32 OVR_DXT4_MAGIC_NUMBER = 0x34545844; // "DXT4" +static const UInt32 OVR_DXT5_MAGIC_NUMBER = 0x35545844; // "DXT5" struct OVR_DDS_PIXELFORMAT { @@ -62,6 +65,20 @@ struct OVR_DDS_HEADER UInt32 Reserved2; }; +// Returns -1 on failure, or a valid TextureFormat value on success +static inline int InterpretPixelFormatFourCC(UInt32 fourCC) { + switch (fourCC) { + case OVR_DXT1_MAGIC_NUMBER: return Texture_DXT1; + case OVR_DXT2_MAGIC_NUMBER: return Texture_DXT3; + case OVR_DXT3_MAGIC_NUMBER: return Texture_DXT3; + case OVR_DXT4_MAGIC_NUMBER: return Texture_DXT5; + case OVR_DXT5_MAGIC_NUMBER: return Texture_DXT5; + } + + // Unrecognized FourCC + return -1; +} + Texture* LoadTextureDDS(RenderDevice* ren, File* f) { OVR_DDS_HEADER header; @@ -87,24 +104,20 @@ Texture* LoadTextureDDS(RenderDevice* ren, File* f) } if(header.PixelFormat.Flags & OVR_DDS_PF_FOURCC) { - if(header.PixelFormat.FourCC == OVR_DTX1_MAGIC_NUMBER) - { - format = Texture_DXT1; - } - else if(header.PixelFormat.FourCC == OVR_DTX5_MAGIC_NUMBER) - { - format = Texture_DXT5; - } - else - { - return NULL; - } + format = InterpretPixelFormatFourCC(header.PixelFormat.FourCC); + if (format == -1) { + return NULL; + } } int byteLen = f->BytesAvailable(); unsigned char* bytes = new unsigned char[byteLen]; f->Read(bytes, byteLen); Texture* out = ren->CreateTexture(format, (int)width, (int)height, bytes, mipCount); + if (!out) { + return NULL; + } + if(strstr(f->GetFilePath(), "_c.")) { out->SetSampleMode(Sample_Clamp); diff --git a/Samples/CommonSrc/Util/OptionMenu.cpp b/Samples/CommonSrc/Util/OptionMenu.cpp new file mode 100644 index 0000000..d9acc44 --- /dev/null +++ b/Samples/CommonSrc/Util/OptionMenu.cpp @@ -0,0 +1,899 @@ +/************************************************************************************ + +Filename : OptionMenu.h +Content : Option selection and editing for OculusWorldDemo +Created : March 7, 2014 +Authors : Michael Antonov, Caleb Leak + +Copyright : Copyright 2012 Oculus VR, Inc. All Rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +*************************************************************************************/ + +#include "OptionMenu.h" + +// Embed the font. +#include "../Render/Render_FontEmbed_DejaVu48.h" + + +//------------------------------------------------------------------------------------- +bool OptionShortcut::MatchKey(OVR::KeyCode key, bool shift) const +{ + for (UInt32 i = 0; i < Keys.GetSize(); i++) + { + if (Keys[i].Key != key) + continue; + + if (!shift && Keys[i].ShiftUsage == ShortcutKey::Shift_RequireOn) + continue; + + if (shift && Keys[i].ShiftUsage == ShortcutKey::Shift_RequireOff) + continue; + + if(Keys[i].ShiftUsage == ShortcutKey::Shift_Modify) + { + pNotify->CallNotify(&shift); + } + else + { + pNotify->CallNotify(); + } + return true; + } + return false; +} + +bool OptionShortcut::MatchGamepadButton(UInt32 gamepadButtonMask) const +{ + for (UInt32 i = 0; i < GamepadButtons.GetSize(); i++) + { + if (GamepadButtons[i] & gamepadButtonMask) + { + if (pNotify != NULL) + { + pNotify->CallNotify(); + } + return true; + } + } + return false; +} + + +//------------------------------------------------------------------------------------- +String OptionMenuItem::PopNamespaceFrom(OptionMenuItem* menuItem) +{ + String label = menuItem->Label; + for (UInt32 i = 0; i < label.GetLength(); i++) + { + if (label.GetCharAt(i) == '.') + { + String ns = label.Substring(0, i); + menuItem->Label = label.Substring(i + 1, label.GetLength()); + return ns; + } + } + return ""; +} + +//------------------------------------------------------------------------------------- + +String OptionVar::FormatEnum(OptionVar* var) +{ + UInt32 index = var->GetEnumIndex(); + if (index < var->EnumValues.GetSize()) + return var->EnumValues[index].Name; + return String("<Bad enum index>"); +} + +String OptionVar::FormatInt(OptionVar* var) +{ + char buff[64]; + OVR_sprintf(buff, sizeof(buff), var->FormatString, *var->AsInt()); + return String(buff); +} + +String OptionVar::FormatFloat(OptionVar* var) +{ + char buff[64]; + OVR_sprintf(buff, sizeof(buff), var->FormatString, *var->AsFloat() * var->FormatScale); + return String(buff); +} + +String OptionVar::FormatBool(OptionVar* var) +{ + return *var->AsBool() ? "On" : "Off"; +} + + +OptionVar::OptionVar(const char* name, void* pvar, VarType type, + FormatFunction formatFunction, + UpdateFunction updateFunction) +{ + Label = name; + Type = type; + this->pVar = pvar; + fFormat = formatFunction; + fUpdate = updateFunction; + pNotify = 0; + FormatString= 0; + + MaxFloat = Math<float>::MaxValue; + MinFloat = -Math<float>::MaxValue; + StepFloat = 1.0f; + FormatScale = 1.0f; + + MaxInt = 0x7FFFFFFF; + MinInt = -(MaxInt) - 1; + StepInt = 1; + + ShortcutUp.pNotify = new FunctionNotifyContext<OptionVar, bool>(this, &OptionVar::NextValue); + ShortcutDown.pNotify = new FunctionNotifyContext<OptionVar, bool>(this, &OptionVar::PrevValue); +} + +OptionVar::OptionVar(const char* name, SInt32* pvar, + SInt32 min, SInt32 max, SInt32 stepSize, + const char* formatString, + FormatFunction formatFunction, + UpdateFunction updateFunction) +{ + Label = name; + Type = Type_Int; + this->pVar = pvar; + fFormat = formatFunction ? formatFunction : FormatInt; + fUpdate = updateFunction; + pNotify = 0; + FormatString= formatString; + + MinInt = min; + MaxInt = max; + StepInt = stepSize; + + ShortcutUp.pNotify = new FunctionNotifyContext<OptionVar, bool>(this, &OptionVar::NextValue); + ShortcutDown.pNotify = new FunctionNotifyContext<OptionVar, bool>(this, &OptionVar::PrevValue); +} + +// Float with range and step size. +OptionVar::OptionVar(const char* name, float* pvar, + float minf, float maxf, float stepSize, + const char* formatString, float formatScale, + FormatFunction formatFunction, + UpdateFunction updateFunction) +{ + Label = name; + Type = Type_Float; + this->pVar = pvar; + fFormat = formatFunction ? formatFunction : FormatFloat; + fUpdate = updateFunction; + pNotify = 0; + FormatString= formatString ? formatString : "%.3f"; + + MinFloat = minf; + MaxFloat = maxf; + StepFloat = stepSize; + FormatScale = formatScale; + + ShortcutUp.pNotify = new FunctionNotifyContext<OptionVar, bool>(this, &OptionVar::NextValue); + ShortcutDown.pNotify = new FunctionNotifyContext<OptionVar, bool>(this, &OptionVar::PrevValue); +} + +OptionVar::~OptionVar() +{ + if (pNotify) + delete pNotify; +} + +void OptionVar::NextValue(bool* pFastStep) +{ + bool fastStep = (pFastStep != NULL && *pFastStep); + switch (Type) + { + case Type_Enum: + *AsInt() = ((GetEnumIndex() + 1) % EnumValues.GetSize()); + break; + + case Type_Int: + *AsInt() = Alg::Min<SInt32>(*AsInt() + StepInt * (fastStep ? 5 : 1), MaxInt); + break; + + case Type_Float: + // TODO: Will behave strange with NaN values. + *AsFloat() = Alg::Min<float>(*AsFloat() + StepFloat * (fastStep ? 5.0f : 1.0f), MaxFloat); + break; + + case Type_Bool: + *AsBool() = !*AsBool(); + break; + } + + SignalUpdate(); +} + +void OptionVar::PrevValue(bool* pFastStep) +{ + bool fastStep = (pFastStep != NULL && *pFastStep); + switch (Type) + { + case Type_Enum: + *AsInt() = ((GetEnumIndex() + (UInt32)EnumValues.GetSize() - 1) % EnumValues.GetSize()); + break; + + case Type_Int: + *AsInt() = Alg::Max<SInt32>(*AsInt() - StepInt * (fastStep ? 5 : 1), MinInt); + break; + + case Type_Float: + // TODO: Will behave strange with NaN values. + *AsFloat() = Alg::Max<float>(*AsFloat() - StepFloat * (fastStep ? 5.0f : 1.0f), MinFloat); + break; + + case Type_Bool: + *AsBool() = !*AsBool(); + break; + } + + SignalUpdate(); +} + +String OptionVar::HandleShortcutUpdate() +{ + SignalUpdate(); + return Label + " - " + GetValue(); +} + +String OptionVar::ProcessShortcutKey(OVR::KeyCode key, bool shift) +{ + if (ShortcutUp.MatchKey(key, shift) || ShortcutDown.MatchKey(key, shift)) + { + return HandleShortcutUpdate(); + } + + return String(); +} + +String OptionVar::ProcessShortcutButton(UInt32 buttonMask) +{ + if (ShortcutUp.MatchGamepadButton(buttonMask) || ShortcutDown.MatchGamepadButton(buttonMask)) + { + return HandleShortcutUpdate(); + } + return String(); +} + + +OptionVar& OptionVar::AddEnumValue(const char* displayName, SInt32 value) +{ + EnumEntry entry; + entry.Name = displayName; + entry.Value = value; + EnumValues.PushBack(entry); + return *this; +} + +String OptionVar::GetValue() +{ + return fFormat(this); +} + +UInt32 OptionVar::GetEnumIndex() +{ + OVR_ASSERT(Type == Type_Enum); + OVR_ASSERT(EnumValues.GetSize() > 0); + + // TODO: Change this from a linear search to binary or a hash. + for (UInt32 i = 0; i < EnumValues.GetSize(); i++) + { + if (EnumValues[i].Value == *AsInt()) + return i; + } + + // Enum values should always be found. + OVR_ASSERT(false); + return 0; +} + + +//------------------------------------------------------------------------------------- + +OptionSelectionMenu::OptionSelectionMenu(OptionSelectionMenu* parentMenu) +{ + DisplayState = Display_None; + SelectedIndex = 0; + SelectionActive = false; + ParentMenu = parentMenu; + + PopupMessageTimeout = 0.0; + PopupMessageBorder = false; + + // Setup handlers for menu navigation actions. + NavShortcuts[Nav_Up].pNotify = new FunctionNotifyContext<OptionSelectionMenu, bool>(this, &OptionSelectionMenu::HandleUp); + NavShortcuts[Nav_Down].pNotify = new FunctionNotifyContext<OptionSelectionMenu, bool>(this, &OptionSelectionMenu::HandleDown); + NavShortcuts[Nav_Left].pNotify = new FunctionNotifySimple<OptionSelectionMenu>(this, &OptionSelectionMenu::HandleLeft); + NavShortcuts[Nav_Right].pNotify = new FunctionNotifySimple<OptionSelectionMenu>(this, &OptionSelectionMenu::HandleRight); + NavShortcuts[Nav_Select].pNotify = new FunctionNotifySimple<OptionSelectionMenu>(this, &OptionSelectionMenu::HandleSelect); + NavShortcuts[Nav_Back].pNotify = new FunctionNotifySimple<OptionSelectionMenu>(this, &OptionSelectionMenu::HandleBack); + ToggleShortcut.pNotify = new FunctionNotifySimple<OptionSelectionMenu>(this, &OptionSelectionMenu::HandleMenuToggle); + ToggleSingleItemShortcut.pNotify = new FunctionNotifySimple<OptionSelectionMenu>(this, &OptionSelectionMenu::HandleSingleItemToggle); + + // Bind keys and buttons to menu navigation actions. + NavShortcuts[Nav_Up].AddShortcut(ShortcutKey(Key_Up, ShortcutKey::Shift_Modify)); + NavShortcuts[Nav_Up].AddShortcut(Gamepad_Up); + + NavShortcuts[Nav_Down].AddShortcut(ShortcutKey(Key_Down, ShortcutKey::Shift_Modify)); + NavShortcuts[Nav_Down].AddShortcut(Gamepad_Down); + + NavShortcuts[Nav_Left].AddShortcut(ShortcutKey(Key_Left)); + NavShortcuts[Nav_Left].AddShortcut(Gamepad_Left); + + NavShortcuts[Nav_Right].AddShortcut(ShortcutKey(Key_Right)); + NavShortcuts[Nav_Right].AddShortcut(Gamepad_Right); + + NavShortcuts[Nav_Select].AddShortcut(ShortcutKey(Key_Return)); + NavShortcuts[Nav_Select].AddShortcut(Gamepad_A); + + NavShortcuts[Nav_Back].AddShortcut(ShortcutKey(Key_Escape)); + NavShortcuts[Nav_Back].AddShortcut(Gamepad_B); + + ToggleShortcut.AddShortcut(ShortcutKey(Key_Tab, ShortcutKey::Shift_Ignore)); + ToggleShortcut.AddShortcut(Gamepad_Start); + + ToggleSingleItemShortcut.AddShortcut(ShortcutKey(Key_Backspace, ShortcutKey::Shift_Ignore)); +} + +OptionSelectionMenu::~OptionSelectionMenu() +{ + for (UInt32 i = 0; i < Items.GetSize(); i++) + delete Items[i]; +} + +bool OptionSelectionMenu::OnKey(OVR::KeyCode key, int chr, bool down, int modifiers) +{ + bool shift = ((modifiers & Mod_Shift) != 0); + + if (down) + { + String s = ProcessShortcutKey(key, shift); + if (!s.IsEmpty()) + { + PopupMessage = s; + PopupMessageTimeout = ovr_GetTimeInSeconds() + 4.0f; + PopupMessageBorder = false; + return true; + } + } + + if (GetSubmenu() != NULL) + { + return GetSubmenu()->OnKey(key, chr, down, modifiers); + } + + if (down) + { + if (ToggleShortcut.MatchKey(key, shift)) + return true; + + if (ToggleSingleItemShortcut.MatchKey(key, shift)) + return true; + + if (DisplayState == Display_None) + return false; + + for (int i = 0; i < Nav_LAST; i++) + { + if (NavShortcuts[i].MatchKey(key, shift)) + return true; + } + } + + // Let the caller process keystroke + return false; +} + +bool OptionSelectionMenu::OnGamepad(UInt32 buttonMask) +{ + // Check global shortcuts first. + String s = ProcessShortcutButton(buttonMask); + if (!s.IsEmpty()) + { + PopupMessage = s; + PopupMessageTimeout = ovr_GetTimeInSeconds() + 4.0f; + return true; + } + + if (GetSubmenu() != NULL) + { + return GetSubmenu()->OnGamepad(buttonMask); + } + + if (ToggleShortcut.MatchGamepadButton(buttonMask)) + return true; + + if (DisplayState == Display_None) + return false; + + for (int i = 0; i < Nav_LAST; i++) + { + if (NavShortcuts[i].MatchGamepadButton(buttonMask)) + return true; + } + + // Let the caller process keystroke + return false; +} + +String OptionSelectionMenu::ProcessShortcutKey(OVR::KeyCode key, bool shift) +{ + String s; + + for (UPInt i = 0; (i < Items.GetSize()) && s.IsEmpty(); i++) + { + s = Items[i]->ProcessShortcutKey(key, shift); + } + + return s; +} + +String OptionSelectionMenu::ProcessShortcutButton(UInt32 buttonMask) +{ + String s; + + for (UPInt i = 0; (i < Items.GetSize()) && s.IsEmpty(); i++) + { + s = Items[i]->ProcessShortcutButton(buttonMask); + } + + return s; +} + +// Fills in inclusive character range; returns false if line not found. +bool FindLineCharRange(const char* text, int searchLine, UPInt charRange[2]) +{ + UPInt i = 0; + + for (int line = 0; line <= searchLine; line ++) + { + if (line == searchLine) + { + charRange[0] = i; + } + + // Find end of line. + while (text[i] != '\n' && text[i] != 0) + { + i++; + } + + if (line == searchLine) + { + charRange[1] = (charRange[0] == i) ? charRange[0] : i-1; + return true; + } + + if (text[i] == 0) + break; + // Skip newline + i++; + } + + return false; +} + + +void OptionSelectionMenu::Render(RenderDevice* prender, String title) +{ + // If we are invisible, render shortcut notifications. + // Both child and parent have visible == true even if only child is shown. + if (DisplayState == Display_None) + { + renderShortcutChangeMessage(prender); + return; + } + + title += Label; + + // Delegate to sub-menu if active. + if (GetSubmenu() != NULL) + { + if (title.GetSize() > 0) + title += " > "; + + GetSubmenu()->Render(prender, title); + return; + } + + Color focusColor(180, 80, 20, 210); + Color pickedColor(120, 55, 10, 140); + Color titleColor(0x18, 0x1A, 0x4D, 210); + Color titleOutlineColor(0x18, 0x18, 0x18, 240); + + float labelsSize[2] = {0.0f, 0.0f}; + float bufferSize[2] = {0.0f, 0.0f}; + float valuesSize[2] = {0.0f, 0.0f}; + float maxValueWidth = 0.0f; + + UPInt selection[2] = { 0, 0 }; + Vector2f labelSelectionRect[2]; + Vector2f valueSelectionRect[2]; + bool havelLabelSelection = false; + bool haveValueSelection = false; + + float textSize = 22.0f; + prender->MeasureText(&DejaVu, " ", textSize, bufferSize); + + String values; + String menuItems; + + int highlightIndex = 0; + if (DisplayState == Display_Menu) + { + highlightIndex = SelectedIndex; + for (UInt32 i = 0; i < Items.GetSize(); i++) + { + if (i > 0) + values += "\n"; + values += Items[i]->GetValue(); + } + + for (UInt32 i = 0; i < Items.GetSize(); i++) + { + if (i > 0) + menuItems += "\n"; + menuItems += Items[i]->GetLabel(); + } + } + else + { + values = Items[SelectedIndex]->GetValue(); + menuItems = Items[SelectedIndex]->GetLabel(); + } + + // Measure labels + const char* menuItemsCStr = menuItems.ToCStr(); + havelLabelSelection = FindLineCharRange(menuItemsCStr, highlightIndex, selection); + prender->MeasureText(&DejaVu, menuItemsCStr, textSize, labelsSize, + selection, labelSelectionRect); + + // Measure label-to-value gap + const char* valuesCStr = values.ToCStr(); + haveValueSelection = FindLineCharRange(valuesCStr, highlightIndex, selection); + prender->MeasureText(&DejaVu, valuesCStr, textSize, valuesSize, selection, valueSelectionRect); + + // Measure max value size (absolute size varies, so just use a reasonable max) + maxValueWidth = prender->MeasureText(&DejaVu, "Max value width", textSize); + maxValueWidth = Alg::Max(maxValueWidth, valuesSize[0]); + + Vector2f borderSize(4.0f, 4.0f); + Vector2f totalDimensions = borderSize * 2 + Vector2f(bufferSize[0], 0) + Vector2f(maxValueWidth, 0) + + Vector2f(labelsSize[0], labelsSize[1]); + + Vector2f fudgeOffset= Vector2f(10.0f, 25.0f); // This offset looks better + Vector2f topLeft = (-totalDimensions / 2.0f) + fudgeOffset; + Vector2f bottomRight = topLeft + totalDimensions; + + // If displaying a single item, shift it down. + if (DisplayState == Display_SingleItem) + { + topLeft.y += textSize * 7; + bottomRight.y += textSize * 7; + } + + prender->FillRect(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y, Color(40,40,100,210)); + + Vector2f labelsPos = topLeft + borderSize; + Vector2f valuesPos = labelsPos + Vector2f(labelsSize[0], 0) + Vector2f(bufferSize[0], 0); + + // Highlight selected label + Vector2f selectionInset = Vector2f(0.3f, 2.0f); + if (DisplayState == Display_Menu) + { + Vector2f labelSelectionTopLeft = labelsPos + labelSelectionRect[0] - selectionInset; + Vector2f labelSelectionBottomRight = labelsPos + labelSelectionRect[1] + selectionInset; + + prender->FillRect(labelSelectionTopLeft.x, labelSelectionTopLeft.y, + labelSelectionBottomRight.x, labelSelectionBottomRight.y, + SelectionActive ? pickedColor : focusColor); + } + + // Highlight selected value if active + if (SelectionActive) + { + Vector2f valueSelectionTopLeft = valuesPos + valueSelectionRect[0] - selectionInset; + Vector2f valueSelectionBottomRight = valuesPos + valueSelectionRect[1] + selectionInset; + prender->FillRect(valueSelectionTopLeft.x, valueSelectionTopLeft.y, + valueSelectionBottomRight.x, valueSelectionBottomRight.y, + focusColor); + } + + // Measure and draw title + if (DisplayState == Display_Menu && title.GetLength() > 0) + { + Vector2f titleDimensions; + prender->MeasureText(&DejaVu, title.ToCStr(), textSize, &titleDimensions.x); + Vector2f titleTopLeft = topLeft - Vector2f(0, borderSize.y) * 2 - Vector2f(0, titleDimensions.y); + titleDimensions.x = totalDimensions.x; + + prender->FillRect(titleTopLeft.x, titleTopLeft.y, + titleTopLeft.x + totalDimensions.x, + titleTopLeft.y + titleDimensions.y + borderSize.y * 2, + titleOutlineColor); + + prender->FillRect(titleTopLeft.x + borderSize.x / 2, titleTopLeft.y + borderSize.y / 2, + titleTopLeft.x + totalDimensions.x - borderSize.x / 2, + titleTopLeft.y + borderSize.y / 2 + titleDimensions.y, + titleColor); + + prender->RenderText(&DejaVu, title.ToCStr(), titleTopLeft.x + borderSize.x, + titleTopLeft.y + borderSize.y, textSize, Color(255,255,0,210)); + } + + prender->RenderText(&DejaVu, menuItemsCStr, labelsPos.x, labelsPos.y, textSize, Color(255,255,0,210)); + + prender->RenderText(&DejaVu, valuesCStr, valuesPos.x, valuesPos.y, textSize, Color(255,255,0,210)); +} + + +void OptionSelectionMenu::renderShortcutChangeMessage(RenderDevice* prender) +{ + if (ovr_GetTimeInSeconds() < PopupMessageTimeout) + { + DrawTextBox(prender, 0, 120, 22.0f, PopupMessage.ToCStr(), + DrawText_Center | (PopupMessageBorder ? DrawText_Border : 0)); + } +} + + +void OptionSelectionMenu::SetPopupMessage(const char* format, ...) +{ + //Lock::Locker lock(pManager->GetHandlerLock()); + char textBuff[2048]; + va_list argList; + va_start(argList, format); + OVR_vsprintf(textBuff, sizeof(textBuff), format, argList); + va_end(argList); + + // Message will time out in 4 seconds. + PopupMessage = textBuff; + PopupMessageTimeout = ovr_GetTimeInSeconds() + 4.0f; + PopupMessageBorder = false; +} + +void OptionSelectionMenu::SetPopupTimeout(double timeoutSeconds, bool border) +{ + PopupMessageTimeout = ovr_GetTimeInSeconds() + timeoutSeconds; + PopupMessageBorder = border; +} + + + +void OptionSelectionMenu::AddItem(OptionMenuItem* menuItem) +{ + String ns = PopNamespaceFrom(menuItem); + + if (ns.GetLength() == 0) + { + Items.PushBack(menuItem); + } + else + { + // Item is part of a submenu, add it to that instead. + GetOrCreateSubmenu(ns)->AddItem(menuItem); + } +} + +//virtual +void OptionSelectionMenu::Select() +{ + SelectedIndex = 0; + SelectionActive = false; + DisplayState = Display_Menu; +} + + +OptionSelectionMenu* OptionSelectionMenu::GetSubmenu() +{ + if (!SelectionActive || !Items[SelectedIndex]->IsMenu()) + return NULL; + + OptionSelectionMenu* submenu = static_cast<OptionSelectionMenu*>(Items[SelectedIndex]); + return submenu; +} + + +OptionSelectionMenu* OptionSelectionMenu::GetOrCreateSubmenu(String submenuName) +{ + for (UInt32 i = 0; i < Items.GetSize(); i++) + { + if (!Items[i]->IsMenu()) + continue; + + OptionSelectionMenu* submenu = static_cast<OptionSelectionMenu*>(Items[i]); + + if (submenu->Label == submenuName) + { + return submenu; + } + } + + // Submenu doesn't exist, create it. + OptionSelectionMenu* newSubmenu = new OptionSelectionMenu(this); + newSubmenu->Label = submenuName; + Items.PushBack(newSubmenu); + return newSubmenu; +} + +void OptionSelectionMenu::HandleUp(bool* pFast) +{ + int numItems = (int)Items.GetSize(); + if (SelectionActive) + Items[SelectedIndex]->NextValue(pFast); + else + SelectedIndex = ((SelectedIndex - 1 + numItems) % numItems); +} + +void OptionSelectionMenu::HandleDown(bool* pFast) +{ + if (SelectionActive) + Items[SelectedIndex]->PrevValue(pFast); + else + SelectedIndex = ((SelectedIndex + 1) % Items.GetSize()); +} + +void OptionSelectionMenu::HandleLeft() +{ + if (DisplayState != Display_Menu) + return; + + if (SelectionActive) + SelectionActive = false; + else if (ParentMenu) + { + // Escape to parent menu + ParentMenu->SelectionActive = false; + DisplayState = Display_Menu; + } +} + +void OptionSelectionMenu::HandleRight() +{ + if (DisplayState != Display_Menu) + return; + + if (!SelectionActive) + { + SelectionActive = true; + Items[SelectedIndex]->Select(); + } +} + +void OptionSelectionMenu::HandleSelect() +{ + if (!SelectionActive) + { + SelectionActive = true; + Items[SelectedIndex]->Select(); + } + else + { + Items[SelectedIndex]->NextValue(); + } +} + +void OptionSelectionMenu::HandleBack() +{ + if (DisplayState != Display_Menu) + return; + + if (!SelectionActive) + DisplayState = Display_None; + else + SelectionActive = false; +} + +void OptionSelectionMenu::HandleMenuToggle() +{ + // Mark this & parent With correct visibility. + OptionSelectionMenu* menu = this; + + if (DisplayState == Display_Menu) + DisplayState = Display_None; + else + DisplayState = Display_Menu; + + while (menu) + { + menu->DisplayState = DisplayState; + menu = menu->ParentMenu; + } + // Hide message + PopupMessageTimeout = 0; +} + +void OptionSelectionMenu::HandleSingleItemToggle() +{ + // Mark this & parent With correct visibility. + OptionSelectionMenu* menu = this; + + if (DisplayState == Display_SingleItem) + DisplayState = Display_None; + else + { + DisplayState = Display_SingleItem; + SelectionActive = true; + } + + while (menu) + { + menu->DisplayState = DisplayState; + menu = menu->ParentMenu; + } + // Hide message + PopupMessageTimeout = 0; +} + + +//------------------------------------------------------------------------------------- +// **** Text Rendering / Management + +void DrawTextBox(RenderDevice* prender, float x, float y, + float textSize, const char* text, unsigned centerType) +{ + float ssize[2] = {0.0f, 0.0f}; + + prender->MeasureText(&DejaVu, text, textSize, ssize); + + // Treat 0 a VCenter. + if (centerType & DrawText_HCenter) + { + x -= ssize[0]/2; + } + if (centerType & DrawText_VCenter) + { + y -= ssize[1]/2; + } + + const float borderSize = 4.0f; + float linesHeight = 0.0f; + + if (centerType & DrawText_Border) + linesHeight = 10.0f; + + prender->FillRect(x-borderSize, y-borderSize - linesHeight, + x+ssize[0]+borderSize, y+ssize[1]+borderSize + linesHeight, + Color(40,40,100,210)); + + if (centerType & DrawText_Border) + { + // Add top & bottom lines + float topLineY = y-borderSize - linesHeight * 0.5f, + bottomLineY = y+ssize[1]+borderSize + linesHeight * 0.5f; + + prender->FillRect(x-borderSize * 0.5f, topLineY, + x+ssize[0]+borderSize * 0.5f, topLineY + 2.0f, + Color(255,255,0,210)); + prender->FillRect(x-borderSize * 0.5f, bottomLineY, + x+ssize[0]+borderSize * 0.5f, bottomLineY + 2.0f, + Color(255,255,0,210)); + } + + prender->RenderText(&DejaVu, text, x, y, textSize, Color(255,255,0,210)); +} + +void CleanupDrawTextFont() +{ + if (DejaVu.fill) + { + DejaVu.fill->Release(); + DejaVu.fill = 0; + } +} diff --git a/Samples/CommonSrc/Util/OptionMenu.h b/Samples/CommonSrc/Util/OptionMenu.h new file mode 100644 index 0000000..d52ba5c --- /dev/null +++ b/Samples/CommonSrc/Util/OptionMenu.h @@ -0,0 +1,445 @@ +/************************************************************************************ + +Filename : OptionMenu.h +Content : Option selection and editing for OculusWorldDemo +Created : March 7, 2014 +Authors : Michael Antonov, Caleb Leak + +Copyright : Copyright 2012 Oculus VR, Inc. All Rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +*************************************************************************************/ + +#ifndef INC_OptionMenu_h +#define INC_OptionMenu_h + +#include "OVR.h" + +#include "../Platform/Platform_Default.h" +#include "../Render/Render_Device.h" +#include "../Platform/Gamepad.h" + +#include "Util/Util_Render_Stereo.h" +using namespace OVR::Util::Render; + +#include <Kernel/OVR_SysFile.h> +#include <Kernel/OVR_Log.h> +#include <Kernel/OVR_Timer.h> + +#include "OVR_DeviceConstants.h" + + +using namespace OVR; +using namespace OVR::Platform; +using namespace OVR::Render; + + +//------------------------------------------------------------------------------------- +struct FunctionNotifyBase : public NewOverrideBase +{ + virtual void CallNotify(void*) { } + virtual void CallNotify() { } +}; + +// Simple member pointer wrapper to support calling class members +template<class C, class X> +struct FunctionNotifyContext : public FunctionNotifyBase +{ + typedef void (C::*FnPtr)(X*); + + FunctionNotifyContext(C* p, FnPtr fn) : pClass(p), pFn(fn), pContext(NULL) { } + FunctionNotifyContext(C* p, FnPtr fn, X* pContext) : pClass(p), pFn(fn), pContext(pContext) { } + virtual void CallNotify(void* var) { (void)(pClass->*pFn)(static_cast<X*>(var)); } + virtual void CallNotify() { (void)(pClass->*pFn)(pContext); } +private: + + X* pContext; + C* pClass; + FnPtr pFn; +}; + +template<class C> +struct FunctionNotifySimple : public FunctionNotifyBase +{ + typedef void (C::*FnPtr)(void); + + FunctionNotifySimple(C* p, FnPtr fn) : pClass(p), pFn(fn) { } + virtual void CallNotify(void*) { CallNotify(); } + virtual void CallNotify() { (void)(pClass->*pFn)(); } +private: + + C* pClass; + FnPtr pFn; +}; + + +//------------------------------------------------------------------------------------- +// Describes a shortcut key +struct ShortcutKey +{ + enum ShiftUsageType + { + Shift_Ignore, + Shift_Modify, + Shift_RequireOn, + Shift_RequireOff + }; + + ShortcutKey(OVR::KeyCode key = Key_None, ShiftUsageType shiftUsage = Shift_RequireOff) + : Key(key), ShiftUsage(shiftUsage) { } + + OVR::KeyCode Key; + ShiftUsageType ShiftUsage; +}; + + +//------------------------------------------------------------------------------------- +struct OptionShortcut +{ + Array<ShortcutKey> Keys; + Array<UInt32> GamepadButtons; + FunctionNotifyBase* pNotify; + + OptionShortcut() : pNotify(NULL) {} + OptionShortcut(FunctionNotifyBase* pNotify) : pNotify(pNotify) {} + ~OptionShortcut() { if (pNotify) delete pNotify; } + + void AddShortcut(ShortcutKey key) { Keys.PushBack(key); } + void AddShortcut(UInt32 gamepadButton) { GamepadButtons.PushBack(gamepadButton); } + + bool MatchKey(OVR::KeyCode key, bool shift) const; + bool MatchGamepadButton(UInt32 gamepadButtonMask) const; +}; + + +//------------------------------------------------------------------------------------- + +// Base class for a menu item. Internally, this can also be OptionSelectionMenu itself +// to support nested menus. Users shouldn't need to use this class. +class OptionMenuItem : public NewOverrideBase +{ +public: + virtual ~OptionMenuItem() { } + + virtual void Select() { } + + virtual void NextValue(bool* pFastStep = NULL) { OVR_UNUSED1(pFastStep); } + virtual void PrevValue(bool* pFastStep = NULL) { OVR_UNUSED1(pFastStep); } + + virtual String GetLabel() { return Label; } + virtual String GetValue() { return ""; } + + // Returns empty string if shortcut not handled + virtual String ProcessShortcutKey(OVR::KeyCode key, bool shift) = 0; + virtual String ProcessShortcutButton(UInt32 buttonMask) = 0; + + virtual bool IsMenu() const { return false; } + +protected: + String Label; + String PopNamespaceFrom(OptionMenuItem* menuItem); +}; + + +//------------------------------------------------------------------------------------- + +// OptionVar implements a basic menu item, which binds to an external variable, +// displaying and editing its state. +class OptionVar : public OptionMenuItem +{ +public: + + enum VarType + { + Type_Enum, + Type_Int, + Type_Float, + Type_Bool + }; + + typedef String (*FormatFunction)(OptionVar*); + typedef void (*UpdateFunction)(OptionVar*); + + static String FormatEnum(OptionVar* var); + static String FormatInt(OptionVar* var); + static String FormatFloat(OptionVar* var); + static String FormatTan(OptionVar* var); + static String FormatBool(OptionVar* var); + + OptionVar(const char* name, void* pVar, VarType type, + FormatFunction formatFunction, + UpdateFunction updateFunction = NULL); + + // Integer with range and step size. + OptionVar(const char* name, SInt32* pVar, + SInt32 min, SInt32 max, SInt32 stepSize=1, + const char* formatString = "%d", + FormatFunction formatFunction = 0, // Default int formatting. + UpdateFunction updateFunction = NULL); + + // Float with range and step size. + OptionVar(const char* name, float* pvar, + float minf, float maxf, float stepSize = 1.0f, + const char* formatString = "%.3f", float formatScale = 1.0f, + FormatFunction formatFunction = 0, // Default float formatting. + UpdateFunction updateFunction = 0 ); + + virtual ~OptionVar(); + + SInt32* AsInt() { return reinterpret_cast<SInt32*>(pVar); } + bool* AsBool() { return reinterpret_cast<bool*>(pVar); } + float* AsFloat() { return reinterpret_cast<float*>(pVar); } + VarType GetType() { return Type; } + + // Step through values (wrap for enums). + virtual void NextValue(bool* pFastStep); + virtual void PrevValue(bool* pFastStep); + + // Executes shortcut message and returns notification string. + // Returns empty string for no action. + String HandleShortcutUpdate(); + virtual String ProcessShortcutKey(OVR::KeyCode key, bool shift); + virtual String ProcessShortcutButton(UInt32 buttonMask); + + OptionVar& AddEnumValue(const char* displayName, SInt32 value); + + template<class C> + OptionVar& SetNotify(C* p, void (C::*fn)(OptionVar*)) + { + OVR_ASSERT(pNotify == 0); // Can't set notifier twice. + pNotify = new FunctionNotifyContext<C, OptionVar>(p, fn, this); + return *this; + } + + + //String Format(); + virtual String GetValue(); + + OptionVar& AddShortcutUpKey(const ShortcutKey& shortcut) + { ShortcutUp.AddShortcut(shortcut); return *this; } + OptionVar& AddShortcutUpKey(OVR::KeyCode key, + ShortcutKey::ShiftUsageType shiftUsage = ShortcutKey::Shift_Modify) + { ShortcutUp.AddShortcut(ShortcutKey(key, shiftUsage)); return *this; } + OptionVar& AddShortcutUpButton(UInt32 gamepadButton) + { ShortcutUp.AddShortcut(gamepadButton); return *this; } + + OptionVar& AddShortcutDownKey(const ShortcutKey& shortcut) + { ShortcutDown.AddShortcut(shortcut); return *this; } + OptionVar& AddShortcutDownKey(OVR::KeyCode key, + ShortcutKey::ShiftUsageType shiftUsage = ShortcutKey::Shift_Modify) + { ShortcutDown.AddShortcut(ShortcutKey(key, shiftUsage)); return *this; } + OptionVar& AddShortcutDownButton(UInt32 gamepadButton) + { ShortcutDown.AddShortcut(gamepadButton); return *this; } + + OptionVar& AddShortcutKey(const ShortcutKey& shortcut) + { return AddShortcutUpKey(shortcut); } + OptionVar& AddShortcutKey(OVR::KeyCode key, + ShortcutKey::ShiftUsageType shiftUsage = ShortcutKey::Shift_RequireOff) + { return AddShortcutUpKey(key, shiftUsage); } + OptionVar& AddShortcutButton(UInt32 gamepadButton) + { return AddShortcutUpButton(gamepadButton); } + +private: + + void SignalUpdate() + { + if (fUpdate) fUpdate(this); + if (pNotify) pNotify->CallNotify(this); + } + + struct EnumEntry + { + // Human readable name for enum. + String Name; + SInt32 Value; + }; + + // Array of possible enum values. + Array<EnumEntry> EnumValues; + // Gets the index of the current enum value. + UInt32 GetEnumIndex(); + + FormatFunction fFormat; + UpdateFunction fUpdate; + FunctionNotifyBase* pNotify; + + VarType Type; + void* pVar; + const char* FormatString; + + OptionShortcut ShortcutUp; + OptionShortcut ShortcutDown; + + float MinFloat; + float MaxFloat; + float StepFloat; + float FormatScale; // Multiply float by this before rendering + + SInt32 MinInt; + SInt32 MaxInt; + SInt32 StepInt; +}; + + +//------------------------------------------------------------------------------------- +// ***** OptionSelectionMenu + +// Implements an overlay option menu, brought up by the 'Tab' key. +// Items are added to the menu with AddBool, AddEnum, AddFloat on startup, +// and are editable by using arrow keys (underlying variable is modified). +// +// Call Render() to render the menu every frame. +// +// Menu also support displaying popup messages with a timeout, displayed +// when menu body isn't up. + +class OptionSelectionMenu : public OptionMenuItem +{ +public: + OptionSelectionMenu(OptionSelectionMenu* parentMenu = NULL); + ~OptionSelectionMenu(); + + + bool OnKey(OVR::KeyCode key, int chr, bool down, int modifiers); + bool OnGamepad(UInt32 buttonMask); + + void Render(RenderDevice* prender, String title = ""); + + void AddItem(OptionMenuItem* menuItem); + + // Adds a boolean toggle. Returns added item to allow customization. + OptionVar& AddBool(const char* name, bool* pvar, + OptionVar::UpdateFunction updateFunction = 0, + OptionVar::FormatFunction formatFunction = OptionVar::FormatBool) + { + OptionVar* p = new OptionVar(name, pvar, OptionVar::Type_Bool, + formatFunction, updateFunction); + AddItem(p); + return *p; + } + + // Adds a boolean toggle. Returns added item to allow customization. + OptionVar& AddEnum(const char* name, void* pvar, + OptionVar::UpdateFunction updateFunction = 0) + { + OptionVar* p = new OptionVar(name, pvar, OptionVar::Type_Enum, + OptionVar::FormatEnum, updateFunction); + AddItem(p); + return *p; + } + + + // Adds a Float variable. Returns added item to allow customization. + OptionVar& AddFloat( const char* name, float* pvar, + float minf, float maxf, float stepSize = 1.0f, + const char* formatString = "%.3f", float formatScale = 1.0f, + OptionVar::FormatFunction formatFunction = 0, // Default float formatting. + OptionVar::UpdateFunction updateFunction = 0 ) + { + OptionVar* p = new OptionVar(name, pvar, minf, maxf, stepSize, + formatString, formatScale, + formatFunction, updateFunction); + AddItem(p); + return *p; + } + + virtual void Select(); + virtual String GetLabel() { return Label + " >"; } + + virtual String ProcessShortcutKey(OVR::KeyCode key, bool shift); + virtual String ProcessShortcutButton(UInt32 buttonMask); + + // Sets a message to display with a time-out. Default time-out is 4 seconds. + // This uses the same overlay approach as used for shortcut notifications. + void SetPopupMessage(const char* format, ...); + // Overrides current timeout, in seconds (not the future default value); + // intended to be called right after SetPopupMessage. + void SetPopupTimeout(double timeoutSeconds, bool border = false); + + virtual bool IsMenu() const { return true; } + +protected: + + void renderShortcutChangeMessage(RenderDevice* prender); + +public: + OptionSelectionMenu* GetSubmenu(); + OptionSelectionMenu* GetOrCreateSubmenu(String submenuName); + + enum DisplayStateType + { + Display_None, + Display_Menu, + Display_SingleItem + }; + + DisplayStateType DisplayState; + OptionSelectionMenu* ParentMenu; + + ArrayPOD<OptionMenuItem*> Items; + int SelectedIndex; + bool SelectionActive; + + String PopupMessage; + double PopupMessageTimeout; + bool PopupMessageBorder; + + // Possible menu navigation actions. + enum NavigationActions + { + Nav_Up, + Nav_Down, + Nav_Left, + Nav_Right, + Nav_Select, + Nav_Back, + Nav_LAST + }; + + // Handlers for navigation actions. + void HandleUp(bool* pFast); + void HandleDown(bool* pFast); + void HandleLeft(); + void HandleRight(); + void HandleSelect(); + void HandleBack(); + + void HandleMenuToggle(); + void HandleSingleItemToggle(); + + OptionShortcut NavShortcuts[Nav_LAST]; + OptionShortcut ToggleShortcut; + OptionShortcut ToggleSingleItemShortcut; +}; + + +//------------------------------------------------------------------------------------- +// Text Rendering Utility +enum DrawTextCenterType +{ + DrawText_NoCenter= 0, + DrawText_VCenter = 0x01, + DrawText_HCenter = 0x02, + DrawText_Center = DrawText_VCenter | DrawText_HCenter, + DrawText_Border = 0x10, +}; + +void DrawTextBox(RenderDevice* prender, float x, float y, + float textSize, const char* text, + unsigned centerType = DrawText_NoCenter); + +void CleanupDrawTextFont(); + + +#endif // INC_OptionMenu_h diff --git a/Samples/CommonSrc/Util/RenderProfiler.cpp b/Samples/CommonSrc/Util/RenderProfiler.cpp new file mode 100644 index 0000000..00bbdd9 --- /dev/null +++ b/Samples/CommonSrc/Util/RenderProfiler.cpp @@ -0,0 +1,99 @@ +/************************************************************************************ + +Filename : RenderProfiler.cpp +Content : Profiling for render. +Created : March 10, 2014 +Authors : Caleb Leak + +Copyright : Copyright 2012 Oculus VR, Inc. All Rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +*************************************************************************************/ + +#include "RenderProfiler.h" + +using namespace OVR; + +RenderProfiler::RenderProfiler() +{ + memset(SampleHistory, 0, sizeof(SampleHistory)); + memset(SampleAverage, 0, sizeof(SampleAverage)); + SampleCurrentFrame = 0; +} + +void RenderProfiler::RecordSample(SampleType sampleType) +{ + if (sampleType == Sample_FrameStart) + { + // Recompute averages and subtract off frame start time. + for (int sample = 1; sample < Sample_LAST; sample++) + { + SampleHistory[SampleCurrentFrame][sample] -= SampleHistory[SampleCurrentFrame][0]; + + // Recompute the average for the current sample type. + SampleAverage[sample] = 0.0; + for (int frame = 0; frame < NumFramesOfTimerHistory; frame++) + { + SampleAverage[sample] += SampleHistory[frame][sample]; + } + SampleAverage[sample] /= NumFramesOfTimerHistory; + } + + SampleCurrentFrame = ((SampleCurrentFrame + 1) % NumFramesOfTimerHistory); + } + + SampleHistory[SampleCurrentFrame][sampleType] = ovr_GetTimeInSeconds(); +} + +const double* RenderProfiler::GetLastSampleSet() const +{ + return SampleHistory[(SampleCurrentFrame - 1 + NumFramesOfTimerHistory) % NumFramesOfTimerHistory]; +} + +void RenderProfiler::DrawOverlay(RenderDevice* prender) +{ + char buf[256 * Sample_LAST]; + OVR_strcpy ( buf, sizeof(buf), "Timing stats" ); // No trailing \n is deliberate. + + /*int timerLastFrame = TimerCurrentFrame - 1; + if ( timerLastFrame < 0 ) + { + timerLastFrame = NumFramesOfTimerHistory - 1; + }*/ + // Timer 0 is always the time at the start of the frame. + + const double* averages = GetAverages(); + const double* lastSampleSet = GetLastSampleSet(); + + for ( int timerNum = 1; timerNum < Sample_LAST; timerNum++ ) + { + char const *pName = ""; + switch ( timerNum ) + { + case Sample_AfterGameProcessing: pName = "AfterGameProcessing"; break; + case Sample_AfterEyeRender : pName = "AfterEyeRender "; break; +// case Sample_BeforeDistortion : pName = "BeforeDistortion "; break; +// case Sample_AfterDistortion : pName = "AfterDistortion "; break; + case Sample_AfterPresent : pName = "AfterPresent "; break; +// case Sample_AfterFlush : pName = "AfterFlush "; break; + default: OVR_ASSERT ( false ); + } + char bufTemp[256]; + OVR_sprintf ( bufTemp, sizeof(bufTemp), "\nRaw: %.2lfms\t400Ave: %.2lfms\t800%s", + lastSampleSet[timerNum] * 1000.0, averages[timerNum] * 1000.0, pName ); + OVR_strcat ( buf, sizeof(buf), bufTemp ); + } + + DrawTextBox(prender, 0.0f, 0.0f, 22.0f, buf, DrawText_Center); +}
\ No newline at end of file diff --git a/Samples/CommonSrc/Util/RenderProfiler.h b/Samples/CommonSrc/Util/RenderProfiler.h new file mode 100644 index 0000000..96ec50a --- /dev/null +++ b/Samples/CommonSrc/Util/RenderProfiler.h @@ -0,0 +1,71 @@ +/************************************************************************************ + +Filename : RenderProfiler.h +Content : Profiling for render. +Created : March 10, 2014 +Authors : Caleb Leak + +Copyright : Copyright 2012 Oculus VR, Inc. All Rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +*************************************************************************************/ + +#ifndef INC_RenderProfiler_h +#define INC_RenderProfiler_h + +#include "OVR.h" + +// TODO: Refactor option menu so dependencies are in a separate file. +#include "OptionMenu.h" + +//------------------------------------------------------------------------------------- +// ***** RenderProfiler + +// Tracks reported timing sample in a frame and dislays them an overlay from DrawOverlay(). +class RenderProfiler +{ +public: + enum { NumFramesOfTimerHistory = 10 }; + + enum SampleType + { + Sample_FrameStart , + Sample_AfterGameProcessing , + Sample_AfterEyeRender , + // Sample_BeforeDistortion , + // Sample_AfterDistortion , + Sample_AfterPresent , + // Sample_AfterFlush , + + Sample_LAST + }; + + RenderProfiler(); + + // Records the current time for the given sample type. + void RecordSample(SampleType sampleType); + + const double* GetAverages() const { return SampleAverage; } + const double* GetLastSampleSet() const; + + void DrawOverlay(RenderDevice* prender); + +private: + + double SampleHistory[NumFramesOfTimerHistory][Sample_LAST]; + double SampleAverage[Sample_LAST]; + int SampleCurrentFrame; +}; + +#endif // INC_RenderProfiler_h |