/*---------------------------------------------------------------------------*
  Project:  Horizon
  File:     graphics.cpp

  Copyright (C)2009 Nintendo Co., Ltd.  All rights reserved.

  These coded instructions, statements, and computer programs contain
  proprietary information of Nintendo of America Inc. and/or Nintendo
  Company Ltd., and are protected by Federal copyright law.  They may
  not be disclosed to third parties or copied or duplicated in any form,
  in whole or in part, without the prior written consent of Nintendo.

  $Rev: 36187 $
 *---------------------------------------------------------------------------*/

#include <nn.h>

#include "graphics.h"
#include "camera_manager.h"
#include "y2r_manager.h"
#include "key_manager.h"
#include "model_manager.h"

//==============================================================================
// 使用するフレームワーク
demo::RenderSystemExt s_RenderSystem;

// 3D/2D切り替え
s32 s_DisplayMode = 1;

//==============================================================================
//namespace {

    const int MEMORY_SIZE_FCRAM_GX = 0x800000;    // グラフィックス用に確保する FCRAM 上のメモリサイズ

    /* buffer id */
    GLuint s_ArrayBufferID;
    GLuint s_ElementArrayBufferID;

    /* program id */
    GLuint s_ProgramID;

    /* shader id */
    GLuint s_ShaderID;

    /* ヒープ */
    uptr s_AddrForGxHeap;

    // テクスチャ
    GLuint s_Texture[2] = { 0, 0 };

//} // namespace

//==============================================================================
namespace {

    // キャルデータ
    nn::camera::StereoCameraCalibrationData * sp_CalData = NULL;

    // 補正に視差を含めるか
    bool s_IsParallax = false;

    // ピントを合わせる距離
    f32  s_Distance = 500.0f;

    // 右にずらすかどうか
    bool s_IsShiftRight = false;

    // テクスチャとなる画像のフォーマット
    nn::y2r::OutputFormat   s_Format    = nn::y2r::OUTPUT_RGB_24;
    nn::y2r::BlockAlignment s_Alignment = nn::y2r::BLOCK_8_BY_8;

    // RGB 画像を表示するときの画像情報
    u8      * spa_RgbImage[ 2 ]  = { NULL, NULL };
    size_t  s_RgbTextureWidth   = 1024;
    size_t  s_RgbTextureHeight  = 1024;
    size_t  s_RgbOriginalWidth  = 640;
    size_t  s_RgbOriginalHeight = 480;


    // カメラ位置
    camera_exp::ModelManager_cl s_CameraModelManager;

} //namespace

//==============================================================================
void LoadObjects(void);
void DeleteObjects( void );
void ReadyObjects(void);
void SetTextureCombiner(void);
void SetTextureCombinerBlend(void);
void DrawDisplay0Common( nn::camera::CameraSelect currentCamera );
void DrawDisplay0ExtCommon( void );

//==============================================================================
int InitializeGx( nn::fnd::ExpHeap & heap )
{
    s_AddrForGxHeap = reinterpret_cast<uptr>(heap.Allocate(MEMORY_SIZE_FCRAM_GX));
    s_RenderSystem.Initialize(s_AddrForGxHeap, MEMORY_SIZE_FCRAM_GX);

    s_ProgramID = glCreateProgram();
    s_ShaderID = glCreateShader(GL_VERTEX_SHADER);

//    nn::fs::FileReader file(L"rom:/shader.shbin");
    nn::fs::FileReader file(L"rom:/camera/shader.shbin");
    size_t fileSize = file.GetSize();
    void* buf = heap.Allocate(fileSize);
    s32 read = file.Read(buf, fileSize);

    glShaderBinary(1, &s_ShaderID, GL_PLATFORM_BINARY_DMP, buf, read);

    file.Finalize();
    heap.Free(buf);

    glAttachShader(s_ProgramID, s_ShaderID);
    glAttachShader(s_ProgramID, GL_DMP_FRAGMENT_SHADER_DMP);

    glBindAttribLocation(s_ProgramID, 0, "aPosition");
    glBindAttribLocation(s_ProgramID, 1, "aTexCoord");

    glLinkProgram(s_ProgramID);
    glValidateProgram(s_ProgramID);
    glUseProgram(s_ProgramID);

    glGenTextures(2, s_Texture);
//    DEMO_ASSERT_GL_ERROR();

    glBindTexture(GL_TEXTURE_2D, s_Texture[0]);
    glBindTexture(GL_TEXTURE_2D, s_Texture[1]);
    glBindTexture(GL_TEXTURE_2D, 0);

    s_RenderSystem.SetClearColor(NN_GX_DISPLAY0, 0.36f, 0.42f, 0.5f, 1.0f);
    s_RenderSystem.SetClearColor(NN_GX_DISPLAY1, 0.0f, 0.0f, 0.0f, 1.0f);
    s_RenderSystem.SetClearColor(NN_GX_DISPLAY0_EXT, 0.36f, 0.42f, 0.5f, 1.0f);

    glClearDepthf(1.f);

    glEnable(GL_CULL_FACE);
    glFrontFace(GL_CCW);
    glCullFace(GL_BACK);

    LoadObjects();

    // カメラ位置の初期化
    s_CameraModelManager.InitPosition();

    return 0;
}

//==============================================================================
void FinalizeGx( nn::fnd::ExpHeap & heap )
{
    DeleteObjects();

    glDeleteTextures( 2, s_Texture );
    glDetachShader( s_ProgramID, GL_DMP_FRAGMENT_SHADER_DMP );
    glDetachShader( s_ProgramID, s_ShaderID );
    glDeleteShader( s_ShaderID );
    glDeleteProgram( s_ProgramID );

    s_RenderSystem.Finalize();

    heap.Free( reinterpret_cast< void * >( s_AddrForGxHeap ) );
}

//==============================================================================
void LoadObjects(void)
{
    GLfloat coords[] = {
        -1.024f, 1.024f, 0.f, 1.f,
        -1.024f,-1.024f, 0.f, 1.f,
         1.024f, 1.024f, 0.f, 1.f,
         1.024f,-1.024f, 0.f, 1.f
    };
    GLfloat texcoords[] = {
        0.f, 1.f, 0.f,
        0.f, 0.f, 0.f,
        1.f, 1.f, 0.f,
        1.f, 0.f, 0.f,
    };

    GLushort idxs[] = {0, 1, 2, 3};

    glGenBuffers(1, &s_ArrayBufferID);
    glBindBuffer(GL_ARRAY_BUFFER, s_ArrayBufferID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(coords) + sizeof(texcoords), 0, GL_STATIC_DRAW);
    glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(coords), coords);
    glBufferSubData(GL_ARRAY_BUFFER, sizeof(coords), sizeof(texcoords), texcoords);
    
    glGenBuffers(1, &s_ElementArrayBufferID);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s_ElementArrayBufferID);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(idxs), idxs, GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);

    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0) ;
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)sizeof(coords));
}

//==============================================================================
void DeleteObjects( void )
{
    glDeleteBuffers( 1, &s_ElementArrayBufferID );
    glDeleteBuffers( 1, &s_ArrayBufferID );
}

//==============================================================================
void ReadyObjects(void)
{
    glUseProgram(s_ProgramID);
    glBindBuffer(GL_ARRAY_BUFFER, s_ArrayBufferID);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s_ElementArrayBufferID);

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);

    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)(16*sizeof(GLfloat)));
}

//==============================================================================
// 透明にしない
void SetTextureCombiner(void)
{
    glUniform4f(glGetUniformLocation(s_ProgramID, "dmp_TexEnv[2].constRgba"), 0.0f, 0.0f, 0.0f, 1.0f);
    glUniform3i(glGetUniformLocation(s_ProgramID, "dmp_TexEnv[2].srcRgb"), GL_TEXTURE0, GL_PREVIOUS, GL_PREVIOUS);
    glUniform3i(glGetUniformLocation(s_ProgramID, "dmp_TexEnv[2].srcAlpha"), GL_CONSTANT, GL_PREVIOUS, GL_PREVIOUS);
    glUniform3i(glGetUniformLocation(s_ProgramID, "dmp_TexEnv[2].operandRgb"), GL_SRC_COLOR, GL_SRC_COLOR, GL_SRC_COLOR);
    glUniform3i(glGetUniformLocation(s_ProgramID, "dmp_TexEnv[2].operandAlpha"),GL_SRC_ALPHA , GL_SRC_ALPHA, GL_SRC_ALPHA);
    glUniform1i(glGetUniformLocation(s_ProgramID, "dmp_TexEnv[2].combineRgb"), GL_REPLACE);
    glUniform1i(glGetUniformLocation(s_ProgramID, "dmp_TexEnv[2].combineAlpha"), GL_REPLACE);
    glUniform1f(glGetUniformLocation(s_ProgramID, "dmp_TexEnv[2].scaleRgb"), 1.0f);
    glUniform1f(glGetUniformLocation(s_ProgramID, "dmp_TexEnv[2].scaleAlpha"), 1.0f);
}

//==============================================================================
// 半透明
void SetTextureCombinerBlend(void)
{
    glUniform4f(glGetUniformLocation(s_ProgramID, "dmp_TexEnv[2].constRgba"), 0.0f, 0.0f, 0.0f, 0.5f);
    glUniform3i(glGetUniformLocation(s_ProgramID, "dmp_TexEnv[2].srcRgb"), GL_TEXTURE0, GL_PREVIOUS, GL_PREVIOUS);
    glUniform3i(glGetUniformLocation(s_ProgramID, "dmp_TexEnv[2].srcAlpha"), GL_CONSTANT, GL_PRIMARY_COLOR, GL_PREVIOUS);
    glUniform3i(glGetUniformLocation(s_ProgramID, "dmp_TexEnv[2].operandRgb"), GL_SRC_COLOR, GL_SRC_COLOR, GL_SRC_COLOR);
    glUniform3i(glGetUniformLocation(s_ProgramID, "dmp_TexEnv[2].operandAlpha"), GL_SRC_ALPHA, GL_SRC_ALPHA, GL_SRC_ALPHA);
    glUniform1i(glGetUniformLocation(s_ProgramID, "dmp_TexEnv[2].combineRgb"), GL_REPLACE);
    glUniform1i(glGetUniformLocation(s_ProgramID, "dmp_TexEnv[2].combineAlpha"), GL_REPLACE);
    glUniform1f(glGetUniformLocation(s_ProgramID, "dmp_TexEnv[2].scaleRgb"), 1.0f);
    glUniform1f(glGetUniformLocation(s_ProgramID, "dmp_TexEnv[2].scaleAlpha"), 1.0f);
}

//==============================================================================
void SetDrawingStereoCamera(
        bool isDrawRgbImage,
        nn::camera::StereoCameraCalibrationData * p_CalData,
        bool isParallax,
        f32  distance,
        bool isShiftRight,
        nn::y2r::OutputFormat format,
        nn::y2r::BlockAlignment alignment )
{
//    s_IsDrawRgbImage = isDrawRgbImage;
    static_cast<void>( isDrawRgbImage );// warning対策
    sp_CalData       = p_CalData;
    s_IsParallax     = isParallax;
    s_Distance       = distance;
    s_IsShiftRight   = isShiftRight;
    s_Format         = format;
    s_Alignment      = alignment;
} //SetDrawingStereoCamera()

//==============================================================================
/** ステレオ画像を貼る処理を一般化
 *  ステレオカメラ画像とBMP画像の両方に対応するため
 */
void DrawStereoTexture( s32 index, bool isBlend,
                        void   * image,
                        size_t textureWidth,  size_t textureHeight,
                        size_t originalWidth, size_t originalHeight NN_IS_UNUSED_VAR )
{
    GLenum type = GL_UNSIGNED_BYTE;
    switch( s_Format )
    {
    case nn::y2r::OUTPUT_RGB_32:
    case nn::y2r::OUTPUT_RGB_24:
        {
            type = GL_UNSIGNED_BYTE;
        }
        break;
    case nn::y2r::OUTPUT_RGB_16_555:
        {
            type = GL_UNSIGNED_SHORT_5_5_5_1;
        }
        break;
    case nn::y2r::OUTPUT_RGB_16_565:
        {
            type = GL_UNSIGNED_SHORT_5_6_5;
        }
        break;
    }

    glBindTexture(GL_TEXTURE_2D, s_Texture[index]);
    if( s_Alignment == nn::y2r::BLOCK_8_BY_8)
    {
        glTexImage2D(
            GL_TEXTURE_2D | NN_GX_MEM_FCRAM | GL_NO_COPY_FCRAM_DMP,
            0,
            GL_RGB_NATIVE_DMP,
            textureWidth,
            textureHeight,
            0,
            GL_RGB_NATIVE_DMP,
            type,
            image );
    }
    else
    {
        glTexImage2D(
            GL_TEXTURE_2D,
            0,
            GL_RGB,
            textureWidth,
            textureHeight,
            0,
            GL_RGB,
            type,
            image );
    }

    ReadyObjects();
    
    // テクスチャコンバイナ設定
    glUniform1i(glGetUniformLocation(s_ProgramID, "dmp_Texture[0].samplerType"), GL_TEXTURE_2D);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, s_Texture[index]);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    // ULCD表示しないときには画像を重ね合わせて表示する
    // 半透明にする必要があるが画像のアルファ値を変更するのではなく
    // テクスチャコンバイナの設定を変更することで対応
    if( isBlend )
    {
        SetTextureCombinerBlend();
    }
    else
    {
        SetTextureCombiner();
    }

    nn::math::Matrix44 proj, m;

    // 透視投影の視体積を決定する
    // 縦横逆なので
    // DISPLAY0_HEIGHT : 400
    // DISPLAY0_WIDTH  : 240
    // となっていることに注意

    nn::math::MTX44Frustum(
        &proj,
        -0.02f,
         0.02f,
        -0.02f* static_cast<f32>(nn::gx::DISPLAY0_HEIGHT) / static_cast<f32>(nn::gx::DISPLAY0_WIDTH),
         0.02f* static_cast<f32>(nn::gx::DISPLAY0_HEIGHT) / static_cast<f32>(nn::gx::DISPLAY0_WIDTH),
         0.2f,
         10.f);
    nn::math::MTX44Transpose(&m, &proj);
    glUniformMatrix4fv(glGetUniformLocation(s_ProgramID, "uProjection"), 1, GL_FALSE, static_cast<f32*>(m));

    // カメラ(3Dモデルを撮影するカメラのこと. カメラモジュールではない)の位置は, 
    // カメラ(こっちはカメラモジュールのこと)画像を pixel by pixel で表示できる位置に置きたい
    // 400 * 240 の左上が (-0.8, -0.48) で
    // ニアクリッピング面の左上が (-0.02*400/240, -0.02) で, 
    // ニアクリッピング面がカメラより z 方向に 0.2 離れているので
    // カメラからのポリゴンの z 方向の位置は
    // 三角比によって -0.48 : 0.02 = z : 0.2 より z = 4.8 となる
    // よってポリゴンの z 座標が 0 のときカメラの位置は 4.8 となる

    nn::math::Matrix34 eye;
    nn::math::Vector3 camPos(0.f, 0.f, 4.8f);
    nn::math::Vector3 camUp(0.f, 1.f, 0.f);
    nn::math::Vector3 target(0.f, 0.f, 0.f);

    nn::math::MTX34LookAt(&eye, &camPos, &camUp, &target);

    // 視点カメラを動かす
    nn::math::Matrix34 camMove( s_CameraModelManager.GetTransMatrix34() );
    nn::math::MTX34Mult( &eye, &camMove, &eye );

    nn::math::MTX34  tmp(eye);
    {
        nn::math::MTX34 move;
        nn::math::MTX34Identity( &move );
        
        // テクスチャサイズが小さいときに引き伸ばしされないようにスケーリングしておく
        // 最初にスケーリングすることで補正や視差調整でのずらし量の計算でテクスチャ引き延ばしを考慮しなくてよい
        f32  sizeScaleF = static_cast< f32 >( textureWidth ) / 512.0f;
        nn::math::VEC3 sizeScaleVec = nn::math::VEC3( sizeScaleF, sizeScaleF, 0.0f );
        nn::math::MTX34 sizeScale;
        nn::math::MTX34Scale( &sizeScale, &sizeScaleVec );
        nn::math::MTX34Mult( &move, &sizeScale, &move );

        // ステレオカメラのキャリブレーション(位置ズレ補正)
        if( index == 1 )        // 左
        {
            // 画像のサイズによってずらす量は異なる
            f32 step = 0.004f * static_cast< f32 >( originalWidth ) / 640.0f;

            // キャリブレーションのための行列を取得する
            // 画像を1ピクセル動かすために必要な移動量は VGA のとき 0.96 / 240.0 = 0.004 (0.96 の範囲に 240 ピクセル写すため)
            nn::math::MTX34 cal;
            nn::camera::GetStereoCameraCalibrationMatrix( &cal, *sp_CalData, step, s_IsParallax );
            
            // 左カメラ画像に位置ズレ補正をかける
            nn::math::MTX34Mult( &move, &cal, &move );
        }

        // 被写体が飛び出して見えるか奥に見えるかは画像の水平方向の移動量によって異なる
        // ここでは指定された距離にある被写体が重なるように、s_Distance [mm] 先の視差を求めて、
        // その分だけ左カメラ画像を並進移動させる
        if( ( index == 1 ) && ( s_Distance > 0.0f ) )
        {
            // 画像のサイズによってずらす量は異なる
            f32 step = 0.004f * static_cast< f32 >( originalWidth ) / 640.0f;

            f32 p = nn::camera::GetParallax( *sp_CalData, s_Distance * 0.001f );

            nn::math::VEC3  transVec( p * step, 0.0f, 0.0f );     // 3D空間上の移動量に変換するために 0.004 をかける
            nn::math::MTX34 trans;
            nn::math::MTX34Translate( &trans, &transVec );
            
            nn::math::MTX34Mult( &move, &trans, &move );
        }

        // 真中を基準にすると右画像の真中と左画像の右端を比較することになるので
        // 画像の左を表示するように右にずらす
        if( s_IsShiftRight
            && ( textureWidth > nn::gx::DISPLAY0_HEIGHT ) )
        {
            f32 right = static_cast< f32 >( ( textureWidth - nn::gx::DISPLAY0_HEIGHT ) / 2 ); 
            nn::math::MTX34 transRight;
            nn::math::VEC3  transRightVec( right * 0.004f, 0.0f, 0.0f );
            nn::math::MTX34Translate( &transRight, &transRightVec );
            nn::math::MTX34Mult( &move, &transRight, &move );
        }

        // 座標系が本体を横持ちしたときに 90 度左に回っているように定義されているので右回りに 90 度回す
        nn::math::MTX34 rot90;
        nn::math::MTX34RotXYZDeg( &rot90, 0.0f, 0.0f, -90.0f );
        nn::math::MTX34Mult( &move, &rot90, &move );

        nn::math::MTX34Mult( &tmp, &tmp, &move );
    }
    nn::math::MTX44 mv(tmp);
    
    nn::math::MTX44Transpose(&mv, &mv);   // ドライバの中の形式に合わせるために転置する
    glUniformMatrix4fv(glGetUniformLocation(s_ProgramID, "uModelView"), 1, GL_FALSE, static_cast<f32*>(mv));

    if( isBlend )
    {
        // アルファブレンド
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

        // Z比較無効にする
        glDisable(GL_DEPTH_TEST);
    }
    else
    {
        glDisable(GL_BLEND);
    }

    glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_SHORT, 0);
} //DrawStereoTexture

//==============================================================================
void DrawStereoCamera( s32 index, bool isBlend )
{
    DrawStereoTexture(
        index,
        isBlend,
        camera_exp::Y2rManager_cl::GetTextureBuffer( index ),
        camera_exp::Y2rManager_cl::GetTextureWidth(),
        camera_exp::Y2rManager_cl::GetTextureHeight(),
        camera_exp::OcamManager_cl::GetCameraManager( index ).GetWidth(),
        camera_exp::OcamManager_cl::GetCameraManager( index ).GetHeight() );
} //DrawStereoCamera

//==============================================================================
void DrawRgbImage( s32 index, bool isBlend )
{
    DrawStereoTexture(
        index,
        isBlend,
        spa_RgbImage[ index ],
        s_RgbTextureWidth,
        s_RgbTextureHeight,
        s_RgbOriginalWidth,
        s_RgbOriginalHeight );
}

//==============================================================================
void DrawDisplay0StereoCommon( nn::camera::CameraSelect currentCamera )
{
    // ULCD表示するかどうかの切り替え
    if(    !camera_exp::KeyManager_cl::IsHold( camera_exp::KeyManager_cl::e_BUTTON_A )
             && !camera_exp::KeyManager_cl::IsHold( camera_exp::KeyManager_cl::e_BUTTON_B )
             && !camera_exp::KeyManager_cl::IsHold( camera_exp::KeyManager_cl::e_BUTTON_Y )
             && !camera_exp::KeyManager_cl::IsHold( camera_exp::KeyManager_cl::e_BUTTON_X )
             && !camera_exp::KeyManager_cl::IsHold( camera_exp::KeyManager_cl::e_BUTTON_R )
             && !camera_exp::KeyManager_cl::IsHold( camera_exp::KeyManager_cl::e_BUTTON_L ) )
    {
        if( camera_exp::KeyManager_cl::IsTrigger( camera_exp::KeyManager_cl::e_AK_DOWN ) )
        {
            if( ++s_DisplayMode >= 4 )
            {
                s_DisplayMode = 0;
            }
        }
        if( camera_exp::KeyManager_cl::IsTrigger( camera_exp::KeyManager_cl::e_AK_UP ) )
        {
            if( --s_DisplayMode < 0 )
            {
                s_DisplayMode = 3;
            }
        }
    }

    if(    ( currentCamera == nn::camera::SELECT_OUT1_OUT2 )
        || ( currentCamera == nn::camera::SELECT_IN1_OUT2 ) )
    {
        switch( s_DisplayMode )
        {
        case 0:
            {
                // シャッターON
                if( s_RenderSystem.GetLcdMode() != NN_GX_DISPLAYMODE_STEREO )
                {
                    s_RenderSystem.SetLcdMode( NN_GX_DISPLAYMODE_STEREO );
                }

// TODO ここは画面描画必要かも
            }
            break;

        case 1:
        case 2:
        case 3:
            // シャッターOFF
            {
                if( s_RenderSystem.GetLcdMode() != NN_GX_DISPLAYMODE_NORMAL )
                {
                    s_RenderSystem.SetLcdMode( NN_GX_DISPLAYMODE_NORMAL );
                }

// TODO ここも画面描画必要そう
            }
            break;
        }
    }
    else
    {
//        s_RenderSystem.SetLcdMode( NN_GX_DISPLAYMODE_NORMAL );
    }

    // 左目用の絵を描画
    DrawDisplay0Common( currentCamera );

    // 右目用の絵を描画
    if( s_RenderSystem.GetLcdMode() == NN_GX_DISPLAYMODE_STEREO )
    {
        DrawDisplay0ExtCommon();
    }

    s_RenderSystem.SwapBuffers();

} //DrawDisplay0StereoCommon()

//==============================================================================
void DrawDisplay0Common( nn::camera::CameraSelect currentCamera )
{
    // 左眼画像
    // STEREO では OUT2 を表示
    s_RenderSystem.SetRenderTarget(NN_GX_DISPLAY0);
    glViewport(0, 0, nn::gx::DISPLAY0_WIDTH, nn::gx::DISPLAY0_HEIGHT);
    s_RenderSystem.Clear();

    if( s_RenderSystem.GetLcdMode() == NN_GX_DISPLAYMODE_STEREO )
    {
        DrawStereoCamera( 1, false );      // 左カメラ画像
    }
    else
    {
        switch( currentCamera )
        {
        case nn::camera::SELECT_OUT1_OUT2:
        case nn::camera::SELECT_IN1_OUT2:
            {
                switch( s_DisplayMode )
                {
                case 1:
                    {
                        // 重ね合わせて表示
                        DrawStereoCamera( 0, true );
                        DrawStereoCamera( 1, true );
                    }
                    break;

                case 2:
                    {
                        DrawStereoCamera( 0, false );
                    }
                    break;

                case 3:
                    {
                        DrawStereoCamera( 1, false );
                    }
                    break;
                }
            }
            break;

        case nn::camera::SELECT_OUT1:
        case nn::camera::SELECT_IN1:
            {
                DrawStereoCamera( 0, false );
            }
            break;

        case nn::camera::SELECT_OUT2:
            {
                DrawStereoCamera( 1, false );
            }
            break;
        }
    }
    s_RenderSystem.Transfer();
} //DrawDisplay0Common()

//==============================================================================
void DrawDisplay0ExtCommon( void )
{
    // 右眼画像
    // STEREO では OUT1 を表示
    s_RenderSystem.SetRenderTarget(NN_GX_DISPLAY0_EXT);
    glViewport(0, 0, nn::gx::DISPLAY0_WIDTH, nn::gx::DISPLAY0_HEIGHT);
    s_RenderSystem.Clear();

    DrawStereoCamera( 0, false );      // 右カメラ画像
    s_RenderSystem.Transfer();
} //DrawDisplay0ExtCommon()

//==============================================================================
void DrawLineFrame( const f32 sx, const f32 sy, const f32 width, const f32 height )
{
    f32 ex = sx + width  - 1.0f;
    f32 ey = sy + height - 1.0f;

    s_RenderSystem.DrawLine( sx, sy, ex, sy );
    s_RenderSystem.DrawLine( sx, sy, sx, ey );
    s_RenderSystem.DrawLine( sx, ey, ex, ey );
    s_RenderSystem.DrawLine( ex, sy, ex, ey );
}

//==============================================================================
void DrawImage(
    GLuint & textureId, const f32 sx, const f32 sy, const f32 width, const f32 height,
    void * p_Image, const s32 imageWidth, const s32 imageHeight )
{
    if( textureId == 0 )
    {
        s_RenderSystem.GenerateTexture(
            GL_TEXTURE_2D | NN_GX_MEM_FCRAM | GL_NO_COPY_FCRAM_DMP,
            GL_RGB_NATIVE_DMP,
            imageWidth,
            imageHeight,
            GL_RGB_NATIVE_DMP,
            GL_UNSIGNED_BYTE,
            p_Image,
            textureId );
    }
    else
    {
        glBindTexture( GL_TEXTURE_2D, textureId );
        glTexImage2D(
            GL_TEXTURE_2D | NN_GX_MEM_FCRAM | GL_NO_COPY_FCRAM_DMP,
            0,
            GL_RGB_NATIVE_DMP,
            imageWidth,
            imageHeight,
            0,
            GL_RGB_NATIVE_DMP,
            GL_UNSIGNED_BYTE,
            p_Image );
    }
    s_RenderSystem.FillTexturedRectangle(
        textureId,
        sx,
        sy,
        width,
        height,
        imageWidth,
        imageHeight,
        imageWidth,
        imageHeight );
} // DrawImage()

