…ということで,今回はWPF上にOpenGLのビューを作成するサンプルを作ってみました。



00035: /// <summary>
00036: /// 初期化処理
00037: /// </summary>
00038: /// <param name="sender"></param>
00039: /// <param name="e"></param>
00040: private void WindowSourceInitialized(object sender, EventArgs e)
00041: {
00042: //ウィンドウハンドル取得
00043: IntPtr hWnd = new WindowInteropHelper(this).Handle;
00044:
00045: //描画クラスの作成
00046: renderer = new GLRenderer(hWnd);
00047: renderer.Initialized();
00048: renderer.SizeChanged(RenderSize);//一度リサイズしておく
00049:
00050: //タイマー
00051: timer = new DispatcherTimer();
00052: timer.Tick += new EventHandler(DispatcherTimerTick);
00053: timer.Interval = new TimeSpan(0, 0, 0, 0, 16); // 16msecで描画
00054: timer.Start();
00055: }
続いて描画処理ですが,描画処理はタイマーイベントで16msec毎に描画するようにします。16msecなのは,60FPSになるようにするため1/60=0.016secだからです。00042: /// <summary>
00043: /// コンストラクタ
00044: /// </summary>
00045: /// <param name="hWnd"></param>
00046: public GLRenderer(IntPtr hWnd)
00047: {
00048: size = new Size();
00049:
00050: //ピクセルフォーマットの設定
00051: SetupPixelFormat(hWnd);
00052: }
SetupPixelFormatメソッドの中身ですが,ピクセルフォーマットの設定とレンダリングコンテキストの作成を行っています。00147: /// <summary>
00148: /// ピクセルフォーマットの設定
00149: /// </summary>
00150: /// <param name="hWnd">ウィンドウハンドル</param>
00151: private void SetupPixelFormat(IntPtr hWnd)
00152: {
00153: // PIXELFORMATDESCRIPTORの設定
00154: Gdi.PIXELFORMATDESCRIPTOR pfd = new Gdi.PIXELFORMATDESCRIPTOR();
00155: pfd.dwFlags = Gdi.PFD_SUPPORT_OPENGL | Gdi.PFD_DRAW_TO_WINDOW | Gdi.PFD_DOUBLEBUFFER;
00156: pfd.iPixelType = Gdi.PFD_TYPE_RGBA;
00157: pfd.cColorBits = 32;
00158: pfd.cAlphaBits = 8;
00159: pfd.cDepthBits = 24;
00160:
00161: // デバイスコンテキストハンドルの取得
00162: hDC = User.GetDC(hWnd);
00163:
00164: // ピクセルフォーマットの選択
00165: int pixelFormat = Gdi.ChoosePixelFormat(this.hDC, ref pfd);
00166: if ( pixelFormat == 0 )
00167: throw new Exception("Error : Cann't Find A Suitable PixelFormat.");
00168:
00169: // ピクセルフォーマットの設定
00170: if (!Gdi.SetPixelFormat(hDC, pixelFormat, ref pfd))
00171: throw new Exception("Error : Cann't Set The PixelFormat.");
00172:
00173: // レンダリングコンテキストの生成
00174: hRC = Wgl.wglCreateContext(hDC);
00175: if (hRC == IntPtr.Zero)
00176: throw new Exception("Error : Cann't Create A GLRendering Context.");
00177:
00178: // レンダリングコンテキストカレントにする
00179: Wgl.wglMakeCurrent(hDC, hRC);
00180:
00181: // GLエラーのチェック
00182: int error = Gl.glGetError();
00183: if (error != Gl.GL_NO_ERROR)
00184: throw new Exception("GL Error : " + error.ToString());
00185:
00186: }