/*
* Glide64 - Glide video plugin for Nintendo 64 emulators.
* Copyright (c) 2002  Dave2001
* Copyright (c) 2003-2009  Sergey 'Gonetz' Lipski
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

//****************************************************************
//
// Glide64 - Glide Plugin for Nintendo 64 emulators (tested mostly with Project64)
// Project started on December 29th, 2001
//
// Authors:
// Dave2001, original author, founded the project in 2001, left it in 2002
// Gugaman, joined the project in 2002, left it in 2002
// Sergey 'Gonetz' Lipski, joined the project in 2002, main author since fall of 2002
// Hiroshi 'KoolSmoky' Morii, joined the project in 2007
//
//****************************************************************
//
// To modify Glide64:
// * Write your name and (optional)email, commented by your work, so I know who did it, and so that you can find which parts you modified when it comes time to send it to me.
// * Do NOT send me the whole project or file that you modified.  Take out your modified code sections, and tell me where to put them.  If people sent the whole thing, I would have many different versions, but no idea how to combine them all.
//
//****************************************************************
//
// Glide64 dialogs
// Created by Gonetz, 2008
//
//****************************************************************

// -*- C++ -*- generated by wxGlade 0.6.3 on Tue Oct 07 22:39:28 2008

#include "Gfx_1.3.h"
#include "DepthBufferRender.h"
#include "Config.h"
#include "trace.h"
#include <Common/StdString.h>

short Set_basic_mode = 0, Set_texture_dir = 0, Set_log_dir = 0, Set_log_flush = 0;

#ifdef _WIN32
#include <Common/CriticalSection.h>
#include "resource.h"

#define _ATL_DISABLE_NOTHROW_NEW
#include <atlbase.h>
#pragma warning(push)
#pragma warning(disable : 4996) // warning C4996: 'GetVersionExA': was declared deprecated
#include <wtl/atlapp.h>
#pragma warning(pop)

#include <atlwin.h>
#include <wtl/atldlgs.h>
#include <wtl/atlctrls.h>
#include <wtl/atlcrack.h>

extern HINSTANCE hinstDLL;

extern CriticalSection * g_ProcessDListCS;

class CGlide64WtlModule :
    public CAppModule
{
public:
    CGlide64WtlModule(HINSTANCE hinst)
    {
        Init(NULL, hinst);
    }
    virtual ~CGlide64WtlModule(void)
    {
        Term();
    }
};

CGlide64WtlModule * WtlModule = NULL;

void ConfigInit(HINSTANCE hinst)
{
    WtlModule = new CGlide64WtlModule(hinst);
}

void ConfigCleanup(void)
{
    if (WtlModule)
    {
        delete WtlModule;
        WtlModule = NULL;
    }
}

#endif


void CloseConfig();

#ifdef TEXTURE_FILTER
uint32_t texfltr[] =
{
    NO_FILTER, //"None"
    SMOOTH_FILTER_1, //"Smooth filtering 1"
    SMOOTH_FILTER_2, //"Smooth filtering 2"
    SMOOTH_FILTER_3, //"Smooth filtering 3"
    SMOOTH_FILTER_4, //"Smooth filtering 4"
    SHARP_FILTER_1,  //"Sharp filtering 1"
    SHARP_FILTER_2,  //"Sharp filtering 2"
};

uint32_t texenht[] =
{
    NO_ENHANCEMENT,    //"None"
    NO_ENHANCEMENT,    //"Store"
    X2_ENHANCEMENT,    //"X2"
    X2SAI_ENHANCEMENT, //"X2SAI"
    HQ2X_ENHANCEMENT,  //"HQ2X"
    HQ2XS_ENHANCEMENT, //"HQ2XS"
    LQ2X_ENHANCEMENT,  //"LQ2X"
    LQ2XS_ENHANCEMENT, //"LQ2XS"
    HQ4X_ENHANCEMENT,  //"HQ4X"
};

uint32_t texcmpr[] =
{
    //NO_COMPRESSION,   //"None"
    //  NCC_COMPRESSION,  //"NCC"
    S3TC_COMPRESSION, //"S3TC"
    FXT1_COMPRESSION, //"FXT1"
};

uint32_t texhirs[] =
{
    NO_HIRESTEXTURES,   //"Do not use"
    RICE_HIRESTEXTURES,  //"Rice format"
    //  GHQ_HIRESTEXTURES, //"GlideHQ format"
    //  JABO_HIRESTEXTURES, //"Jabo format"
};
#endif

#ifdef _WIN32

template < class T, class TT = CToolTipCtrl >
class CToolTipDialog
{
    // Data declarations and members
public:
    TT& GetTT(){ return m_TT; }
protected:
    TT m_TT;
    UINT m_uTTStyle;
    UINT m_uToolFlags;
    // Construction
    CToolTipDialog(UINT uTTSTyle = TTS_NOPREFIX | TTS_BALLOON, UINT uToolFlags = TTF_IDISHWND | TTF_SUBCLASS)
        : m_TT(NULL), m_uTTStyle(uTTSTyle),
        m_uToolFlags(uToolFlags | TTF_SUBCLASS)
    {}

    void TTInit()
    {
        T* pT = (T*)this;
        ATLASSERT(::IsWindow(*pT));
        m_TT.Create(*pT, NULL, NULL, m_uTTStyle);
        CToolInfo ToolInfo(pT->m_uToolFlags, *pT, 0, 0, MAKEINTRESOURCE(pT->IDD));
        m_TT.AddTool(&ToolInfo);
        ::EnumChildWindows(*pT, SetTool, (LPARAM)pT);
        TTSize(0);
        TTActivate(TRUE);
    }
    // Operations
public:
    void TTActivate(BOOL bActivate)
    {
        m_TT.Activate(bActivate);
    }
    void TTSize(int nPixel)
    {
        m_TT.SetMaxTipWidth(nPixel);
    }

    void TTSetTxt(HWND hTool, _U_STRINGorID text)
    {
        m_TT.UpdateTipText(text, hTool);
    }
    void TTSetTxt(UINT idTool, _U_STRINGorID text)
    {
        TTSetTxt(GetHWND(idTool), text);
    }

    BOOL TTAdd(HWND hTool)
    {
        return SetTool(hTool, (LPARAM)(T*)this);
    }
    BOOL TTAdd(UINT idTool)
    {
        return TTAdd(GetHWND(idTool));
    }

    void TTRemove(HWND hTool)
    {
        m_TT.DelTool(hTool);
    }
    void TTRemove(UINT idTool)
    {
        TTRemove(GetHWND(idTool));
    }
    // Message map and handlers
    BEGIN_MSG_MAP(CToolTipDialog)
        MESSAGE_RANGE_HANDLER(WM_MOUSEFIRST, WM_MOUSELAST, OnMouse)
        MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
    END_MSG_MAP()

    LRESULT OnInitDialog(UINT, WPARAM, LPARAM, BOOL& bHandled)
    {
        TTInit();
        bHandled = FALSE;
        return TRUE;
    }

    LRESULT OnMouse(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
    {
        T* pT = (T*)this;
        bHandled = FALSE;
        if (m_TT.IsWindow())
            m_TT.RelayEvent((LPMSG)pT->GetCurrentMessage());
        return 0;
    }
    // Implementation
private:
    HWND GetHWND(UINT idTool)
    {
        return ::GetDlgItem(*(T*)this, idTool);
    }

    static BOOL CALLBACK SetTool(HWND hTool, LPARAM pDlg)
    {
        T* pT = (T*)pDlg;
        int idTool = ::GetWindowLong(hTool, GWL_ID);
        if (idTool != IDC_STATIC)
        {
            CToolInfo ToolInfo(pT->m_uToolFlags, hTool, 0, 0, (LPTSTR)idTool);
            pT->m_TT.AddTool(&ToolInfo);
        }
        return TRUE;
    }
};

void SetComboBoxIndex(CComboBox & cmb, uint32_t data)
{
    cmb.SetCurSel(0);
    for (DWORD i = 0, n = cmb.GetCount(); i < n; i++)
    {
        if (cmb.GetItemData(i) == data)
        {
            cmb.SetCurSel(i);
            break;
        }
    }
}

class CConfigBasicPage;
class CConfigEmuSettings;
class CConfigTextureEnhancement;

class COptionsSheet : public CPropertySheetImpl < COptionsSheet >
{
public:
    // Construction
    COptionsSheet(_U_STRINGorID /*title*/ = (LPCTSTR)NULL, UINT /*uStartPage*/ = 0, HWND /*hWndParent*/ = NULL);
    ~COptionsSheet();

    void UpdateTextureSettings(void);

    // Maps
    BEGIN_MSG_MAP(COptionsSheet)
        CHAIN_MSG_MAP(CPropertySheetImpl<COptionsSheet>)
    END_MSG_MAP()

private:
    // Property pages
    CConfigBasicPage * m_pgBasicPage;
    CConfigEmuSettings * m_pgEmuSettings;
    CConfigTextureEnhancement * m_pgTextureEnhancement;
    HPROPSHEETPAGE m_hTextureEnhancement;
};

class CConfigBasicPage :
    public CPropertyPageImpl<CConfigBasicPage>,
    public CToolTipDialog < CConfigBasicPage >
{
public:
    enum { IDD = IDD_CONFIG_BASIC };

    CConfigBasicPage(COptionsSheet * options_page) :
        m_options_page(options_page)
    {
    }

    BEGIN_MSG_MAP(CConfigBasicPage)
        MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
        COMMAND_HANDLER_EX(IDC_CMB_WINDOW_RES, CBN_SELCHANGE, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CMB_FS_RESOLUTION, CBN_SELCHANGE, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CHK_VERTICAL_SYNC, BN_CLICKED, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CHK_FPS_COUNTER, BN_CLICKED, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CHK_VIS_COUNTER, BN_CLICKED, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CHK_PERCENT_COUNTER, BN_CLICKED, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CHK_CLOCK_ENABLED, BN_CLICKED, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CHK_CLOCK_24, BN_CLICKED, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CHK_TRANSPARENT, BN_CLICKED, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CBXANISOTROPIC, BN_CLICKED, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CHK_SHOW_TEXTURE_ENHANCEMENT, BN_CLICKED, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CHK_AUTODETECT_VRAM, BN_CLICKED, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CHK_USE_FRAME_BUFFER_OBJECT, BN_CLICKED, ItemChanged)
        CHAIN_MSG_MAP(CToolTipDialog<CConfigBasicPage>)
        CHAIN_MSG_MAP(CPropertyPageImpl<CConfigBasicPage>)
    END_MSG_MAP()

    LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
    {
        TTInit();
		TTSize(400);
        m_WindowRes.Attach(GetDlgItem(IDC_CMB_WINDOW_RES));
        m_WindowRes.SetItemData(m_WindowRes.AddString("320x200"), 0);
        m_WindowRes.SetItemData(m_WindowRes.AddString("320x240"), 1);
        m_WindowRes.SetItemData(m_WindowRes.AddString("400x256"), 2);
        m_WindowRes.SetItemData(m_WindowRes.AddString("512x384"), 3);
        m_WindowRes.SetItemData(m_WindowRes.AddString("640x200"), 4);
        m_WindowRes.SetItemData(m_WindowRes.AddString("640x350"), 5);
        m_WindowRes.SetItemData(m_WindowRes.AddString("640x400"), 6);
        m_WindowRes.SetItemData(m_WindowRes.AddString("640x480"), 7);
        m_WindowRes.SetItemData(m_WindowRes.AddString("800x600"), 8);
        m_WindowRes.SetItemData(m_WindowRes.AddString("960x720"), 9);
        m_WindowRes.SetItemData(m_WindowRes.AddString("856x480"), 10);
        m_WindowRes.SetItemData(m_WindowRes.AddString("512x256"), 11);
        m_WindowRes.SetItemData(m_WindowRes.AddString("1024x768"), 12);
        m_WindowRes.SetItemData(m_WindowRes.AddString("1280x1024"), 13);
        m_WindowRes.SetItemData(m_WindowRes.AddString("1600x1200"), 14);
        m_WindowRes.SetItemData(m_WindowRes.AddString("400x300"), 15);
        m_WindowRes.SetItemData(m_WindowRes.AddString("1152x864"), 16);
        m_WindowRes.SetItemData(m_WindowRes.AddString("1280x960"), 17);
        m_WindowRes.SetItemData(m_WindowRes.AddString("1600x1024"), 18);
        m_WindowRes.SetItemData(m_WindowRes.AddString("1792x1344"), 19);
        m_WindowRes.SetItemData(m_WindowRes.AddString("1856x1392"), 20);
        m_WindowRes.SetItemData(m_WindowRes.AddString("1920x1440"), 21);
        m_WindowRes.SetItemData(m_WindowRes.AddString("2048x1536"), 22);
        m_WindowRes.SetItemData(m_WindowRes.AddString("2048x2048"), 23);
        SetComboBoxIndex(m_WindowRes, g_settings->res_data);
        TTSetTxt(IDC_CMB_WINDOW_RES, "Resolution:\n\nThis option selects the windowed resolution.\n\n[Recommended: 640x480, 800x600, 1024x768]");

        m_cbxVSync.Attach(GetDlgItem(IDC_CHK_VERTICAL_SYNC));
        m_cbxVSync.SetCheck(g_settings->vsync ? BST_CHECKED : BST_UNCHECKED);
        TTSetTxt(IDC_CHK_VERTICAL_SYNC, "Vertical sync:\n\nThis option will enable the vertical sync, which will prevent tearing.\nNote: this option will ONLY have effect if vsync is set to \"Software Controlled\".");

        m_cmbScreenShotFormat.Attach(GetDlgItem(IDC_CMB_SCREEN_SHOT_FORMAT));
        for (int f = 0; f < NumOfFormats; f++)
        {
            m_cmbScreenShotFormat.SetItemData(m_cmbScreenShotFormat.AddString(ScreenShotFormats[f].format), ScreenShotFormats[f].type);
        }
        SetComboBoxIndex(m_cmbScreenShotFormat, g_settings->ssformat);
        TTSetTxt(IDC_CMB_SCREEN_SHOT_FORMAT, "Select a format, in which screen shots will be saved");

        m_cbxTextureSettings.Attach(GetDlgItem(IDC_CHK_SHOW_TEXTURE_ENHANCEMENT));
        m_cbxTextureSettings.SetCheck(g_settings->texenh_options ? BST_CHECKED : BST_UNCHECKED);

        m_cbxFPS.Attach(GetDlgItem(IDC_CHK_FPS_COUNTER));
        m_cbxFPS.SetCheck((g_settings->show_fps & 1) > 0 ? BST_CHECKED : BST_UNCHECKED);
        TTSetTxt(IDC_CHK_FPS_COUNTER, "FPS counter:\n\nWhen this option is checked, a FPS (frames per second) counter will be shown in the lower left corner of the screen.\n\n[Recommended: your preference]");

        m_cbxVIS.Attach(GetDlgItem(IDC_CHK_VIS_COUNTER));
        m_cbxVIS.SetCheck((g_settings->show_fps & 2) > 0 ? BST_CHECKED : BST_UNCHECKED);
        TTSetTxt(IDC_CHK_VIS_COUNTER, "VI/s counter:\n\nWhen this option is checked, a VI/s (vertical interrupts per second) counter will be shown in the lower left corner of the screen.\nThis is like the FPS counter but will be consistent at 60 VI/s for full speed on NTSC (U) games and 50 VI/s for full speed on PAL (E) ones.\n\n[Recommended: your preference]");

        m_cbxPercent.Attach(GetDlgItem(IDC_CHK_PERCENT_COUNTER));
        m_cbxPercent.SetCheck((g_settings->show_fps & 4) > 0 ? BST_CHECKED : BST_UNCHECKED);
        TTSetTxt(IDC_CHK_PERCENT_COUNTER, "% speed:\n\nThis displays a percentage of the actual N64 speed in the lower left corner of the screen.\n\n[Recommended: your preference]");

        m_cbxTextTransparent.Attach(GetDlgItem(IDC_CHK_TRANSPARENT));
        m_cbxTextTransparent.SetCheck((g_settings->show_fps & 8) > 0 ? BST_CHECKED : BST_UNCHECKED);
        TTSetTxt(IDC_CHK_TRANSPARENT, "Transparent text background:\n\nIf this is checked, all on-screen messages will have a transparent background.\nOtherwise, it will have a solid black background.\n\n[Recommended: your preference]");

        m_cbxClockEnabled.Attach(GetDlgItem(IDC_CHK_CLOCK_ENABLED));
        m_cbxClockEnabled.SetCheck(g_settings->clock > 0 ? BST_CHECKED : BST_UNCHECKED);
        TTSetTxt(IDC_CHK_CLOCK_ENABLED, "Clock enabled:\n\nThis option will put a clock in the lower right corner of the screen, showing the current time.\n\n[Recommended: your preference]");

        m_cbxClock24.Attach(GetDlgItem(IDC_CHK_CLOCK_24));
        m_cbxClock24.SetCheck(g_settings->clock_24_hr > 0 ? BST_CHECKED : BST_UNCHECKED);
        TTSetTxt(IDC_CHK_CLOCK_24, "Display hours as 24-hour clock.\n\n[Recommended: your preference]");

        m_cmbFSResolution.Attach(GetDlgItem(IDC_CMB_FS_RESOLUTION));
        int32_t size = 0;
        char ** aRes = grQueryResolutionsExt(&size);
        if (aRes && size)
        {
            for (int r = 0; r < size; r++)
            {
                m_cmbFSResolution.AddString(aRes[r]);
            }
            m_cmbFSResolution.SetCurSel(g_settings->wrpResolution < size ? g_settings->wrpResolution : 0);
        }
        TTSetTxt(IDC_CMB_FS_RESOLUTION, "Full screen resolution:\n\nThis sets the full screen resolution.\nAll the resolutions that your video card / monitor support should be displayed.\n\n[Recommended:native(max) resolution of your monitor - unless performance becomes an issue]");

        m_cbxAnisotropic.Attach(GetDlgItem(IDC_CBXANISOTROPIC));
        m_cbxAnisotropic.SetCheck(g_settings->wrpAnisotropic > 0 ? BST_CHECKED : BST_UNCHECKED);
        TTSetTxt(IDC_CBXANISOTROPIC, "Anisotropic filtering:\n\nThis filter sharpens and brings out the details of textures that recede into the distance.\nWhen activated, it will use the max anisotropy your video card supports.\nHowever, this will override native way of texture filtering and may cause visual artifacts in some games.\n\n[Recommended: your preference, game dependant]");

        m_cbxFBO.Attach(GetDlgItem(IDC_CHK_USE_FRAME_BUFFER_OBJECT));
        TTSetTxt(IDC_CHK_USE_FRAME_BUFFER_OBJECT, "Use frame buffer objects:\n\nChanges the way FB effects are rendered - with or without usage of the OpenGL Frame Buffer Objects (FBO) extension.\nThe choice depends on game and your video card. FBO off is good for NVIDIA cards, while for ATI cards, it's usually best that FBOs are turned on.\nAlso, some FB effects works only with one of the methods, no matter, which card you have.\nOn the whole, with FBO off, compatibility/ accuracy is a bit better (which is the case for Resident Evil 2).\nHowever, with FBO on with some systems, it can actually be a bit faster in cases.\n\n[Recommended: video card and game dependant]");
        m_cbxFBO.SetCheck(g_settings->wrpFBO > 0 ? BST_CHECKED : BST_UNCHECKED);

        m_cbxVRAM.Attach(GetDlgItem(IDC_CHK_AUTODETECT_VRAM));
        TTSetTxt(IDC_CHK_AUTODETECT_VRAM, "Autodetect VRAM Size:\n\nSince OpenGL cannot do this reliably at the moment, the option to set this manually is available.\nIf checked, plugin will try to autodetect VRAM size.\nBut if this appears wrong, please uncheck and set it to correct value.\n\n[Recommended: on]");
        m_VramSize.Attach(GetDlgItem(IDC_SPIN_VRAM_SIZE));
        m_VramSize.SetBuddy(GetDlgItem(IDC_TXT_VRAM_SIZE));
        m_spinVRAM.Attach(GetDlgItem(IDC_TXT_VRAM_SIZE));
        m_cbxVRAM.SetCheck(g_settings->wrpVRAM == 0 ? BST_CHECKED : BST_UNCHECKED);
        m_lblMb.Attach(GetDlgItem(IDC_LBL_MB));
        AutoDetectChanged();
        return TRUE;
    }

    bool OnApply()
    {
        char spinVRAM[100];
        m_spinVRAM.GetWindowText(spinVRAM, sizeof(spinVRAM));
        CSettings oldsettings = *g_settings;
        g_settings->res_data = m_WindowRes.GetCurSel();
        g_settings->res_data_org = g_settings->res_data;
        g_settings->scr_res_x = g_settings->res_x = resolutions[g_settings->res_data][0];
        g_settings->scr_res_y = g_settings->res_y = resolutions[g_settings->res_data][1];
        g_settings->vsync = m_cbxVSync.GetCheck() == BST_CHECKED;
        g_settings->ssformat = m_cmbScreenShotFormat.GetCurSel();
        g_settings->show_fps =
            (m_cbxFPS.GetCheck() == BST_CHECKED ? 1 : 0) |
            (m_cbxVIS.GetCheck() == BST_CHECKED ? 2 : 0) |
            (m_cbxPercent.GetCheck() == BST_CHECKED ? 4 : 0) |
            (m_cbxTextTransparent.GetCheck() == BST_CHECKED ? 8 : 0);
        g_settings->texenh_options = m_cbxTextureSettings.GetCheck() == BST_CHECKED;
        g_settings->clock = m_cbxClockEnabled.GetCheck() == BST_CHECKED;
        g_settings->clock_24_hr = m_cbxClock24.GetCheck() == BST_CHECKED;
        g_settings->wrpResolution = m_cmbFSResolution.GetCurSel();
        g_settings->wrpAnisotropic = m_cbxAnisotropic.GetCheck() == BST_CHECKED;
        g_settings->wrpVRAM = m_cbxVRAM.GetCheck() == BST_CHECKED ? 0 : atoi(spinVRAM);
        g_settings->wrpFBO = m_cbxFBO.GetCheck() == BST_CHECKED;

        if (memcmp(&oldsettings, g_settings, sizeof(oldsettings))) //check that settings were changed
        {
            WriteSettings();
        }
        m_options_page->UpdateTextureSettings();
        return true;
    }
private:
    void ItemChanged(UINT /*Code*/, int id, HWND /*ctl*/)
    {
        SendMessage(GetParent(), PSM_CHANGED, (WPARAM)m_hWnd, 0);
        if (id == IDC_CHK_AUTODETECT_VRAM)
        {
            AutoDetectChanged();
        }
    }

    void AutoDetectChanged(void)
    {
        m_spinVRAM.SetWindowText(m_cbxVRAM.GetCheck() == BST_CHECKED ? " auto" : stdstr_f("%d",g_settings->wrpVRAM ? g_settings->wrpVRAM : 32).c_str());
        m_spinVRAM.EnableWindow(m_cbxVRAM.GetCheck() != BST_CHECKED);
        m_VramSize.EnableWindow(m_cbxVRAM.GetCheck() != BST_CHECKED);
        m_lblMb.EnableWindow(m_cbxVRAM.GetCheck() != BST_CHECKED);
    }

    COptionsSheet * m_options_page;
    CComboBox m_WindowRes, m_cmbFSResolution;
    CComboBox m_cmbScreenShotFormat;
    CButton m_cbxVSync;
    CButton m_cbxTextureSettings;
    CButton m_cbxFPS, m_cbxVIS, m_cbxPercent, m_cbxTextTransparent;
    CButton m_cbxClockEnabled, m_cbxClock24;
    CButton m_cbxAnisotropic;
    CButton m_cbxFBO;
    CButton m_cbxVRAM;
    CUpDownCtrl m_VramSize;
    CEdit m_spinVRAM;
    CStatic m_lblMb;
};

class CConfigEmuSettings :
    public CPropertyPageImpl<CConfigEmuSettings>,
    public CToolTipDialog < CConfigEmuSettings >
{
public:
    enum { IDD = IDD_EMULATION_SETTINGS };

    BEGIN_MSG_MAP(CConfigEmuSettings)
        MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
        COMMAND_HANDLER_EX(IDC_CMB_FILTERING_MODE, CBN_SELCHANGE, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CMB_BUFFER_SWAPPING, CBN_SELCHANGE, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CMB_LOD_CALC, CBN_SELCHANGE, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CMB_ASPECT_RATIO, CBN_SELCHANGE, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CHK_FOG, BN_CLICKED, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CHK_BUFFER_CLEAR, BN_CLICKED, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CHK_FRAME_BUFFER_EMULATION, BN_CLICKED, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CHK_HARDWARE_FRAMEBUFFER, BN_CLICKED, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CHK_GET_FRAMEBUFFER, BN_CLICKED, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CHK_READ_EVERY_FRAME, BN_CLICKED, ItemChanged)
        COMMAND_HANDLER_EX(IDC_RENDER_FRAME_AS_TEXTURE, BN_CLICKED, ItemChanged)
        COMMAND_HANDLER_EX(IDC_CHK_DETECT_CPU_WRITE, BN_CLICKED, ItemChanged)
        COMMAND_HANDLER_EX(IDC_SOFTWARE_DEPTH_BUFFER, BN_CLICKED, ItemChanged)
        CHAIN_MSG_MAP(CToolTipDialog<CConfigEmuSettings>)
        CHAIN_MSG_MAP(CPropertyPageImpl<CConfigEmuSettings>)
    END_MSG_MAP()

    LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
    {
        TTInit();
		TTSize(400);

        if (g_romopen)
        {
            ::SetWindowText(GetDlgItem(IDC_INFO), "Current game emulation settings. Change with care!");
        }
        else
        {
            ::SetWindowText(GetDlgItem(IDC_INFO), "Default emulation settings. Not recommended to change!");
        }

        std::string tooltip = "Filtering mode:\n\nThere are three filtering modes possible:\n\n* Automatic filtering - filter exactly how the N64 specifies.\n* Point-sampled filtering - causes texels to appear square and sharp.\n* Bilinear filtering - interpolates the texture to make it appear more smooth.\n\n[Recommended: Automatic]";
        TTSetTxt(IDC_TXT_FILTERING_MODE, tooltip.c_str());
        TTSetTxt(IDC_CMB_FILTERING_MODE, tooltip.c_str());

        m_cmbFiltering.Attach(GetDlgItem(IDC_CMB_FILTERING_MODE));
        m_cmbFiltering.SetItemData(m_cmbFiltering.AddString("Automatic"), 0);
        m_cmbFiltering.SetItemData(m_cmbFiltering.AddString("Force Bilinear"), 1);
        m_cmbFiltering.SetItemData(m_cmbFiltering.AddString("Force Point-sampled"), 2);
        SetComboBoxIndex(m_cmbFiltering, g_settings->filtering);

        tooltip = "Buffer swapping method:\n\nThere are 3 buffer swapping methods:\n\n* old - swap buffers when vertical interrupt has occurred.\n* new - swap buffers when set of conditions is satisfied. Prevents flicker on some games.\n* hybrid - mix of first two methods.  Can prevent even more flickering then previous method, but also can cause artefacts.\nIf you have flickering problems in a game (or graphics that don't show), try to change swapping method.\n\n[Recommended: new (hybrid for Paper Mario)]";
        TTSetTxt(IDC_TXT_BUFFER_SWAPPING, tooltip.c_str());
        TTSetTxt(IDC_CMB_BUFFER_SWAPPING, tooltip.c_str());
        m_cmbBufferSwap.Attach(GetDlgItem(IDC_CMB_BUFFER_SWAPPING));
        m_cmbBufferSwap.SetItemData(m_cmbBufferSwap.AddString("Old"), 0);
        m_cmbBufferSwap.SetItemData(m_cmbBufferSwap.AddString("New"), 1);
        m_cmbBufferSwap.SetItemData(m_cmbBufferSwap.AddString("Hybrid"), 2);
        SetComboBoxIndex(m_cmbBufferSwap, g_settings->swapmode);

        tooltip = "Per-pixel level-of-detail calculation:\n\nN64 uses special mechanism for mip-mapping, which nearly impossible to reproduce correctly on PC hardware.\nThis option enables approximate emulation of this feature.\nFor example, it is required for the Peach/Bowser portrait's transition in Super Mario 64.\nThere are 3 modes:\n\n* off - LOD is not calculated\n* fast - fast imprecise LOD calculation.\n* precise - most precise LOD calculation possible, but more slow.\n\n[Recommended: your preference]";
        TTSetTxt(IDC_TXT_LOD_CALC, tooltip.c_str());
        TTSetTxt(IDC_CMB_LOD_CALC, tooltip.c_str());
        m_cmbLOD.Attach(GetDlgItem(IDC_CMB_LOD_CALC));
        m_cmbLOD.SetItemData(m_cmbLOD.AddString("off"), 0);
        m_cmbLOD.SetItemData(m_cmbLOD.AddString("fast"), 1);
        m_cmbLOD.SetItemData(m_cmbLOD.AddString("precise"), 2);
        SetComboBoxIndex(m_cmbLOD, g_settings->lodmode);

        tooltip = "Aspect ratio of the output:\n\nMost N64 games use 4:3 aspect ratio, but some support widescreen too.\nYou may select appropriate aspect here and set widescreen mode in game settings->\nIn \"Stretch\" mode the output will be stretched to the entire screen, other modes may add black borders if necessary";
        TTSetTxt(IDC_TXT_ASPECT_RATIO, tooltip.c_str());
        TTSetTxt(IDC_CMB_ASPECT_RATIO, tooltip.c_str());

        m_cmbAspect.Attach(GetDlgItem(IDC_CMB_ASPECT_RATIO));
        m_cmbAspect.SetItemData(m_cmbAspect.AddString("4:3 (default)"), 0);
        m_cmbAspect.SetItemData(m_cmbAspect.AddString("Force 16:9"), 1);
        m_cmbAspect.SetItemData(m_cmbAspect.AddString("Stretch"), 2);
        m_cmbAspect.SetItemData(m_cmbAspect.AddString("Original"), 3);
        SetComboBoxIndex(m_cmbAspect, g_settings->aspectmode);

        tooltip = "Fog enabled:\n\nSets fog emulation on//off.\n\n[Recommended: on]";
        TTSetTxt(IDC_CHK_FOG, tooltip.c_str());
        m_cbxFog.Attach(GetDlgItem(IDC_CHK_FOG));
        m_cbxFog.SetCheck(g_settings->fog > 0 ? BST_CHECKED : BST_UNCHECKED);

        tooltip = "Buffer clear on every frame:\n\nForces the frame buffer to be cleared every frame drawn.\nUsually frame buffer clear is controlled by the game.\nHowever, in some cases it is not well emulated, and some garbage may be left on the screen.\nIn such cases, this option must be set on.\n\n[Recommended: on]";
        TTSetTxt(IDC_CHK_BUFFER_CLEAR, tooltip.c_str());
        m_cbxBuffer.Attach(GetDlgItem(IDC_CHK_BUFFER_CLEAR));
        m_cbxBuffer.SetCheck(g_settings->buff_clear > 0 ? BST_CHECKED : BST_UNCHECKED);

        m_cbxFBEnable.Attach(GetDlgItem(IDC_CHK_FRAME_BUFFER_EMULATION));
        TTSetTxt(IDC_CHK_FRAME_BUFFER_EMULATION, "Enable frame buffer emulation:\n\nIf on, plugin will try to detect frame buffer usage and apply appropriate frame buffer emulation.\n\n[Recommended: on for games which use frame buffer effects]");
        m_cbxFBEnable.SetCheck((g_settings->frame_buffer&fb_emulation) > 0 ? BST_CHECKED : BST_UNCHECKED);

        m_cbxFBHWFBE.Attach(GetDlgItem(IDC_CHK_HARDWARE_FRAMEBUFFER));
        TTSetTxt(IDC_CHK_HARDWARE_FRAMEBUFFER, "Enable hardware frame buffer emulation:\n\nIf this option is on, plugin will create auxiliary frame buffers in video memory instead of copying frame buffer content into main memory.\nThis allows plugin to run frame buffer effects without slowdown and without scaling image down to N64's native resolution.\nThis feature is fully supported by Voodoo 4/5 cards and partially by Voodoo3 and Banshee. Modern cards also fully support it.\n\n[Recommended: on, if supported by your hardware]");
        m_cbxFBHWFBE.SetCheck((g_settings->frame_buffer&fb_hwfbe) > 0 ? BST_CHECKED : BST_UNCHECKED);

        m_cbxFBGetFBI.Attach(GetDlgItem(IDC_CHK_GET_FRAMEBUFFER));
        TTSetTxt(IDC_CHK_GET_FRAMEBUFFER, "Get information about frame buffers:\n\nThis is compatibility option. It must be set on for Mupen64 and off for 1964");
        m_cbxFBGetFBI.SetCheck((g_settings->frame_buffer&fb_get_info) > 0 ? BST_CHECKED : BST_UNCHECKED);

        m_cbxFBReadEveryFrame.Attach(GetDlgItem(IDC_CHK_READ_EVERY_FRAME));
        TTSetTxt(IDC_CHK_READ_EVERY_FRAME, "Read every frame:\n\nIn some games plugin can't detect frame buffer usage.\nIn such cases you need to enable this option to see frame buffer effects.\nEvery drawn frame will be read from video card -> it works very slow.\n\n[Recommended: mostly off (needed only for a few games)]");
        m_cbxFBReadEveryFrame.SetCheck((g_settings->frame_buffer&fb_ref) > 0 ? BST_CHECKED : BST_UNCHECKED);

        m_cbxFBasTex.Attach(GetDlgItem(IDC_RENDER_FRAME_AS_TEXTURE));
        TTSetTxt(IDC_RENDER_FRAME_AS_TEXTURE, "Render N64 frame buffer as texture:\n\nWhen this option is enabled, content of each N64 frame buffer is rendered as texture over the frame, rendered by the plugin.\nThis prevents graphics lost, but may cause slowdowns and various glitches in some games.\n\n[Recommended: mostly off]");
        m_cbxFBasTex.SetCheck((g_settings->frame_buffer&fb_read_back_to_screen) > 0 ? BST_CHECKED : BST_UNCHECKED);

        m_cbxDetect.Attach(GetDlgItem(IDC_CHK_DETECT_CPU_WRITE));
        TTSetTxt(IDC_CHK_DETECT_CPU_WRITE, "Detect CPU write to the N64 frame buffer:\n\nThis option works as the previous options, but the plugin is trying to detect, when game uses CPU writes to N64 frame buffer.\nThe N64 frame buffer is rendered only when CPU writes is detected.\nUse this option for those games, in which you see still image or no image at all for some time with no reason.\n\n[Recommended: mostly off]");
        m_cbxDetect.SetCheck((g_settings->frame_buffer&fb_cpu_write_hack) > 0 ? BST_CHECKED : BST_UNCHECKED);

        m_cbxFBDepthBuffer.Attach(GetDlgItem(IDC_SOFTWARE_DEPTH_BUFFER));
        TTSetTxt(IDC_SOFTWARE_DEPTH_BUFFER, "Enable depth buffer rendering:\n\nThis option is used to fully emulate N64 depth buffer.\nIt is required for correct emulation of depth buffer based effects.\nHowever, it requires fast (>1GHz) CPU to work full speed.\n\n[Recommended: on for fast PC]");
        m_cbxFBDepthBuffer.SetCheck((g_settings->frame_buffer&fb_depth_render) > 0 ? BST_CHECKED : BST_UNCHECKED);
        return TRUE;
    }

    bool OnApply()
    {
        CSettings oldsettings = *g_settings;

        g_settings->filtering = m_cmbFiltering.GetItemData(m_cmbFiltering.GetCurSel());
        g_settings->aspectmode = m_cmbAspect.GetItemData(m_cmbAspect.GetCurSel());
        g_settings->swapmode = m_cmbBufferSwap.GetItemData(m_cmbBufferSwap.GetCurSel());
        g_settings->fog = m_cbxFog.GetCheck() == BST_CHECKED;
        g_settings->buff_clear = m_cbxBuffer.GetCheck() == BST_CHECKED;
        g_settings->lodmode = m_cmbLOD.GetItemData(m_cmbLOD.GetCurSel());

        if (m_cbxFBEnable.GetCheck() == BST_CHECKED) g_settings->frame_buffer |= fb_emulation;
        else g_settings->frame_buffer &= ~fb_emulation;
        if (m_cbxFBHWFBE.GetCheck() == BST_CHECKED) g_settings->frame_buffer |= fb_hwfbe;
        else g_settings->frame_buffer &= ~fb_hwfbe;
        if (m_cbxFBReadEveryFrame.GetCheck() == BST_CHECKED) g_settings->frame_buffer |= fb_ref;
        else g_settings->frame_buffer &= ~fb_ref;
        if (m_cbxFBasTex.GetCheck() == BST_CHECKED) g_settings->frame_buffer |= fb_read_back_to_screen;
        else g_settings->frame_buffer &= ~fb_read_back_to_screen;
        if (m_cbxDetect.GetCheck() == BST_CHECKED) g_settings->frame_buffer |= fb_cpu_write_hack;
        else g_settings->frame_buffer &= ~fb_cpu_write_hack;
        if (m_cbxFBGetFBI.GetCheck() == BST_CHECKED) g_settings->frame_buffer |= fb_get_info;
        else g_settings->frame_buffer &= ~fb_get_info;
        if (m_cbxFBDepthBuffer.GetCheck() == BST_CHECKED) g_settings->frame_buffer |= fb_depth_render;
        else g_settings->frame_buffer &= ~fb_depth_render;
        if (memcmp(&oldsettings, g_settings, sizeof(oldsettings))) //check that settings were changed
        {
            WriteSettings();
        }
        return true;
    }
private:
    void ItemChanged(UINT /*Code*/, int /*id*/, HWND /*ctl*/)
    {
        SendMessage(GetParent(), PSM_CHANGED, (WPARAM)m_hWnd, 0);
    }

    CComboBox m_cmbFiltering;
    CComboBox m_cmbBufferSwap;
    CComboBox m_cmbLOD;
    CComboBox m_cmbAspect;
    CButton m_cbxFog;
    CButton m_cbxBuffer;
    CButton m_cbxFBEnable;
    CButton m_cbxFBHWFBE;
    CButton m_cbxFBGetFBI;
    CButton m_cbxFBReadEveryFrame;
    CButton m_cbxFBasTex;
    CButton m_cbxDetect;
    CButton m_cbxFBDepthBuffer;
};

class CConfigTextureEnhancement :
    public CPropertyPageImpl<CConfigTextureEnhancement>,
    public CToolTipDialog < CConfigTextureEnhancement >
{
public:
    enum { IDD = IDD_TEXTURE_ENHANCEMENT };

    BEGIN_MSG_MAP(CConfigTextureEnhancement)
        MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
        CHAIN_MSG_MAP(CToolTipDialog<CConfigTextureEnhancement>)
        CHAIN_MSG_MAP(CPropertyPageImpl<CConfigTextureEnhancement>)
    END_MSG_MAP()

    LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
    {
        TTInit();
		TTSize(400);

        std::string tooltip = "Filters:\n\nApply a filter to either smooth or sharpen textures.\nThere are 4 different smoothing filters and 2 different sharpening filters.\nThe higher the number, the stronger the effect,\ni.e. \"Smoothing filter 4\" will have a much more noticeable effect than \"Smoothing filter 1\".\nBe aware that performance may have an impact depending on the game and/or the PC.\n\n[Recommended: your preference]";
        TTSetTxt(IDC_TXT_ENH_FILTER, tooltip.c_str());
        TTSetTxt(IDC_CMB_ENH_FILTER, tooltip.c_str());
        m_cmbEnhFilter.Attach(GetDlgItem(IDC_CMB_ENH_FILTER));
        m_cmbEnhFilter.SetItemData(m_cmbEnhFilter.AddString("None"), 0);
        m_cmbEnhFilter.SetItemData(m_cmbEnhFilter.AddString("Smooth filtering 1"), 1);
        m_cmbEnhFilter.SetItemData(m_cmbEnhFilter.AddString("Smooth filtering 2"), 2);
        m_cmbEnhFilter.SetItemData(m_cmbEnhFilter.AddString("Smooth filtering 3"), 3);
        m_cmbEnhFilter.SetItemData(m_cmbEnhFilter.AddString("Smooth filtering 4"), 4);
        m_cmbEnhFilter.SetItemData(m_cmbEnhFilter.AddString("Sharp filtering 1"), 5);
        m_cmbEnhFilter.SetItemData(m_cmbEnhFilter.AddString("Sharp filtering 2"), 6);
        SetComboBoxIndex(m_cmbEnhFilter, g_settings->ghq_fltr);

        tooltip = "Texture enhancement:\n\n7 different filters are selectable here, each one with a distinctive look.\nBe aware of possible performance impacts.\n\nIMPORTANT: 'Store' mode - saves textures in cache 'as is'.\nIt can improve performance in games, which load many textures.\nDisable 'Ignore backgrounds' option for better result.\n\n[Recommended: your preference]";
        TTSetTxt(IDC_TXT_ENHANCEMENT, tooltip.c_str());
        TTSetTxt(IDC_CMB_ENHANCEMENT, tooltip.c_str());
        m_cmbEnhEnhancement.Attach(GetDlgItem(IDC_CMB_ENHANCEMENT));
        m_cmbEnhEnhancement.SetItemData(m_cmbEnhEnhancement.AddString("None"), 0);
        m_cmbEnhEnhancement.SetItemData(m_cmbEnhEnhancement.AddString("Store"), 1);
        m_cmbEnhEnhancement.SetItemData(m_cmbEnhEnhancement.AddString("X2"), 2);
        m_cmbEnhEnhancement.SetItemData(m_cmbEnhEnhancement.AddString("X2SAI"), 3);
        m_cmbEnhEnhancement.SetItemData(m_cmbEnhEnhancement.AddString("HQ2X"), 4);
        m_cmbEnhEnhancement.SetItemData(m_cmbEnhEnhancement.AddString("HQ2XS"), 5);
        m_cmbEnhEnhancement.SetItemData(m_cmbEnhEnhancement.AddString("LQ2X"), 6);
        m_cmbEnhEnhancement.SetItemData(m_cmbEnhEnhancement.AddString("LQ2XS"), 7);
        m_cmbEnhEnhancement.SetItemData(m_cmbEnhEnhancement.AddString("HQ4X"), 8);
        SetComboBoxIndex(m_cmbEnhEnhancement, g_settings->ghq_enht);

        tooltip = "Hi-res pack format:\n\nChoose which method is to be used for loading Hi-res texture packs.\nOnly Rice's format is available currently.\nLeave on \"None\" if you will not be needing to load hi-res packs.\n\n[Recommended: Rice's format. Default: \"None\"]";
        TTSetTxt(IDC_TXT_FORMAT_CHOICES, tooltip.c_str());
        TTSetTxt(IDC_CMB_FORMAT_CHOICES, tooltip.c_str());
        m_cmbHrsFormat.Attach(GetDlgItem(IDC_CMB_FORMAT_CHOICES));
        m_cmbHrsFormat.SetItemData(m_cmbHrsFormat.AddString("None"), 0);
        m_cmbHrsFormat.SetItemData(m_cmbHrsFormat.AddString("Rice format"), 1);
        SetComboBoxIndex(m_cmbHrsFormat, g_settings->ghq_hirs);

        m_cmbTextureCompression.Attach(GetDlgItem(IDC_CMB_TEX_COMPRESS_MEHTOD));
        m_cmbTextureCompression.SetItemData(m_cmbTextureCompression.AddString("S3TC"), 0);
        m_cmbTextureCompression.SetItemData(m_cmbTextureCompression.AddString("FXT1"), 1);
        SetComboBoxIndex(m_cmbTextureCompression, g_settings->ghq_cmpr);

        tooltip = "Texture cache size:\n\nEnhanced and filtered textures can be cached to aid performance.\nThis setting will adjust how much PC memory will be dedicated for texture cache.\nThis helps boost performance if there are subsequent requests for the same texture (usually the case).\nNormally, 128MB should be more than enough but there is a sweet spot for each game.\nSuper Mario may not need more than 32megs, but Conker streams a lot of textures, so setting 256+ megs can boost performance.\nAdjust accordingly if you are encountering speed issues.\n'0' disables cache.\n\n[Recommended: PC and game dependant]";
        TTSetTxt(IDC_TXT_TEXTURE_CACHE, tooltip.c_str());
        TTSetTxt(IDC_SPIN_TEXTURE_CACHE, tooltip.c_str());
        TTSetTxt(IDC_TEXT_MB, tooltip.c_str());
        m_textTexCache.Attach(GetDlgItem(IDC_TXT_TEXTURE_CACHE));
        m_textTexCache.SetWindowTextA(stdstr_f("%d", g_settings->ghq_cache_size).c_str());
        m_spinEnhCacheSize.Attach(GetDlgItem(IDC_SPIN_TEXTURE_CACHE));
        m_spinEnhCacheSize.SetBuddy(m_textTexCache);

        TTSetTxt(IDC_CHK_IGNORE_BACKGROUND, "Ignore Backgrounds:\n\nIt is used to skip enhancement for long narrow textures, usually used for backgrounds.\nThis may save texture memory greatly and increase performance.\n\n[Recommended: on (off for 'Store' mode)]");
        m_cbxEnhIgnoreBG.Attach(GetDlgItem(IDC_CHK_IGNORE_BACKGROUND));
        m_cbxEnhIgnoreBG.SetCheck(g_settings->ghq_enht_nobg > 0 ? BST_CHECKED : BST_UNCHECKED);

        tooltip = "Texture compression:\n\nTextures will be compressed using selected texture compression method.\nThe overall compression ratio is about 1/6 for FXT1 and 1/4 for S3TC.\nIn addition to saving space on the texture cache, the space occupied on the GFX hardware's texture RAM, by the enhanced textures, will be greatly reduced.\nThis minimizes texture RAM usage, decreasing the number of texture swaps to the GFX hardware leading to performance gains.\nHowever, due to the nature of lossy compression of FXT1 and S3TC, using this option can sometimes lead to quality degradation of small size textures and color banding of gradient colored textures.\n\n[Recommended: off]";
        TTSetTxt(IDC_CHK_TEX_COMPRESSION, tooltip.c_str());
        TTSetTxt(IDC_CHK_HIRES_TEX_COMPRESSION, tooltip.c_str());

        m_cbxEnhTexCompression.Attach(GetDlgItem(IDC_CHK_TEX_COMPRESSION));
        m_cbxEnhTexCompression.SetCheck(g_settings->ghq_enht_cmpr > 0 ? BST_CHECKED : BST_UNCHECKED);
        m_cbxHrsTexCompression.Attach(GetDlgItem(IDC_CHK_HIRES_TEX_COMPRESSION));
        m_cbxHrsTexCompression.SetCheck(g_settings->ghq_hirs_cmpr > 0 ? BST_CHECKED : BST_UNCHECKED);

        TTSetTxt(IDC_CHK_COMPRESS_CACHE, "Compress texture cache:\n\nMemory will be compressed so that more textures can be held in the texture cache.\nThe compression ratio varies with each texture, but 1/5 of the original size would be a modest approximation.\nThey will be decompressed on-the-fly, before being downloaded to the gfx hardware.\nThis option will still help save memory space even when using texture compression.\n\n[Recommended: on]");
        m_cbxEnhCompressCache.Attach(GetDlgItem(IDC_CHK_COMPRESS_CACHE));
        m_cbxEnhCompressCache.SetCheck(g_settings->ghq_enht_gz > 0 ? BST_CHECKED : BST_UNCHECKED);

        m_cbxHrsTile.Attach(GetDlgItem(IDC_CHK_TILE_TEX));
        TTSetTxt(IDC_CHK_TILE_TEX, "Tile textures:\n\nWhen on, wide texture will be split on several tiles to fit in one 256-width texture.\nThis tiled texture takes much less video memory space and thus overall performance will increase.\nHowever, corresponding polygons must be split too, and this is not polished yet - various issues are possible, including black lines and polygons distortions.\n\n[Recommended: off]");
        m_cbxHrsTile.SetCheck(g_settings->ghq_hirs_tile > 0 ? BST_CHECKED : BST_UNCHECKED);

        m_cbxHrsForce16.Attach(GetDlgItem(IDC_CHK_FORCE_16BPP_TEXT));
        TTSetTxt(IDC_CHK_FORCE_16BPP_TEXT, "Force 16bpp textures:\n\nThe color of the textures will be reduced to 16bpp.\nThis is another space saver and performance enhancer.\nThis halves the space used on the texture cache and the GFX hardware's texture RAM.\nColor reduction is done so that the original quality is preserved as much as possible.\nDepending on the texture, this usually is hardly noticeable.\nSometimes though, it can be: skies are a good example.\n\n[Recommended: off]");
        m_cbxHrsForce16.SetCheck(g_settings->ghq_hirs_tile > 0 ? BST_CHECKED : BST_UNCHECKED);

        m_cbxHrsTexEdit.Attach(GetDlgItem(IDC_CHK_TEX_DUMP_EDIT));
        TTSetTxt(IDC_CHK_TEX_DUMP_EDIT, "Texture dumping mode:\n\nIn this mode, you have that ability to dump textures on screen to the appropriate folder.\nYou can also reload textures while the game is running to see how they look instantly - big time saver!\n\nHotkeys:\n\"R\" reloads hires textures from the texture pack\n\"D\" toggles texture dumps on/off.");
        m_cbxHrsTexEdit.SetCheck(g_settings->ghq_hirs_dump > 0 ? BST_CHECKED : BST_UNCHECKED);

        m_cbxHrsAltCRC.Attach(GetDlgItem(IDC_CHK_ALT_CRC));
        TTSetTxt(IDC_CHK_ALT_CRC, "Alternative CRC calculation:\n\nThis option enables emulation of a palette CRC calculation bug in RiceVideo.\nIf some textures are not loaded, try to set this option on/off.\n\n[Recommended: texture pack dependant, mostly on]");
        m_cbxHrsAltCRC.SetCheck(g_settings->ghq_hirs_altcrc > 0 ? BST_CHECKED : BST_UNCHECKED);
        if (g_settings->ghq_hirs_dump)
        {
            m_cbxHrsAltCRC.EnableWindow(false);
        }

        m_cbxHrsCompressCache.Attach(GetDlgItem(IDC_CHK_HRS_COMPRESS_CACHE));
        TTSetTxt(IDC_CHK_HRS_COMPRESS_CACHE, "Compress texture cache:\n\nWhen game started, plugin loads all its hi-resolution textures into PC memory.\nSince hi-resolution textures are usually large, the whole pack can take hundreds megabytes of memory.\nCache compression allows save memory space greatly.\nTextures will be decompressed on-the-fly, before being downloaded to the gfx hardware.\nThis option will still help save memory space even when using texture compression.\n\n[Recommended: on]");
        m_cbxHrsCompressCache.SetCheck(g_settings->ghq_hirs_gz > 0 ? BST_CHECKED : BST_UNCHECKED);

        m_cbxHrsLetFly.Attach(GetDlgItem(IDC_CHK_USE_ALPHA_FULLY));
        TTSetTxt(IDC_CHK_USE_ALPHA_FULLY, "Use Alpha channel fully:\n\nWhen this option is off, 16bit rgba textures will be loaded using RiceVideo style, with 1bit for alpha channel.\nWhen it is on, GlideHQ will check, how alpha channel is used by the hires texture, and select most appropriate format for it.\nThis gives texture designers freedom to play with alpha, as they need, regardless of format of original N64 texture.\nFor older and badly designed texture packs it can cause unwanted black borders.\n\n[Recommended: texture pack dependant]");
        m_cbxHrsLetFly.SetCheck(g_settings->ghq_hirs_let_texartists_fly > 0 ? BST_CHECKED : BST_UNCHECKED);

        m_cbxSaveTexCache.Attach(GetDlgItem(IDC_CHK_TEX_CACHE_HD));
        TTSetTxt(IDC_CHK_TEX_CACHE_HD, "Save texture cache to HD:\n\nFor enhanced textures cache:\nThis will save all previously loaded and enhanced textures to HD.\nSo upon next game launch, all the textures will be instantly loaded, resulting in smoother performance.\n\nFor high-resolution textures cache:\nAfter creation, loading hi-res texture will take only a few seconds upon game launch, as opposed to the 5 to 60 seconds a pack can take to load without this cache file.\nThe only downside here is upon any changes to the pack, the cache file will need to be manually deleted.\n\nSaved cache files go into a folder called \"Cache\" within the Textures folder.\n\n[Highly Recommended: on]");
        m_cbxSaveTexCache.SetCheck(g_settings->ghq_cache_save > 0 ? BST_CHECKED : BST_UNCHECKED);
        return TRUE;
    }

    bool OnApply()
    {
        char texcache[100];
        m_textTexCache.GetWindowText(texcache, sizeof(texcache));

        CSettings oldsettings = *g_settings;
        g_settings->ghq_fltr = m_cmbEnhFilter.GetItemData(m_cmbEnhFilter.GetCurSel());
        g_settings->ghq_enht = m_cmbEnhEnhancement.GetItemData(m_cmbEnhEnhancement.GetCurSel());
        g_settings->ghq_cache_size = atoi(texcache);
        g_settings->ghq_enht_nobg = (int)m_cbxEnhIgnoreBG.GetCheck() == BST_CHECKED;
        g_settings->ghq_enht_cmpr = (int)m_cbxEnhTexCompression.GetCheck() == BST_CHECKED;
        g_settings->ghq_enht_gz = (int)m_cbxEnhCompressCache.GetCheck() == BST_CHECKED;
        g_settings->ghq_hirs = m_cmbHrsFormat.GetItemData(m_cmbHrsFormat.GetCurSel());
        g_settings->ghq_hirs_tile = (int)m_cbxHrsTile.GetCheck() == BST_CHECKED;
        g_settings->ghq_hirs_f16bpp = (int)m_cbxHrsForce16.GetCheck() == BST_CHECKED;
        g_settings->ghq_hirs_dump = (int)m_cbxHrsTexEdit.GetCheck() == BST_CHECKED;
        g_settings->ghq_hirs_altcrc = (int)m_cbxHrsAltCRC.GetCheck() == BST_CHECKED;
        g_settings->ghq_hirs_cmpr = (int)m_cbxHrsTexCompression.GetCheck() == BST_CHECKED;
        g_settings->ghq_hirs_gz = (int)m_cbxHrsCompressCache.GetCheck() == BST_CHECKED;
        g_settings->ghq_hirs_let_texartists_fly = (int)m_cbxHrsLetFly.GetCheck() == BST_CHECKED;
        g_settings->ghq_cmpr = (int)m_cmbTextureCompression.GetItemData(m_cmbTextureCompression.GetCurSel());
        g_settings->ghq_cache_save = (int)m_cbxSaveTexCache.GetCheck() == BST_CHECKED;
        if (memcmp(&oldsettings, g_settings, sizeof(oldsettings))) //check that settings were changed
        {
            WriteSettings();
        }
        return true;
    }
private:
    void ItemChanged(UINT /*Code*/, int /*id*/, HWND /*ctl*/)
    {
        SendMessage(GetParent(), PSM_CHANGED, (WPARAM)m_hWnd, 0);
    }

    CComboBox m_cmbEnhFilter;
    CComboBox m_cmbEnhEnhancement;
    CComboBox m_cmbHrsFormat;
    CComboBox m_cmbTextureCompression;
    CButton m_cbxEnhIgnoreBG;
    CButton m_cbxEnhTexCompression;
    CButton m_cbxHrsTexCompression;
    CButton m_cbxEnhCompressCache;
    CButton m_cbxHrsTile;
    CButton m_cbxHrsForce16;
    CButton m_cbxHrsTexEdit;
    CButton m_cbxHrsAltCRC;
    CButton m_cbxHrsCompressCache;
    CButton m_cbxHrsLetFly;
    CButton m_cbxSaveTexCache;
    CEdit m_textTexCache;
    CUpDownCtrl m_spinEnhCacheSize;
};

COptionsSheet::COptionsSheet(_U_STRINGorID /*title*/, UINT /*uStartPage*/, HWND /*hWndParent*/) :
    m_pgBasicPage(new CConfigBasicPage(this)),
    m_pgEmuSettings(new CConfigEmuSettings),
    m_pgTextureEnhancement(NULL),
    m_hTextureEnhancement(0)
{
    AddPage(&m_pgBasicPage->m_psp);
    if (g_settings->advanced_options)
    {
        AddPage(&m_pgEmuSettings->m_psp);
    }
    UpdateTextureSettings();
}

COptionsSheet::~COptionsSheet()
{
    delete m_pgBasicPage;
    delete m_pgEmuSettings;
    delete m_pgTextureEnhancement;
}

void COptionsSheet::UpdateTextureSettings(void)
{
    if (g_settings->texenh_options)
    {
        if (m_hTextureEnhancement == NULL)
        {
            m_pgTextureEnhancement = new CConfigTextureEnhancement;
            m_hTextureEnhancement = m_pgTextureEnhancement->Create();
            AddPage(m_hTextureEnhancement);
        }
    }
    else if (m_hTextureEnhancement != NULL)
    {
        RemovePage(m_hTextureEnhancement);
        m_hTextureEnhancement = NULL;
        delete m_pgTextureEnhancement;
        m_pgTextureEnhancement = NULL;
    }
}
#endif

/******************************************************************
Function: DllConfig
Purpose:  This function is optional function that is provided
to allow the user to configure the dll
input:    a handle to the window that calls this function
output:   none
*******************************************************************/
void CALL DllConfig(HWND hParent)
{
    WriteTrace(TraceGlide64, TraceDebug, "-");
#ifdef _WIN32
    CGuard guard(*g_ProcessDListCS);
    ReadSettings();

    if (g_romopen)
    {
        if (evoodoo)// && fullscreen && !ev_fullscreen)
        {
            ReleaseGfx();
            rdp_reset();
        }
#ifdef TEXTURE_FILTER // Hiroshi Morii <koolsmoky@users.sourceforge.net>
        if (g_settings->ghq_use)
        {
            ext_ghq_shutdown();
            g_settings->ghq_use = 0;
        }
#endif
    }
    else
    {
        char name[21] = "DEFAULT";
        ReadSpecialSettings(name);
    }

    COptionsSheet("Glide64 settings").DoModal(hParent);
    CloseConfig();
#endif
}

void CloseConfig()
{
    if (g_romopen)
    {
        if (fb_depth_render_enabled)
            ZLUT_init();
        // re-init evoodoo graphics to resize window
        if (evoodoo)// && !ev_fullscreen)
            InitGfx();
        else
            rdp_reset();
    }
}

#ifdef _WIN32
class CAboutDlg :
    public CDialogImpl<CAboutDlg>
{
public:
    enum { IDD = IDD_ABOUTBOX };

    BEGIN_MSG_MAP(CAboutDlg)
        MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
        COMMAND_ID_HANDLER(IDOK, OnCloseCmd)
        COMMAND_ID_HANDLER(IDCANCEL, OnCloseCmd)
    END_MSG_MAP()

    LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
    {
        CenterWindow(GetParent());
        return TRUE;
    }

    LRESULT OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
    {
        EndDialog(wID);
        return 0;
    }
};
#endif

/******************************************************************
Function: DllAbout
Purpose:  This function is optional function that is provided
to give further information about the DLL.
input:    a handle to the window that calls this function
output:   none
*******************************************************************/
void CALL DllAbout(HWND /*hParent*/)
{
#ifdef _WIN32
    CAboutDlg dlg;
    dlg.DoModal();
#endif
}

void general_setting(short setting_ID, const char * name, unsigned int value)
{
    RegisterSetting(setting_ID, Data_DWORD_General, name, NULL, value, NULL);
}

void game_setting(short setting_ID, const char * name, unsigned int value)
{
    RegisterSetting(setting_ID, Data_DWORD_Game, name, NULL, value, NULL);
}

void game_setting_default(short setting_ID, const char * name, short default_setting)
{
    RegisterSetting2(setting_ID, Data_DWORD_Game, name, NULL, default_setting);
}
