Skip to content
Browse files

GLEssentials before OpenTK1.0 conversion

  • Loading branch information...
1 parent b891556 commit 3a89b4c941b2e68c5fab4afdbc5ed34279cc49c4 Eric Beisecker committed Mar 30, 2012
View
22 iOSGLEssentials/iOSGLEssentials.userprefs
@@ -1,18 +1,26 @@
<Properties>
<MonoDevelop.Ide.Workspace ActiveConfiguration="Debug|iPhoneSimulator" />
- <MonoDevelop.Ide.Workbench ActiveDocument="iOSGLEssentials/MatrixUtil.cs">
+ <MonoDevelop.Ide.Workbench ActiveDocument="iOSGLEssentials/OpenGLRenderer.cs">
<Files>
- <File FileName="iOSGLEssentials/AppDelegate.cs" Line="35" Column="16" />
+ <File FileName="iOSGLEssentials/AppDelegate.cs" Line="19" Column="3" />
<File FileName="iOSGLEssentials/EAGLEView.cs" Line="144" Column="24" />
- <File FileName="iOSGLEssentials/ES2Renderer.cs" Line="17" Column="26" />
- <File FileName="iOSGLEssentials/OpenGLRenderer.cs" Line="80" Column="4" />
- <File FileName="iOSGLEssentials/DemoModel.cs" Line="32" Column="3" />
- <File FileName="iOSGLEssentials/MatrixUtil.cs" Line="95" Column="3" />
+ <File FileName="iOSGLEssentials/ES2Renderer.cs" Line="16" Column="12" />
+ <File FileName="iOSGLEssentials/OpenGLRenderer.cs" Line="226" Column="9" />
+ <File FileName="iOSGLEssentials/MatrixUtil.cs" Line="855" Column="4" />
+ <File FileName="iOSGLEssentials/VectorUtil.cs" Line="8" Column="4" />
+ <File FileName="iOSGLEssentials/GLUtil.cs" Line="8" Column="42" />
+ <File FileName="iOSGLEssentials/DemoImage.cs" Line="55" Column="4" />
+ <File FileName="iOSGLEssentials/DemoSource.cs" Line="9" Column="34" />
+ <File FileName="iOSGLEssentials/DemoModel.cs" Line="278" Column="49" />
</Files>
<Pads>
<Pad Id="ProjectPad">
<State expanded="True">
- <Node name="iOSGLEssentials" expanded="True" selected="True" />
+ <Node name="iOSGLEssentials" expanded="True">
+ <Node name="References" expanded="True" />
+ <Node name="Shaders" expanded="True" />
+ <Node name="OpenGLRenderer.cs" selected="True" />
+ </Node>
</State>
</Pad>
<Pad Id="ClassPad">
View
1,837 iOSGLEssentials/iOSGLEssentials/DataConverter.cs
1,837 additions, 0 deletions not shown because the diff is too large. Please use a local Git client to view these changes.
View
65 iOSGLEssentials/iOSGLEssentials/DemoImage.cs
@@ -0,0 +1,65 @@
+using System;
+using OpenTK.Graphics.ES20;
+using MonoTouch.UIKit;
+using MonoTouch.CoreGraphics;
+using System.Drawing;
+
+namespace iOSGLEssentials
+{
+ public class DemoImage
+ {
+ public byte[] Data {get; set;}
+ public int Size {get; set;}
+
+ public int Width {get; set;}
+ public int Height {get; set;}
+ public All Format {get; set;}
+ public All Type {get; set;}
+
+ public int RowByteSize{get; set;}
+
+ public DemoImage ()
+ {
+ }
+
+ public static DemoImage LoadImage(string filePathName, bool flipVertical)
+ {
+ var imageClass = new UIImage(filePathName);
+
+ var cgImage = imageClass.CGImage;
+ if(cgImage == null)
+ {
+ return null;
+ }
+
+ var image = new DemoImage();
+ image.Width = cgImage.Width;
+ image.Height = cgImage.Height;
+ image.RowByteSize = image.Width * 4;
+ image.Data = new byte[cgImage.Height * cgImage.Width];
+ image.Format = All.Rgba;
+ image.Type = All.UnsignedByte;
+
+ using(var context = new CGBitmapContext(image.Data, image.Width, image.Height, 8, image.RowByteSize, cgImage.ColorSpace, CGImageAlphaInfo.NoneSkipLast))
+ {
+ context.SetBlendMode(CGBlendMode.Copy);
+
+ if(flipVertical)
+ {
+ context.TranslateCTM(0.0f, (float)image.Height);
+ context.ScaleCTM(1.0f, -1.0f);
+ }
+
+ context.DrawImage(new RectangleF(0f, 0f, image.Width, image.Height), cgImage);
+ }
+
+ if(image.Data == null)
+ {
+ return null;
+ }
+
+ return image;
+ }
+ }
+}
+
View
252 iOSGLEssentials/iOSGLEssentials/DemoModel.cs
@@ -1,15 +1,54 @@
using System;
-using OpenTK.Graphics.ES11;
+using OpenTK.Graphics.ES20;
+using System.IO;
+using System.Runtime.InteropServices;
namespace iOSGLEssentials
{
public class DemoModel
{
+ [StructLayout(LayoutKind.Explicit)]
struct ModelHeader
{
- public string FileIdentifier{ get;set; }
- public uint MajorVersion { get; set; }
- public uint MinorVersion { get; set; }
+ [FieldOffset(0)]
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 30)]
+ public string FileIdentifier;
+
+ [FieldOffset(8)]
+ public uint MajorVersion;
+
+ [FieldOffset(12)]
+ public uint MinorVersion;
+ }
+
+ [StructLayout(LayoutKind.Explicit)]
+ struct ModelTOC
+ {
+ [FieldOffset(0)]
+ public int AttribHeaderSize;
+ [FieldOffset(4)]
+ public int ByteElementOffset;
+ [FieldOffset(8)]
+ public int BytePositionOffset;
+ [FieldOffset(12)]
+ public int ByteTexcoordOffset;
+ [FieldOffset(16)]
+ public int ByteNormalOffset;
+ }
+
+ [StructLayout(LayoutKind.Explicit)]
+ struct ModelAttrib
+ {
+ [FieldOffset(0)]
+ public int ByteSize;
+ [FieldOffset(4)]
+ public All DataType;
+ [FieldOffset(8)]
+ public All PrimType;
+ [FieldOffset(12)]
+ public int SizePerElement;
+ [FieldOffset(16)]
+ public int NumElements;
}
#region Properties
@@ -21,6 +60,7 @@ struct ModelHeader
public int PositionArraySize { get; set; }
public byte[] TexCoords { get; set; }
+ public All TexCoordType {get; set;}
public int TexCoordsSize { get; set; }
public int TexCoordArraySize { get; set; }
@@ -42,7 +82,211 @@ public DemoModel ()
}
+ static T ToStruct<T>(byte[] buffer)
+ {
+ var handel = GCHandle.Alloc(buffer, GCHandleType.Pinned);
+ var strct = (T)Marshal.PtrToStructure(handel.AddrOfPinnedObject(), typeof(T));
+ handel.Free();
+ return strct;
+ }
+
+ public static DemoModel LoadModel(string filePathName)
+ {
+ if(string.IsNullOrEmpty(filePathName))
+ {
+ return null;
+ }
+
+ var model = new DemoModel();
+
+ using(var fileStream = File.Open(filePathName, FileMode.Open))
+ using(var binaryReader = new BinaryReader(fileStream))
+ {
+ // Get the Size of the ModelHeader
+ var size = Marshal.SizeOf(typeof(ModelHeader));
+ var buffer = new byte[size];
+
+ // Create the ModelHeader from the bytes Read in.
+ buffer = binaryReader.ReadBytes(size);
+ var modelHeader = ToStruct<ModelHeader>(buffer);
+
+ if(modelHeader.FileIdentifier.CompareTo("AppleOpenGLDemoModelWWDC2010") != 0)
+ {
+ Console.WriteLine("File Identifier incorrect");
+ return null;
+ }
+
+ if(modelHeader.MajorVersion != 0 && modelHeader.MinorVersion != 1)
+ {
+ Console.WriteLine("Model Version Incorrect");
+ return null;
+ }
+
+ // Get the size of the ModelTOC
+ size = Marshal.SizeOf(typeof(ModelTOC));
+ Array.Resize<byte>(ref buffer, size);
+
+ // Convert the Bytes into the Struct
+ buffer = binaryReader.ReadBytes(size);
+ var modelTOC = ToStruct<ModelTOC>(buffer);
+
+ if(modelTOC.AttribHeaderSize > Marshal.SizeOf (typeof(ModelAttrib)))
+ {
+ Console.WriteLine("Model Attribute Size incorrect");
+ return null;
+ }
+
+ fileStream.Seek(modelTOC.ByteElementOffset, SeekOrigin.Begin);
+
+ // Get the size of the ModelAttrib
+ size = Marshal.SizeOf(typeof(ModelAttrib));
+ Array.Resize<byte>(ref buffer, size);
+
+ // Convert the bytes into the struct
+ buffer = binaryReader.ReadBytes(size);
+ var attrib = ToStruct<ModelAttrib>(buffer);
+
+ model.ElementArraySize = attrib.ByteSize;
+ model.ElementType = attrib.DataType;
+ model.NumElements = attrib.NumElements;
+
+ // OpenGL ES cannot use uint element
+ // So if the model has UI elements
+ if(model.ElementType == All.UnsignedInt)
+ {
+ // ...Load the UI elements and convert to UnsignedShort
+
+ var uiElements = new byte[model.ElementArraySize];
+ model.Elements = new byte[model.NumElements * Marshal.SizeOf (typeof(short))];
+
+ uiElements = binaryReader.ReadBytes(model.ElementArraySize);
+
+ var elemNum = 0;
+ for(elemNum = 0; elemNum < model.NumElements; elemNum++)
+ {
+ // We can't hanle this model if an element is out of the UnsignedInt range
+ if(Convert.ToUInt32 (uiElements[elemNum]) >= 0xFFFF)
+ {
+ return null;
+ }
+
+ model.Elements[elemNum] = uiElements[elemNum];
+ }
+
+ model.ElementType = All.UnsignedShort;
+ model.ElementArraySize = model.NumElements * Marshal.SizeOf(typeof(short));
+ }
+ else
+ {
+ model.Elements = new byte[model.ElementArraySize];
+ model.Elements = binaryReader.ReadBytes(model.ElementArraySize);
+ }
+
+ binaryReader.BaseStream.Seek (modelTOC.BytePositionOffset, SeekOrigin.Begin);
+
+ // Convert file bytes to Struct
+ Array.Resize<byte>(ref buffer, modelTOC.AttribHeaderSize);
+ buffer = binaryReader.ReadBytes(modelTOC.AttribHeaderSize);
+ attrib = ToStruct<ModelAttrib>(buffer);
+
+ model.PositionArraySize = attrib.ByteSize;
+ model.PositionType = attrib.DataType;
+ model.PositionSize = attrib.SizePerElement;
+ model.Positions = new byte[model.PositionArraySize];
+
+ model.Positions = binaryReader.ReadBytes(model.PositionArraySize);
+
+ fileStream.Seek(modelTOC.ByteTexcoordOffset, SeekOrigin.Begin);
+
+ // Convert file bytes to Struct
+ Array.Resize<byte>(ref buffer, modelTOC.AttribHeaderSize);
+ buffer = binaryReader.ReadBytes(modelTOC.AttribHeaderSize);
+ attrib = ToStruct<ModelAttrib>(buffer);
+
+ model.TexCoordArraySize = attrib.ByteSize;
+ model.TexCoordType = attrib.DataType;
+ model.TexCoordsSize = attrib.SizePerElement;
+
+ // Must have the same number of texcoords as positions
+ if(model.NumVertcies != attrib.NumElements)
+ {
+ return null;
+ }
+
+ model.TexCoords = new byte[model.TexCoordArraySize];
+
+ fileStream.Seek(modelTOC.ByteNormalOffset, SeekOrigin.Begin);
+
+ model.Normals = binaryReader.ReadBytes(model.NormalArraySize);
+
+ return model;
+ }
+ }
+ public static DemoModel LoadQuadModel()
+ {
+ var posArray = new float[]
+ {
+ -200.0f, 0.0f, -200.0f,
+ 200.0f, 0.0f, -200.0f,
+ 200.0f, 0.0f, 200.0f,
+ -200.0f, 0.0f, 200.0f
+ };
+
+ var texcoordArray = new float[]
+ {
+ 0.0f, 1.0f,
+ 1.0f, 1.0f,
+ 1.0f, 0.0f,
+ 0.0f, 0.0f
+ };
+
+ var normalArray = new float[]
+ {
+ 0.0f, 0.0f, 1.0f,
+ 0.0f, 0.0f, 1.0f,
+ 0.0f, 0.0f, 1.0f,
+ 0.0f, 0.0f, 1.0f,
+ };
+
+ var elementArray = new short[]
+ {
+ 0, 2, 1,
+ 0, 3, 2
+ };
+
+ var model = new DemoModel();
+
+ model.PositionType = All.Float;
+ model.PositionSize = 3;
+ model.PositionArraySize = posArray.Length;
+ model.Positions = new byte[model.PositionArraySize];
+ Array.Copy(posArray, model.Positions, model.PositionArraySize);
+
+ model.TexCoordType = All.Float;
+ model.TexCoordsSize = 2;
+ model.TexCoordArraySize = texcoordArray.Length;
+ model.TexCoords = new byte[model.PositionArraySize];
+ Array.Copy(texcoordArray, model.TexCoords, model.TexCoordArraySize);
+
+ model.NormalType = All.Float;
+ model.NormalSize = 3;
+ model.NormalArraySize = normalArray.Length;
+ model.Normals = new byte[model.NormalArraySize];
+ Array.Copy(normalArray, model.Normals, model.NormalArraySize);
+
+ model.ElementArraySize = elementArray.Length;
+ model.Elements = new byte[model.ElementArraySize];
+ Array.Copy(elementArray, model.Elements, model.ElementArraySize);
+
+ model.PrimType = All.Triangles;
+
+ model.NumElements = elementArray.Length;
+ model.ElementType = All.UnsignedShort;
+ model.NumVertcies = model.PositionArraySize / model.PositionSize;
+
+ return model;
+ }
}
}
View
43 iOSGLEssentials/iOSGLEssentials/DemoSource.cs
@@ -0,0 +1,43 @@
+using System;
+using OpenTK.Graphics.ES20;
+using System.IO;
+
+namespace iOSGLEssentials
+{
+ public class DemoSource
+ {
+ public string String{get; set;}
+ public int ByteSize {get; set;}
+ public All ShaderType {get; set;} // Vertex or Fragment
+
+ public DemoSource ()
+ {
+ }
+
+ public static DemoSource LoadSource(string filePathName)
+ {
+ var source = new DemoSource();
+
+ // Check the file name suffix to determine what type of shader this is
+ if(Path.GetExtension(filePathName) == ".fsh")
+ {
+ source.ShaderType = All.FragmentShader;
+ }
+ else if(Path.GetExtension(filePathName) == ".vsh")
+ {
+ source.ShaderType = All.VertexShader;
+ }
+ else
+ {
+ // Unknown
+ source.ShaderType = (All)0;
+ }
+
+ var fileContent = File.ReadAllText(filePathName);
+ source.String = fileContent;
+
+ return source;
+ }
+ }
+}
+
View
3 iOSGLEssentials/iOSGLEssentials/EAGLEView.cs
@@ -74,7 +74,8 @@ public EAGLEView (NSCoder coder)
throw new ApplicationException("Could not create/set EAGLContext");
}
- m_renderer = new ES2Renderer(m_context, (CAEAGLLayer)LayerClass());
+ m_renderer = new ES2Renderer();
+ m_renderer.InitWithContext(m_context, (CAEAGLLayer)LayerClass());
Animating = false;
displayLinkSupported = false;
View
95 iOSGLEssentials/iOSGLEssentials/ES2Renderer.cs
@@ -9,22 +9,109 @@ namespace iOSGLEssentials
public class ES2Renderer : OpenGLRenderer
{
#region Members
+ EAGLContext m_context;
+ int m_colorRenderbuffer;
+ int m_depthRenderbuffer;
#endregion
- public ES2Renderer (EAGLContext context, CAEAGLLayer layer)
+ public ES2Renderer ()
{
- //GL.GenFramebuffers(1,
+ }
+
+ public void InitWithContext (EAGLContext context, CAEAGLLayer drawable)
+ {
+ GL.GenFramebuffers(1, out m_defaultFBOName);
+
+ // Create default framebuffer object. The backing will be allocated for the current layer in resizeFromLayer
+ GL.GenRenderbuffers(1, out m_colorRenderbuffer);
+ GL.BindFramebuffer(FramebufferTarget.Framebuffer, m_defaultFBOName);
+ GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, m_colorRenderbuffer);
+ m_context = context;
+
+ // This call associates the storage for the current render buffer with the EAGLDrawable (our CAEGLLAyer)
+ // allowing us to draw into a buffer that will later be rendered to the screen wherever the layer is
+ //(which correspondes with our) view.
+ m_context.RenderBufferStorage((uint)All.Renderbuffer, drawable);
+
+ GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferSlot.ColorAttachment0, RenderbufferTarget.Renderbuffer, m_colorRenderbuffer);
+
+ int backingWidth;
+ int backingHeight;
+ GL.GetRenderbufferParameter(RenderbufferTarget.Renderbuffer, RenderbufferParameterName.RenderbufferWidth, out backingWidth);
+ GL.GetRenderbufferParameter(RenderbufferTarget.Renderbuffer, RenderbufferParameterName.RenderbufferHeight, out backingHeight);
+
+ GL.GenRenderbuffers(1, out m_depthRenderbuffer);
+ GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, m_depthRenderbuffer);
+ GL.RenderbufferStorage(RenderbufferTarget.Renderbuffer, RenderbufferInternalFormat.DepthComponent16, backingWidth, backingHeight);
+ GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferSlot.DepthAttachment, RenderbufferTarget.Renderbuffer, m_depthRenderbuffer);
+
+ if(GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete)
+ {
+ //Console.WriteLine(");
+ throw new ApplicationException("Failed to make complete framebuffer object: " + GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer));
+ }
+
+ InitWithDefaultFBO(m_defaultFBOName);
}
#region Public Methods
- public void Render()
+ public override void Render()
{
+ // Replace the implementation of this method to do your own custom drawing
+
+
+ GL.BindFramebuffer(FramebufferTarget.Framebuffer, m_defaultFBOName);
+
+ base.Render();
+
+ GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, m_colorRenderbuffer);
+ m_context.PresentRenderBuffer((uint)All.Renderbuffer);
}
public bool ResizeFromLayer(CAEAGLLayer layer)
{
- throw new NotImplementedException();
+ // The pixel dimensions of the CAEAGLLayer
+ int backingWidth;
+ int backingHeight;
+
+ // Allocate color buffer backing based on the current layer size
+ GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, m_colorRenderbuffer);
+ m_context.RenderBufferStorage((uint)RenderbufferTarget.Renderbuffer, layer);
+ GL.GetRenderbufferParameter(RenderbufferTarget.Renderbuffer, RenderbufferParameterName.RenderbufferWidth, out backingWidth);
+ GL.GetRenderbufferParameter(RenderbufferTarget.Renderbuffer, RenderbufferParameterName.RenderbufferHeight, out backingHeight);
+
+ GL.GenRenderbuffers(1, out m_depthRenderbuffer);
+ GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, m_depthRenderbuffer);
+ GL.RenderbufferStorage(RenderbufferTarget.Renderbuffer, RenderbufferInternalFormat.DepthComponent16, backingWidth, backingHeight);
+ GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferSlot.DepthAttachment, RenderbufferTarget.Renderbuffer, m_depthRenderbuffer);
+
+ base.ResizeWithWidth(backingWidth, backingHeight);
+
+ if(GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete)
+ {
+ Console.WriteLine("Failed to make complete framebuffer object", GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer));
+ return false;
+ }
+
+ return true;
+ }
+
+ public new void Dispose ()
+ {
+ if(m_defaultFBOName != 0)
+ {
+ GL.DeleteFramebuffers(1, ref m_defaultFBOName);
+ m_defaultFBOName = 0;
+ }
+
+ if(m_colorRenderbuffer != 0)
+ {
+ GL.DeleteRenderbuffers(1, ref m_colorRenderbuffer);
+ m_colorRenderbuffer = 0;
+ }
+
+ base.Dispose();
}
#endregion
}
View
7 iOSGLEssentials/iOSGLEssentials/GLUtil.cs
@@ -1,10 +1,15 @@
using System;
+using OpenTK.Graphics.ES20;
namespace iOSGLEssentials
{
public static class GLUtil
{
-
+ public static string GetGLErrorString(All error)
+ {
+ var errorString = Enum.GetName(typeof(All), error);
+ return errorString;
+ }
}
}
View
755 iOSGLEssentials/iOSGLEssentials/OpenGLRenderer.cs
@@ -12,61 +12,236 @@
using MonoTouch.Foundation;
using OpenTK.Graphics.ES20;
using System.Drawing;
+using System.Runtime.InteropServices;
+using System.Text;
namespace iOSGLEssentials
{
public class OpenGLRenderer : NSObject
{
#region Members
- uint m_defaultFBOName;
+ protected int m_defaultFBOName;
const int POS_ATTRIB_IDX = 1;
const int NORMAL_ATTRIB_IDX = 2;
const int TEXCOORD_ATTRIB_IDX = 3;
#endregion
- public OpenGLRenderer ()
- {
- }
-
#region GL Members
void BufferOffset(int i)
{
}
#if RENDER_REFLECTION
- DemoModel m_quadModel;
- All m_quadPrimType;
- All m_quadElementType;
- int m_quadNumElements;
- int m_reflectVAOName;
- int m_reflectTexName;
- int m_reflectFBOName;
- int m_reflectWidth;
- int m_reflectHeight;
- int m_reflectPrgName;
- int m_reflectModelViewUniformIdx;
- int m_reflectProjectionuniformIdx;
- int m_reflectNormalMatrixUniformIdx;
+ protected DemoModel m_quadModel;
+ protected All m_quadPrimType;
+ protected All m_quadElementType;
+ protected int m_quadNumElements;
+ protected int m_reflectVAOName;
+ protected int m_reflectTexName;
+ protected int m_reflectFBOName;
+ protected int m_reflectWidth;
+ protected int m_reflectHeight;
+ protected int m_reflectPrgName;
+ protected int m_reflectModelViewUniformIdx;
+ protected int m_reflectProjectionuniformIdx;
+ protected int m_reflectNormalMatrixUniformIdx;
#endif
- int m_characterPrgName;
- int m_characterMvpUniformIdx;
- int m_characterVAOName;
- int m_characterTexName;
- DemoModel m_characterModel;
- All m_characterPrimType;
- All m_characterElementType;
- int m_characterNumElements;
- float m_characterAngle;
+ protected int m_characterPrgName;
+ protected int m_characterMvpUniformIdx;
+ protected int m_characterVAOName;
+ protected int m_characterTexName;
+ protected DemoModel m_characterModel;
+ protected All m_characterPrimType;
+ protected All m_characterElementType;
+ protected int m_characterNumElements;
+ protected float m_characterAngle;
- int m_viewWidth;
- int m_viewHeight;
+ protected int m_viewWidth;
+ protected int m_viewHeight;
- bool m_useVBOs;
+ protected bool m_useVBOs;
#endregion
+ public OpenGLRenderer ()
+ {
+ }
+
+ protected void InitWithDefaultFBO(int defaultFBOName)
+ {
+ Console.WriteLine(string.Format("{0} {1}", GL.GetString(StringName.Renderer), GL.GetString(StringName.Version)));
+
+ ////////////////////////////////////////////////////
+ // Build all of our and setup initial state here //
+ // Don't wait until our real time run loop begins //
+ ////////////////////////////////////////////////////
+ m_defaultFBOName = defaultFBOName;
+
+ m_viewWidth = 100;
+ m_viewHeight = 100;
+
+ m_characterAngle = 0;
+#if USE_VERTEX_BUFFER_OBJECTS
+ m_useVBOs = true;
+#else
+ m_useVBOs = false;
+#endif
+
+ var filePathName = string.Empty;
+
+ //////////////////////////////
+ // Load our character model //
+ //////////////////////////////
+
+ filePathName = NSBundle.MainBundle.PathForResource("demon", "model");
+ m_characterModel = DemoModel.LoadModel(filePathName);
+
+ // Build Vertex uffer Objects (VBOs) and Vertex Array Objects (VAOs) with our model data
+ m_characterVAOName = BuildVAO(m_characterModel);
+
+ // Cache the number of element and primtType to use later in our GL.DrawElements calls
+ m_characterNumElements = m_characterModel.NumElements;
+ m_characterPrimType = m_characterModel.PrimType;
+ m_characterElementType = m_characterModel.ElementType;
+
+ if(m_useVBOs)
+ {
+ //If we're using VBOs we can destroy all this memory since buffers are
+ // loaded into GL and we've saved anything else we need
+ m_characterModel = null;
+ }
+
+
+ ////////////////////////////////////
+ // Load texture for our character //
+ ////////////////////////////////////
+
+ filePathName = NSBundle.MainBundle.PathForResource("demon", "png");
+ var image = DemoImage.LoadImage(filePathName, false);
+
+ // Build a texture object with our image data
+ m_characterTexName = BuildTexture(image);
+
+ ////////////////////////////////////////////////////
+ // Load and Setup shaders for character rendering //
+ ////////////////////////////////////////////////////
+
+ DemoSource vtxSource = null;
+ DemoSource frgSource = null;
+
+ filePathName = NSBundle.MainBundle.PathForResource("character", "vsh");
+ vtxSource = DemoSource.LoadSource(filePathName);
+
+ filePathName = NSBundle.MainBundle.PathForResource("character", "fsh");
+ frgSource = DemoSource.LoadSource(filePathName);
+
+ // Build program
+ m_characterPrgName = BuildProgramWithVertexSource(vtxSource, frgSource, false, true);
+
+ m_characterMvpUniformIdx = GL.GetUniformLocation(m_characterPrgName, "modelViewProjectionMatrix");
+
+ if(m_characterMvpUniformIdx < 0)
+ Console.WriteLine("No modelViewProjectionMatrix in character shader");
+
+#if RENDER_REFLECTION
+
+ m_reflectWidth = 512;
+ m_reflectHeight = 512;
+
+ ////////////////////////////////////////////////
+ // Load a model for a quad for the reflection //
+ ////////////////////////////////////////////////
+
+ m_quadModel = DemoModel.LoadQuadModel();
+
+ // build Vertex Buffer Objects (VBOs) and Vertex Array Object (VAOs) with our model data
+ m_reflectVAOName = BuildVAO(m_quadModel);
+
+ // Cache the number of element and prim type to use later in our GL.DrawElements calls
+ m_quadNumElements = m_quadModel.NumElements;
+ m_quadPrimType = m_quadModel.PrimType;
+ m_quadElementType = m_quadModel.ElementType;
+
+ if(m_useVBOs)
+ {
+ // Release quad Model;
+ m_quadModel = null;
+ }
+
+ /////////////////////////////////////////////////////
+ // Create texture and FBO for reflection rendering //
+ /////////////////////////////////////////////////////
+
+ m_reflectFBOName = BuildFBOWithWidth(m_reflectWidth, m_reflectHeight);
+
+ // Get the texture we created in buildReflectFBO by binding the
+ // reflection FBO and getting the buffer attached to color 0
+ GL.BindFramebuffer(All.Framebuffer, m_reflectFBOName);
+
+ int iReflectTexName = 0;
+
+ GL.GetFramebufferAttachmentParameter(All.Framebuffer, All.ColorAttachment0, All.FramebufferAttachmentObjectName, ref iReflectTexName);
+
+ m_reflectTexName = iReflectTexName;
+
+ /////////////////////////////////////////////////////
+ // Load and setup shaders for reflection rendering //
+ /////////////////////////////////////////////////////
+
+ filePathName = NSBundle.MainBundle.PathForResource("reflect", "vsh");
+ vtxSource = DemoSource.LoadSource(filePathName);
+
+ filePathName = NSBundle.MainBundle.PathForResource("reflect", "fsh");
+ frgSource = DemoSource.LoadSource (filePathName);
+
+ // Build Program
+ m_reflectPrgName = BuildProgramWithVertexSource(vtxSource, frgSource, true, false);
+
+ m_reflectModelViewUniformIdx = GL.GetUniformLocation(m_reflectPrgName, "modelViewMatrix");
+
+ if(m_reflectModelViewUniformIdx < 0)
+ Console.WriteLine("No modelViewMatrix in reflection shader");
+
+ m_reflectProjectionuniformIdx = GL.GetUniformLocation(m_reflectPrgName, "modelViewProjectionMatrix");
+
+ if(m_reflectProjectionuniformIdx < 0)
+ Console.WriteLine("No modelViewProjectionMatrix in reflection shader");
+
+ m_reflectNormalMatrixUniformIdx = GL.GetUniformLocation(m_reflectPrgName, "normalMatrix");
+
+ if(m_reflectNormalMatrixUniformIdx <0)
+ Console.WriteLine("No normalMatrix in reflection shader");
+
+#endif // RENDER_REFLECTION
+
+ ////////////////////////////////////////////////
+ // Set up OpenGL state that will never change //
+ ////////////////////////////////////////////////
+
+ // Depth test will always be enabled
+ GL.Enable(All.DepthTest);
+
+ // We will always cull back faces for better performance
+ GL.Enable(All.CullFace);
+
+ // Always use this clear color
+ GL.ClearColor(.5f, .4f, .5f, 1.0f);
+
+ // Draw our scene once without presenting the rendered image.
+ // This is done in order to pre-warm OpenGL
+ // We don't need to present the buffer since we don't actually want the
+ // user to see this, we're only drawing as a pre-warm stage
+ Render();
+
+ // Reset the m_characterAngle which is incremented in render
+ m_characterAngle = 0;
+
+ // Check for errors to make sure all of our setup went ok
+ GetGLError();
+ }
+
#region Public Methods
public void ResizeWithWidth(int width, int height)
{
@@ -76,7 +251,7 @@ public void ResizeWithWidth(int width, int height)
m_viewHeight = height;
}
- public void Render()
+ public virtual void Render()
{
// Set up the modelview and projection matricies
var modelView = new float[16];
@@ -112,7 +287,7 @@ public void Render()
GL.UniformMatrix4(m_characterMvpUniformIdx, 1, false, mvp);
// Bind our vertex array object
- //GL.Vertex
+ GL.Oes.BindVertexArray(m_characterVAOName);
// Bind the texture to be used
GL.BindTexture(All.Texture2D, m_characterTexName);
@@ -160,6 +335,9 @@ public void Render()
// Bind the texture to be used
GL.BindTexture(All.Texture2D, m_characterTexName);
+ // Bind our vertex array object
+ GL.Oes.BindVertexArray(m_characterVAOName);
+
// Cull back faces now that we no longer render
// with an inverted matrix
GL.CullFace(All.Back);
@@ -217,6 +395,8 @@ public void Render()
// mipmaps here
GL.GenerateMipmap(All.Texture2D);
#endif
+ // Bind our vertex array object
+ GL.Oes.BindVertexArray(m_reflectVAOName);
// Draw our reflection plane
if(m_useVBOs)
@@ -253,17 +433,524 @@ unsafe static int GetGLTypeSize(All type)
return 0;
}
- int BuildVAO(DemoModel model)
+ unsafe int BuildVAO(DemoModel model)
{
int vaoName = 0;
// Create a vertex array object (VAO) to cache model parameters
+ GL.Oes.GenVertexArrays(1, out vaoName);
+ GL.Oes.BindVertexArray(vaoName);
+
+ if(m_useVBOs)
+ {
+ int posBufferName = 0;
+
+ // Creat a vertex buffer object (VBO) to store positions
+ GL.GenBuffers(1, out posBufferName);
+
+ // Allocate and load position data into the VBO
+ //int size = (int) model.PositionArraySize;
+ //fixed (void *ptr = &size) {
+ // GL.BufferData(All.ArrayBuffer, new IntPtr (ptr), model.Positions, All.StaticDraw);
+ //}
+ GL.BufferData(All.ArrayBuffer, (IntPtr)model.PositionArraySize, model.Positions, All.StaticDraw);
+
+ // Enable the position attribute for this VAO
+ GL.EnableVertexAttribArray(POS_ATTRIB_IDX);
+
+ // Get the size of the position type so we can set the stride properly
+ var posTypeSize = GetGLTypeSize(model.PositionType);
+
+ // Setup parameters for position attribute in the VAO including,
+ // size, type, stride, and offset in the currently bound VAO
+ // This also attaches the position VBO to the VAO
+ GL.VertexAttribPointer(POS_ATTRIB_IDX, // What attribute index will this array feed in the vertex shader (see BuildProgram)
+ model.PositionSize, // How many element are there per position?
+ model.PositionType, // What is the type of this data?
+ false, // Do we want to normalize this data (0-1 range for fixed-point types)
+ model.PositionSize * posTypeSize, // What is the stride (i.e. bytes between position)?
+ new int[0]);
+
+ if(model.Normals != null)
+ {
+ int normalBufferName = 0;
+
+ // Create a vertex buffer object (VBO) to store positions
+ GL.GenBuffers(1, out normalBufferName);
+ GL.BindBuffer(All.ArrayBuffer, normalBufferName);
+
+ // Allocate and load normal data into the VBO
+ GL.BufferData(All.ArrayBuffer, (IntPtr)model.NormalArraySize, model.Normals, All.StaticDraw);
+
+ // Enable the normal attribute for this VAO
+ GL.EnableVertexAttribArray(NORMAL_ATTRIB_IDX);
+
+ // Get the size of the normal type so we can set the stride properly
+ var normalTypeSize = GetGLTypeSize(model.NormalType);
+
+ // Set up parameters for position attribute in the VAO including,
+ // size, type, stride, and offset in the currently bound VAO
+ // This also attaches the position VBO to the VAO
+ GL.VertexAttribPointer(NORMAL_ATTRIB_IDX, // What attribue index will this array feed in the vertex shader
+ model.NormalSize, // How many elements are there per normal?
+ model.NormalType, // What is the type of this data?
+ false, // Do we want to normalize this data (0-1 range for fixed-point types)
+ model.NormalSize * normalTypeSize, // What is the stride.
+ new int[0]);
+ }
+
+ if(model.TexCoords != null)
+ {
+ int texcoordBufferName = 0;
+
+ // Create a VBO to store texcoords
+ GL.GenBuffers(1, out texcoordBufferName);
+ GL.BindBuffer(All.ArrayBuffer, texcoordBufferName);
+
+ // Allocate and load texcoord data into the VBO
+ GL.BufferData(All.ArrayBuffer, (IntPtr)model.TexCoordArraySize, model.TexCoords, All.StaticDraw);
+
+ // Enable the texcoord attribute for this VAO
+ GL.EnableVertexAttribArray(TEXCOORD_ATTRIB_IDX);
+
+ // Get the size of the texcoord type so we can set the stride properly
+ var texcoordTypeSize = GetGLTypeSize(model.TexCoordType);
+
+ // Set up parameters for texcoord attribute in the VAO including,
+ // size, type, stride, and oofset in the currently bound VAO
+ // This also attaches the texcoord VBO to VAO
+ GL.VertexAttribPointer(TEXCOORD_ATTRIB_IDX, // What attribute index will this array feed in the vertex shader
+ model.TexCoordsSize, // How many elements are there per texture coord?
+ model.TexCoordType, // What is the type of this data in the array?
+ true, // Do we want to normalize this data
+ model.TexCoordsSize * texcoordTypeSize, // What is the stride
+ new int[0]);
+ }
+
+ int elementBufferName = 0;
+
+ // Create a VBO to vertex array elements
+ // This also attaches the element array buffer to the VAO
+ GL.GenBuffers(1, out elementBufferName);
+ GL.BindBuffer(All.ArrayBuffer, elementBufferName);
+
+ // Allocate and load vertex array element data into VBO
+ GL.BufferData(All.ArrayBuffer, (IntPtr)model.ElementArraySize, model.Elements, All.StaticDraw);
+ }
+ else{
+
+ // Enable the position attribute for this VAO
+ GL.EnableVertexAttribArray(POS_ATTRIB_IDX);
+
+ // Get the size of the position type so we can set the stride propertly
+ var posTypeSize = GetGLTypeSize(model.PositionType);
+
+ // Set up parameters for position attribute in the VAO including,
+ // size, type, stride, and offset in the currently bound VAO
+ // This also attaches the position VBO to the VAO
+ GL.VertexAttribPointer(POS_ATTRIB_IDX, // What attibute index will this array feed in the vertex shader? (also see buildProgram)
+ model.PositionSize, // How many elements are there per position?
+ model.PositionType, // What is the type of this data
+ false, // Do we want to normalize this data (0-1 range for fixed-pont types)
+ model.PositionSize*posTypeSize, // What is the stride (i.e. bytes between positions)?
+ model.Positions); // Where is the position data in memory?
+
+ if(model.Normals != null)
+ {
+ // Enable the normal attribute for this VAO
+ GL.EnableVertexAttribArray(NORMAL_ATTRIB_IDX);
+
+ // Get the size of the normal type so we can set the stride properly
+ var normalTypeSize = GetGLTypeSize(model.NormalType);
+
+ // Set up parmeters for position attribute in the VAO including,
+ // size, type, stride, and offset in the currenly bound VAO
+ // This also attaches the position VBO to the VAO
+ GL.VertexAttribPointer(NORMAL_ATTRIB_IDX, // What attibute index will this array feed in the vertex shader (see buildProgram)
+ model.NormalSize, // How many elements are there per normal?
+ model.NormalType, // What is the type of this data?
+ false, // Do we want to normalize this data (0-1 range for fixed-pont types)
+ model.NormalSize * normalTypeSize, // What is the stride (i.e. bytes between normals)?
+ model.Normals); // Where is normal data in memory?
+ }
+
+ if(model.TexCoords != null)
+ {
+ // Enable the texcoord attribute for this VAO
+ GL.EnableVertexAttribArray(TEXCOORD_ATTRIB_IDX);
+
+ // Get the size of the texcoord type so we can set the stride properly
+ var texcoordTypeSize = GetGLTypeSize(model.TexCoordType);
+
+ // Set up parmeters for texcoord attribute in the VAO including,
+ // size, type, stride, and offset in the currenly bound VAO
+ // This also attaches the texcoord array in memory to the VAO
+ GL.VertexAttribPointer(TEXCOORD_ATTRIB_IDX, // What attibute index will this array feed in the vertex shader (see buildProgram)
+ model.TexCoordsSize, // How many elements are there per texture coord?
+ model.TexCoordType, // What is the type of this data in the array?
+ false, // Do we want to normalize this data (0-1 range for fixed-point types)
+ model.TexCoordsSize * texcoordTypeSize, // What is the stride (i.e. bytes between texcoords)?
+ model.TexCoords); // Where is the texcood data in memory?
+ }
+
+ }
+
+ GetGLError();
return vaoName;
}
- public void Dispose()
+ void DestroyVAO(int vaoName)
{
+ int index = 0;
+ int bufName = -1;
+
+ // Bind the VAO so we can get data from it
+ GL.Oes.BindVertexArray(vaoName);
+
+ // For every possible attribute set in the VAO
+ for(index = 0; index < 16; index++)
+ {
+ // Get the VBO set for that attibute
+ GL.GetVertexAttrib(index , All.VertexAttribArrayBufferBinding, ref bufName);
+
+ // If there was a VBO set...
+ if(bufName != -1)
+ {
+ //...delete the VBO
+ GL.DeleteBuffers(1, ref bufName);
+ }
+ }
+
+ // Get any element array VBO set in the VAO
+ GL.GetInteger(All.ElementArrayBufferBinding, ref bufName);
+
+ // If there was a element array VBO set in the VAO
+ if(bufName != -1)
+ {
+ //...delete the VBO
+ GL.DeleteBuffers(1, ref bufName);
+ }
+
+ // Finally, delete the VAO
+ GL.Oes.DeleteVertexArrays(1, ref vaoName);
+
+ GetGLError();
+ }
+
+ int BuildTexture(DemoImage image)
+ {
+ int texName = 0;
+
+ // Create a texture object to apply to model
+ GL.GenTextures(1, out texName);
+ GL.BindTexture(All.Texture2D, texName);
+
+ // Set up filter and wrap modes for this texture object
+ GL.TexParameter(All.Texture2D, All.TextureWrapS, (int)All.ClampToEdge);
+ GL.TexParameter(All.Texture2D, All.TextureWrapT, (int)All.ClampToEdge);
+ GL.TexParameter(All.Texture2D, All.TextureMagFilter, (int)All.Linear);
+ GL.TexParameter(All.Texture2D, All.TextureMinFilter, (int)All.LinearMipmapLinear);
+
+ // Indicate that pixel rows are tightly packed
+ // (defaults to stride of 4 which is kind of only good for
+ // RGBA or FLOAT data types)
+ GL.PixelStore(All.UnpackAlignment, 1);
+
+ // Allocate and load image data into texture
+ GL.TexImage2D<byte>(All.Texture2D, 0, (int)image.Format, image.Width, image.Height, 0,
+ image.Format, image.Type, image.Data);
+
+ // Create mipmaps for this texture for better image quality
+ GL.GenerateMipmap(All.Texture2D);
+
+ GetGLError();
+
+ return texName;
+ }
+
+ void DeleteFBOAttachment(All attachment)
+ {
+ int param = 0;
+ int objName = 0;
+
+ GL.GetFramebufferAttachmentParameter(All.Framebuffer, attachment,
+ All.FramebufferAttachmentObjectType,
+ ref param);
+
+ if((int)All.Renderbuffer == param)
+ {
+ GL.GetFramebufferAttachmentParameter(All.Framebuffer, attachment,
+ All.FramebufferAttachmentObjectName,
+ ref param);
+
+ objName = param;
+ GL.DeleteRenderbuffers(1, ref objName);
+ }
+ else if((int)All.Texture == param)
+ {
+
+ GL.GetFramebufferAttachmentParameter(All.Framebuffer, attachment,
+ All.FramebufferAttachmentObjectName,
+ ref param);
+
+ objName = param;
+ GL.DeleteTextures(1, ref objName);
+ }
+
+ }
+
+ void DestroyFBO(int fboName)
+ {
+ if(0 == fboName)
+ {
+ return;
+ }
+
+ GL.BindFramebuffer(All.Framebuffer, fboName);
+
+
+ int maxColorAttachments = 1;
+
+ int colorAttachment = 0;
+
+ // For every color buffer attached
+ for(colorAttachment = 0; colorAttachment < maxColorAttachments; colorAttachment++)
+ {
+ // Delete the attachment
+ DeleteFBOAttachment((All)((int)All.ColorAttachment0 + colorAttachment));
+ }
+
+ // Delete any depth or stencil buffer attached
+ DeleteFBOAttachment(All.DepthAttachment);
+
+ DeleteFBOAttachment(All.StencilAttachment);
+
+ GL.DeleteFramebuffers(1, ref fboName);
+ }
+
+ int BuildFBOWithWidth(int width, int height)
+ {
+ int fboName = 0;
+
+ int colorTexture = 0;
+
+ // Create a texture object to apply to model
+ GL.GenTextures(1, out colorTexture);
+ GL.BindTexture(All.Texture2D, colorTexture);
+
+ // Set up filter and wrap modes for this texture object
+ GL.TexParameter(All.Texture2D, All.TextureWrapS, (int)All.ClampToEdge);
+ GL.TexParameter(All.Texture2D, All.TextureWrapT, (int)All.ClampToEdge);
+ GL.TexParameter(All.Texture2D, All.TextureMagFilter, (int)All.Linear);
+
+ GL.TexParameter(All.Texture2D, All.TextureMinFilter, (int)All.Linear);
+
+ // Allocate a texture image with which we can render to
+ // Pass NULL for the data parameter since we don't need to load image data.
+ // We will be generating the image by rendering to this texture
+ byte[] dummy = null;
+ GL.TexImage2D<byte>(All.Texture2D, 0, (int)All.Rgba, width, height, 0,
+ All.Rgba, All.UnsignedByte, dummy);
+
+ int depthRenderbuffer = 0;
+ GL.GenRenderbuffers(1, out depthRenderbuffer);
+ GL.BindRenderbuffer(All.Renderbuffer, depthRenderbuffer);
+ GL.RenderbufferStorage(All.Renderbuffer, All.DepthComponent16, width, height);
+
+ GL.GenFramebuffers(1, out fboName);
+ GL.BindFramebuffer(All.Framebuffer, fboName);
+ GL.FramebufferTexture2D(All.Framebuffer, All.ColorAttachment0, All.Texture2D, colorTexture, 0);
+ GL.FramebufferRenderbuffer(All.Framebuffer, All.DepthAttachment, All.Renderbuffer, depthRenderbuffer);
+
+ if(GL.CheckFramebufferStatus(All.Framebuffer) != All.FramebufferComplete)
+ {
+ Console.WriteLine("failed to make complete framebuffer object %x", Enum.GetName (typeof(All), GL.CheckFramebufferStatus(All.Framebuffer)));
+ DestroyFBO(fboName);
+ return 0;
+ }
+
+ GetGLError();
+
+ return fboName;
+ }
+
+ int BuildProgramWithVertexSource(DemoSource vertexSource, DemoSource fragmentSource, bool hasNormal, bool hasTexcoord)
+ {
+ int prgName = 0;
+ int logLength = 0, status = 0;
+
+ // String to pass to Gl.ShaderSource
+ var sourceString = string.Empty;
+
+ // Determine if GLSL version 140 is supported by this context.
+ // We'll use this info to generate a GLSL shader source string
+ // with the proper version preprocessor string prepended
+ float glLanguageVersion;
+
+ glLanguageVersion = Convert.ToSingle(GL.GetString(All.ShadingLanguageVersion));
+
+ // All.ShadingLanguageVersion returns the version standard version form
+ // with decimals, but the GLSL version preprocessor directive simply
+ // uses integers (thus 1.10 should 110 and 1.40 should be 140, etc.)
+ // We multiply the floating point number by 100 to get a proper
+ // number for the GLSL preprocessor directive
+ int version = Convert.ToInt32(100 * glLanguageVersion);
+
+ prgName = GL.CreateProgram();
+
+ // Indicate the attribute indicies on which vertex arrays will be
+ // set with GL.VertexAttribPointer
+ // See BuildVAO to see where vertex array are actually set
+ GL.BindAttribLocation(prgName, POS_ATTRIB_IDX, "inPosition");
+
+ if(hasNormal)
+ {
+ GL.BindAttribLocation(prgName, NORMAL_ATTRIB_IDX, "inNormal");
+ }
+
+ if(hasTexcoord)
+ {
+ GL.BindAttribLocation(prgName, TEXCOORD_ATTRIB_IDX, "inTexcoord");
+ }
+
+ //////////////////////////////////////
+ // Specify and compile VertexShader //
+ //////////////////////////////////////
+
+ sourceString = string.Format("#version {0}\n{1}", version, vertexSource.String);
+
+ int vertexShader;
+ if(!CompileShader(out vertexShader, All.VertexShader, sourceString))
+ {
+ Console.WriteLine("Could not Compile Vertex Shader");
+ return 0;
+ }
+
+ GL.AttachShader(prgName, vertexShader);
+
+ /////////////////////////////////////////
+ // Specify and compile Fragment Shader //
+ /////////////////////////////////////////
+
+ sourceString = string.Format("#version {0}\n{1}", version, fragmentSource.String);
+
+ int fragShader;
+ if(!CompileShader(out fragShader, All.FragmentShader, sourceString))
+ {
+ Console.WriteLine("Could not Compile Fragment Shader");
+ return 0;
+ }
+
+ // Attach the fragment shader to our program
+ GL.AttachShader(prgName, fragShader);
+
+ //////////////////////
+ // Link the program //
+ //////////////////////
+
+ GL.LinkProgram(prgName);
+ GL.GetProgram(prgName, All.InfoLogLength, ref logLength);
+ if(logLength > 0)
+ {
+ var log = new StringBuilder(logLength);
+ GL.GetProgramInfoLog(prgName, logLength, out logLength, log);
+ Console.WriteLine("Program link log: " + log.ToString());
+ }
+
+ GL.GetProgram(prgName, All.LinkStatus, ref status);
+ if(status == 0)
+ {
+ Console.WriteLine("Failed to link program");
+ return 0;
+ }
+
+ GL.ValidateProgram(prgName);
+ GL.GetProgram(prgName, All.InfoLogLength, ref logLength);
+ if(logLength > 0)
+ {
+ var log = new StringBuilder(logLength);
+ GL.GetProgramInfoLog(prgName, logLength, out logLength, log);
+ Console.WriteLine("Program validate log: " + log.ToString());
+ }
+
+ GL.GetProgram(prgName, All.ValidateStatus, ref status);
+ if(status == 0)
+ {
+ Console.WriteLine("Failed to validate program");
+ return 0;
+ }
+
+ GL.UseProgram(prgName);
+
+ ///////////////////////////////////////
+ // Setup common program input points //
+ ///////////////////////////////////////
+
+ int sampleLoc = GL.GetUniformLocation(prgName, "diffuseTexture");
+
+ // Indicate that the diffuse texture will be bound to texture uint 0
+ var uint0 = 0;
+ GL.Uniform1 (sampleLoc, uint0);
+
+ GetGLError();
+
+ return prgName;
+ }
+
+ bool CompileShader (out int shader, All type, string path)
+ {
+ string shaderProgram = System.IO.File.ReadAllText (path);
+ int len = shaderProgram.Length, status = 0;
+ shader = GL.CreateShader (type);
+
+ GL.ShaderSource (shader, 1, new string [] { shaderProgram }, ref len);
+ GL.CompileShader (shader);
+ GL.GetShader (shader, All.CompileStatus, ref status);
+
+ if (status == 0) {
+ GL.DeleteShader (shader);
+ return false;
+ }
+ return true;
+ }
+
+ unsafe void DestroyProgram(int prgName)
+ {
+ if(0 == prgName)
+ return;
+
+ int shaderNum;
+ int shaderCount = 0;
+
+ // Get the number of attached shaders
+ GL.GetProgram(prgName, All.AttachedShaders, ref shaderCount);
+
+ var shaders = new int[shaderCount * sizeof(int)];
+
+ // Get the names of the shaders attached to the program
+ GL.GetAttachedShaders(prgName,
+ shaderCount,
+ new int[] { shaderCount },
+ shaders);
+
+ // Delete the shaders attached to the program
+ for(shaderNum = 0; shaderNum < shaderCount; shaderNum++)
+ {
+ GL.DeleteShader(shaders[shaderNum]);
+ }
+
+ GL.DeleteProgram(prgName);
+ GL.UseProgram(0);
+ }
+
+ void GetGLError()
+ {
+ var error = GL.GetError();
+ while(error != ErrorCode.NoError)
+ {
+ Console.WriteLine("GLError " + Enum.GetName(typeof(ErrorCode), error)); //GLUtil.GetGLErrorString(error));
+ }
}
#endregion
}
View
69 iOSGLEssentials/iOSGLEssentials/Shaders/character.fsh
@@ -0,0 +1,69 @@
+/*
+ File: character.fsh
+ Abstract: The fragment shader for character rendering.
+ Version: 1.1
+
+ Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
+ Inc. ("Apple") in consideration of your agreement to the following
+ terms, and your use, installation, modification or redistribution of
+ this Apple software constitutes acceptance of these terms. If you do
+ not agree with these terms, please do not use, install, modify or
+ redistribute this Apple software.
+
+ In consideration of your agreement to abide by the following terms, and
+ subject to these terms, Apple grants you a personal, non-exclusive
+ license, under Apple's copyrights in this original Apple software (the
+ "Apple Software"), to use, reproduce, modify and redistribute the Apple
+ Software, with or without modifications, in source and/or binary forms;
+ provided that if you redistribute the Apple Software in its entirety and
+ without modifications, you must retain this notice and the following
+ text and disclaimers in all such redistributions of the Apple Software.
+ Neither the name, trademarks, service marks or logos of Apple Inc. may
+ be used to endorse or promote products derived from the Apple Software
+ without specific prior written permission from Apple. Except as
+ expressly stated in this notice, no other rights or licenses, express or
+ implied, are granted by Apple herein, including but not limited to any
+ patent rights that may be infringed by your derivative works or by other
+ works in which the Apple Software may be incorporated.
+
+ The Apple Software is provided by Apple on an "AS IS" basis. APPLE
+ MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
+ THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
+ FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
+ OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
+
+ IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
+ MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
+ AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
+ STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+
+ Copyright (C) 2010~2011 Apple Inc. All Rights Reserved.
+
+ */
+
+#ifdef GL_ES
+precision highp float;
+#endif
+
+#if __VERSION__ >= 140
+in vec2 varTexcoord;
+out vec4 fragColor;
+#else
+varying vec2 varTexcoord;
+#endif
+
+uniform sampler2D diffuseTexture;
+
+
+void main (void)
+{
+ #if __VERSION__ >= 140
+ fragColor = texture(diffuseTexture, varTexcoord.st, 0.0);
+ #else
+ gl_FragColor = texture2D(diffuseTexture, varTexcoord.st, 0.0);
+ #endif
+}
View
68 iOSGLEssentials/iOSGLEssentials/Shaders/character.vsh
@@ -0,0 +1,68 @@
+/*
+ File: character.vsh
+ Abstract: The vertex shader for character rendering.
+ Version: 1.1
+
+ Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
+ Inc. ("Apple") in consideration of your agreement to the following
+ terms, and your use, installation, modification or redistribution of
+ this Apple software constitutes acceptance of these terms. If you do
+ not agree with these terms, please do not use, install, modify or
+ redistribute this Apple software.
+
+ In consideration of your agreement to abide by the following terms, and
+ subject to these terms, Apple grants you a personal, non-exclusive
+ license, under Apple's copyrights in this original Apple software (the
+ "Apple Software"), to use, reproduce, modify and redistribute the Apple
+ Software, with or without modifications, in source and/or binary forms;
+ provided that if you redistribute the Apple Software in its entirety and
+ without modifications, you must retain this notice and the following
+ text and disclaimers in all such redistributions of the Apple Software.
+ Neither the name, trademarks, service marks or logos of Apple Inc. may
+ be used to endorse or promote products derived from the Apple Software
+ without specific prior written permission from Apple. Except as
+ expressly stated in this notice, no other rights or licenses, express or
+ implied, are granted by Apple herein, including but not limited to any
+ patent rights that may be infringed by your derivative works or by other
+ works in which the Apple Software may be incorporated.
+
+ The Apple Software is provided by Apple on an "AS IS" basis. APPLE
+ MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
+ THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
+ FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
+ OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
+
+ IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
+ MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
+ AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
+ STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+
+ Copyright (C) 2010~2011 Apple Inc. All Rights Reserved.
+
+ */
+
+#ifdef GL_ES
+precision highp float;
+#endif
+
+uniform mat4 modelViewProjectionMatrix;
+
+#if __VERSION__ >= 140
+in vec4 inPosition;
+in vec2 inTexcoord;
+out vec2 varTexcoord;
+#else
+attribute vec4 inPosition;
+attribute vec2 inTexcoord;
+varying vec2 varTexcoord;
+#endif
+
+void main (void)
+{
+ gl_Position = modelViewProjectionMatrix * inPosition;
+ varTexcoord = inTexcoord;
+}
View
111 iOSGLEssentials/iOSGLEssentials/Shaders/reflect.fsh
@@ -0,0 +1,111 @@
+/*
+ File: reflect.fsh
+ Abstract: The fragment shader for reflection rendering.
+ Version: 1.1
+
+ Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
+ Inc. ("Apple") in consideration of your agreement to the following
+ terms, and your use, installation, modification or redistribution of
+ this Apple software constitutes acceptance of these terms. If you do
+ not agree with these terms, please do not use, install, modify or
+ redistribute this Apple software.
+
+ In consideration of your agreement to abide by the following terms, and
+ subject to these terms, Apple grants you a personal, non-exclusive
+ license, under Apple's copyrights in this original Apple software (the
+ "Apple Software"), to use, reproduce, modify and redistribute the Apple
+ Software, with or without modifications, in source and/or binary forms;
+ provided that if you redistribute the Apple Software in its entirety and
+ without modifications, you must retain this notice and the following
+ text and disclaimers in all such redistributions of the Apple Software.
+ Neither the name, trademarks, service marks or logos of Apple Inc. may
+ be used to endorse or promote products derived from the Apple Software
+ without specific prior written permission from Apple. Except as
+ expressly stated in this notice, no other rights or licenses, express or
+ implied, are granted by Apple herein, including but not limited to any
+ patent rights that may be infringed by your derivative works or by other
+ works in which the Apple Software may be incorporated.
+
+ The Apple Software is provided by Apple on an "AS IS" basis. APPLE
+ MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
+ THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
+ FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
+ OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
+
+ IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
+ MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
+ AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
+ STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+
+ Copyright (C) 2010~2011 Apple Inc. All Rights Reserved.
+
+ */
+
+#ifdef GL_ES
+precision highp float;
+#endif
+
+
+const vec3 Xunitvec = vec3(1.0, 0.0, 0.0);
+const vec3 Yunitvec = vec3(0.0, 1.0, 0.0);
+
+// Color of tint to apply
+const vec4 tintColor = vec4(0.0, 0.0, 1.0, 1.0);
+
+// Amount of tint to apply
+const float tintFactor = 0.2;
+
+#if __VERSION__ >= 140
+in vec3 varNormal;
+in vec3 varEyeDir;
+out vec4 fragColor;
+#else
+varying vec3 varNormal;
+varying vec3 varEyeDir;
+#endif
+
+uniform sampler2D diffuseTexture;
+
+void main (void)
+{
+ // Compute reflection vector
+
+ vec3 reflectDir = reflect(varEyeDir, varNormal);
+
+ // Compute altitude and azimuth angles
+
+ vec2 texcoord;
+
+ texcoord.y = dot(normalize(reflectDir), Yunitvec);
+ reflectDir.y = 0.0;
+ texcoord.x = dot(normalize(reflectDir), Xunitvec) * 0.5;
+
+ // Translate index values into proper range
+
+ if (reflectDir.z >= 0.0)
+ texcoord = (texcoord + 1.0) * 0.5;
+ else
+ {
+ texcoord.t = (texcoord.t + 1.0) * 0.5;
+ texcoord.s = (-texcoord.s) * 0.5 + 1.0;
+ }
+
+
+ #if __VERSION__ >= 140
+ vec4 texColor = texture(diffuseTexture, texcoord);
+ #else
+ vec4 texColor = texture2D(diffuseTexture, texcoord);
+ #endif
+
+ // Do a lookup into the environment map.
+
+ #if __VERSION__ >= 140
+ fragColor = mix(texColor, tintColor, tintFactor);
+ #else
+ gl_FragColor = mix(texColor, tintColor, tintFactor);
+ #endif
+}
View
75 iOSGLEssentials/iOSGLEssentials/Shaders/reflect.vsh
@@ -0,0 +1,75 @@
+/*
+ File: reflect.vsh
+ Abstract: The vertex shader for reflection rendering.
+ Version: 1.1
+
+ Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
+ Inc. ("Apple") in consideration of your agreement to the following
+ terms, and your use, installation, modification or redistribution of
+ this Apple software constitutes acceptance of these terms. If you do
+ not agree with these terms, please do not use, install, modify or
+ redistribute this Apple software.
+
+ In consideration of your agreement to abide by the following terms, and
+ subject to these terms, Apple grants you a personal, non-exclusive
+ license, under Apple's copyrights in this original Apple software (the
+ "Apple Software"), to use, reproduce, modify and redistribute the Apple
+ Software, with or without modifications, in source and/or binary forms;
+ provided that if you redistribute the Apple Software in its entirety and
+ without modifications, you must retain this notice and the following
+ text and disclaimers in all such redistributions of the Apple Software.
+ Neither the name, trademarks, service marks or logos of Apple Inc. may
+ be used to endorse or promote products derived from the Apple Software
+ without specific prior written permission from Apple. Except as
+ expressly stated in this notice, no other rights or licenses, express or
+ implied, are granted by Apple herein, including but not limited to any
+ patent rights that may be infringed by your derivative works or by other
+ works in which the Apple Software may be incorporated.
+
+ The Apple Software is provided by Apple on an "AS IS" basis. APPLE
+ MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
+ THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
+ FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
+ OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
+
+ IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
+ MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
+ AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
+ STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+
+ Copyright (C) 2010~2011 Apple Inc. All Rights Reserved.
+
+ */
+
+#ifdef GL_ES
+precision highp float;
+#endif
+
+uniform mat4 modelViewMatrix;
+uniform mat4 modelViewProjectionMatrix;
+uniform mat3 normalMatrix;
+
+#if __VERSION__ >= 140
+in vec3 inNormal;
+in vec4 inPosition;
+out vec3 varNormal;
+out vec3 varEyeDir;
+#else
+attribute vec3 inNormal;
+attribute vec4 inPosition;
+varying vec3 varNormal;
+varying vec3 varEyeDir;
+#endif
+
+void main (void)
+{
+ gl_Position = modelViewProjectionMatrix * inPosition;
+ vec4 eyePos = modelViewMatrix * inPosition;
+
+ varNormal = normalize(normalMatrix * inNormal);
+ varEyeDir = eyePos.xyz;
+}
View
17 iOSGLEssentials/iOSGLEssentials/iOSGLEssentials.csproj
@@ -64,7 +64,9 @@
<Reference Include="System.Xml" />
<Reference Include="System.Core" />
<Reference Include="monotouch" />
- <Reference Include="OpenTK" />
+ <Reference Include="OpenTK-1.0">
+ <HintPath>..\..\..\..\..\..\Developer\MonoTouch\usr\lib\mono\2.1\OpenTK-1.0.dll</HintPath>
+ </Reference>
</ItemGroup>
<ItemGroup>
<None Include="Info.plist" />
@@ -83,9 +85,22 @@
<Compile Include="MatrixUtil.cs" />
<Compile Include="VectorUtil.cs" />
<Compile Include="GLUtil.cs" />
+ <Compile Include="DemoImage.cs" />
+ <Compile Include="DemoSource.cs" />
+ <Compile Include="DataConverter.cs" />
</ItemGroup>
<ItemGroup>
<InterfaceDefinition Include="iOSGLEssentialsViewController.xib" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
+ <ItemGroup>
+ <Folder Include="Shaders\" />
+ <Folder Include="Resources\" />
+ </ItemGroup>
+ <ItemGroup>
+ <Content Include="Shaders\character.fsh" />
+ <Content Include="Shaders\character.vsh" />
+ <Content Include="Shaders\reflect.fsh" />
+ <Content Include="Shaders\reflect.vsh" />
+ </ItemGroup>
</Project>
View
BIN iOSGLEssentials/iOSGLEssentials/iOSGLEssentials.pidb
Binary file not shown.

0 comments on commit 3a89b4c

Please sign in to comment.
Something went wrong with that request. Please try again.