// Rotating sponge
void Anim()
{
    static DWORD s_PrevTick = GetTickCount();
    DWORD tick = GetTickCount(); // msec
    float dt = float(tick - s_PrevTick) / 1000.0f; // sec
    if (g_Animate && dt > 0 && dt < 0.2f)
    {
        Vector3 axis = Vector3::ZERO;
        float angle = 0;
        AxisAngleFromRotation(axis, angle, g_SpongeRotation);
        if (Length(axis) < 1.0e-6f) 
            axis.v[1] = 1;
        angle += g_AnimationSpeed * dt;
        if (angle >= 2.0f*FLOAT_PI)
            angle -= 2.0f*FLOAT_PI;
        else if (angle <= 0)
            angle += 2.0f*FLOAT_PI;
        g_SpongeRotation = RotationFromAxisAngle(axis, angle);
    }
    s_PrevTick = tick;
}
void AtmosphereSample::Update(double CurrTime, double ElapsedTime)
{
    SampleBase::Update(CurrTime, ElapsedTime);

    m_fElapsedTime = static_cast<float>(ElapsedTime);

    const auto& SCDesc = m_pSwapChain->GetDesc();
    // Set world/view/proj matrices and global shader constants
    float aspectRatio = (float)SCDesc.Width / SCDesc.Height;

    float3 CamZ = normalize( m_f3CameraDir );
    float3 CamX = normalize( cross( float3( 0, 1, 0 ), CamZ ) );
    float3 CamY = normalize( cross( CamZ, CamX ) );

    m_mCameraView =
        translationMatrix( -m_f3CameraPos ) *
        ViewMatrixFromBasis( CamX, CamY, CamZ );


    // This projection matrix is only used to set up directions in view frustum
    // Actual near and far planes are ignored
    float FOV = (float)M_PI/4.f;
    float4x4 mTmpProj = Projection(FOV, aspectRatio, 50.f, 500000.f, m_bIsDXDevice);

    float fEarthRadius = AirScatteringAttribs().fEarthRadius;
    float3 EarthCenter(0, -fEarthRadius, 0);
    float fNearPlaneZ, fFarPlaneZ;
    ComputeApproximateNearFarPlaneDist(m_f3CameraPos,
                                       m_mCameraView,
                                       mTmpProj,
                                       EarthCenter,
                                       fEarthRadius,
                                       fEarthRadius + m_fMinElevation,
                                       fEarthRadius + m_fMaxElevation,
                                       fNearPlaneZ,
                                       fFarPlaneZ);
    fNearPlaneZ = std::max(fNearPlaneZ, 50.f);
    fFarPlaneZ  = std::max(fFarPlaneZ, fNearPlaneZ+100.f);
    fFarPlaneZ  = std::max(fFarPlaneZ, 1000.f);

    m_mCameraProj = Projection(FOV, aspectRatio, fNearPlaneZ, fFarPlaneZ, m_bIsDXDevice);

#if 0
    if( m_bAnimateSun )
    {
        auto &LightOrientationMatrix = *m_pDirLightOrienationCamera->GetParentMatrix();
        float3 RotationAxis( 0.5f, 0.3f, 0.0f );
        float3 LightDir = m_pDirLightOrienationCamera->GetLook() * -1;
        float fRotationScaler = ( LightDir.y > +0.2f ) ? 50.f : 1.f;
        float4x4 RotationMatrix = float4x4RotationAxis(RotationAxis, 0.02f * (float)deltaSeconds * fRotationScaler);
        LightOrientationMatrix = LightOrientationMatrix * RotationMatrix;
        m_pDirLightOrienationCamera->SetParentMatrix(LightOrientationMatrix);
    }

    float dt = (float)ElapsedTime;
    if (m_Animate && dt > 0 && dt < 0.2f)
    {
        float3 axis;
        float angle = 0;
        AxisAngleFromRotation(axis, angle, m_SpongeRotation);
        if (length(axis) < 1.0e-6f) 
            axis[1] = 1;
        angle += m_AnimationSpeed * dt;
        if (angle >= 2.0f*FLOAT_PI)
            angle -= 2.0f*FLOAT_PI;
        else if (angle <= 0)
            angle += 2.0f*FLOAT_PI;
        m_SpongeRotation = RotationFromAxisAngle(axis, angle);
    }
#endif
    UpdateGUI();
}
void AtmosphereSample::Initialize(IRenderDevice *pDevice, IDeviceContext **ppContexts, Uint32 NumDeferredCtx, ISwapChain *pSwapChain)
{
    const auto& deviceCaps = pDevice->GetDeviceCaps();
    if(!deviceCaps.bComputeShadersSupported)
    {
        throw std::runtime_error("Compute shaders are required to run this sample");
    }

    SampleBase::Initialize(pDevice, ppContexts, NumDeferredCtx, pSwapChain);

    m_bIsDXDevice = deviceCaps.DevType == DeviceType::D3D11 ||  deviceCaps.DevType == DeviceType::D3D12;
    if( pDevice->GetDeviceCaps().DevType == DeviceType::OpenGLES )
    {
        m_uiShadowMapResolution = 512;
        m_PPAttribs.m_iFirstCascade = 2;
        m_PPAttribs.m_uiSingleScatteringMode = SINGLE_SCTR_MODE_LUT;
        m_TerrainRenderParams.m_iNumShadowCascades = 4;
        m_TerrainRenderParams.m_iNumRings = 10;
        m_TerrainRenderParams.m_TexturingMode = RenderingParams::TM_MATERIAL_MASK;
    }

    m_f4CustomRlghBeta = m_PPAttribs.m_f4CustomRlghBeta;
    m_f4CustomMieBeta = m_PPAttribs.m_f4CustomMieBeta;

	m_strRawDEMDataFile = "Terrain\\HeightMap.tif";
    m_strMtrlMaskFile = "Terrain\\Mask.png";
    m_strTileTexPaths[0] = "Terrain\\Tiles\\gravel_DM.dds";
    m_strTileTexPaths[1] = "Terrain\\Tiles\\grass_DM.dds";
    m_strTileTexPaths[2] = "Terrain\\Tiles\\cliff_DM.dds";
    m_strTileTexPaths[3] = "Terrain\\Tiles\\snow_DM.dds";
    m_strTileTexPaths[4] = "Terrain\\Tiles\\grassDark_DM.dds";
    m_strNormalMapTexPaths[0] = "Terrain\\Tiles\\gravel_NM.dds";
    m_strNormalMapTexPaths[1] = "Terrain\\Tiles\\grass_NM.dds";
    m_strNormalMapTexPaths[2] = "Terrain\\Tiles\\cliff_NM.dds";
    m_strNormalMapTexPaths[3] = "Terrain\\Tiles\\Snow_NM.jpg";
    m_strNormalMapTexPaths[4] = "Terrain\\Tiles\\grass_NM.dds";

    // Create data source
    try
    {
		m_pElevDataSource.reset( new ElevationDataSource(m_strRawDEMDataFile.c_str()) );
        m_pElevDataSource->SetOffsets(m_TerrainRenderParams.m_iColOffset, m_TerrainRenderParams.m_iRowOffset);
        m_fMinElevation = m_pElevDataSource->GetGlobalMinElevation() * m_TerrainRenderParams.m_TerrainAttribs.m_fElevationScale;
        m_fMaxElevation = m_pElevDataSource->GetGlobalMaxElevation() * m_TerrainRenderParams.m_TerrainAttribs.m_fElevationScale;
    }
    catch(const std::exception &)
    {
        LOG_ERROR("Failed to create elevation data source");
        return;
    }

	const Char *strTileTexPaths[EarthHemsiphere::NUM_TILE_TEXTURES], *strNormalMapPaths[EarthHemsiphere::NUM_TILE_TEXTURES];
	for(int iTile=0; iTile < _countof(strTileTexPaths); ++iTile )
    {
		strTileTexPaths[iTile] = m_strTileTexPaths[iTile].c_str();
        strNormalMapPaths[iTile] = m_strNormalMapTexPaths[iTile].c_str();
    }
    
    CreateUniformBuffer( pDevice, sizeof( CameraAttribs ), "Camera Attribs CB", &m_pcbCameraAttribs );
    CreateUniformBuffer( pDevice, sizeof( LightAttribs ), "Light Attribs CB", &m_pcbLightAttribs );

    const auto &SCDesc = pSwapChain->GetDesc();
    m_pLightSctrPP.reset( new LightSctrPostProcess(m_pDevice, m_pImmediateContext, SCDesc.ColorBufferFormat, SCDesc.DepthBufferFormat, TEX_FORMAT_R11G11B10_FLOAT) );
    auto *pcMediaScatteringParams = m_pLightSctrPP->GetMediaAttribsCB();

    m_EarthHemisphere.Create(m_pElevDataSource.get(), 
                             m_TerrainRenderParams, 
                             m_pDevice, 
                             m_pImmediateContext, 
                             m_strMtrlMaskFile.c_str(), 
                             strTileTexPaths, 
                             strNormalMapPaths, 
                             m_pcbCameraAttribs,
                             m_pcbLightAttribs,
                             pcMediaScatteringParams );

    CreateShadowMap();

    // Create a tweak bar
    TwBar *bar = TwNewBar("Settings");
    TwDefine(" GLOBAL fontsize=3 ");
    int barSize[2] = {300, 900};
#ifdef ANDROID
    barSize[0] = 800;
    barSize[1] = 1000;
#endif
    TwSetParam(bar, NULL, "size", TW_PARAM_INT32, 2, barSize);

    // Add variables to the tweak bar
#if 0
    float3 axis(-1, 1, 0);
    m_SpongeRotation = RotationFromAxisAngle(axis, FLOAT_PI/4);
    TwAddVarRW(bar, "Rotation", TW_TYPE_QUAT4F, &m_SpongeRotation, "opened=true axisz=-z group=Sponge");
#endif

    TwAddVarRW(bar, "FPS", TW_TYPE_FLOAT, &m_fFPS, "readonly=true");

    TwAddVarRW(bar, "Light direction", TW_TYPE_DIR3F, &m_f3LightDir, "opened=true axisz=-z showval=false");
    TwAddVarRW(bar, "Camera direction", TW_TYPE_DIR3F, &m_f3CameraDir, "opened=true axisz=-z showval=false");
    TwAddVarRW( bar, "Camera altitude", TW_TYPE_FLOAT, &m_f3CameraPos.y, "min=2000 max=100000 step=100 keyincr=PGUP keydecr=PGDOWN" );

    // Shadows
    {
        // Define a new enum type for the tweak bar
        TwEnumVal ShadowMapRes[] = // array used to describe the shadow map resolution
        {
            { 512, "512" },
            { 1024, "1024" },
            { 2048, "2048" },
            { 4096, "4096" }
        };
        TwType modeType = TwDefineEnum( "Shadow Map Resolution", ShadowMapRes, _countof( ShadowMapRes ) );  // create a new TwType associated to the enum defined by the ShadowMapRes array
        TwAddVarCB( bar, "Shadow map resolution", modeType, SetShadowMapResCB, GetShadowMapResCB, this, "group=Shadows" );

        TwAddVarRW( bar, "Show cascades", TW_TYPE_BOOLCPP, &m_bVisualizeCascades, "group=Shadows" );
        TwAddVarRW( bar, "Partitioning factor", TW_TYPE_FLOAT, &m_fCascadePartitioningFactor, "min=0 max=1 step=0.01 group=Shadows" );
        TwAddVarRW( bar, "Find best cascade", TW_TYPE_BOOLCPP, &m_TerrainRenderParams.m_bBestCascadeSearch, "group=Shadows" );
        TwAddVarRW( bar, "Smooth shadows", TW_TYPE_BOOLCPP, &m_TerrainRenderParams.m_bSmoothShadows, "group=Shadows" );
        TwAddVarCB( bar, "Num cascades", TW_TYPE_INT32, SetNumCascadesCB, GetNumCascadesCB, this, "min=1 max=8 group=Shadows" );
    }

    TwAddVarRW( bar, "Enable Light Scattering", TW_TYPE_BOOLCPP, &m_bEnableLightScattering, "" );

    // Light scattering GUI controls
    {
        TwAddVarRW( bar, "Enable light shafts", TW_TYPE_BOOLCPP, &m_PPAttribs.m_bEnableLightShafts, "group=Scattering" );

        // Define a new enum type for the tweak bar
        TwEnumVal LightSctrTech[] = // array used to describe the shadow map resolution
        {
            { LIGHT_SCTR_TECHNIQUE_EPIPOLAR_SAMPLING, "Epipolar" },
            { LIGHT_SCTR_TECHNIQUE_BRUTE_FORCE, "Brute force" }
        };
        TwType LightSctrTechType = TwDefineEnum( "Light scattering tech", LightSctrTech, _countof( LightSctrTech ) );
        TwAddVarRW( bar, "Light scattering tech", LightSctrTechType, &m_PPAttribs.m_uiLightSctrTechnique, "group=Scattering" );

        TwEnumVal Pow2Values[] =
        {
            { 1, "1" },
            { 2, "2" },
            { 4, "4" },
            { 8, "8" },
            { 16, "16" },
            { 32, "32" },
            { 64, "64" },
            { 128, "128" },
            { 256, "256" },
            { 512, "512" },
            { 1024, "1024" },
            { 2048, "2048" }
        };
        TwType BigPow2Enum = TwDefineEnum( "Large powers of two", Pow2Values + 7, 5 );
        TwAddVarRW( bar, "NumSlices", BigPow2Enum, &m_PPAttribs.m_uiNumEpipolarSlices, "group=Scattering label=\'Num slices\'" );
        TwAddVarRW( bar, "MaxSamples", BigPow2Enum, &m_PPAttribs.m_uiMaxSamplesInSlice, "group=Scattering label=\'Max samples\'" );
        TwType SmallPow2Enum = TwDefineEnum( "Small powers of two", Pow2Values+2, 5 );
        TwAddVarRW( bar, "IntialStep", SmallPow2Enum, &m_PPAttribs.m_uiInitialSampleStepInSlice, "group=Scattering label=\'Initial step\'" );
        
        TwAddVarRW( bar, "ShowSampling", TW_TYPE_BOOLCPP, &m_PPAttribs.m_bShowSampling, "group=Scattering label=\'Show Sampling\'" );
        TwAddVarRW( bar, "RefinementThreshold", TW_TYPE_FLOAT, &m_PPAttribs.m_fRefinementThreshold, "group=Scattering label=\'Refinement Threshold\' min=0.01 max=0.5 step=0.01" );
        TwAddVarRW( bar, "1DMinMaxOptimization", TW_TYPE_BOOLCPP, &m_PPAttribs.m_bUse1DMinMaxTree, "group=Scattering label=\'Use 1D min/max trees\'" );
        TwAddVarRW( bar, "OptimizeSampleLocations", TW_TYPE_BOOLCPP, &m_PPAttribs.m_bOptimizeSampleLocations, "group=Scattering label=\'Optimize Sample Locations\'" );
        TwAddVarRW( bar, "CorrectScattering", TW_TYPE_BOOLCPP, &m_PPAttribs.m_bCorrectScatteringAtDepthBreaks, "group=Scattering label=\'Correct Scattering At Depth Breaks\'" );
        TwAddVarRW( bar, "ShowDepthBreaks", TW_TYPE_BOOLCPP, &m_PPAttribs.m_bShowDepthBreaks, "group=Scattering label=\'Show Depth Breaks\'" );
        TwAddVarRW( bar, "LightingOnly", TW_TYPE_BOOLCPP, &m_PPAttribs.m_bShowLightingOnly, "group=Scattering label=\'Lighting Only\'" );
        //TwAddVarRW( bar, "ScatteringScale", TW_TYPE_FLOAT, &m_fScatteringScale, "group=Scattering label=\'Scattering scale\' min=0 max=2 step=0.1" );

        TwAddVarRW( bar, "NumIntegrationSteps", TW_TYPE_UINT32, &m_PPAttribs.m_uiInstrIntegralSteps, "min=5 max=100 step=5 group=Advanced label=\'Num Integrtion Steps\'" );
        TwDefine( "Settings/Advanced group=Scattering" );

        {
            TwType EpipoleSamplingDensityEnum = TwDefineEnum( "Epipole sampling density enum", Pow2Values, 4 );
            TwAddVarRW( bar, "EpipoleSamplingDensity", EpipoleSamplingDensityEnum, &m_PPAttribs.m_uiEpipoleSamplingDensityFactor, "group=Advanced label=\'Epipole sampling density\'" );
        }
        {
            TwEnumVal SinglSctrMode[] =
            {
                { SINGLE_SCTR_MODE_NONE, "None" },
                { SINGLE_SCTR_MODE_INTEGRATION, "Integration" },
                { SINGLE_SCTR_MODE_LUT, "Look-up table" }
            };
            TwType SinglSctrModeEnum = TwDefineEnum( "Single scattering mode enum", SinglSctrMode, _countof(SinglSctrMode) );
            TwAddVarRW( bar, "SingleSctrMode", SinglSctrModeEnum, &m_PPAttribs.m_uiSingleScatteringMode, "group=Advanced label=\'Single scattering\'" );
        }
        {
            TwEnumVal MultSctrMode[] =
            {
                { MULTIPLE_SCTR_MODE_NONE, "None" },
                { MULTIPLE_SCTR_MODE_UNOCCLUDED, "Unoccluded" },
                { MULTIPLE_SCTR_MODE_OCCLUDED, "Occluded" }
            };
            TwType MultSctrModeEnum = TwDefineEnum( "Higher-order scattering mode enum", MultSctrMode, _countof( MultSctrMode ) );
            TwAddVarRW( bar, "MultipleSctrMode", MultSctrModeEnum, &m_PPAttribs.m_uiMultipleScatteringMode, "group=Advanced label=\'Higher-order scattering\'" );
        }
        {
            TwEnumVal CascadeProcessingMode[] =
            {
                { CASCADE_PROCESSING_MODE_SINGLE_PASS, "Single pass" },
                { CASCADE_PROCESSING_MODE_MULTI_PASS, "Multi-pass" },
                { CASCADE_PROCESSING_MODE_MULTI_PASS_INST, "Multi-pass inst" }
            };
            TwType CascadeProcessingModeEnum = TwDefineEnum( "Cascade processing mode enum", CascadeProcessingMode, _countof( CascadeProcessingMode ) );
            TwAddVarRW( bar, "CascadeProcessingMode", CascadeProcessingModeEnum, &m_PPAttribs.m_uiCascadeProcessingMode, "group=Advanced label=\'Cascade processing mode\'" );
        }
        TwAddVarRW( bar, "FirstCascadeToRayMarch", TW_TYPE_INT32, &m_PPAttribs.m_iFirstCascade, "min=0 max=8 step=1 group=Advanced label=\'Start cascade\'" );
        TwAddVarRW( bar, "Is32BitMinMaxShadowMap", TW_TYPE_BOOLCPP, &m_PPAttribs.m_bIs32BitMinMaxMipMap, "group=Advanced label=\'Use 32-bit float min/max SM\'" );
        {
            TwEnumVal RefinementCriterion[] =
            {
                { REFINEMENT_CRITERION_DEPTH_DIFF, "Depth difference" },
                { REFINEMENT_CRITERION_INSCTR_DIFF, "Scattering difference" }
            };
            TwType CascadeProcessingModeEnum = TwDefineEnum( "Refinement criterion enum", RefinementCriterion, _countof( RefinementCriterion ) );
            TwAddVarRW( bar, "RefinementCriterion", CascadeProcessingModeEnum, &m_PPAttribs.m_uiRefinementCriterion, "group=Advanced label=\'Refinement criterion\'" );
        }
        {
            TwEnumVal ExtinctionEvalMode[] =
            {
                { EXTINCTION_EVAL_MODE_PER_PIXEL, "Per pixel" },
                { EXTINCTION_EVAL_MODE_EPIPOLAR, "Epipolar" }
            };
            TwType ExtinctionEvalModeEnum = TwDefineEnum( "Extinction eval mode enum", ExtinctionEvalMode, _countof( ExtinctionEvalMode ) );
            TwAddVarRW( bar, "ExtinctionEval", ExtinctionEvalModeEnum, &m_PPAttribs.m_uiExtinctionEvalMode, "group=Advanced label=\'Extinction eval mode\'" );
        }
        TwAddVarRW( bar, "AerosolDensity", TW_TYPE_FLOAT, &m_PPAttribs.m_fAerosolDensityScale, "group=Advanced label=\'Aerosol density\' min=0.1 max=5.0 step=0.1" );
        TwAddVarRW( bar, "AerosolAbsorption", TW_TYPE_FLOAT, &m_PPAttribs.m_fAerosolAbsorbtionScale, "group=Advanced label=\'Aerosol absorption\' min=0.0 max=5.0 step=0.1" );
        TwAddVarRW( bar, "UseCustomSctrCoeffs", TW_TYPE_BOOLCPP, &m_PPAttribs.m_bUseCustomSctrCoeffs, "group=Advanced label=\'Use custom scattering coeffs\'" );

        #define RLGH_COLOR_SCALE 5e-5f
        #define MIE_COLOR_SCALE 5e-5f
        TwAddVarCB(bar, "RayleighColor", TW_TYPE_COLOR4F, 
            []( const void *value, void * clientData )
            {
                AtmosphereSample *pTheSample = reinterpret_cast<AtmosphereSample*>( clientData );
                pTheSample->m_f4CustomRlghBeta = *reinterpret_cast<const float4 *>(value) * RLGH_COLOR_SCALE;
                if( (float3&)pTheSample->m_f4CustomRlghBeta == float3( 0, 0, 0 ) )
                {
                    pTheSample->m_f4CustomRlghBeta = float4( 1, 1, 1, 1 ) * RLGH_COLOR_SCALE / 255.f;
                }
            },
            [](void *value, void * clientData)
            {
                AtmosphereSample *pTheSample = reinterpret_cast<AtmosphereSample*>( clientData );
                float4 RlghColor = pTheSample->m_f4CustomRlghBeta / RLGH_COLOR_SCALE;
                RlghColor.w = 1;
                *reinterpret_cast<float4*>(value) = RlghColor;
            },
            this, "group=Advanced label=\'Rayleigh color\' colormode=rgb");

        TwAddVarCB(bar, "MieColor", TW_TYPE_COLOR4F, 
            []( const void *value, void * clientData )
            {
                AtmosphereSample *pTheSample = reinterpret_cast<AtmosphereSample*>( clientData );
                pTheSample->m_f4CustomMieBeta = *reinterpret_cast<const float4 *>(value) * MIE_COLOR_SCALE;
                if( (float3&)pTheSample->m_f4CustomMieBeta == float3( 0, 0, 0 ) )
                {
                    pTheSample->m_f4CustomMieBeta = float4( 1, 1, 1, 1 ) * MIE_COLOR_SCALE / 255.f;
                }
            },
            [](void *value, void * clientData)
            {
                AtmosphereSample *pTheSample = reinterpret_cast<AtmosphereSample*>( clientData );
                float4 MieColor = pTheSample->m_f4CustomMieBeta / MIE_COLOR_SCALE;
                MieColor.w = 1;
                *reinterpret_cast<float4*>(value) = MieColor;
            },
            this, "group=Advanced label=\'Mie color\' colormode=rgb");
        #undef RLGH_COLOR_SCALE
        #undef MIE_COLOR_SCALE
        TwAddButton(bar, "UpdateCoeffsBtn", 
                    [](void *clientData)
                    {
                        AtmosphereSample *pTheSample = reinterpret_cast<AtmosphereSample*>( clientData );
                        pTheSample->m_PPAttribs.m_f4CustomRlghBeta = pTheSample->m_f4CustomRlghBeta;
                        pTheSample->m_PPAttribs.m_f4CustomMieBeta = pTheSample->m_f4CustomMieBeta;
                    }, 
                    this, "group=Advanced label=\'Update coefficients\'");
    }

    // Tone mapping GUI controls
    {
        {
            TwEnumVal ToneMappingMode[] =
            {
                {TONE_MAPPING_MODE_EXP,          "Exp"},
                {TONE_MAPPING_MODE_REINHARD,     "Reinhard"},
                {TONE_MAPPING_MODE_REINHARD_MOD, "Reinhard Mod"},
                {TONE_MAPPING_MODE_UNCHARTED2,   "Uncharted 2"},
                {TONE_MAPPING_FILMIC_ALU,        "Filmic ALU"},
                {TONE_MAPPING_LOGARITHMIC,       "Logarithmic"},
                {TONE_MAPPING_ADAPTIVE_LOG,      "Adaptive log"}
            };
            TwType ToneMappingModeEnum = TwDefineEnum( "Tone mapping mode enum", ToneMappingMode, _countof( ToneMappingMode ) );
            TwAddVarRW( bar, "ToneMappingMode", ToneMappingModeEnum, &m_PPAttribs.m_uiToneMappingMode, "group=ToneMapping label=\'Mode\'" );
        }
        TwAddVarRW( bar, "WhitePoint", TW_TYPE_FLOAT, &m_PPAttribs.m_fWhitePoint, "group=ToneMapping label=\'White point\' min=0.01 max=10.0 step=0.1" );
        TwAddVarRW( bar, "LumSaturation", TW_TYPE_FLOAT, &m_PPAttribs.m_fLuminanceSaturation, "group=ToneMapping label=\'Luminance saturation\' min=0.01 max=2.0 step=0.1" );
        TwAddVarRW( bar, "MiddleGray", TW_TYPE_FLOAT, &m_PPAttribs.m_fMiddleGray, "group=ToneMapping label=\'Middle Gray\' min=0.01 max=1.0 step=0.01" );
        TwAddVarRW( bar, "AutoExposure", TW_TYPE_BOOLCPP, &m_PPAttribs.m_bAutoExposure, "group=ToneMapping label=\'Auto exposure\'" );
        TwAddVarRW( bar, "LightAdaptation", TW_TYPE_BOOLCPP, &m_PPAttribs.m_bLightAdaptation, "group=ToneMapping label=\'Light adaptation\'" );
    }

    const auto& RG16UAttribs = pDevice->GetTextureFormatInfoExt( TEX_FORMAT_RG16_UNORM );
    const auto& RG32FAttribs = pDevice->GetTextureFormatInfoExt( TEX_FORMAT_RG32_FLOAT );
    bool RG16USupported = RG16UAttribs.Supported && RG16UAttribs.ColorRenderable;
    bool RG32FSupported = RG32FAttribs.Supported && RG32FAttribs.ColorRenderable;
    if( !RG16USupported && !RG32FSupported )
    {
        int32_t IsVisible = 0;
        TwSetParam( bar, "1DMinMaxOptimization", "visible", TW_PARAM_INT32, 1, &IsVisible );
        m_PPAttribs.m_bUse1DMinMaxTree = FALSE;
    }

    if( !RG16USupported || !RG32FSupported )
    {
        int32_t IsVisible = 0;
        TwSetParam( bar, "Is32BitMinMaxShadowMap", "visible", TW_PARAM_INT32, 1, &IsVisible );

        if( RG16USupported && !RG32FSupported )
            m_PPAttribs.m_bIs32BitMinMaxMipMap = FALSE;

        if( !RG16USupported && RG32FSupported )
            m_PPAttribs.m_bIs32BitMinMaxMipMap = TRUE;
    }
}
// Initialize the 3D objects & shaders
HRESULT InitScene()
{
    HRESULT hr;

    // Define the input layout
    D3D11_INPUT_ELEMENT_DESC layout[] =
    {
        { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(Vertex, Position), D3D11_INPUT_PER_VERTEX_DATA, 0 },
        { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(Vertex, Normal), D3D11_INPUT_PER_VERTEX_DATA, 0 },
        { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, offsetof(Vertex, AmbientColor), D3D11_INPUT_PER_VERTEX_DATA, 0 }
    };
    hr = g_D3DDev->CreateInputLayout(layout, sizeof(layout)/sizeof(layout[0]), g_MainVS, sizeof(g_MainVS), &g_InputLayout);
    if (FAILED(hr))
        return hr;

    // Set the input layout
    g_D3DDevCtx->IASetInputLayout(g_InputLayout);

    // Create shaders
    hr = g_D3DDev->CreateVertexShader(g_MainVS, sizeof(g_MainVS), NULL, &g_VertexShader);
    if (FAILED(hr))
        return hr;
    hr = g_D3DDev->CreatePixelShader(g_MainPS, sizeof(g_MainPS), NULL, &g_PixelShader);
    if (FAILED(hr))
        return hr;

    // Set shaders
    g_D3DDevCtx->VSSetShader(g_VertexShader, NULL, 0);
    g_D3DDevCtx->PSSetShader(g_PixelShader, NULL, 0);

    // Create vertex and index buffers
    hr = BuildSponge(g_SpongeLevel, g_SpongeAO);
    if (FAILED(hr))
        return hr;

    // Create constant buffer
    D3D11_BUFFER_DESC bd;
    bd.Usage = D3D11_USAGE_DYNAMIC;
    bd.ByteWidth = sizeof(ShaderConstants);
    bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    bd.MiscFlags = 0;
    bd.StructureByteStride = 0;
    hr = g_D3DDev->CreateBuffer(&bd, NULL, &g_ConstantBuffer);
    if (FAILED(hr))
        return hr;

    // Blend state
    D3D11_BLEND_DESC bsd;
    bsd.AlphaToCoverageEnable = FALSE;
    bsd.IndependentBlendEnable = FALSE;
    for (int i = 0; i < 8; i++)
    {
        bsd.RenderTarget[i].BlendEnable = TRUE;
        bsd.RenderTarget[i].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
        bsd.RenderTarget[i].SrcBlend = D3D11_BLEND_SRC_ALPHA;
        bsd.RenderTarget[i].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
        bsd.RenderTarget[i].BlendOp =  D3D11_BLEND_OP_ADD;
        bsd.RenderTarget[i].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
        bsd.RenderTarget[i].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
        bsd.RenderTarget[i].BlendOpAlpha = D3D11_BLEND_OP_ADD;
    }
    g_D3DDev->CreateBlendState(&bsd, &g_BlendState);
    float blendFactors[4] = { 1, 1, 1, 1 };
    g_D3DDevCtx->OMSetBlendState(g_BlendState, blendFactors, 0xffffffff);

    // Depth-stencil state
    D3D11_DEPTH_STENCILOP_DESC od;
    od.StencilFunc = D3D11_COMPARISON_ALWAYS;
    od.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    od.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    od.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP;
    D3D11_DEPTH_STENCIL_DESC dsd;
    dsd.DepthEnable = TRUE;
    dsd.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
    dsd.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
    dsd.StencilEnable = FALSE;
    dsd.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK;
    dsd.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK;
    dsd.FrontFace = od;
    dsd.BackFace = od;
    g_D3DDev->CreateDepthStencilState(&dsd, &g_DepthStencilState);
    g_D3DDevCtx->OMSetDepthStencilState(g_DepthStencilState, 0);

    // Rasterizer state
    D3D11_RASTERIZER_DESC rs;
    ZeroMemory(&rs, sizeof(rs));
    rs.FillMode = D3D11_FILL_SOLID;
    rs.CullMode = D3D11_CULL_NONE;
    rs.MultisampleEnable = (g_SwapChainDesc.SampleDesc.Count > 0);
    g_D3DDev->CreateRasterizerState(&rs, &g_RasterState);
    g_D3DDevCtx->RSSetState(g_RasterState);

    // Init model rotation
    Vector3 axis = {-1, 1, 0};
    g_SpongeRotation = RotationFromAxisAngle(axis, FLOAT_PI/4);

    return S_OK;
}