程式語言 - C++ Builder 6 - Visual Component Library (VCL) - OpenGL 1.0 - Draw Triangle



參考資訊:
https://github.com/gamedev-net/nehe-opengl

main.cpp

#pragma resource "*.dfm"

#include <vcl.h>
#include <Classes.hpp>
#include <Controls.hpp>
#include <Forms.hpp>
#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>

class TForm1 : public TForm {
public:
    __fastcall TForm1(TComponent* Owner);

protected:
    HDC hDC;
    HGLRC hRC;

    void __fastcall FormCreate(TObject *Sender);
    void __fastcall FormPaint(TObject *Sender);
    void __fastcall FormDestroy(TObject *Sender);
};

TForm1 *Form1;

__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner), hDC(NULL), hRC(NULL) {
    OnCreate = FormCreate;
    OnPaint = FormPaint;
    OnDestroy = FormDestroy;
}

void __fastcall TForm1::FormCreate(TObject *Sender) {
    PIXELFORMATDESCRIPTOR pfd = { 0 };

    hDC = ::GetDC(Handle);
    pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 16;
    pfd.cDepthBits = 16;
    pfd.iLayerType = PFD_MAIN_PLANE;

    int fmt = ChoosePixelFormat(hDC, &pfd);

    SetPixelFormat(hDC, fmt, &pfd);
    hRC = wglCreateContext(hDC);
    wglMakeCurrent(hDC, hRC);

    RECT rc;
    ::GetClientRect(Handle, &rc);
    float aspect = (float)(rc.right - rc.left) / (rc.bottom - rc.top);

    glViewport(0, 0, rc.right - rc.left, rc.bottom - rc.top);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-aspect, aspect, -1.0, 1.0, -1.0, 1.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void __fastcall TForm1::FormPaint(TObject *Sender) {
    glLoadIdentity();
    glBegin(GL_TRIANGLES);
        glVertex3f(0.0f, 0.5f, 0.0f);
        glVertex3f(-0.5f, -0.5f, 0.0f);
        glVertex3f(0.5f, -0.5f, 0.0f);
    glEnd();

    SwapBuffers(hDC);
}

void __fastcall TForm1::FormDestroy(TObject *Sender) {
    wglMakeCurrent(NULL, NULL);
    wglDeleteContext(hRC);
    ::ReleaseDC(Handle, hDC);
}

WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) {
    Application->Initialize();
    Application->CreateForm(__classid(TForm1), &Form1);
    Application->Run();

    return 0;
}

main.dfm

object Form1: TForm1
    Left = 0
    Top = 0
    Width = 320
    Height = 240
    Caption = 'main'
    Color = clBtnFace
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -16
    Font.Name = 'MS Sans Serif'
    Font.Style = []
    OldCreateOrder = False
    PixelsPerInch = 144
    TextHeight = 20
end

編譯、執行

$ BOX86_DYNAREC=0 myx86 make -f main.mak

完成