#include "i_render.h"
#include "renderer.h"
#include "ui/i_ui.h"
#include "font.h"
#include "particle_engine.h"
#include "render_target.h"
#include "platform/settings.h"
#include "sprite_phase_cache.h"
#include "engine/engine.h"
#include "engine/activity_system.h"
#include "light_system.h"
#include "core/i_light_component.h"
#include "core/i_position_component.h"
#include <boost/assign.hpp>
#include "engine/system_suppressor.h"

namespace engine {
namespace {
double GetCamSize( Camera* cam )
{
    static float const activityMult = Settings::Get().GetFloat( "activity.camera_multiplier", 0.5 );
    auto const& view = cam->VisibleRegion();
    return std::max( view.z - view.x, view.w - view.y ) * activityMult;
}
enum ShownLayer
{
    Normal,
    SpriteCache,
    BumpMap,
    PostprocessMask,
    ShadowUnwrap,
    Shadows,
    FsShadows,
    Lights,
    TopLights,
    AllLights,
};
ShownLayer shownLayer()
{
    static std::string const layer = Settings::Get().GetStr( "graphics.shown_layer", "normal" );
    static std::map<std::string,ShownLayer> const layers = {
        { "normal", Normal },
        { "sprite_cache", SpriteCache },
        { "bump_map", BumpMap },
        { "postprocess_mask", PostprocessMask },
        { "shadow_unwrap", ShadowUnwrap },
        { "fsshadows", FsShadows },
        { "shadows", Shadows },
        { "lights", Lights },
        { "top_lights", TopLights },
        { "all_lights", AllLights },
    };
    auto i = layers.find( layer );
    return i == layers.end() ? Normal : i->second;
}
} // namespace anonymous

RendererSystem::RendererSystem()
    : mWorldProjector( -1000.0f, 1000.0f )
    , mUiProjector( 100.0f, 0.0f, Projection::VM_Fixed )
    , mCamera( mWorldProjector )
    , mUi( Ui::Get() )
    , mDecalEngine( DecalEngine::Get() )
    , mShaderManager( ShaderManager::Get() )
    , mMouseRawPos( 0 )
    , mMouseWorldPos( 0 )
{
    Font::Get();
    mMouseMoveId = EventServer<ScreenMouseMoveEvent>::Get().Subscribe( boost::bind( &RendererSystem::OnMouseMoveEvent, this, _1 ) );
    mMousePressId = EventServer<ScreenMousePressEvent>::Get().Subscribe( boost::bind( &RendererSystem::OnMousePressEvent, this, _1 ) );
    mMouseReleaseId = EventServer<ScreenMouseReleaseEvent>::Get().Subscribe( boost::bind( &RendererSystem::OnMouseReleaseEvent, this, _1 ) );
    core::ActivityTraits::SetActorScaleFunc( std::bind( &RenderableRepo::GetMaxScale, &RenderableRepo::Get(), std::placeholders::_1 ) );
    core::ActivityTraits::SetActiveSizeFunc( std::bind( &GetCamSize, &mCamera ) );
    Init();
}

RendererSystem::~RendererSystem()
{

}

void RendererSystem::SetupIdentity()
{
    static glm::mat4 const id(1.0);
    mShaderManager.UploadGlobalData( GlobalShaderData::WorldProjection, id );
    mShaderManager.UploadGlobalData( GlobalShaderData::WorldCamera, id );
// NOTE: this function is called before world rendering
// and the "original" inverse matrix is required there, not the identity-inverse
// to get the raw world coords from frag coords
//    mShaderManager.UploadGlobalData( GlobalShaderData::InverseProjection, id );
}

void RendererSystem::SetupRenderer( const Camera& cam, float Scale )
{
    auto const& proj = cam.GetProjection();
    Viewport const& Vp = proj.GetViewport();
    glViewport( Vp.X, Vp.Y, Vp.Width * Scale, Vp.Height * Scale );

    mShaderManager.UploadGlobalData( GlobalShaderData::WorldProjection, proj.GetMatrix() );
    mShaderManager.UploadGlobalData( GlobalShaderData::WorldCamera, cam.GetView() );
    mShaderManager.UploadGlobalData( GlobalShaderData::InverseProjection, glm::inverse( cam.GetView() ) * glm::inverse( proj.GetMatrix() ) );
    mShaderManager.UploadGlobalData( GlobalShaderData::Resolution, glm::vec2( Vp.Width * Scale, Vp.Height * Scale ) );
}

void RendererSystem::OnMouseMoveEvent( const ScreenMouseMoveEvent& Event )
{
    glm::vec3 EvtPos( Event.Pos.x, Event.Pos.y, 0 );
    mMouseRawPos = EvtPos;
    glm::vec3 UiEvtPos = mUiProjector.Unproject( EvtPos );
    UiMouseMoveEvent UiEvt( glm::vec2( UiEvtPos.x, UiEvtPos.y ) );
    if( EventServer<UiMouseMoveEvent>::Get().SendEvent( UiEvt ) )
    {
        return;
    }
}

void RendererSystem::OnMousePressEvent( const ScreenMousePressEvent& Event )
{
    glm::vec3 EvtPos( Event.Pos.x, Event.Pos.y, 0 );
    glm::vec3 UiEvtPos = mUiProjector.Unproject( EvtPos );
    UiMousePressEvent UiEvt( glm::vec2( UiEvtPos.x, UiEvtPos.y ), Event.Button );
    if( EventServer<UiMousePressEvent>::Get().SendEvent( UiEvt ) )
    {
        return;
    }

    glm::vec3 WorldEvtPos( mCamera.GetInverseView()*glm::vec4( mWorldProjector.Unproject( EvtPos ), 1.0 ) );

    WorldMousePressEvent WorldEvt( glm::vec2( WorldEvtPos.x, WorldEvtPos.y ), Event.Button );
    EventServer<WorldMousePressEvent>::Get().SendEvent( WorldEvt );
}

void RendererSystem::OnMouseReleaseEvent( const ScreenMouseReleaseEvent& Event )
{
    glm::vec3 EvtPos( Event.Pos.x, Event.Pos.y, 0 );
    glm::vec3 UiEvtPos = mUiProjector.Unproject( EvtPos );
    UiMouseReleaseEvent UiEvt( glm::vec2( UiEvtPos.x, UiEvtPos.y ), Event.Button );
    if( EventServer<UiMouseReleaseEvent>::Get().SendEvent( UiEvt ) )
    {
        return;
    }

    glm::vec3 WorldEvtPos( mCamera.GetInverseView()*glm::vec4( mWorldProjector.Unproject( EvtPos ), 1.0 ) );
    WorldMouseReleaseEvent WorldEvt( glm::vec2( WorldEvtPos.x, WorldEvtPos.y ), Event.Button );
    EventServer<WorldMouseReleaseEvent>::Get().SendEvent( WorldEvt );
}

void RendererSystem::Init()
{
    glEnable( GL_TEXTURE_2D );
    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
    glEnable( GL_BLEND );
}

namespace {
std::set<int32_t> blacklistedPostprocessors()
{
    static bool inited = false;
    static std::set<int32_t> rv;
    if( inited )
    {
        return rv;
    }
    inited = true;
    Json::Value bl = Settings::Get().Resolve( "graphics.pp_blacklist" );
    if( !bl.isArray() )
    {
        return rv;
    }
    for( auto it : bl )
    {
        rv.insert( AutoId( it.asString() ) );
    }
    return rv;
}
void getActiveActorProps( std::set<int32_t>& shadowLevels, std::set<int32_t>& postprocessorIds )
{
    static auto activityS = engine::Engine::Get().GetSystem<engine::ActivitySystem>();
    auto const& Lst = activityS->GetActiveActors();
    std::set<int32_t> pps;
    for( auto i = Lst.begin(), e = Lst.end(); i != e; ++i )
    {
        const Actor& Object = **i;
        Opt<IRenderableComponent> renderableC( Object.Get<IRenderableComponent>() );
        if( !renderableC.IsValid() )
        {
            continue;
        }
        shadowLevels.insert( renderableC->GetCastShadow() );
        shadowLevels.insert( renderableC->GetReceiveShadow() );
        auto const& procs = renderableC->GetPostProcessIds();
        pps.insert( procs.begin(), procs.end() );
    }
    shadowLevels.erase( 0 );
    static auto const bls = blacklistedPostprocessors();
    std::set_difference( pps.begin(), pps.end(), bls.begin(), bls.end(), std::inserter( postprocessorIds, postprocessorIds.end() ) );
}
bool selectBloodReceivers( IRenderableComponent const& renderableC )
{
    return renderableC.GetReceiveBlood() != 0;
}
bool selectNonBloodReceivers( IRenderableComponent const& renderableC )
{
    return renderableC.GetReceiveBlood() == 0;
}
bool selectShadowReceivers( IRenderableComponent const& renderableC, int32_t shadowLevel )
{
    return renderableC.GetReceiveBlood() == 0 && renderableC.GetReceiveShadow() == shadowLevel;
}

bool selectShadowCasters( IRenderableComponent const& renderableC, int32_t shadowLevel )
{
    return renderableC.GetReceiveBlood() == 0 && renderableC.GetCastShadow() == shadowLevel;
}

bool selectShadowCastersExcept( IRenderableComponent const& renderableC, int32_t shadowLevel, IRenderableComponent const* except )
{
    return &renderableC != except && renderableC.GetReceiveBlood() == 0 && renderableC.GetCastShadow() == shadowLevel;
}
struct LightDesc
{
    Opt<ILightComponent> lightC;
    Opt<IRenderableComponent> renderableC;
    glm::vec2 center;
    GLfloat orientation;
};
std::vector<LightDesc> getLights()
{
    static auto lightS = engine::Engine::Get().GetSystem<render::LightSystem>();
    std::vector<LightDesc> lds;
    lds.push_back(
        std::move( LightDesc{ Opt<ILightComponent>(),
        Opt<IRenderableComponent>(),
        glm::vec2( std::numeric_limits<double>::max(), std::numeric_limits<double>::max() ),
        0.0 } )
        );
    for( auto light : lightS->GetActiveLights() )
    {
        auto positionC = light->Get<IPositionComponent>();
        glm::vec2 center( std::numeric_limits<double>::max(), std::numeric_limits<double>::max() );
        GLfloat heading = 0.0;
        if( positionC.IsValid() )
        {
            center = glm::vec2( positionC->GetX(), positionC->GetY() );
            heading = positionC->GetOrientation();
        }
        lds.push_back(
            std::move( LightDesc{ light->Get<ILightComponent>(),
            light->Get<IRenderableComponent>(),
            center,
            heading } )
            );
    }
    return lds;
}
} // namespace anonymous

void RendererSystem::Update( double DeltaTime )
{
    using render::RenderTargetProps;
    perf::Timer_t method;
    method.Log( "start render" );
    bool const isSuppressed = engine::SystemSuppressor::Get().IsSuppressed();
    static render::SpritePhaseCache& cache( render::SpritePhaseCache::Get() );
    render::RenderTarget& rt( render::RenderTarget::Get() );
    SendWorldMouseMoveEvent();

    if( isSuppressed )
    {
        glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
        SetupIdentity();
        Viewport const& Vp = mUiProjector.GetViewport();
        glViewport( Vp.X, Vp.Y, Vp.Width, Vp.Height );
        mShaderManager.UploadGlobalData( GlobalShaderData::Resolution, glm::vec2( Vp.Width, Vp.Height ) );
        rt.SetTargetScreen();
        mUiRenderer.Draw( mUi.GetRoot(), mUiProjector.GetMatrix() );
        mMouseRenderer.Draw( mTextSceneRenderer );
        mTextSceneRenderer.Draw();
        return;
    }

    render::ParticleEngine::Get().Update( DeltaTime );
    mCamera.Update();
    SetupRenderer( mCamera );
    // render world
    // allocate render target ids
    static uint32_t const world = rt.GetFreeId();
    static uint32_t const shadowOutline = rt.GetFreeId();
    static uint32_t const shadowDedicatedOutline = rt.GetFreeId();
    static uint32_t const shadowUnwrap = rt.GetFreeId();
    static uint32_t const shadowDedicatedUnwrap = rt.GetFreeId();
    static uint32_t const lightsLayer = rt.GetFreeId();
    static uint32_t const lightsDedicated = rt.GetFreeId();
    static uint32_t const worldBumped = rt.GetFreeId();
    static uint32_t const worldEffects = rt.GetFreeId();
    static uint32_t const worldPostProcess = rt.GetFreeId();
    static uint32_t const worldDedicatedPostProcess = rt.GetFreeId();
    static uint32_t const sunOutline = rt.GetFreeId();
    static uint32_t const sunDedicatedOutline = rt.GetFreeId();
    static uint32_t const cumulativeLight = rt.GetFreeId();
    static uint32_t const topcasters = rt.GetFreeId();
    static uint32_t const fullsizeshadows = rt.GetFreeId();

    static auto lightS = engine::Engine::Get().GetSystem<render::LightSystem>();
    auto const& lights = getLights();

    std::vector<Camera const*> cameras;
    std::vector<std::unique_ptr<Projection> > tempProjections;
    std::vector<std::unique_ptr<Camera> > tempCameras;
    cameras.push_back( &mCamera );
    // add cameras for lights
    for( auto const& light : lights )
    {
        GLfloat lightSize = light.lightC.IsValid() ? light.lightC->GetRadius() : 10.0;
        std::unique_ptr<Projection> proj( new Projection( -lightSize * 1.5, lightSize * 1.5 ) );
        std::unique_ptr<Camera> cam( new Camera( *proj ) );
        cam->SetCenter( light.center );
        cameras.push_back( cam.get() );
        tempProjections.push_back( std::move( proj ) );
        tempCameras.push_back( std::move( cam ) );
    }

    RenderTargetProps worldProps( mWorldProjector.GetViewport().Size(), {GL_RGBA, GL_RGB } );
    rt.SetTargetTexture( world, worldProps);
    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
    Scene& Scen( Scene::Get() );
    mPerfTimer.Log( "pre prepare" );
    mActorRenderer.Prepare( Scen, cameras, DeltaTime );
    mPerfTimer.Log( "post prepare" );
    mActorRenderer.Draw( &selectBloodReceivers );
    mDecalEngine.Draw();

    static bool const castShadows = Settings::Get().GetInt( "graphics.cast_shadows", 1 );
    mPerfTimer.Log( "pre shadow" );
    std::set<int32_t> shadowLevels, postProcessorIds;
    getActiveActorProps( shadowLevels, postProcessorIds );
    static int32_t lightsid( AutoId( "lights" ) );
    static int32_t unwrapid( AutoId( "shadow_unwrap" ) );
    static int32_t solidid( AutoId( "world_solid_objects" ) );
    static int32_t sunlight( AutoId( "sunlight" ) );
    static int32_t topcastersid( AutoId( "topcasters" ) );
    static int32_t lightmap( AutoId( "lightmap" ) );
    static int32_t mergelights( AutoId( "mergelights" ) );
    static float const shadowmult = Settings::Get().GetFloat( "graphics.shadow_scale", 0.3 );
    float maxShadow = lightS->GetMaxShadow();
    glm::vec2 lightVec = lightS->GetShadowVector();
    glm::vec4 ambientLight = lightS->GetAmbientLight();
    int numShadowSteps = ceil( std::max( std::abs( lightVec.x ), std::abs( lightVec.y ) ) / 10.0 );
    LL() << maxShadow << " (" << lightVec.x
        << " " << lightVec.y
        << ") ("
        << ambientLight.x << " "
        << ambientLight.y << " "
        << ambientLight.z << " "
        << ambientLight.w
        << ") "
        << numShadowSteps;
    if( castShadows != 0 )
    {
        rt.SetTargetTexture( cumulativeLight, RenderTargetProps( mWorldProjector.GetViewport().Size() * shadowmult, { GL_RGBA } ) );
        glClearColor( 1,1,1,1 );
        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );
        for( auto shadowLevel : shadowLevels )
        {
            bool topmost = shadowLevel == std::numeric_limits<int32_t>::max();
            uint32_t outline = topmost ? shadowOutline : shadowDedicatedOutline;
            uint32_t unwrap = topmost ? shadowUnwrap : shadowDedicatedUnwrap;
            uint32_t lightrl = topmost ? lightsLayer : lightsDedicated;
            uint32_t sunline = topmost ? sunOutline : sunDedicatedOutline;

            glBlendEquation( GL_FUNC_ADD );
            rt.SelectTargetTexture( world );
            SetupRenderer( mCamera );
            mActorRenderer.Draw( std::bind( &selectShadowReceivers, std::placeholders::_1, shadowLevel ) );

            rt.SetTargetTexture( lightrl, RenderTargetProps( mWorldProjector.GetViewport().Size() * shadowmult, { GL_RGBA, GL_RGBA } ) );
            rt.SelectTargetTexture( lightrl, true );

            // lightrl collects the lights, we have to init it to 0 - complete darkness
            // we use GL_MAX when drawing to it
            glClearColor( 0, 0, 0, 1 );
            glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );
            rt.SelectTargetTexture( lightrl );
            glBlendEquation( GL_MAX );

            // -- direct sunlight to outline
            // render the normal shadowcasters with a "tail" ( lightVec )
            rt.SetTargetTexture( sunline, RenderTargetProps( mCamera.GetProjection().GetViewport().Size() * shadowmult, { GL_RGBA4 } ) );
            SetupRenderer( mCamera, shadowmult );
            mActorRenderer.Draw(
                std::bind( &selectShadowCasters, std::placeholders::_1, shadowLevel),
                [&](ShaderManager& ShaderMgr)->void{
                    ShaderMgr.UploadData( "resolution", mCamera.GetProjection().GetViewport().Size() * shadowmult );
                    ShaderMgr.UploadData( "lightVec", lightVec );
                },
                numShadowSteps
            );
            // fill lights except outline
            // use the previously rendered sun outline to draw into the lightrl map
            // lightrl: r/g/b is the alpha from sunline
            // as GL_MAX uses rgb, no alpha
            SetupIdentity();
            rt.SelectTargetTexture( lightrl, true );
            mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( sunline ), sunlight,
                [&](ShaderManager& ShaderMgr)->void{
                    ShaderMgr.UploadData( "resolution", mCamera.GetProjection().GetViewport().Size() * shadowmult );
                    ShaderMgr.UploadData( "ambient", ambientLight );
                } );
            // direct sunlight end
            rt.SelectTargetTexture( lightrl );

            auto lightCamIt = tempCameras.begin();
            auto lightProjIt = tempProjections.begin();
            for( auto const& light : lights )
            {
                auto const& lightCam = **lightCamIt++;
                auto const& camProjection = **lightProjIt++;
                GLfloat lightSize = light.lightC.IsValid() ? light.lightC->GetRadius() : -1.0;
                glm::vec4 pos( light.center.x, light.center.y, 1, 1 );
                glm::vec4 sizePos( light.center.x + lightSize, light.center.y + lightSize, 1, 1 );
                GLfloat ori = light.orientation; // radians
                GLfloat aperture = ( light.lightC.IsValid() ? light.lightC->GetAperture() : 0 ) * 3.141592654 / 180.0;
                GLfloat fsaperture = ( light.lightC.IsValid() ? light.lightC->GetFullStrengthAperture() : 0 ) * 3.141592654 / 180.0;
                // lightPos4 is in player view space
                auto lightPos4 =  mCamera.GetProjection().GetMatrix() * mCamera.GetView() * pos;
                auto sizePos4 =  mCamera.GetProjection().GetMatrix() * mCamera.GetView() * sizePos;
                // create camera with max light range range, pos center
                // use that cam + world to render outline to small shadow map
                // use small shadow map to create 1d map
                // use that map + pos to render shadow layer
                rt.SetTargetTexture( outline, RenderTargetProps( lightCam.GetProjection().GetViewport().Size() * shadowmult, { GL_RGBA4, GL_RGB4 } ) );
                SetupRenderer( lightCam, shadowmult );
                mActorRenderer.Draw( std::bind( &selectShadowCastersExcept,
                            std::placeholders::_1,
                            shadowLevel,
                            light.renderableC.Get() ) );

                SetupIdentity();

                glm::vec2 shadowsize( lightCam.GetProjection().GetViewport().Size() * shadowmult );
                glm::vec2 uwsize( shadowsize.x, 1 );
                glm::vec2 lightPos = glm::vec2( lightPos4.x + 1, lightPos4.y + 1 ) / 2.0;
                glm::vec2 sizePos2 = glm::vec2( sizePos4.x + 1, sizePos4.y + 1 ) / 2.0;
                glm::vec2 lightPosInShadowTex( 0.5, 0.5 );
                // lightpos: 0..1 ^2 ( vagy screenen kivul )
                rt.SetTargetTexture( unwrap, RenderTargetProps( uwsize, { GL_RGBA } ) );
                mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( outline ), unwrapid,
                    [&](ShaderManager& ShaderMgr)->void{
                        ShaderMgr.UploadData( "resolution", shadowsize );
                        ShaderMgr.UploadData( "lightPosition", lightPosInShadowTex );
                        ShaderMgr.UploadData( "lightSize", lightSize );
                    } );
                rt.SelectTargetTexture( lightrl );
                float distanceMult = mWorldProjector.GetVisibleRegion().y * 1.0f / camProjection.GetVisibleRegion().y;
                mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( unwrap ), lightsid,
                    [&](ShaderManager& ShaderMgr)->void{
                        ShaderMgr.UploadData( "resolution", mCamera.GetProjection().GetViewport().Size() * shadowmult );
                        ShaderMgr.UploadData( "lightPosition", lightPos );
                        ShaderMgr.UploadData( "lightRect", sizePos2 );
                        ShaderMgr.UploadData( "lightSize", lightSize );
                        ShaderMgr.UploadData( "distanceMult", distanceMult );
                        ShaderMgr.UploadData( "heading", ori );
                        ShaderMgr.UploadData( "aperture", aperture );
                        ShaderMgr.UploadData( "fsaperture", fsaperture );
                    } );
            }

            // !---- cumulative lights for normal maps
            glBlendEquation( GL_MIN );
            rt.SelectTargetTexture( cumulativeLight );
            mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( lightrl, 1 ), mergelights,
                     [&](ShaderManager& ShaderMgr)->void{
                        ShaderMgr.UploadData( "resolution", mCamera.GetProjection().GetViewport().Size() );
                    } );
            glBlendEquation( GL_FUNC_ADD );
            SetupRenderer( mCamera, shadowmult );
            // remove self-cast shadows from the normal map mask
            // note: we use the alpha channel only from the cumul. lights map, so we can simply use the default draw shader. yay.
            mActorRenderer.Draw( std::bind( &selectShadowCasters, std::placeholders::_1, shadowLevel) );

            glBlendEquation( GL_FUNC_ADD );
            if( topmost )  // on topmost level, only the shadow receivers should be visibly illuminated, not the lower shadow receiver layers
            {   // note: topmost level must use full-size texture, as we are cutting out the highest shadow receivers
                // and if we apply scaling, the cut-out might leave bright pixels on the cut edges
                SetupRenderer( mCamera );
                SetupIdentity();
                rt.SetTargetTexture( fullsizeshadows, RenderTargetProps( mCamera.GetProjection().GetViewport().Size(), { GL_RGBA4 } ) );
                mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( lightrl ), solidid );
                rt.SetTargetTexture( topcasters, RenderTargetProps( mCamera.GetProjection().GetViewport().Size(), { GL_RGBA4, GL_RGB4 } ) );
                SetupRenderer( mCamera );
                mActorRenderer.Draw( std::bind( &selectShadowReceivers, std::placeholders::_1, shadowLevel ) );
                glBlendFuncSeparate( GL_ZERO, GL_ONE, GL_DST_ALPHA, GL_ZERO );
                rt.SelectTargetTexture( fullsizeshadows );
                SetupIdentity();
                // !---- lights/shadows
                mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( topcasters ), topcastersid );
            }

            glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
            rt.SelectTargetTexture( world );
            SetupRenderer( mCamera );
            // using a small(ish) shadow mult with linear texture mag filter, we can simply render the shadow layer instead of using a more expensive blur filter ( and that even a few times )
            SetupIdentity();
            // !---- lights/shadows
            mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( topmost ? fullsizeshadows : lightrl ), lightmap,
                     [&](ShaderManager& ShaderMgr)->void{
                        ShaderMgr.UploadData( "resolution", mCamera.GetProjection().GetViewport().Size() * shadowmult );
                        ShaderMgr.UploadData( "maxShadow", maxShadow );
                    } );
        }
    }
    else
    {
        mActorRenderer.Draw( &selectNonBloodReceivers );
    }
    mPerfTimer.Log( "post shadow" );

    // render the world to the worldBumped texture using the bump mapping shader
    SetupRenderer( mCamera );
    rt.SetTargetTexture( worldBumped, RenderTargetProps( mWorldProjector.GetViewport().Size() ) );
    SetupIdentity();
    glBlendFunc( GL_ONE, GL_ONE );
    glBlendEquation( GL_MAX );
    static int32_t bumpid = AutoId( "bump_map_mp" );
    glDepthFunc( GL_LEQUAL );
    for( auto const& light : lights )
    {
        auto lightPos4 =  mWorldProjector.GetMatrix() * mCamera.GetView()
            * glm::vec4( light.center.x, light.center.y, 1, 1 );
        glm::vec2 lightPos = glm::vec2( lightPos4.x + 1, lightPos4.y + 1 ) / 2.0;
        GLfloat lightSize = light.lightC.IsValid() ? light.lightC->GetRadius() : -1.0;

        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( world ), bumpid,
            [&](ShaderManager& ShaderMgr)->void{
                ShaderMgr.UploadData( "secondaryTexture", GLuint( 2 ) );
                ShaderMgr.UploadData( "lightTexture", GLuint( 3 ) );
                ShaderMgr.UploadData( "resolution", mWorldProjector.GetViewport().Size() );
                ShaderMgr.UploadData( "lightPosition", lightPos );
                ShaderMgr.UploadData( "lightSize", lightSize );
                glActiveTexture( GL_TEXTURE0 + 2 );
                glBindTexture( GL_TEXTURE_2D, rt.GetTextureId( world, 1 ) );
                glActiveTexture( GL_TEXTURE0 + 3 );
                glBindTexture( GL_TEXTURE_2D, rt.GetTextureId( cumulativeLight ) );
            } );
    }
    glBlendFunc( GL_ONE, GL_ONE );
    glBlendEquation( GL_FUNC_ADD );
    glDepthFunc( GL_LESS );

    rt.SetTargetTexture( worldEffects, RenderTargetProps( mWorldProjector.GetViewport().Size() ) );
    mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( worldBumped ), solidid );

    static bool const enablePostprocessing = Settings::Get().GetBool( "graphics.postprocess", true );
    if( enablePostprocessing )
    {
        RenderTargetProps worldPPProps( mWorldProjector.GetViewport().Size(), { GL_RED } );
        // render the per-actor effects
        glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
        for( auto id : postProcessorIds )
        {
            // TODO: downscale
            static int32_t debuggedPP = AutoId( Settings::Get().GetStr( "graphics.shown_layer_pp_id", "" ) );
            uint32_t pp = id == debuggedPP ? worldDedicatedPostProcess : worldPostProcess;
            rt.SetTargetTexture( pp, worldPPProps );
            SetupRenderer( mCamera );
            mActorRenderer.Draw( id );

            GLuint srcTexture = rt.GetTextureId( worldBumped );
            GLuint maskTexture = rt.GetTextureId( pp );
            rt.SelectTargetTexture( worldEffects );
            SetupIdentity();
            mWorldRenderer.Draw( DeltaTime, srcTexture, id, maskTexture );
        }
    }
    // set painting to screen
    rt.SetTargetScreen();
    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
    SetupIdentity();

    // paint the previous textures to screen with custom additional effects
    // actually we could skip this by painting directly to screen in prev. step
    // but we can possibly upscale here for sweet sweet fps

    static auto const layer = shownLayer();
    switch( layer )
    {
    case PostprocessMask:
        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( worldDedicatedPostProcess ), solidid );
        break;
    case SpriteCache:
        mWorldRenderer.Draw( DeltaTime, cache.mTargetTexId, solidid );
        break;
    case BumpMap:
        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( world, 1 ), solidid );
        break;
    case ShadowUnwrap:
        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( shadowDedicatedUnwrap ), solidid );
        break;
    case Shadows:
        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( shadowDedicatedOutline ), solidid );
        break;
    case Lights:
        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( lightsDedicated ), solidid );
        break;
    case TopLights:
        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( topcasters ), solidid );
        break;
    case FsShadows:
        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( fullsizeshadows ), solidid );
        break;
    case AllLights:
        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( cumulativeLight ), solidid );
        break;
    default:
        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( worldEffects ), solidid );
    }

    SetupRenderer( mCamera );
    render::ParticleEngine::Get().Draw();

    Viewport const& Vp = mUiProjector.GetViewport();
    glViewport( Vp.X, Vp.Y, Vp.Width, Vp.Height );
    mShaderManager.UploadGlobalData( GlobalShaderData::Resolution, glm::vec2( Vp.Width, Vp.Height ) );

    static bool const showNames = Settings::Get().GetBool( "graphics.show_names", true );
    static bool const showHealthbars = Settings::Get().GetBool( "graphics.show_healthbars", true );

    mUiRenderer.Draw( mUi.GetRoot(), mUiProjector.GetMatrix() );
    if( showNames )
    {
        mNameRenderer.Draw( mTextSceneRenderer );
    }
    mPathBoxRenderer.Draw( mTextSceneRenderer );
    if( showHealthbars )
    {
        mHealthBarRenderer.Draw();
    }
    mMouseRenderer.Draw( mTextSceneRenderer );
    mTextSceneRenderer.Draw();
    method.Log( "end draw" );
    cache.ProcessPending();
    method.Log( "end process pending" );
    method.Log( "end render" );
}

void RendererSystem::SendWorldMouseMoveEvent()
{
    glm::vec3 newMouseWorldPos = glm::vec3( mCamera.GetInverseView() * glm::vec4( mWorldProjector.Unproject( mMouseRawPos ), 1.0 ) );
    if ( newMouseWorldPos != mMouseWorldPos )
    {
        mMouseWorldPos = newMouseWorldPos;
        WorldMouseMoveEvent WorldEvt( glm::vec2( mMouseWorldPos.x, mMouseWorldPos.y ) );
        EventServer<WorldMouseMoveEvent>::Get().SendEvent( WorldEvt );
    }
}

Camera const& RendererSystem::GetCamera() const
{
    return mCamera;
}

TextSceneRenderer& RendererSystem::GetTextSceneRenderer()
{
    return mTextSceneRenderer;
}

} // namespace engine


// Boost.Geometry
// This file is manually converted from PROJ4

// This file was modified by Oracle on 2017.
// Modifications copyright (c) 2017, Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

// This file is converted from PROJ4, http://trac.osgeo.org/proj
// PROJ4 is originally written by Gerald Evenden (then of the USGS)
// PROJ4 is maintained by Frank Warmerdam
// This file was converted to Geometry Library by Adam Wulkiewicz

// Original copyright notice:

/***************************************************************************/
/* RSC IDENTIFIER:  GEOCENTRIC
 *
 * ABSTRACT
 *
 *    This component provides conversions between Geodetic coordinates (latitude,
 *    longitude in radians and height in meters) and Geocentric coordinates
 *    (X, Y, Z) in meters.
 *
 * ERROR HANDLING
 *
 *    This component checks parameters for valid values.  If an invalid value
 *    is found, the error code is combined with the current error code using
 *    the bitwise or.  This combining allows multiple error codes to be
 *    returned. The possible error codes are:
 *
 *      GEOCENT_NO_ERROR        : No errors occurred in function
 *      GEOCENT_LAT_ERROR       : Latitude out of valid range
 *                                 (-90 to 90 degrees)
 *      GEOCENT_LON_ERROR       : Longitude out of valid range
 *                                 (-180 to 360 degrees)
 *      GEOCENT_A_ERROR         : Semi-major axis lessthan or equal to zero
 *      GEOCENT_B_ERROR         : Semi-minor axis lessthan or equal to zero
 *      GEOCENT_A_LESS_B_ERROR  : Semi-major axis less than semi-minor axis
 *
 *
 * REUSE NOTES
 *
 *    GEOCENTRIC is intended for reuse by any application that performs
 *    coordinate conversions between geodetic coordinates and geocentric
 *    coordinates.
 *
 *
 * REFERENCES
 *
 *    An Improved Algorithm for Geocentric to Geodetic Coordinate Conversion,
 *    Ralph Toms, February 1996  UCRL-JC-123138.
 *
 *    Further information on GEOCENTRIC can be found in the Reuse Manual.
 *
 *    GEOCENTRIC originated from : U.S. Army Topographic Engineering Center
 *                                 Geospatial Information Division
 *                                 7701 Telegraph Road
 *                                 Alexandria, VA  22310-3864
 *
 * LICENSES
 *
 *    None apply to this component.
 *
 * RESTRICTIONS
 *
 *    GEOCENTRIC has no restrictions.
 *
 * ENVIRONMENT
 *
 *    GEOCENTRIC was tested and certified in the following environments:
 *
 *    1. Solaris 2.5 with GCC version 2.8.1
 *    2. Windows 95 with MS Visual C++ version 6
 *
 * MODIFICATIONS
 *
 *    Date              Description
 *    ----              -----------
 *    25-02-97          Original Code
 *
 */

#ifndef BOOST_GEOMETRY_SRS_PROJECTIONS_IMPL_GEOCENT_HPP
#define BOOST_GEOMETRY_SRS_PROJECTIONS_IMPL_GEOCENT_HPP

#include <boost/geometry/util/math.hpp>

namespace boost { namespace geometry { namespace projections
{

namespace detail
{

/***************************************************************************/
/*
 *                               DEFINES
 */
static const long GEOCENT_NO_ERROR       = 0x0000;
static const long GEOCENT_LAT_ERROR      = 0x0001;
static const long GEOCENT_LON_ERROR      = 0x0002;
static const long GEOCENT_A_ERROR        = 0x0004;
static const long GEOCENT_B_ERROR        = 0x0008;
static const long GEOCENT_A_LESS_B_ERROR = 0x0010;

template <typename T>
struct GeocentricInfo
{
    T Geocent_a;        /* Semi-major axis of ellipsoid in meters */
    T Geocent_b;        /* Semi-minor axis of ellipsoid           */
    T Geocent_a2;       /* Square of semi-major axis */
    T Geocent_b2;       /* Square of semi-minor axis */
    T Geocent_e2;       /* Eccentricity squared  */
    T Geocent_ep2;      /* 2nd eccentricity squared */
};

template <typename T>
inline T COS_67P5()
{
    /*return 0.38268343236508977*/;
    return cos(T(67.5) * math::d2r<T>());  /* cosine of 67.5 degrees */
}
template <typename T>
inline T AD_C()
{
    return 1.0026000;            /* Toms region 1 constant */
}

/***************************************************************************/
/*
 *                              FUNCTIONS
 */

template <typename T>
inline long pj_Set_Geocentric_Parameters (GeocentricInfo<T> & gi, T const& a, T const& b)

{ /* BEGIN Set_Geocentric_Parameters */
/*
 * The function Set_Geocentric_Parameters receives the ellipsoid parameters
 * as inputs and sets the corresponding state variables.
 *
 *    a  : Semi-major axis, in meters.          (input)
 *    b  : Semi-minor axis, in meters.          (input)
 */
    long Error_Code = GEOCENT_NO_ERROR;

    if (a <= 0.0)
        Error_Code |= GEOCENT_A_ERROR;
    if (b <= 0.0)
        Error_Code |= GEOCENT_B_ERROR;
    if (a < b)
        Error_Code |= GEOCENT_A_LESS_B_ERROR;
    if (!Error_Code)
    {
        gi.Geocent_a = a;
        gi.Geocent_b = b;
        gi.Geocent_a2 = a * a;
        gi.Geocent_b2 = b * b;
        gi.Geocent_e2 = (gi.Geocent_a2 - gi.Geocent_b2) / gi.Geocent_a2;
        gi.Geocent_ep2 = (gi.Geocent_a2 - gi.Geocent_b2) / gi.Geocent_b2;
    }
    return (Error_Code);
} /* END OF Set_Geocentric_Parameters */

template <typename T>
inline void pj_Get_Geocentric_Parameters (GeocentricInfo<T> const& gi,
                                          T & a,
                                          T & b)
{ /* BEGIN Get_Geocentric_Parameters */
/*
 * The function Get_Geocentric_Parameters returns the ellipsoid parameters
 * to be used in geocentric coordinate conversions.
 *
 *    a  : Semi-major axis, in meters.          (output)
 *    b  : Semi-minor axis, in meters.          (output)
 */

    a = gi.Geocent_a;
    b = gi.Geocent_b;
} /* END OF Get_Geocentric_Parameters */

template <typename T>
inline long pj_Convert_Geodetic_To_Geocentric (GeocentricInfo<T> const& gi,
                                               T Longitude, T Latitude, T Height,
                                               T & X, T & Y, T & Z)
{ /* BEGIN Convert_Geodetic_To_Geocentric */
/*
 * The function Convert_Geodetic_To_Geocentric converts geodetic coordinates
 * (latitude, longitude, and height) to geocentric coordinates (X, Y, Z),
 * according to the current ellipsoid parameters.
 *
 *    Latitude  : Geodetic latitude in radians                     (input)
 *    Longitude : Geodetic longitude in radians                    (input)
 *    Height    : Geodetic height, in meters                       (input)
 *    X         : Calculated Geocentric X coordinate, in meters    (output)
 *    Y         : Calculated Geocentric Y coordinate, in meters    (output)
 *    Z         : Calculated Geocentric Z coordinate, in meters    (output)
 *
 */
  long Error_Code = GEOCENT_NO_ERROR;
  T Rn;            /*  Earth radius at location  */
  T Sin_Lat;       /*  sin(Latitude)  */
  T Sin2_Lat;      /*  Square of sin(Latitude)  */
  T Cos_Lat;       /*  cos(Latitude)  */

  static const T PI = math::pi<T>();
  static const T PI_OVER_2 = math::half_pi<T>();

  /*
  ** Don't blow up if Latitude is just a little out of the value
  ** range as it may just be a rounding issue.  Also removed longitude
  ** test, it should be wrapped by cos() and sin().  NFW for PROJ.4, Sep/2001.
  */
  if( Latitude < -PI_OVER_2 && Latitude > -1.001 * PI_OVER_2 )
      Latitude = -PI_OVER_2;
  else if( Latitude > PI_OVER_2 && Latitude < 1.001 * PI_OVER_2 )
      Latitude = PI_OVER_2;
  else if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2))
  { /* Latitude out of range */
    Error_Code |= GEOCENT_LAT_ERROR;
  }

  if (!Error_Code)
  { /* no errors */
    if (Longitude > PI)
      Longitude -= (2*PI);
    Sin_Lat = sin(Latitude);
    Cos_Lat = cos(Latitude);
    Sin2_Lat = Sin_Lat * Sin_Lat;
    Rn = gi.Geocent_a / (sqrt(1.0e0 - gi.Geocent_e2 * Sin2_Lat));
    X = (Rn + Height) * Cos_Lat * cos(Longitude);
    Y = (Rn + Height) * Cos_Lat * sin(Longitude);
    Z = ((Rn * (1 - gi.Geocent_e2)) + Height) * Sin_Lat;
  }
  return (Error_Code);
} /* END OF Convert_Geodetic_To_Geocentric */

/*
 * The function Convert_Geocentric_To_Geodetic converts geocentric
 * coordinates (X, Y, Z) to geodetic coordinates (latitude, longitude,
 * and height), according to the current ellipsoid parameters.
 *
 *    X         : Geocentric X coordinate, in meters.         (input)
 *    Y         : Geocentric Y coordinate, in meters.         (input)
 *    Z         : Geocentric Z coordinate, in meters.         (input)
 *    Latitude  : Calculated latitude value in radians.       (output)
 *    Longitude : Calculated longitude value in radians.      (output)
 *    Height    : Calculated height value, in meters.         (output)
 */

#define BOOST_GEOMETRY_PROJECTIONS_USE_ITERATIVE_METHOD

template <typename T>
inline void pj_Convert_Geocentric_To_Geodetic (GeocentricInfo<T> const& gi,
                                               T X, T Y, T Z,
                                               T & Longitude, T & Latitude, T & Height)
{ /* BEGIN Convert_Geocentric_To_Geodetic */

    static const T PI_OVER_2 = math::half_pi<T>();

#if !defined(BOOST_GEOMETRY_PROJECTIONS_USE_ITERATIVE_METHOD)

    static const T COS_67P5 = detail::COS_67P5<T>();
    static const T AD_C = detail::AD_C<T>();

/*
 * The method used here is derived from 'An Improved Algorithm for
 * Geocentric to Geodetic Coordinate Conversion', by Ralph Toms, Feb 1996
 */

/* Note: Variable names follow the notation used in Toms, Feb 1996 */

    T W;        /* distance from Z axis */
    T W2;       /* square of distance from Z axis */
    T T0;       /* initial estimate of vertical component */
    T T1;       /* corrected estimate of vertical component */
    T S0;       /* initial estimate of horizontal component */
    T S1;       /* corrected estimate of horizontal component */
    T Sin_B0;   /* sin(B0), B0 is estimate of Bowring aux variable */
    T Sin3_B0;  /* cube of sin(B0) */
    T Cos_B0;   /* cos(B0) */
    T Sin_p1;   /* sin(phi1), phi1 is estimated latitude */
    T Cos_p1;   /* cos(phi1) */
    T Rn;       /* Earth radius at location */
    T Sum;      /* numerator of cos(phi1) */
    bool At_Pole;     /* indicates location is in polar region */

    At_Pole = false;
    if (X != 0.0)
    {
        Longitude = atan2(Y,X);
    }
    else
    {
        if (Y > 0)
        {
            Longitude = PI_OVER_2;
        }
        else if (Y < 0)
        {
            Longitude = -PI_OVER_2;
        }
        else
        {
            At_Pole = true;
            Longitude = 0.0;
            if (Z > 0.0)
            {  /* north pole */
                Latitude = PI_OVER_2;
            }
            else if (Z < 0.0)
            {  /* south pole */
                Latitude = -PI_OVER_2;
            }
            else
            {  /* center of earth */
                Latitude = PI_OVER_2;
                Height = -Geocent_b;
                return;
            }
        }
    }
    W2 = X*X + Y*Y;
    W = sqrt(W2);
    T0 = Z * AD_C;
    S0 = sqrt(T0 * T0 + W2);
    Sin_B0 = T0 / S0;
    Cos_B0 = W / S0;
    Sin3_B0 = Sin_B0 * Sin_B0 * Sin_B0;
    T1 = Z + gi.Geocent_b * gi.Geocent_ep2 * Sin3_B0;
    Sum = W - gi.Geocent_a * gi.Geocent_e2 * Cos_B0 * Cos_B0 * Cos_B0;
    S1 = sqrt(T1*T1 + Sum * Sum);
    Sin_p1 = T1 / S1;
    Cos_p1 = Sum / S1;
    Rn = gi.Geocent_a / sqrt(1.0 - gi.Geocent_e2 * Sin_p1 * Sin_p1);
    if (Cos_p1 >= COS_67P5)
    {
        Height = W / Cos_p1 - Rn;
    }
    else if (Cos_p1 <= -COS_67P5)
    {
        Height = W / -Cos_p1 - Rn;
    }
    else
    {
        Height = Z / Sin_p1 + Rn * (gi.Geocent_e2 - 1.0);
    }
    if (At_Pole == false)
    {
        Latitude = atan(Sin_p1 / Cos_p1);
    }
#else /* defined(BOOST_GEOMETRY_PROJECTIONS_USE_ITERATIVE_METHOD) */
/*
* Reference...
* ============
* Wenzel, H.-G.(1985): Hochauflösende Kugelfunktionsmodelle für
* das Gravitationspotential der Erde. Wiss. Arb. Univ. Hannover
* Nr. 137, p. 130-131.

* Programmed by GGA- Leibniz-Institute of Applied Geophysics
*               Stilleweg 2
*               D-30655 Hannover
*               Federal Republic of Germany
*               Internet: www.gga-hannover.de
*
*               Hannover, March 1999, April 2004.
*               see also: comments in statements
* remarks:
* Mathematically exact and because of symmetry of rotation-ellipsoid,
* each point (X,Y,Z) has at least two solutions (Latitude1,Longitude1,Height1) and
* (Latitude2,Longitude2,Height2). Is point=(0.,0.,Z) (P=0.), so you get even
* four solutions,	every two symmetrical to the semi-minor axis.
* Here Height1 and Height2 have at least a difference in order of
* radius of curvature (e.g. (0,0,b)=> (90.,0.,0.) or (-90.,0.,-2b);
* (a+100.)*(sqrt(2.)/2.,sqrt(2.)/2.,0.) => (0.,45.,100.) or
* (0.,225.,-(2a+100.))).
* The algorithm always computes (Latitude,Longitude) with smallest |Height|.
* For normal computations, that means |Height|<10000.m, algorithm normally
* converges after to 2-3 steps!!!
* But if |Height| has the amount of length of ellipsoid's axis
* (e.g. -6300000.m),	algorithm needs about 15 steps.
*/

/* local definitions and variables */
/* end-criterium of loop, accuracy of sin(Latitude) */
static const T genau   = 1.E-12;
static const T genau2  = (genau*genau);
static const int maxiter = 30;

    T P;        /* distance between semi-minor axis and location */
    T RR;       /* distance between center and location */
    T CT;       /* sin of geocentric latitude */
    T ST;       /* cos of geocentric latitude */
    T RX;
    T RK;
    T RN;       /* Earth radius at location */
    T CPHI0;    /* cos of start or old geodetic latitude in iterations */
    T SPHI0;    /* sin of start or old geodetic latitude in iterations */
    T CPHI;     /* cos of searched geodetic latitude */
    T SPHI;     /* sin of searched geodetic latitude */
    T SDPHI;    /* end-criterium: addition-theorem of sin(Latitude(iter)-Latitude(iter-1)) */
    int iter;   /* # of continuous iteration, max. 30 is always enough (s.a.) */

    P = sqrt(X*X+Y*Y);
    RR = sqrt(X*X+Y*Y+Z*Z);

/*	special cases for latitude and longitude */
    if (P/gi.Geocent_a < genau) {

/*  special case, if P=0. (X=0., Y=0.) */
	Longitude = 0.;

/*  if (X,Y,Z)=(0.,0.,0.) then Height becomes semi-minor axis
 *  of ellipsoid (=center of mass), Latitude becomes PI/2 */
        if (RR/gi.Geocent_a < genau) {
            Latitude = PI_OVER_2;
            Height   = -gi.Geocent_b;
            return ;

        }
    }
    else {
/*  ellipsoidal (geodetic) longitude
 *  interval: -PI < Longitude <= +PI */
        Longitude=atan2(Y,X);
    }

/* --------------------------------------------------------------
 * Following iterative algorithm was developed by
 * "Institut für Erdmessung", University of Hannover, July 1988.
 * Internet: www.ife.uni-hannover.de
 * Iterative computation of CPHI,SPHI and Height.
 * Iteration of CPHI and SPHI to 10**-12 radian resp.
 * 2*10**-7 arcsec.
 * --------------------------------------------------------------
 */
    CT = Z/RR;
    ST = P/RR;
    RX = 1.0/sqrt(1.0-gi.Geocent_e2*(2.0-gi.Geocent_e2)*ST*ST);
    CPHI0 = ST*(1.0-gi.Geocent_e2)*RX;
    SPHI0 = CT*RX;
    iter = 0;

/* loop to find sin(Latitude) resp. Latitude
 * until |sin(Latitude(iter)-Latitude(iter-1))| < genau */
    do
    {
        iter++;
        RN = gi.Geocent_a/sqrt(1.0-gi.Geocent_e2*SPHI0*SPHI0);

/*  ellipsoidal (geodetic) height */
        Height = P*CPHI0+Z*SPHI0-RN*(1.0-gi.Geocent_e2*SPHI0*SPHI0);

        RK = gi.Geocent_e2*RN/(RN+Height);
        RX = 1.0/sqrt(1.0-RK*(2.0-RK)*ST*ST);
        CPHI = ST*(1.0-RK)*RX;
        SPHI = CT*RX;
        SDPHI = SPHI*CPHI0-CPHI*SPHI0;
        CPHI0 = CPHI;
        SPHI0 = SPHI;
    }
    while (SDPHI*SDPHI > genau2 && iter < maxiter);

/*	ellipsoidal (geodetic) latitude */
    Latitude=atan(SPHI/fabs(CPHI));

    return;
#endif /* defined(BOOST_GEOMETRY_PROJECTIONS_USE_ITERATIVE_METHOD) */
} /* END OF Convert_Geocentric_To_Geodetic */

} // namespace detail

}}} // namespace boost::geometry::projections

#endif // BOOST_GEOMETRY_SRS_PROJECTIONS_IMPL_GEOCENT_HPP