2017-08-03 72 views
0

我正在編寫一個C#Windows窗體應用程序。我從NuGet軟件包使用OpenGL.Net和OpenGL.Net Win Forms v0.5.2。我已經爲我的表單添加了一個glControl。我想在進入任何有趣的事情之前正確設置它。爲什麼Gl.Ortho()拋出異常,我該如何解決它?

這裏是我的glControl

private void glControl1_Load(object sender, EventArgs e) 
    { 
     //Initialize Here 
     Gl.ClearColor(0.0f, 0.0f, 1.0f, 1.0f); 
    } 

負荷事件這是我的渲染事件的glControl

private void glControl1_Render(object sender, GlControlEventArgs e) 
    { 
     //Clear first 
     Gl.Clear(ClearBufferMask.ColorBufferBit); 

     Gl.MatrixMode(MatrixMode.Projection); 
     Gl.PushMatrix(); 
     Gl.LoadIdentity(); 
     Gl.Ortho(0, glControl1.Width, 0, glControl1.Height, -1, 1); 

     Gl.MatrixMode(MatrixMode.Modelview); 
     Gl.PushMatrix(); 
     Gl.LoadIdentity(); 

     Gl.Enable(EnableCap.Texture2d); 
     Gl.Enable(EnableCap.Blend); 
     Gl.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha); 

     //Draw Here 


     Gl.Disable(EnableCap.Blend); 
     Gl.Disable(EnableCap.Texture2d); 
     Gl.BindTexture(TextureTarget.Texture2d, 0); 

     Gl.PopMatrix(); 
     Gl.MatrixMode(MatrixMode.Projection); 
     Gl.PopMatrix(); 

     Gl.Finish(); 
    } 

我從打電話Gl.Ortho得到一個異常()。如果我將其註釋掉,我不會遇到任何運行時問題。

System.NullReferenceException occurred 
HResult=0x80004003 
Message=Object reference not set to an instance of an object. 
Source=OpenGL.Net 
StackTrace: 
at OpenGL.Gl.Ortho(Single l, Single r, Single b, Single t, Single n, Single f) 
at AnimationTool.Form1.glControl1_Render(Object sender, GlControlEventArgs e) 
Project\AnimationTool\AnimationTool\Form1.cs:line 53 
at OpenGL.GlControl.OnRender() 
at OpenGL.GlControl.OnPaint(PaintEventArgs e) 

我不明白我可以如何使openGL調用,只有我的Gl.Ortho()引發異常。到底是怎麼回事?

+1

確保在將glControl1傳遞給Gl.Ortho()之前設置了「glControl1」。 – Ripi2

+0

@ Ripi2:如果異常來自屬性訪問'glControl1.Width'(或'Height'),那麼'gl.Ortho'不會出現在調用堆棧中。 –

+0

@Michael:在OpenGL上下文初始化之前,''GLControl'有時會導致'Paint'和'Render'回調。嘗試在初始化之前使用OpenGL調用將失敗。嘗試在Load事件中設置一個布爾標誌(一個好名字是'isGLReady'),如果該標誌沒有設置,則在Paint或Render中立即返回。 –

回答

0

實際撥打Gl.Ortho指向glOrthof,這是一個OpenGL 1.0 ES命令。由於您有桌面GL上下文沒有函數加載,因此NullReferenceException

爲了解決你的問題,只要使用正確的方法重載:

Gl.Ortho(0.0, (double)glControl1.Width, 0.0, (double)glControl1.Height, -1.0, 1.0); 

這個問題在項目wiki已經解釋。

相關問題