diff --git a/OpenTK.sln b/OpenTK.sln index 4cc0b5d4..ca9ac77c 100644 --- a/OpenTK.sln +++ b/OpenTK.sln @@ -9,11 +9,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenTK", "Source\OpenTK\Ope {C426C9D1-8857-4E52-BAC7-4C05EE6070AB} = {C426C9D1-8857-4E52-BAC7-4C05EE6070AB} EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenTK.Examples", "Source\Examples\OpenTK.Examples.csproj", "{868E37B3-0000-0000-0000-000000000000}" - ProjectSection(ProjectDependencies) = postProject - {75DC22B1-113F-4A66-96B9-2FF8208C10E8} = {75DC22B1-113F-4A66-96B9-2FF8208C10E8} - EndProjectSection -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenTK.GLControl", "Source\GLControl\OpenTK.GLControl.csproj", "{A625BE88-0000-0000-0000-000000000000}" ProjectSection(ProjectDependencies) = postProject {75DC22B1-113F-4A66-96B9-2FF8208C10E8} = {75DC22B1-113F-4A66-96B9-2FF8208C10E8} @@ -25,7 +20,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Build.Installer.Nsis", "Ins {650C6F3D-33B5-4216-9536-956AB42C0624} = {650C6F3D-33B5-4216-9536-956AB42C0624} {A625BE88-0000-0000-0000-000000000000} = {A625BE88-0000-0000-0000-000000000000} {75DC22B1-113F-4A66-96B9-2FF8208C10E8} = {75DC22B1-113F-4A66-96B9-2FF8208C10E8} - {868E37B3-0000-0000-0000-000000000000} = {868E37B3-0000-0000-0000-000000000000} EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Build.Docs", "Documentation\Build.Docs.csproj", "{650C6F3D-33B5-4216-9536-956AB42C0624}" @@ -51,7 +45,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Build.Installer.Zip", "Inst {650C6F3D-33B5-4216-9536-956AB42C0624} = {650C6F3D-33B5-4216-9536-956AB42C0624} {A625BE88-0000-0000-0000-000000000000} = {A625BE88-0000-0000-0000-000000000000} {75DC22B1-113F-4A66-96B9-2FF8208C10E8} = {75DC22B1-113F-4A66-96B9-2FF8208C10E8} - {868E37B3-0000-0000-0000-000000000000} = {868E37B3-0000-0000-0000-000000000000} EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Build.Installer.Nuget", "Installers\Nuget\Build.Installer.Nuget.csproj", "{ADC34399-7613-44D2-90B2-19250F12FE7B}" @@ -97,15 +90,6 @@ Global {A37A7E14-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU {A37A7E14-0000-0000-0000-000000000000}.ReleaseMinimal|Any CPU.ActiveCfg = ReleaseMinimal|Any CPU {A37A7E14-0000-0000-0000-000000000000}.ReleaseMinimal|Any CPU.Build.0 = ReleaseMinimal|Any CPU - {868E37B3-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {868E37B3-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU - {868E37B3-0000-0000-0000-000000000000}.DebugMinimal|Any CPU.ActiveCfg = Debug|Any CPU - {868E37B3-0000-0000-0000-000000000000}.Documentation|Any CPU.ActiveCfg = Documentation|Any CPU - {868E37B3-0000-0000-0000-000000000000}.Nsis|Any CPU.ActiveCfg = Nsis|Any CPU - {868E37B3-0000-0000-0000-000000000000}.Nsis|Any CPU.Build.0 = Nsis|Any CPU - {868E37B3-0000-0000-0000-000000000000}.Release|Any CPU.ActiveCfg = Release|Any CPU - {868E37B3-0000-0000-0000-000000000000}.Release|Any CPU.Build.0 = Release|Any CPU - {868E37B3-0000-0000-0000-000000000000}.ReleaseMinimal|Any CPU.ActiveCfg = ReleaseMinimal|Any CPU {A625BE88-0000-0000-0000-000000000000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A625BE88-0000-0000-0000-000000000000}.Debug|Any CPU.Build.0 = Debug|Any CPU {A625BE88-0000-0000-0000-000000000000}.DebugMinimal|Any CPU.ActiveCfg = DebugMinimal|Any CPU diff --git a/Source/Examples/Data/Audio/the_ring_that_fell.wav b/Source/Examples/Data/Audio/the_ring_that_fell.wav deleted file mode 100644 index e0dd41f3..00000000 Binary files a/Source/Examples/Data/Audio/the_ring_that_fell.wav and /dev/null differ diff --git a/Source/Examples/Data/Poem.txt b/Source/Examples/Data/Poem.txt deleted file mode 100644 index 0b37c28b..00000000 --- a/Source/Examples/Data/Poem.txt +++ /dev/null @@ -1,51 +0,0 @@ -Waiting for the Barbarians -What are we waiting for, assembled in the forum? - -The barbarians are to arrive today. - -Why such inaction in the Senate? -Why do the Senators sit and pass no laws? - -Because the barbarians are to arrive today. -What laws can the Senators pass any more? -When the barbarians come they will make the laws. - -Why did our emperor wake up so early, -and sits at the greatest gate of the city, -on the throne, solemn, wearing the crown? - -Because the barbarians are to arrive today. -And the emperor waits to receive -their chief. Indeed he has prepared -to give him a scroll. Therein he inscribed -many titles and names of honor. - -Why have our two consuls and the praetors come out -today in their red, embroidered togas; -why do they wear amethyst-studded bracelets, -and rings with brilliant, glittering emeralds; -why are they carrying costly canes today, -wonderfully carved with silver and gold? - -Because the barbarians are to arrive today, -and such things dazzle the barbarians. - -Why don't the worthy orators come as always -to make their speeches, to have their say? - -Because the barbarians are to arrive today; -and they get bored with eloquence and orations. - -Why all of a sudden this unrest -and confusion. (How solemn the faces have become). -Why are the streets and squares clearing quickly, -and all return to their homes, so deep in thought? - -Because night is here but the barbarians have not come. -And some people arrived from the borders, -and said that there are no longer any barbarians. - -And now what shall become of us without any barbarians? -Those people were some kind of solution. - -- Constantine P. Cavafy (1904) \ No newline at end of file diff --git a/Source/Examples/Data/Shaders/CubeMap_FS.glsl b/Source/Examples/Data/Shaders/CubeMap_FS.glsl deleted file mode 100644 index 23769234..00000000 --- a/Source/Examples/Data/Shaders/CubeMap_FS.glsl +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) 2008 the OpenTK Team. See license.txt for legal bla - -uniform samplerCube Earth; -varying vec3 Normal; - -void main() -{ - gl_FragColor = textureCube( Earth, Normal.xyz ); -} \ No newline at end of file diff --git a/Source/Examples/Data/Shaders/CubeMap_VS.glsl b/Source/Examples/Data/Shaders/CubeMap_VS.glsl deleted file mode 100644 index 21b3c991..00000000 --- a/Source/Examples/Data/Shaders/CubeMap_VS.glsl +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) 2008 the OpenTK Team. See license.txt for legal bla - -// MUST be written to for FS -varying vec3 Normal; - -void main() -{ - gl_Position = ftransform(); - Normal = /*gl_NormalMatrix * */ gl_Normal ; -} \ No newline at end of file diff --git a/Source/Examples/Data/Shaders/JuliaSet_SM2_FS.glsl b/Source/Examples/Data/Shaders/JuliaSet_SM2_FS.glsl deleted file mode 100644 index 10fe5cd5..00000000 --- a/Source/Examples/Data/Shaders/JuliaSet_SM2_FS.glsl +++ /dev/null @@ -1,66 +0,0 @@ -#version 110 -// www.OpenTK.net GLSL Julia Set (c) 2008 Christoph Brandtner - -// uniforms from OpenGL -uniform sampler1D COLORTABLE; -uniform float CETX; -uniform float CETY; -uniform float SCALINGX; -uniform float SCALINGY; -uniform float OFFSETX; -uniform float OFFSETY; - -// GLSL internal variables. -const int MAXIterations = 16; // must be greater than zero, 16 is a good blend between detail and speed -float XPos; -float YPos; -float XQuad; -float YQuad; // half precision floating point could be used on those 4 floats for speed, but will throw a warning. -int TableIndex; -int LoopCount; - -// this function reduces duplicate code -void Iterate(void) -{ - YPos = 2.0 * XPos * YPos + CETY; - XPos = XQuad - YQuad + CETX; - XQuad = pow(XPos, 2.0); - YQuad = pow(YPos, 2.0); - TableIndex++; - if ( (XQuad + YQuad) > 4.0 ) LoopCount = MAXIterations; // skip further iterations for this Pixel - LoopCount++; -} - -// Shader entry point, this is executed per Pixel -void main(void) -{ - XPos = gl_FragCoord.x / SCALINGX - OFFSETX; - YPos = gl_FragCoord.y / SCALINGY - OFFSETY; - XQuad = pow(XPos, 2.0); - YQuad = pow(YPos, 2.0); - TableIndex = -1; - LoopCount = 0; - // the loop is unrolled for SM 2.0 compatibility - if ( LoopCount <= MAXIterations ) Iterate(); // TableIndex==0 - if ( LoopCount > 1 ) discard; // attempt to early-out, will affect ~1/3 of all Pixels - if ( LoopCount <= MAXIterations ) Iterate(); - if ( LoopCount <= MAXIterations ) Iterate(); - if ( LoopCount <= MAXIterations ) Iterate(); - if ( LoopCount <= MAXIterations ) Iterate(); - if ( LoopCount <= MAXIterations ) Iterate(); - if ( LoopCount <= MAXIterations ) Iterate(); - if ( LoopCount <= MAXIterations ) Iterate(); - if ( LoopCount <= MAXIterations ) Iterate(); - if ( LoopCount <= MAXIterations ) Iterate(); - if ( LoopCount <= MAXIterations ) Iterate(); - if ( LoopCount <= MAXIterations ) Iterate(); - if ( LoopCount <= MAXIterations ) Iterate(); - if ( LoopCount <= MAXIterations ) Iterate(); - if ( LoopCount <= MAXIterations ) Iterate(); - if ( LoopCount <= MAXIterations ) Iterate(); - if ( LoopCount <= MAXIterations ) Iterate(); // TableIndex==16 - float FinalTableIndex = float( TableIndex ) / float( MAXIterations ); - - gl_FragColor = texture1D( COLORTABLE, FinalTableIndex ); // lookup texture for output -// gl_FragColor.rgb = vec3(FinalTableIndex); // Debug: output greyscale -} \ No newline at end of file diff --git a/Source/Examples/Data/Shaders/JuliaSet_SM3_FS.glsl b/Source/Examples/Data/Shaders/JuliaSet_SM3_FS.glsl deleted file mode 100644 index 003068b8..00000000 --- a/Source/Examples/Data/Shaders/JuliaSet_SM3_FS.glsl +++ /dev/null @@ -1,41 +0,0 @@ -#version 120 -// www.OpenTK.net GLSL Julia Set (c) 2008 Christoph Brandtner - -uniform sampler1D COLORTABLE; -uniform float CETX; -uniform float CETY; -uniform float SCALINGX; -uniform float SCALINGY; -uniform float OFFSETX; -uniform float OFFSETY; - -const int MAXIterations = 32; // *must* be > 0 - -void main(void) -{ - float XPos = gl_FragCoord.x / SCALINGX - OFFSETX; - float YPos = gl_FragCoord.y / SCALINGY - OFFSETY; - float XQuad = pow( XPos, 2.0 ); - float YQuad = pow( YPos, 2.0 ); - int TableIndex = -1; - int LoopCount = 0; - while ( LoopCount <= MAXIterations ) - { - YPos = 2.0 * XPos * YPos + CETY; - XPos = XQuad - YQuad + CETX; - XQuad = pow( XPos, 2.0 ); - YQuad = pow( YPos, 2.0 ); - TableIndex++; - if ( (XQuad + YQuad) > 4.0 ) - { - if (TableIndex == 0) - discard; - LoopCount = MAXIterations; - } - LoopCount++; - } - float FinalTableIndex = float( TableIndex ) / float( MAXIterations ); - - gl_FragColor = texture1D( COLORTABLE, FinalTableIndex ); // lookup texture for output - // gl_FragColor.rgb = vec3( FinalTableIndex ); // Debug: output greyscale -} \ No newline at end of file diff --git a/Source/Examples/Data/Shaders/JuliaSet_VS.glsl b/Source/Examples/Data/Shaders/JuliaSet_VS.glsl deleted file mode 100644 index cbee9423..00000000 --- a/Source/Examples/Data/Shaders/JuliaSet_VS.glsl +++ /dev/null @@ -1,4 +0,0 @@ -void main(void) -{ - gl_Position = ftransform(); // gl_ModelViewProjectionMatrix * gl_Vertex; -} \ No newline at end of file diff --git a/Source/Examples/Data/Shaders/Parallax_FS.glsl b/Source/Examples/Data/Shaders/Parallax_FS.glsl deleted file mode 100644 index ea259a47..00000000 --- a/Source/Examples/Data/Shaders/Parallax_FS.glsl +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2008 the OpenTK Team. See license.txt for legal bla - -// Material uniforms -uniform sampler2D Material_DiffuseAndHeight; -uniform sampler2D Material_NormalAndGloss; -uniform vec3 Material_ScaleBiasShininess; // x=Scale, y=Bias, z=Shininess - -// Light uniforms -uniform vec3 Light_DiffuseColor; -uniform vec3 Light_SpecularColor; - -// from VS -varying vec3 VaryingLightVector; -varying vec3 VaryingEyeVector; - -vec3 normal; - -void main() -{ - vec3 lightVector = normalize( VaryingLightVector ); - vec3 eyeVector = normalize( VaryingEyeVector ); - - // first, find the parallax displacement by reading only the height map - float parallaxOffset = texture2D( Material_DiffuseAndHeight, gl_TexCoord[0].st ).a * - Material_ScaleBiasShininess.x - Material_ScaleBiasShininess.y; - vec2 newTexCoords = gl_TexCoord[0].st + ( parallaxOffset * eyeVector.xy ); // displace texcoords according to viewer - - // knowing the displacement, read RGB, Normal and Gloss - vec3 diffuseColor = texture2D( Material_DiffuseAndHeight, newTexCoords.st ).rgb; - vec4 temp = texture2D( Material_NormalAndGloss, newTexCoords.st ); - - // build a usable normal vector - normal.xy = temp.ag * 2.0 - 1.0; // swizzle alpha and green to x/y and scale to [-1..+1] - normal.z = sqrt( 1.0 - normal.x*normal.x - normal.y*normal.y ); // z = sqrt(1-x^2-y^2) - - // move other properties to be better readable - float gloss = temp.r; - -// float alpha = temp.b; -// if ( alpha < 0.2 ) // optimization: should move this test before reading RGB texture -// discard; - - // tweaked phong lighting - float lambert = max( dot( lightVector, normal ), 0.0 ); - - gl_FragColor = vec4( Light_DiffuseColor * diffuseColor, 1.0 ) * - lambert; - - if ( lambert > 0.0 ) - { - float specular = pow( - clamp( dot( reflect( -lightVector, normal ), eyeVector ), 0.0, 1.0 ), - Material_ScaleBiasShininess.z ); - - gl_FragColor += vec4( Light_SpecularColor * diffuseColor, 1.0 ) * ( specular * gloss ); - } -} \ No newline at end of file diff --git a/Source/Examples/Data/Shaders/Parallax_VS.glsl b/Source/Examples/Data/Shaders/Parallax_VS.glsl deleted file mode 100644 index 49268be8..00000000 --- a/Source/Examples/Data/Shaders/Parallax_VS.glsl +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2008 the OpenTK Team. See license.txt for legal bla - -// custom vertex attribute -attribute vec3 AttributeTangent; - -// world uniforms -uniform vec3 Light_Position; -uniform vec3 Camera_Position; - -// MUST be written to for FS -varying vec3 VaryingLightVector; -varying vec3 VaryingEyeVector; - -void main() -{ - gl_Position = ftransform(); - gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0; - - vec3 nor = normalize( gl_NormalMatrix * gl_Normal ); - vec3 tan = normalize( gl_NormalMatrix * AttributeTangent ); - vec3 bi = cross(nor, tan); - - // need positions in tangent space - vec3 vertex = vec3( gl_ModelViewMatrix * gl_Vertex ); - - vec3 temp = Light_Position - vertex; - VaryingLightVector.x = dot(temp, tan); // optimization, calculate dot products rather than building TBN matrix - VaryingLightVector.y = dot(temp, bi); - VaryingLightVector.z = dot(temp, nor); - - temp = Camera_Position - vertex; - VaryingEyeVector.x = dot(temp, tan); - VaryingEyeVector.y = dot(temp, bi); - VaryingEyeVector.z = dot(temp, nor); -} \ No newline at end of file diff --git a/Source/Examples/Data/Shaders/Picking_FS.glsl b/Source/Examples/Data/Shaders/Picking_FS.glsl deleted file mode 100644 index f4e2af63..00000000 --- a/Source/Examples/Data/Shaders/Picking_FS.glsl +++ /dev/null @@ -1,8 +0,0 @@ -#version 120 - -flat varying vec4 vColor; - -void main(void) -{ - gl_FragColor = vColor; -} \ No newline at end of file diff --git a/Source/Examples/Data/Shaders/Picking_VS.glsl b/Source/Examples/Data/Shaders/Picking_VS.glsl deleted file mode 100644 index 0deb5328..00000000 --- a/Source/Examples/Data/Shaders/Picking_VS.glsl +++ /dev/null @@ -1,9 +0,0 @@ -#version 120 - -flat varying vec4 vColor; // must be flat, cannot have this interpolated in any way - -void main(void) -{ - vColor = gl_Color; - gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; // ftransform(); -} \ No newline at end of file diff --git a/Source/Examples/Data/Shaders/Simple_FS.glsl b/Source/Examples/Data/Shaders/Simple_FS.glsl deleted file mode 100644 index 85e2a856..00000000 --- a/Source/Examples/Data/Shaders/Simple_FS.glsl +++ /dev/null @@ -1,5 +0,0 @@ -/* Copies incoming fragment color without change. */ -void main() -{ - gl_FragColor = gl_Color; -} \ No newline at end of file diff --git a/Source/Examples/Data/Shaders/Simple_VS.glsl b/Source/Examples/Data/Shaders/Simple_VS.glsl deleted file mode 100644 index b0fc2a6f..00000000 --- a/Source/Examples/Data/Shaders/Simple_VS.glsl +++ /dev/null @@ -1,8 +0,0 @@ -/* Copies incoming vertex color without change. - * Applies the transformation matrix to vertex position. - */ -void main() -{ - gl_FrontColor = gl_Color; - gl_Position = ftransform(); -} \ No newline at end of file diff --git a/Source/Examples/Data/Textures/JuliaColorTable.bmp b/Source/Examples/Data/Textures/JuliaColorTable.bmp deleted file mode 100644 index d99204f9..00000000 Binary files a/Source/Examples/Data/Textures/JuliaColorTable.bmp and /dev/null differ diff --git a/Source/Examples/Data/Textures/Swizzled Textures License.txt b/Source/Examples/Data/Textures/Swizzled Textures License.txt deleted file mode 100644 index 59a5c554..00000000 --- a/Source/Examples/Data/Textures/Swizzled Textures License.txt +++ /dev/null @@ -1,18 +0,0 @@ -The files named "Swizzled *.dds" for the Parallax mapping demo originate from -http://www.TyphoonLabs.com ShaderDesigner application. Used with permission. - -The Textures have been altered from the layout: - -Diffuse R, Diffuse G, Diffuse B, Gloss -Normal X, Normal Y, Normal Z, Height - -to - -Diffuse R, Diffuse G, Diffuse B, Height -Gloss, Normal Y, Gloss, Normal X - -Additionally, the Textures in this folder have been compressed with a lossy -algorithm (S3TC) and do not reflect the quality of the source Textures. - -Please refer to the above website for unaltered versions of the textures, -or licensing information. diff --git a/Source/Examples/Data/Textures/cursor.png b/Source/Examples/Data/Textures/cursor.png deleted file mode 100644 index 5c7de625..00000000 Binary files a/Source/Examples/Data/Textures/cursor.png and /dev/null differ diff --git a/Source/Examples/Data/Textures/earth-cubemap.dds b/Source/Examples/Data/Textures/earth-cubemap.dds deleted file mode 100644 index 5f884de5..00000000 Binary files a/Source/Examples/Data/Textures/earth-cubemap.dds and /dev/null differ diff --git a/Source/Examples/Data/Textures/logo-dark.jpg b/Source/Examples/Data/Textures/logo-dark.jpg deleted file mode 100644 index 38758e31..00000000 Binary files a/Source/Examples/Data/Textures/logo-dark.jpg and /dev/null differ diff --git a/Source/Examples/Data/Textures/logo.jpg b/Source/Examples/Data/Textures/logo.jpg deleted file mode 100644 index e08a1bb9..00000000 Binary files a/Source/Examples/Data/Textures/logo.jpg and /dev/null differ diff --git a/Source/Examples/Data/Textures/metal.jpg b/Source/Examples/Data/Textures/metal.jpg deleted file mode 100644 index 9d16ad05..00000000 Binary files a/Source/Examples/Data/Textures/metal.jpg and /dev/null differ diff --git a/Source/Examples/Data/Textures/swizzled-rock-diffuse-height.dds b/Source/Examples/Data/Textures/swizzled-rock-diffuse-height.dds deleted file mode 100644 index c7557fa0..00000000 Binary files a/Source/Examples/Data/Textures/swizzled-rock-diffuse-height.dds and /dev/null differ diff --git a/Source/Examples/Data/Textures/swizzled-rock-normal-gloss.dds b/Source/Examples/Data/Textures/swizzled-rock-normal-gloss.dds deleted file mode 100644 index 5ca89a84..00000000 Binary files a/Source/Examples/Data/Textures/swizzled-rock-normal-gloss.dds and /dev/null differ diff --git a/Source/Examples/DependencyLoader.cs b/Source/Examples/DependencyLoader.cs deleted file mode 100644 index 99bfac77..00000000 --- a/Source/Examples/DependencyLoader.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Runtime.InteropServices; -using System.Text; -using OpenTK; - -namespace Examples -{ - class DependencyLoader : IDisposable - { - bool disposed; - readonly List LoadedLibraries = new List(); - - enum TargetCpu - { - x86, - x86_64, - } - - static readonly TargetCpu Cpu = IntPtr.Size == 4 ? TargetCpu.x86 : TargetCpu.x86_64; - - public void LoadDependencies() - { - string path = Path.Combine("Dependencies", Cpu == TargetCpu.x86 ? "x86" : "x64"); - - if (Directory.Exists(path)) - { - if (Configuration.RunningOnWindows) - { - foreach (var file in Directory.GetFiles(path, "*.dll")) - { - IntPtr lib = NativeMethods.LoadLibrary(file); - if (lib == IntPtr.Zero) - { - Debug.Print("Failed to load dependency {0} with {1}", file, - Marshal.GetLastWin32Error()); - } - else - { - LoadedLibraries.Add(lib); - Debug.Print("Loaded dependency {0}", file); - } - } - } - } - } - - static class NativeMethods - { - [DllImport("kernel32.dll", SetLastError = true)] - internal static extern IntPtr LoadLibrary(string dllName); - - [DllImport("kernel32.dll", SetLastError = true)] - internal static extern int FreeLibrary(IntPtr dll); - } - - #region IDisposable Members - - void Dispose(bool manual) - { - if (!disposed) - { - if (manual) - { - foreach (var lib in LoadedLibraries) - { - NativeMethods.FreeLibrary(lib); - } - } - - disposed = true; - } - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - ~DependencyLoader() - { - Dispose(false); - } - - #endregion - } -} diff --git a/Source/Examples/ExampleAttribute.cs b/Source/Examples/ExampleAttribute.cs deleted file mode 100644 index 00fbb190..00000000 --- a/Source/Examples/ExampleAttribute.cs +++ /dev/null @@ -1,59 +0,0 @@ -#region --- License --- -/* Copyright (c) 2006-2008 the OpenTK team - * See license.txt for licensing details - */ -#endregion - -using System; -using System.Collections.Generic; -using System.Text; - -namespace Examples -{ - [AttributeUsage(AttributeTargets.Class)] - public class ExampleAttribute : System.Attribute - { - string title; - bool visible = true; - public string Title { get { return title; } internal set { title = value; } } - public readonly ExampleCategory Category; - public readonly string Subcategory; - public int Difficulty; - public string Documentation; - public bool Visible { get { return visible; } set { visible = value; } } - - public ExampleAttribute(string title, ExampleCategory category, string subcategory) - : this(title, category, subcategory, Int32.MaxValue, true) { } - - public ExampleAttribute(string title, ExampleCategory category, string subcategory, int difficulty) - : this(title, category, subcategory, difficulty, true) { } - - public ExampleAttribute(string title, ExampleCategory category, string subcategory, bool visible) - : this(title, category, subcategory, Int32.MaxValue, visible) { } - - public ExampleAttribute(string title, ExampleCategory category, string subcategory, int difficulty, bool visible) - { - this.Title = title; - this.Category = category; - this.Subcategory = subcategory; - this.Difficulty = difficulty; - this.Visible = visible; - } - - public override string ToString() - { - if (Difficulty != 0) - return String.Format("{0} {1}: {2}", Category, Difficulty, Title); - return String.Format("{0}: {1}", Category, Title); - } - } - - public enum ExampleCategory - { - OpenTK = 0, - OpenGL, - OpenAL, - OpenCL, - OpenGLES - } -} diff --git a/Source/Examples/ExampleBrowser.Designer.cs b/Source/Examples/ExampleBrowser.Designer.cs deleted file mode 100644 index 2f38bd30..00000000 --- a/Source/Examples/ExampleBrowser.Designer.cs +++ /dev/null @@ -1,321 +0,0 @@ -namespace Examples -{ - partial class ExampleBrowser - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.components = new System.ComponentModel.Container(); - this.splitContainer1 = new System.Windows.Forms.SplitContainer(); - this.treeViewSamples = new System.Windows.Forms.TreeView(); - this.contextMenuStripSamples = new System.Windows.Forms.ContextMenuStrip(this.components); - this.runSampleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); - this.viewDescriptionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.viewSourceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.imageListSampleCategories = new System.Windows.Forms.ImageList(this.components); - this.tabControlSample = new System.Windows.Forms.TabControl(); - this.tabDescription = new System.Windows.Forms.TabPage(); - this.richTextBoxDescription = new System.Windows.Forms.RichTextBox(); - this.contextMenuStripDescription = new System.Windows.Forms.ContextMenuStrip(this.components); - this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.tabSource = new System.Windows.Forms.TabPage(); - this.richTextBoxSource = new System.Windows.Forms.RichTextBox(); - this.contextMenuStripSource = new System.Windows.Forms.ContextMenuStrip(this.components); - this.copyToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); - this.tabPageOutput = new System.Windows.Forms.TabPage(); - this.textBoxOutput = new System.Windows.Forms.TextBox(); - this.contextMenuStripOutput = new System.Windows.Forms.ContextMenuStrip(this.components); - this.copyToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem(); - this.toolTipSamples = new System.Windows.Forms.ToolTip(this.components); - this.splitContainer1.Panel1.SuspendLayout(); - this.splitContainer1.Panel2.SuspendLayout(); - this.splitContainer1.SuspendLayout(); - this.contextMenuStripSamples.SuspendLayout(); - this.tabControlSample.SuspendLayout(); - this.tabDescription.SuspendLayout(); - this.contextMenuStripDescription.SuspendLayout(); - this.tabSource.SuspendLayout(); - this.contextMenuStripSource.SuspendLayout(); - this.tabPageOutput.SuspendLayout(); - this.contextMenuStripOutput.SuspendLayout(); - this.SuspendLayout(); - // - // splitContainer1 - // - this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; - this.splitContainer1.Location = new System.Drawing.Point(0, 0); - this.splitContainer1.Name = "splitContainer1"; - // - // splitContainer1.Panel1 - // - this.splitContainer1.Panel1.Controls.Add(this.treeViewSamples); - // - // splitContainer1.Panel2 - // - this.splitContainer1.Panel2.Controls.Add(this.tabControlSample); - this.splitContainer1.Size = new System.Drawing.Size(784, 564); - this.splitContainer1.SplitterDistance = 261; - this.splitContainer1.TabIndex = 0; - // - // treeViewSamples - // - this.treeViewSamples.ContextMenuStrip = this.contextMenuStripSamples; - this.treeViewSamples.Dock = System.Windows.Forms.DockStyle.Fill; - this.treeViewSamples.FullRowSelect = true; - this.treeViewSamples.HideSelection = false; - this.treeViewSamples.HotTracking = true; - this.treeViewSamples.ImageIndex = 0; - this.treeViewSamples.ImageList = this.imageListSampleCategories; - this.treeViewSamples.Indent = 32; - this.treeViewSamples.Location = new System.Drawing.Point(0, 0); - this.treeViewSamples.Name = "treeViewSamples"; - this.treeViewSamples.SelectedImageIndex = 0; - this.treeViewSamples.Size = new System.Drawing.Size(261, 564); - this.treeViewSamples.TabIndex = 0; - this.toolTipSamples.SetToolTip(this.treeViewSamples, "Right-click a sample for more options."); - this.treeViewSamples.AfterExpand += new System.Windows.Forms.TreeViewEventHandler(this.treeViewSamples_AfterExpand); - this.treeViewSamples.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeViewSamples_AfterSelect); - this.treeViewSamples.NodeMouseDoubleClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.treeViewSamples_NodeMouseDoubleClick); - this.treeViewSamples.KeyDown += new System.Windows.Forms.KeyEventHandler(this.treeViewSamples_KeyDown); - this.treeViewSamples.MouseDown += new System.Windows.Forms.MouseEventHandler(this.treeViewSamples_MouseDown); - // - // contextMenuStripSamples - // - this.contextMenuStripSamples.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.runSampleToolStripMenuItem, - this.toolStripMenuItem1, - this.viewDescriptionToolStripMenuItem, - this.viewSourceToolStripMenuItem}); - this.contextMenuStripSamples.Name = "contextMenuStripSamples"; - this.contextMenuStripSamples.Size = new System.Drawing.Size(170, 76); - this.contextMenuStripSamples.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.contextMenuStripSamples_ItemClicked); - // - // runSampleToolStripMenuItem - // - this.runSampleToolStripMenuItem.Name = "runSampleToolStripMenuItem"; - this.runSampleToolStripMenuItem.Size = new System.Drawing.Size(169, 22); - this.runSampleToolStripMenuItem.Text = "&Run Sample"; - // - // toolStripMenuItem1 - // - this.toolStripMenuItem1.Name = "toolStripMenuItem1"; - this.toolStripMenuItem1.Size = new System.Drawing.Size(166, 6); - // - // viewDescriptionToolStripMenuItem - // - this.viewDescriptionToolStripMenuItem.Name = "viewDescriptionToolStripMenuItem"; - this.viewDescriptionToolStripMenuItem.Size = new System.Drawing.Size(169, 22); - this.viewDescriptionToolStripMenuItem.Text = "View Description"; - // - // viewSourceToolStripMenuItem - // - this.viewSourceToolStripMenuItem.Name = "viewSourceToolStripMenuItem"; - this.viewSourceToolStripMenuItem.Size = new System.Drawing.Size(169, 22); - this.viewSourceToolStripMenuItem.Text = "View Source Code"; - // - // imageListSampleCategories - // - this.imageListSampleCategories.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit; - this.imageListSampleCategories.ImageSize = new System.Drawing.Size(35, 35); - this.imageListSampleCategories.TransparentColor = System.Drawing.Color.Transparent; - // - // tabControlSample - // - this.tabControlSample.Controls.Add(this.tabDescription); - this.tabControlSample.Controls.Add(this.tabSource); - this.tabControlSample.Controls.Add(this.tabPageOutput); - this.tabControlSample.Dock = System.Windows.Forms.DockStyle.Fill; - this.tabControlSample.Location = new System.Drawing.Point(0, 0); - this.tabControlSample.Name = "tabControlSample"; - this.tabControlSample.SelectedIndex = 0; - this.tabControlSample.Size = new System.Drawing.Size(519, 564); - this.tabControlSample.TabIndex = 0; - // - // tabDescription - // - this.tabDescription.Controls.Add(this.richTextBoxDescription); - this.tabDescription.Location = new System.Drawing.Point(4, 22); - this.tabDescription.Name = "tabDescription"; - this.tabDescription.Padding = new System.Windows.Forms.Padding(3); - this.tabDescription.Size = new System.Drawing.Size(511, 538); - this.tabDescription.TabIndex = 0; - this.tabDescription.Text = "Description"; - this.tabDescription.UseVisualStyleBackColor = true; - // - // richTextBoxDescription - // - this.richTextBoxDescription.ContextMenuStrip = this.contextMenuStripDescription; - this.richTextBoxDescription.Dock = System.Windows.Forms.DockStyle.Fill; - this.richTextBoxDescription.Location = new System.Drawing.Point(3, 3); - this.richTextBoxDescription.Name = "richTextBoxDescription"; - this.richTextBoxDescription.ReadOnly = true; - this.richTextBoxDescription.Size = new System.Drawing.Size(505, 532); - this.richTextBoxDescription.TabIndex = 0; - this.richTextBoxDescription.Text = ""; - this.richTextBoxDescription.MouseDown += new System.Windows.Forms.MouseEventHandler(this.richTextBoxDescription_MouseDown); - // - // contextMenuStripDescription - // - this.contextMenuStripDescription.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.copyToolStripMenuItem}); - this.contextMenuStripDescription.Name = "contextMenuStripDescription"; - this.contextMenuStripDescription.Size = new System.Drawing.Size(103, 26); - this.contextMenuStripDescription.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.contextMenuStripDescription_ItemClicked); - // - // copyToolStripMenuItem - // - this.copyToolStripMenuItem.Name = "copyToolStripMenuItem"; - this.copyToolStripMenuItem.Size = new System.Drawing.Size(102, 22); - this.copyToolStripMenuItem.Text = "&Copy"; - // - // tabSource - // - this.tabSource.Controls.Add(this.richTextBoxSource); - this.tabSource.Location = new System.Drawing.Point(4, 22); - this.tabSource.Name = "tabSource"; - this.tabSource.Padding = new System.Windows.Forms.Padding(3); - this.tabSource.Size = new System.Drawing.Size(511, 538); - this.tabSource.TabIndex = 1; - this.tabSource.Text = "Source Code"; - this.tabSource.UseVisualStyleBackColor = true; - // - // richTextBoxSource - // - this.richTextBoxSource.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(216)))), ((int)(((byte)(242)))), ((int)(((byte)(240))))); - this.richTextBoxSource.ContextMenuStrip = this.contextMenuStripSource; - this.richTextBoxSource.Dock = System.Windows.Forms.DockStyle.Fill; - this.richTextBoxSource.Location = new System.Drawing.Point(3, 3); - this.richTextBoxSource.Name = "richTextBoxSource"; - this.richTextBoxSource.ReadOnly = true; - this.richTextBoxSource.Size = new System.Drawing.Size(505, 532); - this.richTextBoxSource.TabIndex = 0; - this.richTextBoxSource.Text = ""; - this.richTextBoxSource.MouseDown += new System.Windows.Forms.MouseEventHandler(this.richTextBoxSource_MouseDown); - // - // contextMenuStripSource - // - this.contextMenuStripSource.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.copyToolStripMenuItem1}); - this.contextMenuStripSource.Name = "contextMenuStripSource"; - this.contextMenuStripSource.Size = new System.Drawing.Size(103, 26); - this.contextMenuStripSource.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.contextMenuStripSource_ItemClicked); - // - // copyToolStripMenuItem1 - // - this.copyToolStripMenuItem1.Name = "copyToolStripMenuItem1"; - this.copyToolStripMenuItem1.Size = new System.Drawing.Size(102, 22); - this.copyToolStripMenuItem1.Text = "&Copy"; - // - // tabPageOutput - // - this.tabPageOutput.Controls.Add(this.textBoxOutput); - this.tabPageOutput.Location = new System.Drawing.Point(4, 22); - this.tabPageOutput.Name = "tabPageOutput"; - this.tabPageOutput.Padding = new System.Windows.Forms.Padding(3); - this.tabPageOutput.Size = new System.Drawing.Size(511, 538); - this.tabPageOutput.TabIndex = 2; - this.tabPageOutput.Text = "Output"; - this.tabPageOutput.UseVisualStyleBackColor = true; - // - // textBoxOutput - // - this.textBoxOutput.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(216)))), ((int)(((byte)(242)))), ((int)(((byte)(240))))); - this.textBoxOutput.ContextMenuStrip = this.contextMenuStripOutput; - this.textBoxOutput.Dock = System.Windows.Forms.DockStyle.Fill; - this.textBoxOutput.Location = new System.Drawing.Point(3, 3); - this.textBoxOutput.MaxLength = 1048576; - this.textBoxOutput.Multiline = true; - this.textBoxOutput.Name = "textBoxOutput"; - this.textBoxOutput.ReadOnly = true; - this.textBoxOutput.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; - this.textBoxOutput.Size = new System.Drawing.Size(505, 532); - this.textBoxOutput.TabIndex = 0; - // - // contextMenuStripOutput - // - this.contextMenuStripOutput.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.copyToolStripMenuItem2}); - this.contextMenuStripOutput.Name = "contextMenuStripOutput"; - this.contextMenuStripOutput.Size = new System.Drawing.Size(103, 26); - // - // copyToolStripMenuItem2 - // - this.copyToolStripMenuItem2.Name = "copyToolStripMenuItem2"; - this.copyToolStripMenuItem2.Size = new System.Drawing.Size(102, 22); - this.copyToolStripMenuItem2.Text = "&Copy"; - // - // ExampleBrowser - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(784, 564); - this.Controls.Add(this.splitContainer1); - this.Name = "ExampleBrowser"; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; - this.Text = "The Open Toolkit Sample Browser"; - this.splitContainer1.Panel1.ResumeLayout(false); - this.splitContainer1.Panel2.ResumeLayout(false); - this.splitContainer1.ResumeLayout(false); - this.contextMenuStripSamples.ResumeLayout(false); - this.tabControlSample.ResumeLayout(false); - this.tabDescription.ResumeLayout(false); - this.contextMenuStripDescription.ResumeLayout(false); - this.tabSource.ResumeLayout(false); - this.contextMenuStripSource.ResumeLayout(false); - this.tabPageOutput.ResumeLayout(false); - this.tabPageOutput.PerformLayout(); - this.contextMenuStripOutput.ResumeLayout(false); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.SplitContainer splitContainer1; - private System.Windows.Forms.TabControl tabControlSample; - private System.Windows.Forms.TabPage tabDescription; - private System.Windows.Forms.TabPage tabSource; - private System.Windows.Forms.RichTextBox richTextBoxDescription; - private System.Windows.Forms.RichTextBox richTextBoxSource; - private System.Windows.Forms.TreeView treeViewSamples; - private System.Windows.Forms.ImageList imageListSampleCategories; - private System.Windows.Forms.ContextMenuStrip contextMenuStripDescription; - private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem; - private System.Windows.Forms.ContextMenuStrip contextMenuStripSource; - private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem1; - private System.Windows.Forms.ContextMenuStrip contextMenuStripSamples; - private System.Windows.Forms.ToolStripMenuItem runSampleToolStripMenuItem; - private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; - private System.Windows.Forms.ToolStripMenuItem viewDescriptionToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem viewSourceToolStripMenuItem; - private System.Windows.Forms.ToolTip toolTipSamples; - private System.Windows.Forms.TabPage tabPageOutput; - private System.Windows.Forms.TextBox textBoxOutput; - private System.Windows.Forms.ContextMenuStrip contextMenuStripOutput; - private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem2; - } -} \ No newline at end of file diff --git a/Source/Examples/ExampleBrowser.cs b/Source/Examples/ExampleBrowser.cs deleted file mode 100644 index 41f303b7..00000000 --- a/Source/Examples/ExampleBrowser.cs +++ /dev/null @@ -1,447 +0,0 @@ -#region License -// -// The Open Toolkit Library License -// -// Copyright (c) 2006 - 2009 the Open Toolkit library. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -// the Software, and to permit persons to whom the Software is furnished to do -// so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// -#endregion - -using System; -using System.Diagnostics; -using System.Drawing; -using System.Drawing.Text; -using System.Reflection; -using System.Windows.Forms; -using OpenTK.Examples.Properties; -using System.Threading; -using System.IO; - -namespace Examples -{ - public partial class ExampleBrowser : Form - { - #region Fields - - //PrivateFontCollection font_collection = new PrivateFontCollection(); - bool show_warning = true; - readonly string SourcePath; - - #endregion - - #region Constructors - - public ExampleBrowser() - { - SourcePath = - FindSourcePath(Directory.GetCurrentDirectory()) ?? - FindSourcePath(Assembly.GetExecutingAssembly().Location); - - Font = SystemFonts.DialogFont; - - InitializeComponent(); - Icon = Resources.App; - - // Windows 6 (Vista) and higher come with Consolas, a high-quality monospace font. Use that or fallback to - // the generic monospace font on other systems. - if (System.Environment.OSVersion.Platform == PlatformID.Win32NT && - System.Environment.OSVersion.Version.Major >= 6) - { - textBoxOutput.Font = richTextBoxSource.Font = new Font("Consolas", 10.0f, FontStyle.Regular); - } - else - { - textBoxOutput.Font = richTextBoxSource.Font = - new Font(FontFamily.GenericMonospace, 10.0f, FontStyle.Regular); - } - } - - #endregion - - #region Protected Members - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - // Add those by hand, because using the designer results in an empty - // image list when cross-compiling on Mono. - imageListSampleCategories.Images.Add("OpenAL", Resources.OpenAL); - imageListSampleCategories.Images.Add("OpenGL", Resources.OpenGL); - imageListSampleCategories.Images.Add("OpenGLES", Resources.OpenGLES); - imageListSampleCategories.Images.Add("OpenCL", Resources.OpenCL); - imageListSampleCategories.Images.Add("OpenTK", Resources.OpenTK); - imageListSampleCategories.Images.Add("1.x", Resources.v1x); - imageListSampleCategories.Images.Add("2.x", Resources.v2x); - imageListSampleCategories.Images.Add("3.x", Resources.v3x); - imageListSampleCategories.Images.Add("4.x", Resources.v4x); - - treeViewSamples.TreeViewNodeSorter = new SamplesTreeViewSorter(); - - LoadSamplesFromAssembly(Assembly.GetExecutingAssembly()); - } - - protected override void OnShown(EventArgs e) - { - if (show_warning) - { - //MessageBox.Show("The new Sample Browser is not complete. Please report any issues at http://www.opentk.com/project/issues.", - // "Work in Progress", MessageBoxButtons.OK, MessageBoxIcon.Information); - show_warning = false; - } - } - - #endregion - - #region Private Members - - #region Events - - #region TreeView - - private void treeViewSamples_AfterSelect(object sender, TreeViewEventArgs e) - { - const string no_docs = "Documentation has not been entered."; - const string no_source = "Source code has not been entered."; - - if (SourcePath != null && e.Node.Tag != null && - !String.IsNullOrEmpty(((ExampleInfo)e.Node.Tag).Attribute.Documentation)) - { - string docs = null; - string source = null; - - ExampleInfo einfo = (ExampleInfo)e.Node.Tag; - string sample = einfo.Attribute.Documentation; - string category = einfo.Attribute.Category.ToString(); - string subcategory = einfo.Attribute.Subcategory; - - string path = Path.Combine(Path.Combine(Path.Combine(SourcePath, category), subcategory), sample); - string sample_rtf = Path.ChangeExtension(path, "rtf"); - string sample_cs = Path.ChangeExtension(path, "cs"); - - if (File.Exists(sample_rtf)) - { - docs = File.ReadAllText(sample_rtf); - } - - if (File.Exists(sample_cs)) - { - source = File.ReadAllText(sample_cs); - } - - if (String.IsNullOrEmpty(docs)) - richTextBoxDescription.Text = String.Format("File {0} not found.", sample_rtf); - else - richTextBoxDescription.Rtf = docs; - - if (String.IsNullOrEmpty(source)) - richTextBoxSource.Text = String.Format("File {0} not found.", sample_cs); - else - richTextBoxSource.Text = source; - } - else - { - richTextBoxDescription.Text = no_docs; - richTextBoxSource.Text = no_source; - } - } - - private void treeViewSamples_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) - { - if (e.Node.Tag != null) - { - ActivateNode(e.Node); - } - } - - private void treeViewSamples_KeyDown(object sender, KeyEventArgs e) - { - // The enter key activates a node (either expands/collapses or executes its sample). - switch (e.KeyCode) - { - case Keys.Enter: - ActivateNode(treeViewSamples.SelectedNode); - e.Handled = true; - e.SuppressKeyPress = true; - break; - } - } - - private void treeViewSamples_MouseDown(object sender, MouseEventArgs e) - { - // Make sure that right-clicking a new node will select that node before displaying - // the context menu. Without this, right-clicking a node does not select it, which - // is completely disorienting. - // As a bonus, make any mouse button select the underlying node, - TreeNode node = treeViewSamples.HitTest(e.Location).Node; - if (node != null) - treeViewSamples.SelectedNode = node; - - // Middle click selects and activates a node (either expands/collapses or executes its sample). - // Right button displays the context menu. - // All other mouse buttons simply select the underlying node. - switch (e.Button) - { - case MouseButtons.Middle: - ActivateNode(node); - break; - - case MouseButtons.Right: - treeViewSamples.ContextMenuStrip.Show(sender as Control, e.Location); - break; - } - } - - private void treeViewSamples_AfterExpand(object sender, TreeViewEventArgs e) - { - foreach (TreeNode child in e.Node.Nodes) - child.EnsureVisible(); - } - - private void contextMenuStripSamples_ItemClicked(object sender, ToolStripItemClickedEventArgs e) - { - switch (e.ClickedItem.Text) - { - case "&Run Sample": RunSample(this, (ExampleInfo)treeViewSamples.SelectedNode.Tag); break; - case "View Description": tabControlSample.SelectedTab = tabDescription; break; - case "View Source Code": tabControlSample.SelectedTab = tabSource; break; - } - } - - #endregion - - #region Description - - private void richTextBoxDescription_MouseDown(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtons.Right) - { - richTextBoxDescription.ContextMenuStrip.Show(sender as Control, e.X, e.Y); - } - } - - private void contextMenuStripDescription_ItemClicked(object sender, ToolStripItemClickedEventArgs e) - { - if (e.ClickedItem.Text == "&Copy") - { - Clipboard.SetText(richTextBoxDescription.SelectedRtf, TextDataFormat.Rtf); - } - } - - #endregion - - #region Source Code - - private void richTextBoxSource_MouseDown(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtons.Right) - { - richTextBoxSource.ContextMenuStrip.Show(sender as Control, e.X, e.Y); - } - } - - private void contextMenuStripSource_ItemClicked(object sender, ToolStripItemClickedEventArgs e) - { - if (e.ClickedItem.Text == "&Copy") - { - Clipboard.SetText(richTextBoxSource.SelectedText, TextDataFormat.Text); - } - } - - #endregion - - #endregion - - #region Actions - - void LoadSamplesFromAssembly(Assembly assembly) - { - if (assembly == null) - throw new ArgumentNullException("assembly"); - - Type[] types = assembly.GetTypes(); - foreach (Type type in types) - { - object[] attributes = type.GetCustomAttributes(false); - ExampleAttribute example = null; - foreach (object attr in attributes) - { - if (attr is ExampleAttribute) - { - example = (ExampleAttribute)attr; - - if (example.Visible) - { - // Add this example to the sample TreeView. - // First check whether the ExampleCategory exists in the tree (and add it if it doesn't). - // Then add the example as a child node on this category. - - if (!treeViewSamples.Nodes.ContainsKey(example.Category.ToString())) - { - int category_index = GetImageIndexForSample(imageListSampleCategories, example.Category.ToString(), String.Empty); - treeViewSamples.Nodes.Add(example.Category.ToString(), String.Format("{0} samples", example.Category), - category_index, category_index); - } - - int image_index = GetImageIndexForSample(imageListSampleCategories, example.Category.ToString(), example.Subcategory); - TreeNode node = new TreeNode(example.Title, image_index, image_index); - node.Name = example.Title; - node.Tag = new ExampleInfo(type, example); - treeViewSamples.Nodes[example.Category.ToString()].Nodes.Add(node); - } - } - } - } - - treeViewSamples.Sort(); - } - - void ActivateNode(TreeNode node) - { - if (node == null) - return; - - if (node.Tag == null) - { - if (node.IsExpanded) - node.Collapse(); - else - node.Expand(); - } - else - { - tabControlSample.SelectedTab = tabPageOutput; - textBoxOutput.Clear(); - RunSample(node.TreeView.TopLevelControl, (ExampleInfo)node.Tag); - } - } - - static int GetImageIndexForSample(ImageList list, string category, string subcategory) - { - if (list == null) - throw new ArgumentNullException("list"); - - foreach (string extension in new string[] { "", ".png", ".jpg" }) - { - string name = subcategory.ToString() + extension; - if (list.Images.ContainsKey(name)) - return list.Images.IndexOfKey(name); - - name = category.ToString() + extension; - if (list.Images.ContainsKey(name)) - return list.Images.IndexOfKey(name); - } - - return -1; - } - - void RunSample(Control parent, ExampleInfo e) - { - if (e == null) - return; - - try - { - if (parent != null) - { - parent.Visible = false; - Application.DoEvents(); - } - Trace.WriteLine(String.Format("Launching sample: \"{0}\"", e.Attribute.Title)); - Trace.WriteLine(String.Empty); - - var info = new ProcessStartInfo - { - FileName = Application.ExecutablePath,//.Replace("vshost.exe", String.Empty), - Arguments = e.Example.ToString() - }; - var process = Process.Start(info); - process.WaitForExit(); - } - finally - { - if (parent != null) - { - try - { - textBoxOutput.Text = File.ReadAllText("debug.log"); - } - catch (Exception ex) - { - Debug.Print(ex.ToString()); - } - parent.Visible = true; - parent.Focus(); - Application.DoEvents(); - } - } - - } - - // Tries to detect the path that contains the source for the examples. - static string FindSourcePath(string guess) - { - guess = Path.GetDirectoryName(guess); - - // Typically, our working directory is either "[opentk]/Binaries/OpenTK/[config]" or "[opentk]". - // The desired source path is "[opentk]/Source/Examples/[ExampleCategory]" - if (CheckPath(ref guess)) - return guess; // We were in [opentk] after all - - for (int i = 0; i < 3; i++) - { - DirectoryInfo dir = Directory.GetParent(guess); - if (dir == null || !dir.Exists) - break; - guess = dir.FullName; - } - - if (CheckPath(ref guess)) - return guess; // We were in [opentk]/Binaries/OpenTK/[config] after all - - return null; - } - - static bool CheckPath(ref string path) - { - string guess = path; - if (Directory.Exists(guess)) - { - guess = Path.Combine(guess, "Source"); - if (Directory.Exists(guess)) - { - guess = Path.Combine(guess, "Examples"); - if (Directory.Exists(guess)) - { - // We are have found [opentk]/Source/Examples - path = guess; - return true; - } - } - } - return false; - } - - #endregion - - #endregion - } -} diff --git a/Source/Examples/ExampleBrowser.resx b/Source/Examples/ExampleBrowser.resx deleted file mode 100644 index 16e620ff..00000000 --- a/Source/Examples/ExampleBrowser.resx +++ /dev/null @@ -1,138 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 616, 17 - - - 17, 17 - - - 810, 17 - - - 219, 17 - - - 430, 17 - - - 945, 17 - - \ No newline at end of file diff --git a/Source/Examples/ExampleInfo.cs b/Source/Examples/ExampleInfo.cs deleted file mode 100644 index a7487710..00000000 --- a/Source/Examples/ExampleInfo.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Examples -{ - /// - /// Contains the information necessary to display and launch an example thorugh the ExampleLauncer. - /// - class ExampleInfo - { - public readonly Type Example; - public readonly ExampleAttribute Attribute; - - public ExampleInfo(Type example, ExampleAttribute attr) - { - Example = example; - Attribute = attr; - } - - public override string ToString() - { - return Attribute.ToString(); - } - } -} diff --git a/Source/Examples/IExample.cs b/Source/Examples/IExample.cs deleted file mode 100644 index 92853529..00000000 --- a/Source/Examples/IExample.cs +++ /dev/null @@ -1,23 +0,0 @@ -#region --- License --- -/* Licensed under the MIT/X11 license. - * Copyright (c) 2006-2008 the OpenTK Team. - * This notice may not be removed from any source distribution. - * See license.txt for licensing details. - */ -#endregion - -using System; -using System.Collections.Generic; -using System.Text; - -namespace Examples -{ - /// - /// This interface is is used by the ExampleLauncher to identify OpenTK examples, - /// your applications do not need to implement or use it. - /// - interface IExample - { - void Launch(); - } -} diff --git a/Source/Examples/Main.cs b/Source/Examples/Main.cs deleted file mode 100644 index 6f63e861..00000000 --- a/Source/Examples/Main.cs +++ /dev/null @@ -1,128 +0,0 @@ -#region License -// -// The Open Toolkit Library License -// -// Copyright (c) 2006 - 2010 the Open Toolkit library, except where noted. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -// the Software, and to permit persons to whom the Software is furnished to do -// so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// -#endregion - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Drawing; -using System.IO; -using System.Reflection; -using System.Text; -using System.Windows.Forms; - -using OpenTK; - -namespace Examples -{ - static class Program - { - static void LaunchExample(string type) - { - try - { - if (File.Exists("debug.log")) - File.Delete("debug.log"); - if (File.Exists("trace.log")) - File.Delete("trace.log"); - } - catch (Exception e) - { - Trace.WriteLine(String.Format("Could not access debug.log", e.ToString())); - } - - ToolkitOptions options = ToolkitOptions.Default; - if (type.Contains("GLControl") || type.Contains("Form")) - { - // SDL does not currently support embedding in foreign windows - // such as GLControl. We need to use a native OpenTK.Platform - // backend in that case. This hack is specific to the example-browser - // architecture - you do not need to do anything like this in your - // own code (it will just work). - options = new ToolkitOptions - { - Backend = PlatformBackend.PreferNative - }; - } - - using (TextWriterTraceListener dbg = new TextWriterTraceListener("debug.log")) - using (Toolkit.Init(options)) - { - Trace.Listeners.Add(dbg); - - try - { - var example = Type.GetType(type); - if (example != null) - { - example.InvokeMember("Main", - BindingFlags.InvokeMethod | BindingFlags.Static | - BindingFlags.Public | BindingFlags.NonPublic, - null, null, null); - } - } - catch (Exception e) - { - Trace.WriteLine(String.Format("Exception occured in example {0}: {1}", - type, e.ToString())); - } - - Trace.Listeners.Remove(dbg); - - dbg.Flush(); - dbg.Close(); - } - } - - [STAThread] - public static void Main(string[] args) - { - if (args.Length > 0) - { - LaunchExample(args[0]); - } - else - { - try - { - Application.EnableVisualStyles(); - Application.SetCompatibleTextRenderingDefault(false); - - using (Form browser = new ExampleBrowser()) - { - Application.Run(browser); - } - } - catch (System.Security.SecurityException e) - { - MessageBox.Show("The Example Launcher failed to start, due to insufficient permissions. This may happen if you execute the application from a network share.", "OpenTK Example Launcher failed to start.", - MessageBoxButtons.OK, MessageBoxIcon.Exclamation); - Trace.WriteLine(e.ToString()); - } - } - } - } -} diff --git a/Source/Examples/OpenAL/1.1/Parrot.Designer.cs b/Source/Examples/OpenAL/1.1/Parrot.Designer.cs deleted file mode 100644 index b50fdab4..00000000 --- a/Source/Examples/OpenAL/1.1/Parrot.Designer.cs +++ /dev/null @@ -1,283 +0,0 @@ -namespace Examples -{ - partial class Parrot - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.components = new System.ComponentModel.Container(); - this.comboBox_RecorderSelection = new System.Windows.Forms.ComboBox(); - this.groupBox_RecorderParameters = new System.Windows.Forms.GroupBox(); - this.label2 = new System.Windows.Forms.Label(); - this.label1 = new System.Windows.Forms.Label(); - this.numericUpDown_PlaybackGain = new System.Windows.Forms.NumericUpDown(); - this.label_MONO16BIT = new System.Windows.Forms.Label(); - this.label_RINGBUFFER = new System.Windows.Forms.Label(); - this.label_FREQUENCY = new System.Windows.Forms.Label(); - this.numericUpDown_BufferLength = new System.Windows.Forms.NumericUpDown(); - this.numericUpDown_Frequency = new System.Windows.Forms.NumericUpDown(); - this.groupBox_RecordingControls = new System.Windows.Forms.GroupBox(); - this.label_SamplesConsumed = new System.Windows.Forms.Label(); - this.button_Start = new System.Windows.Forms.Button(); - this.timer_GetSamples = new System.Windows.Forms.Timer(this.components); - this.groupBox_RecorderParameters.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)(this.numericUpDown_PlaybackGain)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.numericUpDown_BufferLength)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.numericUpDown_Frequency)).BeginInit(); - this.groupBox_RecordingControls.SuspendLayout(); - this.SuspendLayout(); - // - // comboBox_RecorderSelection - // - this.comboBox_RecorderSelection.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.comboBox_RecorderSelection.FormattingEnabled = true; - this.comboBox_RecorderSelection.Location = new System.Drawing.Point(6, 19); - this.comboBox_RecorderSelection.Name = "comboBox_RecorderSelection"; - this.comboBox_RecorderSelection.Size = new System.Drawing.Size(216, 21); - this.comboBox_RecorderSelection.TabIndex = 0; - // - // groupBox_RecorderParameters - // - this.groupBox_RecorderParameters.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.groupBox_RecorderParameters.Controls.Add(this.label2); - this.groupBox_RecorderParameters.Controls.Add(this.label1); - this.groupBox_RecorderParameters.Controls.Add(this.numericUpDown_PlaybackGain); - this.groupBox_RecorderParameters.Controls.Add(this.label_MONO16BIT); - this.groupBox_RecorderParameters.Controls.Add(this.label_RINGBUFFER); - this.groupBox_RecorderParameters.Controls.Add(this.label_FREQUENCY); - this.groupBox_RecorderParameters.Controls.Add(this.numericUpDown_BufferLength); - this.groupBox_RecorderParameters.Controls.Add(this.numericUpDown_Frequency); - this.groupBox_RecorderParameters.Controls.Add(this.comboBox_RecorderSelection); - this.groupBox_RecorderParameters.Location = new System.Drawing.Point(12, 12); - this.groupBox_RecorderParameters.Name = "groupBox_RecorderParameters"; - this.groupBox_RecorderParameters.Size = new System.Drawing.Size(228, 168); - this.groupBox_RecorderParameters.TabIndex = 2; - this.groupBox_RecorderParameters.TabStop = false; - this.groupBox_RecorderParameters.Text = "Recording Device Setup"; - // - // label2 - // - this.label2.AutoSize = true; - this.label2.Location = new System.Drawing.Point(6, 132); - this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(74, 13); - this.label2.TabIndex = 105; - this.label2.Text = "Sample format"; - // - // label1 - // - this.label1.AutoSize = true; - this.label1.Location = new System.Drawing.Point(6, 102); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(96, 13); - this.label1.TabIndex = 104; - this.label1.Text = "Playback gain (dB)"; - // - // numericUpDown_PlaybackGain - // - this.numericUpDown_PlaybackGain.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.numericUpDown_PlaybackGain.Location = new System.Drawing.Point(145, 100); - this.numericUpDown_PlaybackGain.Maximum = new decimal(new int[] { - 64, - 0, - 0, - 0}); - this.numericUpDown_PlaybackGain.Minimum = new decimal(new int[] { - 1, - 0, - 0, - 65536}); - this.numericUpDown_PlaybackGain.Name = "numericUpDown_PlaybackGain"; - this.numericUpDown_PlaybackGain.Size = new System.Drawing.Size(76, 20); - this.numericUpDown_PlaybackGain.TabIndex = 103; - this.numericUpDown_PlaybackGain.ThousandsSeparator = true; - this.numericUpDown_PlaybackGain.Value = new decimal(new int[] { - 4, - 0, - 0, - 0}); - // - // label_MONO16BIT - // - this.label_MONO16BIT.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.label_MONO16BIT.AutoSize = true; - this.label_MONO16BIT.Location = new System.Drawing.Point(142, 132); - this.label_MONO16BIT.Name = "label_MONO16BIT"; - this.label_MONO16BIT.Size = new System.Drawing.Size(64, 13); - this.label_MONO16BIT.TabIndex = 102; - this.label_MONO16BIT.Text = "Mono 16-bit"; - // - // label_RINGBUFFER - // - this.label_RINGBUFFER.AutoSize = true; - this.label_RINGBUFFER.Location = new System.Drawing.Point(6, 76); - this.label_RINGBUFFER.Name = "label_RINGBUFFER"; - this.label_RINGBUFFER.Size = new System.Drawing.Size(89, 13); - this.label_RINGBUFFER.TabIndex = 101; - this.label_RINGBUFFER.Text = "Buffer length (ms)"; - // - // label_FREQUENCY - // - this.label_FREQUENCY.AutoSize = true; - this.label_FREQUENCY.Location = new System.Drawing.Point(6, 50); - this.label_FREQUENCY.Name = "label_FREQUENCY"; - this.label_FREQUENCY.Size = new System.Drawing.Size(85, 13); - this.label_FREQUENCY.TabIndex = 100; - this.label_FREQUENCY.Text = "Sample rate (Hz)"; - // - // numericUpDown_BufferLength - // - this.numericUpDown_BufferLength.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.numericUpDown_BufferLength.Location = new System.Drawing.Point(145, 74); - this.numericUpDown_BufferLength.Maximum = new decimal(new int[] { - 1000, - 0, - 0, - 0}); - this.numericUpDown_BufferLength.Minimum = new decimal(new int[] { - 1, - 0, - 0, - 0}); - this.numericUpDown_BufferLength.Name = "numericUpDown_BufferLength"; - this.numericUpDown_BufferLength.Size = new System.Drawing.Size(76, 20); - this.numericUpDown_BufferLength.TabIndex = 2; - this.numericUpDown_BufferLength.ThousandsSeparator = true; - this.numericUpDown_BufferLength.Value = new decimal(new int[] { - 50, - 0, - 0, - 0}); - // - // numericUpDown_Frequency - // - this.numericUpDown_Frequency.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.numericUpDown_Frequency.Location = new System.Drawing.Point(145, 48); - this.numericUpDown_Frequency.Maximum = new decimal(new int[] { - 100000, - 0, - 0, - 0}); - this.numericUpDown_Frequency.Minimum = new decimal(new int[] { - 1, - 0, - 0, - 0}); - this.numericUpDown_Frequency.Name = "numericUpDown_Frequency"; - this.numericUpDown_Frequency.Size = new System.Drawing.Size(76, 20); - this.numericUpDown_Frequency.TabIndex = 1; - this.numericUpDown_Frequency.ThousandsSeparator = true; - this.numericUpDown_Frequency.Value = new decimal(new int[] { - 16000, - 0, - 0, - 0}); - // - // groupBox_RecordingControls - // - this.groupBox_RecordingControls.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.groupBox_RecordingControls.Controls.Add(this.label_SamplesConsumed); - this.groupBox_RecordingControls.Controls.Add(this.button_Start); - this.groupBox_RecordingControls.Location = new System.Drawing.Point(12, 186); - this.groupBox_RecordingControls.Name = "groupBox_RecordingControls"; - this.groupBox_RecordingControls.Size = new System.Drawing.Size(228, 78); - this.groupBox_RecordingControls.TabIndex = 3; - this.groupBox_RecordingControls.TabStop = false; - this.groupBox_RecordingControls.Text = "Talk to the parrot"; - // - // label_SamplesConsumed - // - this.label_SamplesConsumed.AutoSize = true; - this.label_SamplesConsumed.Location = new System.Drawing.Point(6, 52); - this.label_SamplesConsumed.Name = "label_SamplesConsumed"; - this.label_SamplesConsumed.Size = new System.Drawing.Size(108, 13); - this.label_SamplesConsumed.TabIndex = 103; - this.label_SamplesConsumed.Text = "Samples consumed: -"; - // - // button_Start - // - this.button_Start.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.button_Start.Location = new System.Drawing.Point(35, 19); - this.button_Start.Name = "button_Start"; - this.button_Start.Size = new System.Drawing.Size(159, 24); - this.button_Start.TabIndex = 3; - this.button_Start.Text = "Start recording"; - this.button_Start.UseVisualStyleBackColor = true; - this.button_Start.Click += new System.EventHandler(this.button_Start_Click); - // - // timer_GetSamples - // - this.timer_GetSamples.Tick += new System.EventHandler(this.timer_UpdateSamples_Tick); - // - // Parrot - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(252, 276); - this.Controls.Add(this.groupBox_RecordingControls); - this.Controls.Add(this.groupBox_RecorderParameters); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; - this.MaximizeBox = false; - this.Name = "Parrot"; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; - this.Text = "OpenAL Parrot"; - this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Parrot_FormClosing); - this.groupBox_RecorderParameters.ResumeLayout(false); - this.groupBox_RecorderParameters.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)(this.numericUpDown_PlaybackGain)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.numericUpDown_BufferLength)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.numericUpDown_Frequency)).EndInit(); - this.groupBox_RecordingControls.ResumeLayout(false); - this.groupBox_RecordingControls.PerformLayout(); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.ComboBox comboBox_RecorderSelection; - private System.Windows.Forms.GroupBox groupBox_RecorderParameters; - private System.Windows.Forms.Label label_RINGBUFFER; - private System.Windows.Forms.Label label_FREQUENCY; - private System.Windows.Forms.NumericUpDown numericUpDown_BufferLength; - private System.Windows.Forms.NumericUpDown numericUpDown_Frequency; - private System.Windows.Forms.GroupBox groupBox_RecordingControls; - private System.Windows.Forms.Label label_SamplesConsumed; - private System.Windows.Forms.Button button_Start; - private System.Windows.Forms.Label label_MONO16BIT; - private System.Windows.Forms.Timer timer_GetSamples; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.NumericUpDown numericUpDown_PlaybackGain; - private System.Windows.Forms.Label label2; - - } -} diff --git a/Source/Examples/OpenAL/1.1/Parrot.cs b/Source/Examples/OpenAL/1.1/Parrot.cs deleted file mode 100644 index efceefc7..00000000 --- a/Source/Examples/OpenAL/1.1/Parrot.cs +++ /dev/null @@ -1,239 +0,0 @@ -#region License -// -// The Open Toolkit Library License -// -// Copyright (c) 2006 - 2009 the Open Toolkit library. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -// the Software, and to permit persons to whom the Software is furnished to do -// so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// -#endregion - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.Runtime.InteropServices; -using System.Threading; - -using OpenTK; -using OpenTK.Audio; -using OpenTK.Audio.OpenAL; - -namespace Examples -{ - [Example("Parrot Audio Capture", ExampleCategory.OpenAL, "1.1", Documentation = "Parrot")] - public partial class Parrot : Form - { - #region Fields - - AudioContext audio_context; - AudioCapture audio_capture; - - int src; - short[] buffer = new short[512]; - const byte SampleToByte = 2; - - #endregion - - #region Constructors - - public Parrot() - { - InitializeComponent(); - - this.Text = "OpenAL Parrot (" + (IntPtr.Size == 4 ? "x86" : "x64") + ")"; - - // Add available capture devices to the combo box. - IList recorders = AudioCapture.AvailableDevices; - for (int i = 0; i < recorders.Count; i++) - { - if (!String.IsNullOrEmpty(recorders[i])) - comboBox_RecorderSelection.Items.Add(recorders[i]); - } - if (comboBox_RecorderSelection.Items.Count > 0) - comboBox_RecorderSelection.SelectedIndex = 0; - } - - #endregion - - #region Events - - private void button_Start_Click(object sender, EventArgs e) - { - if (audio_capture == null || !audio_capture.IsRunning) - { - button_Start.Text = "Stop Recording"; - groupBox_RecorderParameters.Enabled = false; - this.StartRecording(); - } - else - { - button_Start.Text = "Start Recording"; - groupBox_RecorderParameters.Enabled = true; - this.StopRecording(); - } - } - - private void timer_UpdateSamples_Tick(object sender, EventArgs e) - { - this.UpdateSamples(); - } - - private void Parrot_FormClosing(object sender, FormClosingEventArgs e) - { - this.StopRecording(); - } - - #endregion - - #region Private Members - - void StartRecording() - { - try - { - audio_context = new AudioContext(); - } - catch (AudioException ae) - { - MessageBox.Show("Fatal: Cannot continue without a playback device.\nException caught when opening playback device.\n" + ae.Message); - Application.Exit(); - } - - AL.Listener(ALListenerf.Gain, (float)numericUpDown_PlaybackGain.Value); - src = AL.GenSource(); - - int sampling_rate = (int)numericUpDown_Frequency.Value; - double buffer_length_ms = (double)numericUpDown_BufferLength.Value; - int buffer_length_samples = (int)((double)numericUpDown_BufferLength.Value * sampling_rate * 0.001 / BlittableValueType.StrideOf(buffer)); - - try - { - audio_capture = new AudioCapture((string)comboBox_RecorderSelection.SelectedItem, - sampling_rate, ALFormat.Mono16, buffer_length_samples); - } - catch (AudioDeviceException ade) - { - MessageBox.Show("Exception caught when opening recording device.\n" + ade.Message); - audio_capture = null; - } - - if (audio_capture == null) - return; - - audio_capture.Start(); - - timer_GetSamples.Start(); - timer_GetSamples.Interval = (int)(buffer_length_ms / 2 + 0.5); // Tick when half the buffer is full. - } - - void StopRecording() - { - timer_GetSamples.Stop(); - - if (audio_capture != null) - { - audio_capture.Stop(); - audio_capture.Dispose(); - audio_capture = null; - } - - if (audio_context != null) - { - int r; - AL.GetSource(src, ALGetSourcei.BuffersQueued, out r); - ClearBuffers(r); - - AL.DeleteSource(src); - - audio_context.Dispose(); - audio_context = null; - } - } - - void UpdateSamples() - { - if (audio_capture == null) - return; - - int available_samples = audio_capture.AvailableSamples; - - if (available_samples * SampleToByte > buffer.Length * BlittableValueType.StrideOf(buffer)) - { - buffer = new short[MathHelper.NextPowerOfTwo( - (int)(available_samples * SampleToByte / (double)BlittableValueType.StrideOf(buffer) + 0.5))]; - } - - if (available_samples > 0) - { - audio_capture.ReadSamples(buffer, available_samples); - - int buf = AL.GenBuffer(); - AL.BufferData(buf, ALFormat.Mono16, buffer, (int)(available_samples * BlittableValueType.StrideOf(buffer)), audio_capture.SampleFrequency); - AL.SourceQueueBuffer(src, buf); - - label_SamplesConsumed.Text = "Samples consumed: " + available_samples; - - if (AL.GetSourceState(src) != ALSourceState.Playing) - AL.SourcePlay(src); - } - - ClearBuffers(0); - } - - void ClearBuffers(int input) - { - if (audio_context == null || audio_context == null) - return; - - int[] freedbuffers; - if (input == 0) - { - int BuffersProcessed; - AL.GetSource(src, ALGetSourcei.BuffersProcessed, out BuffersProcessed); - if (BuffersProcessed == 0) - return; - freedbuffers = AL.SourceUnqueueBuffers(src, BuffersProcessed); - } - else - { - freedbuffers = AL.SourceUnqueueBuffers(src, input); - } - AL.DeleteBuffers(freedbuffers); - } - - #endregion - - #region Main - - [STAThread] - static void Main() - { - using (Parrot parrot = new Parrot()) - { - parrot.ShowDialog(); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/Source/Examples/OpenAL/1.1/Parrot.resx b/Source/Examples/OpenAL/1.1/Parrot.resx deleted file mode 100644 index 46accf4f..00000000 --- a/Source/Examples/OpenAL/1.1/Parrot.resx +++ /dev/null @@ -1,132 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - True - - - True - - - True - - - 17, 17 - - \ No newline at end of file diff --git a/Source/Examples/OpenAL/1.1/Parrot.rtf b/Source/Examples/OpenAL/1.1/Parrot.rtf deleted file mode 100644 index 1ff4ec25..00000000 Binary files a/Source/Examples/OpenAL/1.1/Parrot.rtf and /dev/null differ diff --git a/Source/Examples/OpenAL/1.1/PlayStatic.cs b/Source/Examples/OpenAL/1.1/PlayStatic.cs deleted file mode 100644 index 122416cd..00000000 --- a/Source/Examples/OpenAL/1.1/PlayStatic.cs +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2006, Creative Labs Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, this list of conditions and - * the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions - * and the following disclaimer in the documentation and/or other materials provided with the distribution. - * * Neither the name of Creative Labs Inc. nor the names of its contributors may be used to endorse or - * promote products derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A - * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Threading; - -using OpenTK.Audio; - - -namespace Examples -{ -#if false - [Example("PlayStatic Sample", ExampleCategory.OpenAL)] - public partial class PlayStatic - { - public static void Main() - { - AudioContext context = new AudioContext(); - - Sound sound = new Sound("Data\\Audio\\Asterisk.wav"); - uint buffer; - uint source; - int state; - - Trace.WriteLine("PlayStatic Test Application\n"); - - // Generate an AL Buffer - AL.GenBuffers(out buffer); - - // Load Wave file into OpenAL Buffer - AL.BufferData(buffer, sound.ReadToEnd()); - - // Generate a Source to playback the Buffer - AL.GenSources(out source); - - // Attach Source to Buffer - AL.Source(source, ALSourcei.Buffer, (int)buffer); - - // Play Source - AL.SourcePlay(source); - Trace.WriteLine("Playing Source "); - - do - { - Thread.Sleep(100); - Trace.Write("."); - // Get Source State - AL.GetSource(source, ALGetSourcei.SourceState, out state); - } while ((ALSourceState)state == ALSourceState.Playing); - - Trace.WriteLine(); - - // Clean up by deleting Source(s) and Buffer(s) - AL.SourceStop(source); - AL.DeleteSources(ref source); - AL.DeleteBuffers(ref buffer); - - return; - } - } -#endif -} diff --git a/Source/Examples/OpenAL/1.1/Playback.cs b/Source/Examples/OpenAL/1.1/Playback.cs deleted file mode 100644 index ea9a1913..00000000 --- a/Source/Examples/OpenAL/1.1/Playback.cs +++ /dev/null @@ -1,112 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Diagnostics; -using System.Threading; -using System.IO; - -using OpenTK.Audio; -using OpenTK.Audio.OpenAL; - -#pragma warning disable 219 // variable assigned but never used, we do that on purpose - -namespace Examples -{ - [Example("Playback", ExampleCategory.OpenAL, "1.1", Documentation="Playback")] - public class Playback - { - static readonly string filename = Path.Combine(Path.Combine("Data", "Audio"), "the_ring_that_fell.wav"); - - // Loads a wave/riff audio file. - public static byte[] LoadWave(Stream stream, out int channels, out int bits, out int rate) - { - if (stream == null) - throw new ArgumentNullException("stream"); - - using (BinaryReader reader = new BinaryReader(stream)) - { - // RIFF header - string signature = new string(reader.ReadChars(4)); - if (signature != "RIFF") - throw new NotSupportedException("Specified stream is not a wave file."); - - int riff_chunck_size = reader.ReadInt32(); - - string format = new string(reader.ReadChars(4)); - if (format != "WAVE") - throw new NotSupportedException("Specified stream is not a wave file."); - - // WAVE header - string format_signature = new string(reader.ReadChars(4)); - if (format_signature != "fmt ") - throw new NotSupportedException("Specified wave file is not supported."); - - int format_chunk_size = reader.ReadInt32(); - int audio_format = reader.ReadInt16(); - int num_channels = reader.ReadInt16(); - int sample_rate = reader.ReadInt32(); - int byte_rate = reader.ReadInt32(); - int block_align = reader.ReadInt16(); - int bits_per_sample = reader.ReadInt16(); - - string data_signature = new string(reader.ReadChars(4)); - if (data_signature != "data") - throw new NotSupportedException("Specified wave file is not supported."); - - int data_chunk_size = reader.ReadInt32(); - - channels = num_channels; - bits = bits_per_sample; - rate = sample_rate; - - return reader.ReadBytes((int)reader.BaseStream.Length); - } - } - - public static ALFormat GetSoundFormat(int channels, int bits) - { - switch (channels) - { - case 1: return bits == 8 ? ALFormat.Mono8 : ALFormat.Mono16; - case 2: return bits == 8 ? ALFormat.Stereo8 : ALFormat.Stereo16; - default: throw new NotSupportedException("The specified sound format is not supported."); - } - } - - public static void Main() - { - using (AudioContext context = new AudioContext()) - { - int buffer = AL.GenBuffer(); - int source = AL.GenSource(); - int state; - - int channels, bits_per_sample, sample_rate; - byte[] sound_data = LoadWave(File.Open(filename, FileMode.Open), out channels, out bits_per_sample, out sample_rate); - AL.BufferData(buffer, GetSoundFormat(channels, bits_per_sample), sound_data, sound_data.Length, sample_rate); - - AL.Source(source, ALSourcei.Buffer, buffer); - AL.SourcePlay(source); - - Trace.Write("Playing"); - - // Query the source to find out when it stops playing. - do - { - Thread.Sleep(250); - Trace.Write("."); - AL.GetSource(source, ALGetSourcei.SourceState, out state); - } - while ((ALSourceState)state == ALSourceState.Playing); - - Trace.WriteLine(""); - - AL.SourceStop(source); - AL.DeleteSource(source); - AL.DeleteBuffer(buffer); - } - } - } -} diff --git a/Source/Examples/OpenAL/1.1/Playback.rtf b/Source/Examples/OpenAL/1.1/Playback.rtf deleted file mode 100644 index 404db1f5..00000000 Binary files a/Source/Examples/OpenAL/1.1/Playback.rtf and /dev/null differ diff --git a/Source/Examples/OpenAL/1.1/StreamingPlayback.cs b/Source/Examples/OpenAL/1.1/StreamingPlayback.cs deleted file mode 100644 index 2333dd3a..00000000 --- a/Source/Examples/OpenAL/1.1/StreamingPlayback.cs +++ /dev/null @@ -1,94 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Diagnostics; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.ComponentModel; - -using OpenTK.Audio; -using OpenTK.Audio.OpenAL; - -namespace Examples.OpenAL -{ - // Not working correctly (sound pops). - - //[Example("Streaming Playback", ExampleCategory.OpenAL)] - public class StreamingPlayback - { - const string filename = "Data\\Audio\\the_ring_that_fell.wav"; - const int buffer_size = (int)(0.5*44100); - const int buffer_count = 4; - - //static object openal_lock = new object(); // Should be global in your app. - - public static void Main() - { - using (AudioContext context = new AudioContext()) - { - int source = AL.GenSource(); - int[] buffers = AL.GenBuffers(buffer_count); - int state; - - Trace.WriteLine("Testing WaveReader({0}).ReadSamples()", filename); - - Trace.Write("Playing"); - - //foreach (int buffer in buffers) - // AL.BufferData(buffer, sound.ReadSamples(buffer_size)); - AL.SourceQueueBuffers(source, buffers.Length, buffers); - AL.SourcePlay(source); - - int processed_count, queued_count; - - do - { - //Trace.Write("."); - - do - { - AL.GetSource(source, ALGetSourcei.BuffersProcessed, out processed_count); - //Thread.Sleep(1); - } - while (processed_count == 0); - - Trace.WriteLine(processed_count); - //while (processed_count > 0) - //{ - // int buffer = AL.SourceUnqueueBuffer(source); - // if (buffer != 0 && !sound.EndOfFile) - // { - // Trace.WriteLine(" " + buffer.ToString()); - // AL.BufferData(buffer, sound.ReadSamples(buffer_size)); - // AL.SourceQueueBuffer(source, buffer); - // } - // --processed_count; - //} - - AL.GetSource(source, ALGetSourcei.BuffersQueued, out queued_count); - if (queued_count > 0) - { - AL.GetSource(source, ALGetSourcei.SourceState, out state); - if ((ALSourceState)state != ALSourceState.Playing) - { - AL.SourcePlay(source); - Trace.WriteLine("r"); - } - } - else - break; - } - while (true); - - AL.SourceStop(source); - AL.DeleteSource(source); - AL.DeleteBuffers(buffers); - } - - Trace.WriteLine(""); - } - } -} diff --git a/Source/Examples/OpenAL/EFX/EFXReverb.cs b/Source/Examples/OpenAL/EFX/EFXReverb.cs deleted file mode 100644 index ef4c087b..00000000 --- a/Source/Examples/OpenAL/EFX/EFXReverb.cs +++ /dev/null @@ -1,98 +0,0 @@ -#region License -// -// The Open Toolkit Library License -// -// Copyright (c) 2006 - 2009 the Open Toolkit library. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -// the Software, and to permit persons to whom the Software is furnished to do -// so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// -#endregion - -using System; -using System.Diagnostics; -using System.Threading; -using System.IO; -using OpenTK.Audio; -using OpenTK.Audio.OpenAL; - -namespace Examples -{ - [Example("EFX: Reverb", ExampleCategory.OpenAL, "EFX", Documentation="EFXReverb")] - public class ReverbExample - { - static readonly string filename = Path.Combine(Path.Combine("Data", "Audio"), "the_ring_that_fell.wav"); - - public static void Main() - { - using (AudioContext context = new AudioContext()) - { - Trace.WriteLine("Testing WaveReader({0}).ReadToEnd()", filename); - - EffectsExtension efx = new EffectsExtension(); - - int buffer = AL.GenBuffer(); - int source = AL.GenSource(); - int state; - - int effect = efx.GenEffect(); - int slot = efx.GenAuxiliaryEffectSlot(); - - efx.BindEffect(effect, EfxEffectType.Reverb); - efx.Effect(effect, EfxEffectf.ReverbDecayTime, 3.0f); - efx.Effect(effect, EfxEffectf.ReverbDecayHFRatio, 0.91f); - efx.Effect(effect, EfxEffectf.ReverbDensity, 0.7f); - efx.Effect(effect, EfxEffectf.ReverbDiffusion, 0.9f); - efx.Effect(effect, EfxEffectf.ReverbRoomRolloffFactor, 3.1f); - efx.Effect(effect, EfxEffectf.ReverbReflectionsGain, 0.723f); - efx.Effect(effect, EfxEffectf.ReverbReflectionsDelay, 0.03f); - efx.Effect(effect, EfxEffectf.ReverbGain, 0.23f); - - efx.AuxiliaryEffectSlot(slot, EfxAuxiliaryi.EffectslotEffect, effect); - - int channels, bits, rate; - byte[] data = Playback.LoadWave(File.Open(filename, FileMode.Open), out channels, out bits, out rate); - AL.BufferData(buffer, Playback.GetSoundFormat(channels, bits), data, data.Length, rate); - - AL.Source(source, ALSourcef.ConeOuterGain, 1.0f); - AL.Source(source, ALSourcei.Buffer, buffer); - AL.SourcePlay(source); - - Trace.Write("Playing"); - - // Query the source to find out when it stops playing. - do - { - Thread.Sleep(250); - Trace.Write("."); - AL.GetSource(source, ALGetSourcei.SourceState, out state); - } - while ((ALSourceState)state == ALSourceState.Playing); - - Trace.WriteLine(""); - - AL.SourceStop(source); - AL.DeleteSource(source); - AL.DeleteBuffer(buffer); - efx.DeleteEffect(effect); - efx.DeleteAuxiliaryEffectSlot(slot); - } - } - } -} \ No newline at end of file diff --git a/Source/Examples/OpenAL/Test/OpenALDiagnostics.cs b/Source/Examples/OpenAL/Test/OpenALDiagnostics.cs deleted file mode 100644 index bf2d0613..00000000 --- a/Source/Examples/OpenAL/Test/OpenALDiagnostics.cs +++ /dev/null @@ -1,632 +0,0 @@ -#region License -// -// The Open Toolkit Library License -// -// Copyright (c) 2006 - 2009 the Open Toolkit library. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -// the Software, and to permit persons to whom the Software is furnished to do -// so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// -#endregion - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Threading; -using System.Runtime.InteropServices; - -using OpenTK; -using OpenTK.Audio; -using OpenTK.Audio.OpenAL; - -namespace Examples -{ - /// - /// A text-based diagnosis program for OpenAL. - /// The constructors will call the OpenAL commands, the Print() methods just show the information. - /// - [Example("OpenAL diagnostics", ExampleCategory.OpenAL, "Test", 0, true)] - class OpenALDiagnostics - { - public static void checkForErrors() - { - { - IntPtr device = Alc.GetContextsDevice(Alc.GetCurrentContext()); - AlcError error = Alc.GetError(device); - - if (error != AlcError.NoError) - Trace.WriteLine("ALC ERROR: (" + error + ") " + Alc.GetString(device, (AlcGetString)error)); - } - { - ALError error = AL.GetError(); - if (error != ALError.NoError) - Trace.WriteLine("AL ERROR: (" + error + ") " + AL.GetErrorString(error)); - } - } - - [STAThread] - static void Main() - { - Trace.Listeners.RemoveAt(0); - Trace.Listeners.Add(new ConsoleTraceListener()); - - Trace.WriteLine("This application is currently running as " + (IntPtr.Size == 4 ? "x86" : "x64")); - - DeviceDiagnostic DevDiag = new DeviceDiagnostic(); - DevDiag.Print(); - DevDiag = null; - - using (AudioContext A = new AudioContext()) - { - AlcDiagnostic AlcDiag = new AlcDiagnostic(Alc.GetContextsDevice(Alc.GetCurrentContext())); - checkForErrors(); - AlcDiag.Print(); - AlcDiag = null; - - ALDiagnostic ALdiag = new ALDiagnostic(A); - checkForErrors(); - ALdiag.Print(); - ALdiag = null; - - EfxDiagnostic EfxDiag = new EfxDiagnostic(); - checkForErrors(); - EfxDiag.Print(); - EfxDiag = null; - - XRamDiagnostic XRamDiag = new XRamDiagnostic(); - checkForErrors(); - XRamDiag.Print(); - XRamDiag = null; - - RecorderDiagnostic rec = new RecorderDiagnostic(); - rec.Print(); - rec = null; - } - - // Trace.WriteLine("All done. Press Enter to exit."); - // Console.ReadLine(); - } - } - - class DeviceDiagnostic - { - #region Fields - public readonly IList AllPlaybackDevices; - public readonly IList AllRecordingDevices; - - public readonly string DefaultPlaybackDevice; - public readonly string DefaultRecordingDevice; - #endregion Fields - - public DeviceDiagnostic() - { - Trace.WriteLine("--- Device related errors ---"); - - AllPlaybackDevices = AudioContext.AvailableDevices; - AllRecordingDevices = AudioCapture.AvailableDevices; - - DefaultPlaybackDevice = AudioContext.DefaultDevice; - DefaultRecordingDevice = AudioCapture.DefaultDevice; - } - - public void Print() - { - Trace.WriteLine("--- Device related analysis ---"); - Trace.Indent(); - { - Trace.WriteLine("Default playback device: " + DefaultPlaybackDevice); - Trace.WriteLine("All known playback devices:"); - Trace.Indent(); - { - foreach (string s in AllPlaybackDevices) - Trace.WriteLine(s); - } - Trace.Unindent(); - - Trace.WriteLine("Default recording device: " + DefaultRecordingDevice); - Trace.WriteLine("All known recording devices:"); - Trace.Indent(); - { - foreach (string s in AllRecordingDevices) - Trace.WriteLine(s); - } - Trace.Unindent(); - } - Trace.Unindent(); - } - } - - class AlcDiagnostic - { - #region Fields - private string[] Alc_Extension_C_Names = new string[] - { - "ALC_ENUMERATE_ALL_EXT", - "ALC_ENUMERATION_EXT", - "ALC_EXT_ASA", - "ALC_EXT_ASA_DISTORTION", - "ALC_EXT_ASA_ROGER_BEEP", - "ALC_EXT_BRS_GAME_LICENSE_REQUIRED", - "ALC_EXT_capture", - "ALC_EXT_DEDICATED", - "ALC_EXT_EFX", - }; - - public readonly int MajorVersion; - public readonly int MinorVersion; - public readonly int EfxMajorVersion; - public readonly int EfxMinorVersion; - public readonly int EfxMaxAuxiliarySends; - public readonly string ExtensionString; - public readonly Dictionary Extensions = new Dictionary(); - #endregion Fields - - public AlcDiagnostic(IntPtr dev) - { - Trace.WriteLine("--- Alc related errors ---"); - - Alc.GetInteger(dev, AlcGetInteger.MajorVersion, 1, out MajorVersion); - Alc.GetInteger(dev, AlcGetInteger.MinorVersion, 1, out MinorVersion); - Alc.GetInteger(dev, AlcGetInteger.EfxMajorVersion, 1, out EfxMajorVersion); - Alc.GetInteger(dev, AlcGetInteger.EfxMinorVersion, 1, out EfxMinorVersion); - Alc.GetInteger(dev, AlcGetInteger.EfxMaxAuxiliarySends, 1, out EfxMaxAuxiliarySends); - - ExtensionString = Alc.GetString(dev, AlcGetString.Extensions); - - foreach (string s in Alc_Extension_C_Names) - Extensions.Add(s, Alc.IsExtensionPresent(dev, s)); - } - - public void Print() - { - Trace.WriteLine("--- Alc related analysis ---"); - Trace.Indent(); - { - Trace.WriteLine("Alc Version: " + MajorVersion + "." + MinorVersion); - Trace.WriteLine("Efx Version: " + EfxMajorVersion + "." + EfxMinorVersion); - Trace.WriteLine("Efx max. Auxiliary sends: " + EfxMaxAuxiliarySends); - Trace.WriteLine("Alc Extension string: " + ExtensionString); - - Trace.WriteLine("Confirmed Alc Extensions:"); - Trace.Indent(); - { - foreach (KeyValuePair pair in Extensions) - Trace.WriteLine(pair.Key + ": " + pair.Value); - } - Trace.Unindent(); - } - Trace.Unindent(); - } - } - - class ALDiagnostic - { - #region Fields - private string[] AL_Extension_Names = new string[] - { - "AL_EXT_ALAW", - "AL_EXT_BFORMAT", - "AL_EXT_double", - "AL_EXT_EXPONENT_DISTANCE", - "AL_EXT_float32", - "AL_EXT_FOLDBACK", - "AL_EXT_IMA4", - "AL_EXT_LINEAR_DISTANCE", - "AL_EXT_MCFORMATS", - "AL_EXT_mp3", - "AL_EXT_MULAW", - "AL_EXT_OFFSET", - "AL_EXT_vorbis", - "AL_LOKI_quadriphonic", - "EAX-RAM", - "EAX", - "EAX1.0", - "EAX2.0", - "EAX3.0", - "EAX3.0EMULATED", - "EAX4.0", - "EAX4.0EMULATED", - "EAX5.0" - }; - - public readonly Dictionary Extensions = new Dictionary(); - - public readonly string DeviceName; - public readonly float SpeedOfSound; - public readonly string ExtensionString; - public readonly string Renderer; - public readonly string Vendor; - public readonly string Version; - public readonly ALDistanceModel DistanceModel; - - const uint MaxSourcesLimit = 128; - public readonly uint MaxSources; - #endregion Fields - - public ALDiagnostic(AudioContext ac) - { - Trace.WriteLine("--- AL related errors ---"); - - DeviceName = ac.CurrentDevice; - - ExtensionString = AL.Get(ALGetString.Extensions); - Renderer = AL.Get(ALGetString.Renderer); - Vendor = AL.Get(ALGetString.Vendor); - Version = AL.Get(ALGetString.Version); - - SpeedOfSound = AL.Get(ALGetFloat.SpeedOfSound); - DistanceModel = AL.GetDistanceModel(); - - foreach (string s in AL_Extension_Names) - Extensions.Add(s, AL.IsExtensionPresent(s)); - - AL.GetError(); // clear it, need this for the source counting to work properly - uint[] dummy_sources = new uint[MaxSourcesLimit]; - for (MaxSources = 0; MaxSources < MaxSourcesLimit; MaxSources++) - { - AL.GenSource(out dummy_sources[MaxSources]); - if (AL.GetError() != ALError.NoError) - break; - } - - for (int i = 0; i < MaxSources; i++) - AL.DeleteSource(ref dummy_sources[i]); - } - - public void Print() - { - Trace.WriteLine("--- AL related analysis ---"); - Trace.Indent(); - { - Trace.WriteLine("Used Device: "+DeviceName); - Trace.WriteLine("AL Renderer: " + Renderer); - Trace.WriteLine("AL Vendor: " + Vendor); - Trace.WriteLine("AL Version: " + Version); - - Trace.WriteLine("AL Speed of sound: " + SpeedOfSound); - Trace.WriteLine("AL Distance Model: " + DistanceModel.ToString()); - Trace.WriteLine("AL Maximum simultanous Sources: " + MaxSources); - - Trace.WriteLine("AL Extension string: " + ExtensionString); - Trace.WriteLine("Confirmed AL Extensions:"); - Trace.Indent(); - { - foreach (KeyValuePair pair in Extensions) - Trace.WriteLine(pair.Key + ": " + pair.Value); - } - Trace.Unindent(); - } - Trace.Unindent(); - } - } - - class EfxDiagnostic - { - #region Fields - private EfxEffectType[] EffectNames = new EfxEffectType[] - { - EfxEffectType.Autowah, - EfxEffectType.Chorus, - EfxEffectType.Compressor, - EfxEffectType.Distortion, - EfxEffectType.EaxReverb, - EfxEffectType.Echo, - EfxEffectType.Equalizer, - EfxEffectType.Flanger, - EfxEffectType.FrequencyShifter, - EfxEffectType.PitchShifter, - EfxEffectType.Reverb, - EfxEffectType.RingModulator, - EfxEffectType.VocalMorpher, - }; - - private EfxFilterType[] FilterNames = new EfxFilterType[] - { - EfxFilterType.Bandpass, - EfxFilterType.Highpass, - EfxFilterType.Lowpass, - }; - - public readonly Dictionary Effects = new Dictionary(); - public readonly Dictionary Filters = new Dictionary(); - - const uint MaxAuxiliaryEffectSlotsLimit = 4; - public readonly uint MaxAuxiliaryEffectSlots; - #endregion Fields - - public EfxDiagnostic() - { - Trace.WriteLine("--- Efx related errors ---"); - - EffectsExtension Efx = new EffectsExtension(); - Trace.Assert(Efx.IsInitialized); - - #region Test for available Effects - uint effect; - Efx.GenEffect(out effect); - AL.GetError(); - foreach (EfxEffectType e in EffectNames) - { - Efx.BindEffect(effect, e); - Effects.Add(e.ToString(), AL.GetError() == ALError.NoError); - } - Efx.DeleteEffect(ref effect); - #endregion Test for available Effects - - #region Test for available Filters - uint filter; - Efx.GenFilter(out filter); - AL.GetError(); - foreach (EfxFilterType f in FilterNames) - { - Efx.Filter(filter, EfxFilteri.FilterType, (int)f); - Filters.Add(f.ToString(), AL.GetError() == ALError.NoError); - } - Efx.DeleteFilter(ref filter); - #endregion Test for available Filters - - AL.GetError(); - uint[] dummy_slots = new uint[MaxAuxiliaryEffectSlotsLimit]; - for (MaxAuxiliaryEffectSlots = 0; MaxAuxiliaryEffectSlots < MaxAuxiliaryEffectSlotsLimit; MaxAuxiliaryEffectSlots++) - { - Efx.GenAuxiliaryEffectSlot(out dummy_slots[MaxAuxiliaryEffectSlots]); - if (AL.GetError() != ALError.NoError) - break; - } - for (uint i = 0; i < MaxAuxiliaryEffectSlots; i++) - Efx.DeleteAuxiliaryEffectSlot(ref dummy_slots[i]); - } - - public void Print() - { - Trace.WriteLine("--- Efx related analysis ---"); - Trace.Indent(); - { - Trace.WriteLine("Efx Effects supported:"); - Trace.Indent(); - { - foreach (KeyValuePair pair in Effects) - Trace.WriteLine(pair.Key + ": " + pair.Value); - } - Trace.Unindent(); - - Trace.WriteLine("Efx Filters supported:"); - Trace.Indent(); - { - foreach (KeyValuePair pair in Filters) - Trace.WriteLine(pair.Key + ": " + pair.Value); - } - Trace.Unindent(); - - Trace.WriteLine("Efx max. Auxiliary Effect Slots: " + MaxAuxiliaryEffectSlots); - } - Trace.Unindent(); - } - } - - class XRamDiagnostic - { - #region Fields - private XRamExtension.XRamStorage[] storagemodes = new XRamExtension.XRamStorage[] - { - XRamExtension.XRamStorage.Hardware, - XRamExtension.XRamStorage.Accessible, - XRamExtension.XRamStorage.Automatic, - }; - - public readonly bool XRamFound; - public readonly int RamTotal; - public readonly int RamFree; - public readonly Dictionary BufferModes = new Dictionary(); - #endregion Fields - - public XRamDiagnostic() - { - Trace.WriteLine("--- X-RAM related errors ---"); - - XRamExtension XRam = new XRamExtension(); - if (XRam.IsInitialized) - { - XRamFound = true; - - RamTotal = XRam.GetRamSize; - RamFree = XRam.GetRamFree; - - uint buffer; - AL.GenBuffer(out buffer); - - foreach (XRamExtension.XRamStorage m in storagemodes) - { - XRam.SetBufferMode(1, ref buffer, m); - BufferModes.Add(m.ToString(), m == XRam.GetBufferMode(ref buffer)); - } - - AL.DeleteBuffer(ref buffer); - } - else - XRamFound = false; - } - - public void Print() - { - Trace.WriteLine("--- X-RAM related analysis ---"); - - if (XRamFound) - { - Trace.Indent(); // * - Trace.WriteLine("X-RAM extension found."); - } - else - { - Trace.Indent(); - { - Trace.WriteLine("X-RAM extension is not available, skipping test."); - } - Trace.Unindent(); - return; - } - - Trace.WriteLine("Ram status (free/total) in bytes: " + RamFree + "/" + RamTotal); - - Trace.WriteLine("Available buffer modes:"); - Trace.Indent(); - { - foreach (KeyValuePair pair in BufferModes) - Trace.WriteLine(pair.Key + ": " + pair.Value); - } - Trace.Unindent(); - - Trace.Unindent(); // * - } - } - - class RecorderDiagnostic - { - #region Fields - bool IsDeviceAvailable; - bool BufferContentsAllZero; - short MaxSample = short.MinValue; - short MinSample = short.MaxValue; - - private AudioCapture r; - Dictionary Errorlist = new Dictionary(); - - string DeviceName; - - #endregion Fields - - private void CheckRecorderError(string location) - { - AlcError err = r.CurrentError; - if (err != AlcError.NoError) - Errorlist.Add(location, err); - } - - public RecorderDiagnostic() - { - Trace.WriteLine("--- AudioCapture related errors ---"); - IsDeviceAvailable = false; - - try - { - r = new AudioCapture(AudioCapture.DefaultDevice, 16000, ALFormat.Mono16, 4096); - } - catch (AudioDeviceException ade) - { - Trace.WriteLine("AudioCapture Exception caught: " + ade.Message); - return; - } - IsDeviceAvailable = true; - DeviceName = r.CurrentDevice; - CheckRecorderError("Alc.CaptureOpenDevice"); - - r.Start(); - CheckRecorderError("Alc.CaptureStart"); - Thread.Sleep(100); - r.Stop(); - CheckRecorderError("Alc.CaptureStop"); - - byte[] Buffer = new byte[8192]; - - Thread.Sleep(10); // Wait for a few samples to become available. - int SamplesBefore = r.AvailableSamples; - - CheckRecorderError("Alc.GetInteger(...CaptureSamples...)"); - r.ReadSamples(Buffer, (SamplesBefore > 4096 ? 4096 : SamplesBefore)); - CheckRecorderError("Alc.CaptureSamples"); - - int SamplesCaptured = SamplesBefore - r.AvailableSamples; - - uint ZeroCounter = 0; - for (int i = 0; i < SamplesCaptured * 2; i++) - { - if (Buffer[i] == 0) - ZeroCounter++; - } - - for (int i = 0; i < SamplesCaptured; i++) - { - short sample = BitConverter.ToInt16(Buffer, i * 2); - if (sample > MaxSample) - MaxSample = sample; - if (sample < MinSample) - MinSample = sample; - } - - if (ZeroCounter < SamplesCaptured * 2 && SamplesCaptured > 0) - BufferContentsAllZero = false; - else - BufferContentsAllZero = true; - - r.Dispose(); - CheckRecorderError("Alc.CaptureCloseDevice"); - - // no playback test needed due to Parrot test app. - /* - uint buf; - AL.GenBuffer(out buf); - AL.BufferData(buf, ALFormat.Mono16, BufferPtr, SamplesCaptured * 2, 16000); - uint src; - AL.GenSource(out src); - AL.BindBufferToSource(src, buf); - AL.Listener(ALListenerf.Gain, 16.0f); - AL.SourcePlay(src); - while (AL.GetSourceState(src) == ALSourceState.Playing) - { - Thread.Sleep(0); - } - AL.SourceStop(src); - - AL.DeleteSource(ref src); - AL.DeleteBuffer(ref buf); - */ - } - - public void Print() - { - Trace.WriteLine("--- AudioCapture related analysis ---"); - - if (!IsDeviceAvailable) - { - Trace.WriteLine("Capture Device could not be initlialized (no microphone plugged into the jack?). Skipping test."); - return; - } - - Trace.Indent(); - { - Trace.WriteLine("Using capture device: " + DeviceName); - if (Errorlist.Count > 0) - { - Trace.WriteLine("Found Alc Errors:"); - Trace.Indent(); - { - foreach (KeyValuePair pair in Errorlist) - Trace.WriteLine(pair.Key + ": " + pair.Value); - } - Trace.Unindent(); - - - } - Trace.WriteLine("Buffer contents after capture was all 0's: " + BufferContentsAllZero); - Trace.WriteLine("Sample min/max in recorded data: " + MinSample + " / " + MaxSample); - } - Trace.Unindent(); - } - } -} \ No newline at end of file diff --git a/Source/Examples/OpenAL/Test/TestAudioContext.cs b/Source/Examples/OpenAL/Test/TestAudioContext.cs deleted file mode 100644 index 906876cb..00000000 --- a/Source/Examples/OpenAL/Test/TestAudioContext.cs +++ /dev/null @@ -1,203 +0,0 @@ -#region --- License --- -/* Licensed under the MIT/X11 license. - * Copyright (c) 2006-2008 the OpenTK Team. - * This notice may not be removed from any source distribution. - * See license.txt for licensing details. - */ -#endregion - -using System; -using System.Diagnostics; - -using OpenTK.Audio; -using OpenTK.Audio.OpenAL; - -using AlContext = System.IntPtr; -using AlDevice = System.IntPtr; - -namespace Examples -{ - [Example("AudioContext Test", ExampleCategory.OpenTK, "Test", 0, false)] - class TestApp - { - public static void PrintOpenALErrors( IntPtr device ) - { - ALError AlErr = AL.GetError(); - Trace.WriteLine("OpenAL error: {0}"+ AlErr); - } - - public static void Main() - { - AlcUnitTestFunc(); - } - - public static void AlcUnitTestFunc() - { - AudioContext context = new AudioContext(); - - Trace.WriteLine("Testing AudioContext functions."); - Trace.Indent(); - -// Trace.WriteLine("Suspend()..."); -// context.Suspend(); -// Trace.Assert(!context.IsProcessing); -// -// Trace.WriteLine("Process()..."); -// context.Process(); -// Trace.Assert(context.IsProcessing); - - //Trace.WriteLine("MakeCurrent()..."); - //context.MakeCurrent(); - //Trace.Assert(context.IsCurrent); - - //Trace.WriteLine("IsCurrent = false..."); - //context.IsCurrent = false; - //Trace.Assert(!context.IsCurrent); - - //Trace.WriteLine("IsCurrent = true..."); - //context.IsCurrent = true; - //Trace.Assert(context.IsCurrent); - - Trace.WriteLine("AudioContext.CurrentContext..."); - Trace.Assert(AudioContext.CurrentContext == context); - - #region Get Attribs - - //int AttribCount; - //Alc.GetInteger(context.Device, AlcGetInteger.AttributesSize, sizeof(int), out AttribCount); - //Trace.WriteLine("AttributeSize: " + AttribCount); - - //if (AttribCount > 0) - //{ - // int[] Attribs = new int[AttribCount]; - // Alc.GetInteger(context.Device, AlcGetInteger.AllAttributes, AttribCount, out Attribs[0]); - // for (int i = 0; i < Attribs.Length; i++) - // { - // Trace.Write(Attribs[i]); - // Trace.Write(" "); - // } - // Trace.WriteLine(); - //} - - #endregion Get Attribs - -#if false - AlDevice MyDevice; - AlContext MyContext; - - // Initialize Open AL - MyDevice = Alc.OpenDevice( null );// open default device - if ( MyDevice != Al.Null ) - { - Trace.WriteLine( "Device allocation succeeded." ); - MyContext = Alc.CreateContext( MyDevice, Al.Null ); // create context - if ( MyContext != Al.Null ) - { - Trace.WriteLine( "Context allocation succeeded." ); - GetOpenALErrors( MyDevice ); - - Alc.SuspendContext( MyContext ); // disable context - Alc.ProcessContext( MyContext ); // enable context. The default state of a context created by alcCreateContext is that it is processing. - Al.Bool result = Alc.MakeContextCurrent( MyContext ); // set active context - Trace.WriteLine( "MakeContextCurrent succeeded? " + result ); - GetOpenALErrors( MyDevice ); - - Trace.WriteLine( "Default: " + Alc.GetString( MyDevice, Enums.AlcGetString.DefaultDeviceSpecifier ) ); - Trace.WriteLine( "Device: " + Alc.GetString( MyDevice, Enums.AlcGetString.DeviceSpecifier ) ); - Trace.WriteLine( "Extensions: " + Alc.GetString( MyDevice, Enums.AlcGetString.Extensions ) ); - GetOpenALErrors( MyDevice ); - - #region Get Attribs - int AttribCount; - Alc.GetInteger( MyDevice, Enums.AlcGetInteger.AttributesSize, sizeof( int ), out AttribCount ); - Trace.WriteLine( "AttributeSize: " + AttribCount ); - - if ( AttribCount > 0 ) - { - int[] Attribs = new int[AttribCount]; - Alc.GetInteger( MyDevice, Enums.AlcGetInteger.AttributesSize, AttribCount, out Attribs[0] ); - for ( int i = 0; i < Attribs.Length; i++ ) - Trace.Write( ", " + Attribs[i] ); - Trace.WriteLine( ); - } - #endregion Get Attribs - GetOpenALErrors( MyDevice ); - - AlDevice currdev = Alc.GetContextsDevice( MyContext ); - AlContext currcon = Alc.GetCurrentContext( ); - - if ( MyDevice == currdev ) - Trace.WriteLine( "Devices match." ); - else - Trace.WriteLine( "Error: Devices do not match." ); - - if ( MyContext == currcon ) - Trace.WriteLine( "Context match." ); - else - Trace.WriteLine( "Error: Contexts do not match." ); - - // exit - Alc.MakeContextCurrent( Al.Null ); // results in no context being current - Alc.DestroyContext( MyContext ); - result = Alc.CloseDevice( MyDevice ); - Trace.WriteLine( "Result: " + result ); - Trace.ReadLine( ); - } - else - { - Trace.WriteLine( "Context creation failed." ); - } - } - else - { - Trace.WriteLine( "Failed to find suitable Device." ); - } -#endif - /* -include -include - -int -main (int argc, char **argv) -{ - ALuint helloBuffer, helloSource; - alutInit (&argc, argv); - helloBuffer = alutCreateBufferHelloWorld (); alGenSources (1, &helloSource); - alSourcei (helloSource, AL_Buffer, helloBuffer); - alSourcePlay (helloSource); - alutSleep (1); - alutExit (); - return EXIT_SUCCESS; -}*/ - - /* - - * Processing Loop Example: -// PlaceCamera - places OpenGL camera & updates OpenAL listener buffer -void AVEnvironment::PlaceCamera() -{ -// update OpenGL camera position -glMatrixMode(GL_PROJECTION); -glLoadIdentity(); -glFrustum(-0.1333, 0.1333, -0.1, 0.1, 0.2, 50.0); -gluLookAt(listenerPos[0], listenerPos[1], listenerPos[2], -(listenerPos[0] + sin(listenerAngle)), listenerPos[1], -(listenerPos[2] - cos(listenerAngle)), -0.0, 1.0, 0.0); -// update OpenAL -// place listener at camera -alListener3f(AL_POSITION, listenerPos[0], listenerPos[1], listenerPos[2]); -float directionvect[6]; -directionvect[0] = (float) sin(listenerAngle); -directionvect[1] = 0; -directionvect[2] = (float) cos(listenerAngle); -directionvect[3] = 0; -directionvect[4] = 1; -directionvect[5] = 0; -alListenerfv(AL_ORIENTATION, directionvect); -} - - */ - } - } -} diff --git a/Source/Examples/OpenCL/VectorAdd.cs b/Source/Examples/OpenCL/VectorAdd.cs deleted file mode 100644 index ef0bd215..00000000 --- a/Source/Examples/OpenCL/VectorAdd.cs +++ /dev/null @@ -1,145 +0,0 @@ -#if EXPERIMENTAL - -using System; -using System.Collections.Generic; -using System.Text; -using OpenTK.Compute.CL10; - -namespace Examples -{ - - using cl_context = IntPtr; - using cl_device_id = IntPtr; - using cl_command_queue = IntPtr; - using cl_program = IntPtr; - using cl_kernel = IntPtr; - using cl_mem = IntPtr; - - [Example("Vector Addition", ExampleCategory.OpenCL, "1.0")] - class VectorAdd - { - public static void Main() - { - const int cnBlockSize = 4; - const int cnBlocks = 3; - IntPtr cnDimension = new IntPtr(cnBlocks * cnBlockSize); - string sProgramSource = @" -__kernel void -vectorAdd(__global const float * a, - __global const float * b, - __global float * c) -{ - // Vector element index - int nIndex = get_global_id(0); - c[nIndex] = a[nIndex] + b[nIndex]; -} -"; - - ErrorCode error; - - // create OpenCL device & context - cl_context hContext; - unsafe { hContext = CL.CreateContextFromType((ContextProperties*)null, DeviceTypeFlags.DeviceTypeDefault, IntPtr.Zero, IntPtr.Zero, &error); } - - // query all devices available to the context - IntPtr nContextDescriptorSize; - CL.GetContextInfo(hContext, ContextInfo.ContextDevices, IntPtr.Zero, IntPtr.Zero, out nContextDescriptorSize); - cl_device_id[] aDevices = new cl_device_id[nContextDescriptorSize.ToInt32()]; - unsafe - { - fixed (cl_device_id* ptr = aDevices) - { - IntPtr ret; - CL.GetContextInfo(hContext, ContextInfo.ContextDevices, nContextDescriptorSize, new IntPtr(ptr), out ret); - } - } - - - // create a command queue for first device the context reported - cl_command_queue hCmdQueue = CL.CreateCommandQueue(hContext, aDevices[0], (CommandQueueFlags)0, out error); - // create & compile program - cl_program hProgram; - unsafe { hProgram = CL.CreateProgramWithSource(hContext, 1, new string[] { sProgramSource }, null, &error); } - CL.BuildProgram(hProgram, 0, (IntPtr[])null, null, IntPtr.Zero, IntPtr.Zero); - - // create kernel - cl_kernel hKernel = CL.CreateKernel(hProgram, "vectorAdd", out error); - // allocate host vectors - float[] A = new float[cnDimension.ToInt32()]; - float[] B = new float[cnDimension.ToInt32()]; - float[] C = new float[cnDimension.ToInt32()]; - // initialize host memory - Random rand = new Random(); - for (int i = 0; i < A.Length; i++) - { - A[i] = rand.Next() % 256; - B[i] = rand.Next() % 256; - } - - // allocate device memory - unsafe - { - fixed (float* pA = A) - fixed (float* pB = B) - fixed (float* pC = C) - { - cl_mem hDeviceMemA, hDeviceMemB, hDeviceMemC; - hDeviceMemA = CL.CreateBuffer(hContext, - MemFlags.MemReadOnly | MemFlags.MemCopyHostPtr, - new IntPtr(cnDimension.ToInt32() * sizeof(float)), - new IntPtr(pA), - out error); - hDeviceMemB = CL.CreateBuffer(hContext, - MemFlags.MemReadOnly | MemFlags.MemCopyHostPtr, - new IntPtr(cnDimension.ToInt32() * sizeof(float)), - new IntPtr(pA), - out error); - hDeviceMemC = CL.CreateBuffer(hContext, - MemFlags.MemWriteOnly, - new IntPtr(cnDimension.ToInt32() * sizeof(float)), - IntPtr.Zero, - out error); - - // setup parameter values - CL.SetKernelArg(hKernel, 0, new IntPtr(sizeof(cl_mem)), new IntPtr(&hDeviceMemA)); - CL.SetKernelArg(hKernel, 1, new IntPtr(sizeof(cl_mem)), new IntPtr(&hDeviceMemB)); - CL.SetKernelArg(hKernel, 2, new IntPtr(sizeof(cl_mem)), new IntPtr(&hDeviceMemC)); - - // write data from host to device - CL.EnqueueWriteBuffer(hCmdQueue, hDeviceMemA, true, IntPtr.Zero, - new IntPtr(cnDimension.ToInt32() * sizeof(float)), - new IntPtr(pA), 0, null, (IntPtr[])null); - CL.EnqueueWriteBuffer(hCmdQueue, hDeviceMemB, true, IntPtr.Zero, - new IntPtr(cnDimension.ToInt32() * sizeof(float)), - new IntPtr(pB), 0, null, (IntPtr[])null); - - // execute kernel - error = (ErrorCode)CL.EnqueueNDRangeKernel(hCmdQueue, hKernel, 1, null, &cnDimension, null, 0, null, null); - if (error != ErrorCode.Success) - throw new Exception(error.ToString()); - - // copy results from device back to host - IntPtr event_handle = IntPtr.Zero; - error = (ErrorCode)CL.EnqueueReadBuffer(hCmdQueue, hDeviceMemC, true, IntPtr.Zero, - new IntPtr(cnDimension.ToInt32() * sizeof(float)), - new IntPtr(pC), 0, null, (IntPtr[])null); - if (error != ErrorCode.Success) - throw new Exception(error.ToString()); - - CL.Finish(hCmdQueue); - - CL.ReleaseMemObject(hDeviceMemA); - CL.ReleaseMemObject(hDeviceMemB); - CL.ReleaseMemObject(hDeviceMemC); - } - } - - for (int i = 0; i < A.Length; i++) - { - System.Diagnostics.Trace.WriteLine(String.Format("{0} + {1} = {2}", A[i], B[i], C[i])); - } - } - } -} - -#endif \ No newline at end of file diff --git a/Source/Examples/OpenGL/1.x/Anaglyph.cs b/Source/Examples/OpenGL/1.x/Anaglyph.cs deleted file mode 100644 index 861742d7..00000000 --- a/Source/Examples/OpenGL/1.x/Anaglyph.cs +++ /dev/null @@ -1,209 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Drawing; -using System.Collections.Generic; -using System.Diagnostics; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; -using OpenTK.Input; - -namespace Examples.Tutorial -{ - [Example( "Anaglyph Stereo", ExampleCategory.OpenGL, "1.x", Documentation = "Anaglyph" )] - - class Anaglyph : GameWindow - { - - Examples.Shapes.DrawableShape Object; - - /// Creates a 800x600 window with the specified title. - public Anaglyph() - : base(800, 600, GraphicsMode.Default, "OpenTK Quick Start Sample", GameWindowFlags.Default, DisplayDevice.Default, 3, 1, GraphicsContextFlags.Default) - { - VSync = VSyncMode.On; - } - - /// Load resources here. - /// Not used. - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - GL.ClearColor(System.Drawing.Color.Black); - GL.Enable(EnableCap.DepthTest); - - GL.Enable( EnableCap.Lighting ); - GL.Enable( EnableCap.Light0 ); - - Object = new Examples.Shapes.MengerSponge(1.0, Shapes.MengerSponge.eSubdivisions.Two, true ); - // Object = new Examples.Shapes.TorusKnot( 256, 32, 0.1, 3, 4, 1, true ); - } - - protected override void OnUnload( EventArgs e ) - { - base.OnUnload( e ); - - Object.Dispose(); - } - - /// - /// Called when your window is resized. Set your viewport here. It is also - /// a good place to set up your projection matrix (which probably changes - /// along when the aspect ratio of your window). - /// - /// Not used. - protected override void OnResize(EventArgs e) - { - base.OnResize(e); - - GL.Viewport(ClientRectangle); - } - - /// - /// Called when it is time to setup the next frame. Add you game logic here. - /// - /// Contains timing information for framerate independent logic. - protected override void OnUpdateFrame(FrameEventArgs e) - { - base.OnUpdateFrame(e); - - var keyboard = OpenTK.Input.Keyboard.GetState(); - if (keyboard[Key.Escape]) - Exit(); - } - - struct Camera - { - public Vector3 Position, Direction, Up; - public double NearPlane, FarPlane; - public double EyeSeparation; - public double Aperture; // FOV in degrees - public double FocalLength; - } - - enum Eye - { - left, - right, - } - - void SetupCamera( Eye eye ) - { - Camera camera; - - camera.Position = Vector3.UnitZ; - camera.Up = Vector3.UnitY; - camera.Direction = -Vector3.UnitZ; - camera.NearPlane = 1.0; - camera.FarPlane = 5.0; - camera.FocalLength = 2.0; - camera.EyeSeparation = camera.FocalLength / 30.0; - camera.Aperture = 75.0; - - double left, right, - bottom, top; - - double widthdiv2 = camera.NearPlane * Math.Tan( MathHelper.DegreesToRadians( (float)( camera.Aperture / 2.0 ) ) ); // aperture in radians - double precalc1 = ClientRectangle.Width / (double)ClientRectangle.Height * widthdiv2; - double precalc2 = 0.5 * camera.EyeSeparation * camera.NearPlane / camera.FocalLength; - - Vector3 Right = Vector3.Cross( camera.Direction, camera.Up ); // Each unit vectors - Right.Normalize(); - - Right.X *= (float)( camera.EyeSeparation / 2.0 ); - Right.Y *= (float)( camera.EyeSeparation / 2.0 ); - Right.Z *= (float)( camera.EyeSeparation / 2.0 ); - - // Projection Matrix - top = widthdiv2; - bottom = -widthdiv2; - if ( eye == Eye.right ) - { - left = -precalc1 - precalc2; - right = precalc1 - precalc2; - } - else - { - left = -precalc1 + precalc2; - right = precalc1 + precalc2; - } - - GL.MatrixMode( MatrixMode.Projection ); - GL.LoadIdentity(); - GL.Frustum( left, right, bottom, top, camera.NearPlane, camera.FarPlane ); - - // Modelview Matrix - Matrix4 modelview; - if ( eye == Eye.right ) - { - modelview = Matrix4.LookAt( - new Vector3( camera.Position.X + Right.X, camera.Position.Y + Right.Y, camera.Position.Z + Right.Z ), - new Vector3( camera.Position.X + Right.X + camera.Direction.X, camera.Position.Y + Right.Y + camera.Direction.Y, camera.Position.Z + Right.Z + camera.Direction.Z ), - camera.Up ); - } - else - { - modelview = Matrix4.LookAt( - new Vector3( camera.Position.X - Right.X, camera.Position.Y - Right.Y, camera.Position.Z - Right.Z ), - new Vector3( camera.Position.X - Right.X + camera.Direction.X, camera.Position.Y - Right.Y + camera.Direction.Y, camera.Position.Z - Right.Z + camera.Direction.Z ), - camera.Up ); - } - GL.MatrixMode( MatrixMode.Modelview ); - GL.LoadIdentity(); - GL.MultMatrix( ref modelview ); - - } - - float Angle; - - void Draw() - { - GL.Translate( 0f, 0f, -2f ); - GL.Rotate( Angle, Vector3.UnitY ); - Object.Draw(); - } - - /// - /// Called when it is time to render the next frame. Add your rendering code here. - /// - /// Contains timing information. - protected override void OnRenderFrame( FrameEventArgs e ) - { - Angle += (float)(e.Time *20.0); - - - GL.Clear( ClearBufferMask.DepthBufferBit | ClearBufferMask.ColorBufferBit ); - SetupCamera( Eye.right ); - GL.ColorMask( true, false, false, true ); - Draw(); - - GL.Clear( ClearBufferMask.DepthBufferBit ); // - SetupCamera( Eye.left ); - GL.ColorMask( false, true, true, true ); - Draw(); - - GL.ColorMask( true, true, true, true ); - SwapBuffers(); - } - - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() - { - // The 'using' idiom guarantees proper resource cleanup. - // We request 30 UpdateFrame events per second, and unlimited - // RenderFrame events (as fast as the computer can handle). - using (Anaglyph game = new Anaglyph()) - { - game.Run(10.0); - } - } - } -} \ No newline at end of file diff --git a/Source/Examples/OpenGL/1.x/Anaglyph.rtf b/Source/Examples/OpenGL/1.x/Anaglyph.rtf deleted file mode 100644 index ee156c5d..00000000 Binary files a/Source/Examples/OpenGL/1.x/Anaglyph.rtf and /dev/null differ diff --git a/Source/Examples/OpenGL/1.x/DisplayLists.cs b/Source/Examples/OpenGL/1.x/DisplayLists.cs deleted file mode 100644 index 62974090..00000000 --- a/Source/Examples/OpenGL/1.x/DisplayLists.cs +++ /dev/null @@ -1,157 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -#region --- Using Directives --- - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.Threading; - -using OpenTK; -using OpenTK.Graphics.OpenGL; - -#endregion --- Using Directives --- - -namespace Examples.Tutorial -{ - [Example("Display Lists", ExampleCategory.OpenGL, "1.x", 2, Documentation = "DisplayLists")] - public class T07_Display_Lists_Flower : GameWindow - { - #region --- Fields --- - - const int num_lists = 13; - int[] lists = new int[num_lists]; - - #endregion - - #region --- Constructor --- - - public T07_Display_Lists_Flower() - : base(800, 600) - { - } - - #endregion - - #region OnLoad - - protected override void OnLoad(EventArgs e) - { - GL.ClearColor(Color.MidnightBlue); - GL.Enable(EnableCap.DepthTest); - - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadIdentity(); - - // Build some display lists. - int first_list = GL.GenLists(num_lists); - float c = 0; - for (int i = 0; i < num_lists; i++) - { - lists[i] = first_list + i; - GL.NewList(first_list + i, ListMode.Compile); - - GL.Color3(0.3 + 0.7 * c * c, 0.3 + 1.4 * c * c, 0.7 - 0.7 * c * c); - c += 1 / (float)num_lists; - - GL.PushMatrix(); - - GL.Rotate(c * 360.0f, 0.0, 0.0, 1.0); - GL.Translate(5.0, 0.0, 0.0); - - GL.Begin(PrimitiveType.Quads); - - GL.Vertex3(-1.0f, -1.0f, 1.0f); - GL.Vertex3(1.0f, -1.0f, 1.0f); - GL.Vertex3(1.0f, 1.0f, 1.0f); - GL.Vertex3(-1.0f, 1.0f, 1.0f); - - GL.End(); - - GL.PopMatrix(); - - GL.EndList(); - } - } - - #endregion - - #region OnUnload - - protected override void OnUnload(EventArgs e) - { - GL.DeleteLists(lists[0], num_lists); - } - - #endregion - - #region OnResize - - protected override void OnResize(EventArgs e) - { - GL.Viewport(ClientRectangle); - - float aspect = this.ClientSize.Width / (float)this.ClientSize.Height; - - Matrix4 projection_matrix; - Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, aspect, 1, 64, out projection_matrix); - - GL.MatrixMode(MatrixMode.Projection); - GL.LoadMatrix(ref projection_matrix); - } - - #endregion - - #region OnUpdateFrame - - protected override void OnUpdateFrame(FrameEventArgs e) - { - var keyboard = OpenTK.Input.Keyboard.GetState(); - if (keyboard[OpenTK.Input.Key.Escape]) - { - this.Exit(); - } - } - - #endregion - - #region OnRenderFrame - - protected override void OnRenderFrame(FrameEventArgs e) - { - Matrix4 lookat = Matrix4.LookAt(0, 0, 16, 0, 0, 0, 0, 1, 0); - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadMatrix(ref lookat); - - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - GL.CallLists(num_lists, ListNameType.Int, lists); - - SwapBuffers(); - } - - #endregion - - #region public static void Main() - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - using (T07_Display_Lists_Flower example = new T07_Display_Lists_Flower()) - { - Utilities.SetWindowTitle(example); - example.Run(30.0, 0.0); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/Source/Examples/OpenGL/1.x/DisplayLists.rtf b/Source/Examples/OpenGL/1.x/DisplayLists.rtf deleted file mode 100644 index aa6bf63c..00000000 Binary files a/Source/Examples/OpenGL/1.x/DisplayLists.rtf and /dev/null differ diff --git a/Source/Examples/OpenGL/1.x/FramebufferObject.cs b/Source/Examples/OpenGL/1.x/FramebufferObject.cs deleted file mode 100644 index 743fd790..00000000 --- a/Source/Examples/OpenGL/1.x/FramebufferObject.cs +++ /dev/null @@ -1,286 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Diagnostics; -using System.Drawing; - -using OpenTK; -using OpenTK.Input; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; - -namespace Examples.Tutorial -{ - [Example("Framebuffer Objects", ExampleCategory.OpenGL, "1.x", Documentation = "FramebufferObject")] - public class SimpleFBO : GameWindow - { - public SimpleFBO() - : base(800, 400) - { - } - - uint ColorTexture; - uint DepthTexture; - uint FBOHandle; - - const int TextureSize = 512; - - Examples.Shapes.DrawableShape Object; - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - if (!GL.GetString(StringName.Extensions).Contains("GL_EXT_framebuffer_object")) - { - throw new NotSupportedException( - "GL_EXT_framebuffer_object extension is required. Please update your drivers."); - } - - Object = new Shapes.TorusKnot(256, 16, 0.2, 7,8, 1, true); - - GL.Enable(EnableCap.DepthTest); - GL.ClearDepth(1.0); - GL.DepthFunc(DepthFunction.Lequal); - - GL.Enable(EnableCap.CullFace); - - // Create Color Tex - GL.GenTextures(1, out ColorTexture); - GL.BindTexture(TextureTarget.Texture2D, ColorTexture); - GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, TextureSize, TextureSize, 0, PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToBorder); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToBorder); - // GL.Ext.GenerateMipmap( GenerateMipmapTarget.Texture2D ); - - // Create Depth Tex - GL.GenTextures(1, out DepthTexture); - GL.BindTexture(TextureTarget.Texture2D, DepthTexture); - GL.TexImage2D(TextureTarget.Texture2D, 0, (PixelInternalFormat)All.DepthComponent32, TextureSize, TextureSize, 0, PixelFormat.DepthComponent, PixelType.UnsignedInt, IntPtr.Zero); - // things go horribly wrong if DepthComponent's Bitcount does not match the main Framebuffer's Depth - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToBorder); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToBorder); - // GL.Ext.GenerateMipmap( GenerateMipmapTarget.Texture2D ); - - // Create a FBO and attach the textures - GL.Ext.GenFramebuffers(1, out FBOHandle); - GL.Ext.BindFramebuffer(FramebufferTarget.FramebufferExt, FBOHandle); - GL.Ext.FramebufferTexture2D(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, TextureTarget.Texture2D, ColorTexture, 0); - GL.Ext.FramebufferTexture2D(FramebufferTarget.FramebufferExt, FramebufferAttachment.DepthAttachmentExt, TextureTarget.Texture2D, DepthTexture, 0); - - #region Test for Error - - switch (GL.Ext.CheckFramebufferStatus(FramebufferTarget.FramebufferExt)) - { - case FramebufferErrorCode.FramebufferCompleteExt: - { - Console.WriteLine("FBO: The framebuffer is complete and valid for rendering."); - break; - } - case FramebufferErrorCode.FramebufferIncompleteAttachmentExt: - { - Console.WriteLine("FBO: One or more attachment points are not framebuffer attachment complete. This could mean there’s no texture attached or the format isn’t renderable. For color textures this means the base format must be RGB or RGBA and for depth textures it must be a DEPTH_COMPONENT format. Other causes of this error are that the width or height is zero or the z-offset is out of range in case of render to volume."); - break; - } - case FramebufferErrorCode.FramebufferIncompleteMissingAttachmentExt: - { - Console.WriteLine("FBO: There are no attachments."); - break; - } - /* case FramebufferErrorCode.GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT_EXT: - { - Console.WriteLine("FBO: An object has been attached to more than one attachment point."); - break; - }*/ - case FramebufferErrorCode.FramebufferIncompleteDimensionsExt: - { - Console.WriteLine("FBO: Attachments are of different size. All attachments must have the same width and height."); - break; - } - case FramebufferErrorCode.FramebufferIncompleteFormatsExt: - { - Console.WriteLine("FBO: The color attachments have different format. All color attachments must have the same format."); - break; - } - case FramebufferErrorCode.FramebufferIncompleteDrawBufferExt: - { - Console.WriteLine("FBO: An attachment point referenced by GL.DrawBuffers() doesn’t have an attachment."); - break; - } - case FramebufferErrorCode.FramebufferIncompleteReadBufferExt: - { - Console.WriteLine("FBO: The attachment point referenced by GL.ReadBuffers() doesn’t have an attachment."); - break; - } - case FramebufferErrorCode.FramebufferUnsupportedExt: - { - Console.WriteLine("FBO: This particular FBO configuration is not supported by the implementation."); - break; - } - default: - { - Console.WriteLine("FBO: Status unknown. (yes, this is really bad.)"); - break; - } - } - - // using FBO might have changed states, e.g. the FBO might not support stereoscopic views or double buffering - int[] queryinfo = new int[6]; - GL.GetInteger(GetPName.MaxColorAttachmentsExt, out queryinfo[0]); - GL.GetInteger(GetPName.AuxBuffers, out queryinfo[1]); - GL.GetInteger(GetPName.MaxDrawBuffers, out queryinfo[2]); - GL.GetInteger(GetPName.Stereo, out queryinfo[3]); - GL.GetInteger(GetPName.Samples, out queryinfo[4]); - GL.GetInteger(GetPName.Doublebuffer, out queryinfo[5]); - Console.WriteLine("max. ColorBuffers: " + queryinfo[0] + " max. AuxBuffers: " + queryinfo[1] + " max. DrawBuffers: " + queryinfo[2] + - "\nStereo: " + queryinfo[3] + " Samples: " + queryinfo[4] + " DoubleBuffer: " + queryinfo[5]); - - Console.WriteLine("Last GL Error: " + GL.GetError()); - - #endregion Test for Error - - GL.PushAttrib(AttribMask.ViewportBit); - { - GL.Viewport(0, 0, TextureSize, TextureSize); - - // clear the screen in red, to make it very obvious what the clear affected. only the FBO, not the real framebuffer - GL.ClearColor(1f, 0f, 0f, 0f); - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - OpenTK.Matrix4 perspective = OpenTK.Matrix4.CreatePerspectiveFieldOfView( MathHelper.PiOver4, TextureSize / (float)TextureSize, 2.5f, 6f ); - GL.MatrixMode( MatrixMode.Projection ); - GL.LoadMatrix( ref perspective ); - - Matrix4 lookat = Matrix4.LookAt( 0f, 0f, 4.5f, 0f, 0f, 0f, 0f, 1f, 0f ); - GL.MatrixMode( MatrixMode.Modelview ); - GL.LoadMatrix( ref lookat ); - - // draw some complex object into the FBO's textures - GL.Enable( EnableCap.Lighting ); - GL.Enable( EnableCap.Light0 ); - GL.Enable( EnableCap.ColorMaterial ); - GL.Color3( 0f, 1f, 0f ); - Object.Draw(); - GL.Disable( EnableCap.ColorMaterial ); - GL.Disable( EnableCap.Light0 ); - GL.Disable( EnableCap.Lighting ); - - } - GL.PopAttrib(); - GL.Ext.BindFramebuffer(FramebufferTarget.FramebufferExt, 0); // disable rendering into the FBO - - GL.ClearColor(.1f, .2f, .3f, 0f); - GL.Color3(1f, 1f, 1f); - - GL.Enable(EnableCap.Texture2D); // enable Texture Mapping - GL.BindTexture(TextureTarget.Texture2D, 0); // bind default texture - } - - protected override void OnUnload(EventArgs e) - { - Object.Dispose(); - - // Clean up what we allocated before exiting - if (ColorTexture != 0) - GL.DeleteTextures(1, ref ColorTexture); - - if (DepthTexture != 0) - GL.DeleteTextures(1, ref DepthTexture); - - if (FBOHandle != 0) - GL.Ext.DeleteFramebuffers(1, ref FBOHandle); - } - - protected override void OnResize(EventArgs e) - { - GL.Viewport(0, 0, Width, Height); - - double aspect_ratio = Width / (double)Height; - - OpenTK.Matrix4 perspective = OpenTK.Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, (float)aspect_ratio, 1, 64); - GL.MatrixMode(MatrixMode.Projection); - GL.LoadMatrix(ref perspective); - - Matrix4 lookat = Matrix4.LookAt(0, 0, 3, 0, 0, 0, 0, 1, 0); - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadMatrix(ref lookat); - - base.OnResize(e); - } - - protected override void OnUpdateFrame(FrameEventArgs e) - { - base.OnUpdateFrame(e); - - var keyboard = OpenTK.Input.Keyboard.GetState(); - if (keyboard[Key.Escape]) - this.Exit(); - } - - protected override void OnRenderFrame(FrameEventArgs e) - { - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - GL.PushMatrix(); - { - // Draw the Color Texture - GL.Translate(-1.1f, 0f, 0f); - GL.BindTexture(TextureTarget.Texture2D, ColorTexture); - GL.Begin(PrimitiveType.Quads); - { - GL.TexCoord2(0f, 1f); - GL.Vertex2(-1.0f, 1.0f); - GL.TexCoord2(0.0f, 0.0f); - GL.Vertex2(-1.0f, -1.0f); - GL.TexCoord2(1.0f, 0.0f); - GL.Vertex2(1.0f, -1.0f); - GL.TexCoord2(1.0f, 1.0f); - GL.Vertex2(1.0f, 1.0f); - } - GL.End(); - - // Draw the Depth Texture - GL.Translate(+2.2f, 0f, 0f); - GL.BindTexture(TextureTarget.Texture2D, DepthTexture); - GL.Begin(PrimitiveType.Quads); - { - GL.TexCoord2(0f, 1f); - GL.Vertex2(-1.0f, 1.0f); - GL.TexCoord2(0.0f, 0.0f); - GL.Vertex2(-1.0f, -1.0f); - GL.TexCoord2(1.0f, 0.0f); - GL.Vertex2(1.0f, -1.0f); - GL.TexCoord2(1.0f, 1.0f); - GL.Vertex2(1.0f, 1.0f); - } - GL.End(); - } - GL.PopMatrix(); - - this.SwapBuffers(); - } - - #region public static void Main() - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - using (SimpleFBO example = new SimpleFBO()) - { - Utilities.SetWindowTitle(example); - example.Run(30.0, 0.0); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/Source/Examples/OpenGL/1.x/FramebufferObject.rtf b/Source/Examples/OpenGL/1.x/FramebufferObject.rtf deleted file mode 100644 index fff69875..00000000 Binary files a/Source/Examples/OpenGL/1.x/FramebufferObject.rtf and /dev/null differ diff --git a/Source/Examples/OpenGL/1.x/ImmediateMode.cs b/Source/Examples/OpenGL/1.x/ImmediateMode.cs deleted file mode 100644 index 76d8e9f8..00000000 --- a/Source/Examples/OpenGL/1.x/ImmediateMode.cs +++ /dev/null @@ -1,192 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -#region --- Using Directives --- - -using System; -using System.Collections.Generic; -using System.Windows.Forms; -using System.Threading; -using System.Drawing; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; - -#endregion - -namespace Examples.Tutorial -{ - /// - /// Demonstrates immediate mode rendering. - /// - [Example("Immediate mode", ExampleCategory.OpenGL, "1.x", 1, Documentation = "ImmediateMode")] - public class T03_Immediate_Mode_Cube : GameWindow - { - #region --- Fields --- - - const float rotation_speed = 180.0f; - float angle; - - #endregion - - #region --- Constructor --- - - public T03_Immediate_Mode_Cube() - : base(800, 600) - { } - - #endregion - - #region OnLoad - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - GL.ClearColor(Color.MidnightBlue); - GL.Enable(EnableCap.DepthTest); - } - - #endregion - - #region OnResize - - /// - /// Called when the user resizes the window. - /// - /// Contains the new width/height of the window. - /// - /// You want the OpenGL viewport to match the window. This is the place to do it! - /// - protected override void OnResize(EventArgs e) - { - base.OnResize(e); - - GL.Viewport(0, 0, Width, Height); - - double aspect_ratio = Width / (double)Height; - - OpenTK.Matrix4 perspective = OpenTK.Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, (float)aspect_ratio, 1, 64); - GL.MatrixMode(MatrixMode.Projection); - GL.LoadMatrix(ref perspective); - } - - #endregion - - #region OnUpdateFrame - - /// - /// Prepares the next frame for rendering. - /// - /// - /// Place your control logic here. This is the place to respond to user input, - /// update object positions etc. - /// - protected override void OnUpdateFrame(FrameEventArgs e) - { - base.OnUpdateFrame(e); - - var keyboard = OpenTK.Input.Keyboard.GetState(); - if (keyboard[OpenTK.Input.Key.Escape]) - { - this.Exit(); - return; - } - } - - #endregion - - #region OnRenderFrame - - /// - /// Place your rendering code here. - /// - protected override void OnRenderFrame(FrameEventArgs e) - { - base.OnRenderFrame(e); - - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - Matrix4 lookat = Matrix4.LookAt(0, 5, 5, 0, 0, 0, 0, 1, 0); - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadMatrix(ref lookat); - - angle += rotation_speed * (float)e.Time; - GL.Rotate(angle, 0.0f, 1.0f, 0.0f); - - DrawCube(); - - this.SwapBuffers(); - Thread.Sleep(1); - } - - #endregion - - #region private void DrawCube() - - private void DrawCube() - { - GL.Begin(PrimitiveType.Quads); - - GL.Color3(Color.Silver); - GL.Vertex3(-1.0f, -1.0f, -1.0f); - GL.Vertex3(-1.0f, 1.0f, -1.0f); - GL.Vertex3(1.0f, 1.0f, -1.0f); - GL.Vertex3(1.0f, -1.0f, -1.0f); - - GL.Color3(Color.Honeydew); - GL.Vertex3(-1.0f, -1.0f, -1.0f); - GL.Vertex3(1.0f, -1.0f, -1.0f); - GL.Vertex3(1.0f, -1.0f, 1.0f); - GL.Vertex3(-1.0f, -1.0f, 1.0f); - - GL.Color3(Color.Moccasin); - - GL.Vertex3(-1.0f, -1.0f, -1.0f); - GL.Vertex3(-1.0f, -1.0f, 1.0f); - GL.Vertex3(-1.0f, 1.0f, 1.0f); - GL.Vertex3(-1.0f, 1.0f, -1.0f); - - GL.Color3(Color.IndianRed); - GL.Vertex3(-1.0f, -1.0f, 1.0f); - GL.Vertex3(1.0f, -1.0f, 1.0f); - GL.Vertex3(1.0f, 1.0f, 1.0f); - GL.Vertex3(-1.0f, 1.0f, 1.0f); - - GL.Color3(Color.PaleVioletRed); - GL.Vertex3(-1.0f, 1.0f, -1.0f); - GL.Vertex3(-1.0f, 1.0f, 1.0f); - GL.Vertex3(1.0f, 1.0f, 1.0f); - GL.Vertex3(1.0f, 1.0f, -1.0f); - - GL.Color3(Color.ForestGreen); - GL.Vertex3(1.0f, -1.0f, -1.0f); - GL.Vertex3(1.0f, 1.0f, -1.0f); - GL.Vertex3(1.0f, 1.0f, 1.0f); - GL.Vertex3(1.0f, -1.0f, 1.0f); - - GL.End(); - } - - #endregion - - #region public static void Main() - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - using (T03_Immediate_Mode_Cube example = new T03_Immediate_Mode_Cube()) - { - Utilities.SetWindowTitle(example); - example.Run(30.0, 0.0); - } - } - - #endregion - } -} diff --git a/Source/Examples/OpenGL/1.x/ImmediateMode.rtf b/Source/Examples/OpenGL/1.x/ImmediateMode.rtf deleted file mode 100644 index dcf28cd2..00000000 Binary files a/Source/Examples/OpenGL/1.x/ImmediateMode.rtf and /dev/null differ diff --git a/Source/Examples/OpenGL/1.x/OpenGLDiagnostics.cs b/Source/Examples/OpenGL/1.x/OpenGLDiagnostics.cs deleted file mode 100644 index ea3a45b3..00000000 --- a/Source/Examples/OpenGL/1.x/OpenGLDiagnostics.cs +++ /dev/null @@ -1,443 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Drawing; -using System.Collections.Generic; -using System.Diagnostics; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; -using OpenTK.Input; - -namespace Examples.Tutorial -{ - [Example( "OpenGL Diagnostics", ExampleCategory.OpenGL, "1.x", Documentation = "OpenGLDiagnostics" )] - - class GLDiagnostics : GameWindow - { - /// Creates a 800x600 window with the specified title. - public GLDiagnostics() - : base(80, 60, GraphicsMode.Default, "OpenTK Quick Start Sample", GameWindowFlags.Default, DisplayDevice.Default, 3, 1, GraphicsContextFlags.Default) - { - VSync = VSyncMode.On; - this.Context.ErrorChecking = false; - } - - struct TexFormat - { - public PixelInternalFormat pif; - public PixelFormat pf; - public PixelType pt; - - public TexFormat(PixelInternalFormat _pif, PixelFormat _pf, PixelType _pt) - { - pif = _pif; - pf = _pf; - pt = _pt; - } - } - - TexFormat[] TextureFormats = new TexFormat[] - { - new TexFormat( PixelInternalFormat.Alpha, PixelFormat.Alpha, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.Alpha4, PixelFormat.Alpha, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.Alpha8, PixelFormat.Alpha, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.Alpha12, PixelFormat.Alpha, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.Alpha16, PixelFormat.Alpha, PixelType.UnsignedByte), - new TexFormat( (PixelInternalFormat)All.Alpha16fArb, PixelFormat.Alpha, PixelType.HalfFloat), - new TexFormat( (PixelInternalFormat)All.Alpha32fArb, PixelFormat.Alpha, PixelType.Float), - - new TexFormat( PixelInternalFormat.DepthComponent, PixelFormat.DepthComponent, PixelType.Int), - new TexFormat( PixelInternalFormat.DepthComponent16, PixelFormat.DepthComponent, PixelType.Float), - new TexFormat( PixelInternalFormat.DepthComponent24, PixelFormat.DepthComponent, PixelType.Float), - new TexFormat( PixelInternalFormat.DepthComponent32, PixelFormat.DepthComponent, PixelType.Float), - new TexFormat( PixelInternalFormat.DepthComponent32f, PixelFormat.DepthComponent, PixelType.Float), - new TexFormat( PixelInternalFormat.DepthStencil, PixelFormat.DepthStencil, PixelType.UnsignedInt248), - new TexFormat( PixelInternalFormat.Depth24Stencil8, PixelFormat.DepthStencil, PixelType.UnsignedInt248), - new TexFormat( PixelInternalFormat.Depth32fStencil8, PixelFormat.DepthStencil, PixelType.Float32UnsignedInt248Rev), - - new TexFormat( PixelInternalFormat.One, PixelFormat.Red, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.Two, PixelFormat.Rg, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.Rgb, PixelFormat.Rgb, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.Rgba, PixelFormat.Rgba, PixelType.UnsignedByte), - - new TexFormat( PixelInternalFormat.Srgb, PixelFormat.Rgb, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.SrgbAlpha, PixelFormat.Rgb, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.Srgb8, PixelFormat.Rgb, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.Srgb8Alpha8, PixelFormat.Rgba, PixelType.UnsignedByte), - - new TexFormat( PixelInternalFormat.R16f, PixelFormat.Red, PixelType.HalfFloat), - new TexFormat( PixelInternalFormat.Rg16f, PixelFormat.Rg, PixelType.HalfFloat), - new TexFormat( PixelInternalFormat.Rgb16f, PixelFormat.Rgb, PixelType.HalfFloat), - new TexFormat( PixelInternalFormat.Rgba16f, PixelFormat.Rgba, PixelType.HalfFloat), - new TexFormat( PixelInternalFormat.R32f, PixelFormat.Red, PixelType.Float), - new TexFormat( PixelInternalFormat.Rg32f, PixelFormat.Rg, PixelType.Float), - new TexFormat( PixelInternalFormat.Rgb32f, PixelFormat.Rgb, PixelType.Float), - new TexFormat( PixelInternalFormat.Rgba32f, PixelFormat.Rgba, PixelType.Float), - - new TexFormat( PixelInternalFormat.R8, PixelFormat.Red, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.Rg8, PixelFormat.Rg, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.Rgb8, PixelFormat.Rgb, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.Rgba8, PixelFormat.Rgba, PixelType.UnsignedByte), - - new TexFormat( PixelInternalFormat.R8ui, PixelFormat.Red, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.Rg8ui, PixelFormat.Rg, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.Rgb8ui, PixelFormat.Rgb, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.Rgba8ui, PixelFormat.Rgba, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.R16ui, PixelFormat.Red, PixelType.UnsignedShort), - new TexFormat( PixelInternalFormat.Rg16ui, PixelFormat.Rg, PixelType.UnsignedShort), - new TexFormat( PixelInternalFormat.Rgb16ui, PixelFormat.Rgb, PixelType.UnsignedShort), - new TexFormat( PixelInternalFormat.Rgba16ui, PixelFormat.Rgba, PixelType.UnsignedShort), - new TexFormat( PixelInternalFormat.R32ui, PixelFormat.Red, PixelType.UnsignedInt), - new TexFormat( PixelInternalFormat.Rg32ui, PixelFormat.Rg, PixelType.UnsignedInt), - new TexFormat( PixelInternalFormat.Rgb32ui, PixelFormat.Rgb, PixelType.UnsignedInt), - new TexFormat( PixelInternalFormat.Rgba32ui, PixelFormat.Rgba, PixelType.UnsignedInt), - - new TexFormat( PixelInternalFormat.R8i, PixelFormat.Red, PixelType.Byte), - new TexFormat( PixelInternalFormat.Rg8i, PixelFormat.Rg, PixelType.Byte), - new TexFormat( PixelInternalFormat.Rgb8i, PixelFormat.Rgb, PixelType.Byte), - new TexFormat( PixelInternalFormat.Rgba8i, PixelFormat.Rgba, PixelType.Byte), - new TexFormat( PixelInternalFormat.R16i, PixelFormat.Red, PixelType.Short), - new TexFormat( PixelInternalFormat.Rg16i, PixelFormat.Rg, PixelType.Short), - new TexFormat( PixelInternalFormat.Rgb16i, PixelFormat.Rgb, PixelType.Short), - new TexFormat( PixelInternalFormat.Rgba16i, PixelFormat.Rgba, PixelType.Short), - new TexFormat( PixelInternalFormat.R32i, PixelFormat.Red, PixelType.Int), - new TexFormat( PixelInternalFormat.Rg32i, PixelFormat.Rg, PixelType.Int), - new TexFormat( PixelInternalFormat.Rgb32i, PixelFormat.Rgb, PixelType.Int), - new TexFormat( PixelInternalFormat.Rgba32i, PixelFormat.Rgba, PixelType.Int), - - new TexFormat( PixelInternalFormat.R3G3B2, PixelFormat.Rgb, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.Rgb10A2, PixelFormat.Rgba, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.Rgb5A1, PixelFormat.Rgb, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.Rgb9E5, PixelFormat.Rgb, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.R11fG11fB10f, PixelFormat.Rgb, PixelType.UnsignedByte), - - new TexFormat( PixelInternalFormat.CompressedAlpha, PixelFormat.Alpha, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.CompressedIntensity, PixelFormat.Luminance, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.CompressedLuminance, PixelFormat.Luminance, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.CompressedLuminanceAlpha, PixelFormat.LuminanceAlpha, PixelType.UnsignedByte), - new TexFormat( (PixelInternalFormat)All.CompressedLuminanceLatc1Ext, PixelFormat.Luminance, PixelType.UnsignedByte), - new TexFormat( (PixelInternalFormat)All.CompressedLuminanceAlphaLatc2Ext, PixelFormat.LuminanceAlpha, PixelType.UnsignedByte), - - new TexFormat( PixelInternalFormat.CompressedRed, PixelFormat.Red, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.CompressedRedRgtc1, PixelFormat.Red, PixelType.UnsignedByte), - new TexFormat( (PixelInternalFormat)All.CompressedRedGreenRgtc2Ext, PixelFormat.Rg, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.CompressedRg, PixelFormat.Rg, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.CompressedRgRgtc2, PixelFormat.Rg, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.CompressedRgb, PixelFormat.Rgb, PixelType.UnsignedByte), - new TexFormat( (PixelInternalFormat)All.CompressedRgbFxt13Dfx, PixelFormat.Rgb, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.CompressedRgba, PixelFormat.Rgba, PixelType.UnsignedByte), - new TexFormat( (PixelInternalFormat)All.CompressedRgbaFxt13Dfx, PixelFormat.Rgba, PixelType.UnsignedByte), - - new TexFormat( (PixelInternalFormat)All.CompressedSignedLuminanceAlphaLatc2Ext, PixelFormat.LuminanceAlpha, PixelType.UnsignedByte), - new TexFormat( (PixelInternalFormat)All.CompressedSignedLuminanceLatc1Ext, PixelFormat.Luminance, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.CompressedSignedRedRgtc1, PixelFormat.Red, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.CompressedSignedRgRgtc2, PixelFormat.Rg, PixelType.UnsignedByte), - - new TexFormat( PixelInternalFormat.CompressedSluminance, PixelFormat.Luminance, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.CompressedSluminanceAlpha, PixelFormat.LuminanceAlpha, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.CompressedSrgb, PixelFormat.Rgb, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.CompressedSrgbAlpha, PixelFormat.Rgba, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.CompressedSrgbS3tcDxt1Ext, PixelFormat.Rgb, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.CompressedSrgbAlphaS3tcDxt1Ext, PixelFormat.Rgba, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.CompressedSrgbAlphaS3tcDxt3Ext, PixelFormat.Rgba, PixelType.UnsignedByte), - new TexFormat( PixelInternalFormat.CompressedSrgbAlphaS3tcDxt5Ext, PixelFormat.Rgba, PixelType.UnsignedByte), - - new TexFormat( (PixelInternalFormat)All.CompressedRgbS3tcDxt1Ext, PixelFormat.Rgb, PixelType.UnsignedByte), - new TexFormat( (PixelInternalFormat)All.CompressedRgbaS3tcDxt1Ext, PixelFormat.Rgba, PixelType.UnsignedByte), - new TexFormat( (PixelInternalFormat)All.CompressedRgbaS3tcDxt3Ext, PixelFormat.Rgba, PixelType.UnsignedByte), - new TexFormat( (PixelInternalFormat)All.CompressedRgbaS3tcDxt5Ext, PixelFormat.Rgba, PixelType.UnsignedByte), - - }; - - #region GL.Get* Helper - - public enum eType - { - Boolean, - Int, - IntEnum, - IntArray2, - IntArray4, - Float, - FloatArray2, - FloatArray4, - } - - public void Analyze(GetPName pname, eType type) - { - bool result1b; - int result1i; - int[] result2i = new int[2]; - int[] result4i = new int[4]; - float result1f; - Vector2 result2f; - Vector4 result4f; - string output; - - switch (type) - { - case eType.Boolean: - GL.GetBoolean(pname, out result1b); - output = pname + ": " + result1b; - break; - case eType.Int: - GL.GetInteger(pname, out result1i); - output = pname + ": " + result1i; - break; - case eType.IntEnum: - GL.GetInteger(pname, out result1i); - output = pname + ": " + (All)result1i; - break; - case eType.IntArray2: - GL.GetInteger(pname, result2i); - output = pname + ": ( " + result2i[0] + ", " + result2i[1] + " )"; - break; - case eType.IntArray4: - GL.GetInteger(pname, result4i); - output = pname + ": ( " + result4i[0] + ", " + result4i[1] + " ) ( " + result4i[2] + ", " + result4i[3] + " )"; - break; - case eType.Float: - GL.GetFloat(pname, out result1f); - output = pname + ": " + result1f; - break; - case eType.FloatArray2: - GL.GetFloat(pname, out result2f); - output = pname + ": ( " + result2f.X + ", " + result2f.Y + " )"; - break; - case eType.FloatArray4: - GL.GetFloat(pname, out result4f); - output = pname + ": ( " + result4f.X + ", " + result4f.Y + ", " + result4f.Z + ", " + result4f.W + " )"; - break; - default: throw new NotImplementedException(); - } - - ErrorCode err = GL.GetError(); - if (err != ErrorCode.NoError) - Trace.WriteLine("Unsupported Token: " + pname); - else - Trace.WriteLine(output); - - } - - #endregion GL.Get* Helper - - /// Load resources here. - /// Not used. - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - GL.ClearColor(System.Drawing.Color.MidnightBlue); - GL.Enable(EnableCap.DepthTest); - - // returns 0 formats, driver broken? - /* - int CompressedTextureFormatCount; - GL.GetInteger(GetPName.NumCompressedTextureFormats, out CompressedTextureFormatCount); - if (CompressedTextureFormatCount > 0) - { - int[] CompressedTextureFormats = new int[CompressedTextureFormatCount]; - GL.GetInteger(GetPName.CompressedTextureFormats, CompressedTextureFormats); - Trace.WriteLine("Supported compressed Texture formats:"); - for (int i = 0; i < CompressedTextureFormats.Length; i++) - Trace.Write((All)CompressedTextureFormats[i] + ", "); - } - */ - - string Renderer = GL.GetString(StringName.Renderer); - string GLSLang = GL.GetString(StringName.ShadingLanguageVersion); - string Vendor = GL.GetString(StringName.Vendor); - string Version = GL.GetString(StringName.Version); - - string ExtensionsRaw = GL.GetString(StringName.Extensions); - string[] splitter = new string[] { " " }; - string[] Extensions = ExtensionsRaw.Split(splitter, StringSplitOptions.None); - - Trace.WriteLine("Vendor: " + Vendor); - Trace.WriteLine("Renderer: " + Renderer); - Trace.WriteLine("GL Version: " + Version); - Analyze(GetPName.MajorVersion, eType.Int); - Analyze(GetPName.MinorVersion, eType.Int); - Trace.WriteLine("GLSL Version: " + GLSLang); - Trace.WriteLine("Extensions: "); - for (int i = 0; i < Extensions.Length; i++) - Trace.WriteLine(Extensions[i]); - - Trace.WriteLine("--- Framebuffer ---"); - Analyze(GetPName.Doublebuffer, eType.Boolean); - Analyze(GetPName.MaxColorAttachments, eType.Int); - Analyze(GetPName.MaxDrawBuffers, eType.Int); - Analyze(GetPName.AuxBuffers, eType.Int); - Analyze(GetPName.DrawBuffer, eType.IntEnum); - Analyze(GetPName.MaxSamples, eType.Int); - Analyze(GetPName.MaxViewportDims, eType.IntArray2); - Analyze(GetPName.Viewport, eType.IntArray4); - - Trace.WriteLine("--- Framebuffer channels ---"); - Analyze(GetPName.RedBits, eType.Int); - Analyze(GetPName.GreenBits, eType.Int); - Analyze(GetPName.BlueBits, eType.Int); - Analyze(GetPName.AlphaBits, eType.Int); - Analyze(GetPName.DepthBits, eType.Int); - Analyze(GetPName.StencilBits, eType.Int); - - Analyze(GetPName.AccumRedBits, eType.Int); - Analyze(GetPName.AccumGreenBits, eType.Int); - Analyze(GetPName.AccumBlueBits, eType.Int); - Analyze(GetPName.AccumAlphaBits, eType.Int); - - Trace.WriteLine("--- Textures ---"); - Analyze(GetPName.MaxCombinedTextureImageUnits, eType.Int); - Analyze(GetPName.MaxVertexTextureImageUnits, eType.Int); - Analyze(GetPName.MaxTextureImageUnits, eType.Int); - Analyze(GetPName.MaxTextureUnits, eType.Int); - Analyze(GetPName.MaxTextureSize, eType.Int); - Analyze(GetPName.Max3DTextureSize, eType.Int); - Analyze(GetPName.MaxCubeMapTextureSize, eType.Int); - Analyze(GetPName.MaxRenderbufferSize, eType.Int); - Analyze(GetPName.MaxTextureLodBias, eType.Int); - - Queue Supported = new Queue(); - Queue Unsupported = new Queue(); - - uint DummyTexture; - foreach (TexFormat t in TextureFormats) - { - GL.GenTextures(1, out DummyTexture); - GL.BindTexture(TextureTarget.Texture2D, DummyTexture); - GL.TexImage2D(TextureTarget.Texture2D, 0, t.pif, 4, 4, 0, t.pf, t.pt, IntPtr.Zero); - if (GL.GetError() == ErrorCode.NoError) - Supported.Enqueue(t); - else - Unsupported.Enqueue(t); - GL.DeleteTextures(1, ref DummyTexture); - } - GL.BindTexture(TextureTarget.Texture2D, 0); - - Trace.WriteLine("--- UN-supported Texture formats ---"); - while (Unsupported.Count > 0) - { - TexFormat tex = Unsupported.Dequeue(); - Trace.Write((All)tex.pif+", "); - } - Trace.WriteLine( " " ); - - Trace.WriteLine("--- SUPPORTED Texture formats ---"); - while (Supported.Count > 0) - { - TexFormat tex = Supported.Dequeue(); - Trace.WriteLine((All)tex.pif+" " +tex.pf + " "+tex.pt); - } - Trace.WriteLine(" "); - - Trace.WriteLine("--- Point&Line volumes ---"); - Analyze(GetPName.AliasedPointSizeRange, eType.FloatArray2); - Analyze(GetPName.PointSizeMin, eType.Float); - Analyze(GetPName.PointSizeMax, eType.Float); - Analyze(GetPName.PointSizeGranularity, eType.Float); - Analyze(GetPName.PointSizeRange, eType.FloatArray2); - - Analyze(GetPName.AliasedLineWidthRange, eType.FloatArray2); - Analyze(GetPName.LineWidthGranularity, eType.Float); - Analyze(GetPName.LineWidthRange, eType.FloatArray2); - - Trace.WriteLine("--- VBO ---"); - Analyze(GetPName.MaxElementsIndices, eType.Int); - Analyze(GetPName.MaxElementsVertices, eType.Int); - Analyze(GetPName.MaxVertexAttribs, eType.Int); - - Trace.WriteLine("--- GLSL ---"); - Analyze(GetPName.MaxCombinedFragmentUniformComponents, eType.Int); - Analyze(GetPName.MaxCombinedGeometryUniformComponents, eType.Int); - Analyze(GetPName.MaxCombinedVertexUniformComponents, eType.Int); - Analyze(GetPName.MaxFragmentUniformComponents, eType.Int); - Analyze(GetPName.MaxVertexUniformComponents, eType.Int); - - Analyze(GetPName.MaxCombinedUniformBlocks, eType.Int); - Analyze(GetPName.MaxFragmentUniformBlocks, eType.Int); - Analyze(GetPName.MaxGeometryUniformBlocks, eType.Int); - Analyze(GetPName.MaxVertexUniformBlocks, eType.Int); - Analyze(GetPName.MaxUniformBlockSize, eType.Int); - Analyze(GetPName.MaxUniformBufferBindings, eType.Int); - - Analyze(GetPName.MaxVaryingFloats, eType.Int); - - Trace.WriteLine("--- Transform Feedback ---"); - Analyze(GetPName.MaxTransformFeedbackInterleavedComponents, eType.Int); - Analyze(GetPName.MaxTransformFeedbackSeparateAttribs, eType.Int); - Analyze(GetPName.MaxTransformFeedbackSeparateComponents, eType.Int); - - Trace.WriteLine("--- Fixed-Func Stacks, GL.Push* and GL.Pop* ---"); - Analyze(GetPName.MaxClientAttribStackDepth, eType.Int); - Analyze(GetPName.MaxAttribStackDepth, eType.Int); - Analyze(GetPName.MaxProjectionStackDepth, eType.Int); - Analyze(GetPName.MaxModelviewStackDepth, eType.Int); - Analyze(GetPName.MaxTextureStackDepth, eType.Int); - Analyze(GetPName.MaxNameStackDepth, eType.Int); - - Trace.WriteLine("--- Fixed-Func misc. stuff ---"); - Analyze(GetPName.MaxEvalOrder, eType.Int); - Analyze(GetPName.MaxClipPlanes, eType.Int); - Analyze(GetPName.MaxArrayTextureLayers, eType.Int); - Analyze(GetPName.MaxListNesting, eType.Int); - Analyze(GetPName.MaxLights, eType.Int); - Analyze(GetPName.MaxTextureCoords, eType.Int); - - this.Exit(); - } - - /// - /// Called when your window is resized. Set your viewport here. It is also - /// a good place to set up your projection matrix (which probably changes - /// along when the aspect ratio of your window). - /// - /// Not used. - protected override void OnResize(EventArgs e) - { - base.OnResize(e); - - GL.Viewport(ClientRectangle); - } - - /// - /// Called when it is time to setup the next frame. Add you game logic here. - /// - /// Contains timing information for framerate independent logic. - protected override void OnUpdateFrame(FrameEventArgs e) - { - base.OnUpdateFrame(e); - - var keyboard = OpenTK.Input.Keyboard.GetState(); - if (keyboard[Key.Escape]) - Exit(); - } - - /// - /// Called when it is time to render the next frame. Add your rendering code here. - /// - /// Contains timing information. - protected override void OnRenderFrame(FrameEventArgs e) - { - base.OnRenderFrame(e); - } - - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() - { - // The 'using' idiom guarantees proper resource cleanup. - // We request 30 UpdateFrame events per second, and unlimited - // RenderFrame events (as fast as the computer can handle). - using (GLDiagnostics game = new GLDiagnostics()) - { - game.Run(10.0); - } - } - } -} \ No newline at end of file diff --git a/Source/Examples/OpenGL/1.x/OpenGLDiagnostics.rtf b/Source/Examples/OpenGL/1.x/OpenGLDiagnostics.rtf deleted file mode 100644 index c97ed1b6..00000000 Binary files a/Source/Examples/OpenGL/1.x/OpenGLDiagnostics.rtf and /dev/null differ diff --git a/Source/Examples/OpenGL/1.x/Picking.cs b/Source/Examples/OpenGL/1.x/Picking.cs deleted file mode 100644 index deb28812..00000000 --- a/Source/Examples/OpenGL/1.x/Picking.cs +++ /dev/null @@ -1,323 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.IO; -using System.Drawing; -using System.Diagnostics; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; -using OpenTK.Input; - -using Examples.Shapes; - -namespace Examples.Tutorial -{ - /// - /// This demo shows over which triangle the cursor is, it does so by assigning all 3 vertices of a triangle the same Ids. - /// Each Id is a uint, split into 4 bytes and used as triangle color. In an extra pass, the screen is cleared to uint.MaxValue, - /// and then the mesh is drawn using color. Using GL.ReadPixels() the value under the mouse cursor is read and can be converted. - /// - [Example("Picking", ExampleCategory.OpenGL, "1.x", Documentation = "Picking")] - class Picking : GameWindow - { - int mouse_x, mouse_y; - - /// Creates a 800x600 window with the specified title. - public Picking() - : base(800, 600, GraphicsMode.Default, "Picking", GameWindowFlags.Default, DisplayDevice.Default, 1, 1, GraphicsContextFlags.Default) - { - VSync = VSyncMode.On; - - MouseMove += (sender, e) => - { - mouse_x = e.X; - mouse_y = e.Y; - }; - } - - struct Byte4 - { - public byte R, G, B, A; - - public Byte4(byte[] input) - { - R = input[0]; - G = input[1]; - B = input[2]; - A = input[3]; - } - - public uint ToUInt32() - { - byte[] temp = new byte[] { this.R, this.G, this.B, this.A }; - return BitConverter.ToUInt32(temp, 0); - } - - public override string ToString() - { - return this.R + ", " + this.G + ", " + this.B + ", " + this.A; - } - } - - struct Vertex - { - public Byte4 Color; // 4 bytes - public Vector3 Position; // 12 bytes - - public const byte SizeInBytes = 16; - } - - const TextureTarget Target = TextureTarget.TextureRectangleArb; - float angle; - PrimitiveType VBO_PrimMode; - Vertex[] VBO_Array; - uint VBO_Handle; - - uint SelectedTriangle; - - // int VertexShaderObject, FragmentShaderObject, ProgramObject; - - /// Load resources here. - /// Not used. - protected override void OnLoad(EventArgs e) - { - GL.Enable(EnableCap.DepthTest); - GL.Enable(EnableCap.CullFace); - - #region prepare data for VBO from procedural object - DrawableShape temp_obj = new SierpinskiTetrahedron(3f, SierpinskiTetrahedron.eSubdivisions.Five, false); - VertexT2fN3fV3f[] temp_VBO; - uint[] temp_IBO; - temp_obj.GetArraysforVBO(out VBO_PrimMode, out temp_VBO, out temp_IBO); - temp_obj.Dispose(); - if (temp_IBO != null) - throw new Exception("Expected data for GL.DrawArrays, but Element Array is not null."); - - // Convert from temp mesh to final object, copy position and add triangle Ids for the color attribute. - VBO_Array = new Vertex[temp_VBO.Length]; - int TriangleCounter = -1; - for (int i = 0; i < temp_VBO.Length; i++) - { - // Position - VBO_Array[i].Position = temp_VBO[i].Position; - - // Index - if (i % 3 == 0) - TriangleCounter++; - VBO_Array[i].Color = new Byte4(BitConverter.GetBytes(TriangleCounter)); - } - #endregion prepare data for VBO from procedural object - - #region Setup VBO for drawing - GL.GenBuffers(1, out VBO_Handle); - GL.BindBuffer(BufferTarget.ArrayBuffer, VBO_Handle); - GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(VBO_Array.Length * Vertex.SizeInBytes), VBO_Array, BufferUsageHint.StaticDraw); - GL.InterleavedArrays(InterleavedArrayFormat.C4ubV3f, 0, IntPtr.Zero); - - ErrorCode err = GL.GetError(); - if (err != ErrorCode.NoError) - Trace.WriteLine("VBO Setup failed (Error: " + err + "). Attempting to continue."); - #endregion Setup VBO for drawing - - #region Shader - /* - // Load&Compile Vertex Shader - - using (StreamReader sr = new StreamReader("Data/Shaders/Picking_VS.glsl")) - { - VertexShaderObject = GL.CreateShader(ShaderType.VertexShader); - GL.ShaderSource(VertexShaderObject, sr.ReadToEnd()); - GL.CompileShader(VertexShaderObject); - } - - err = GL.GetError(); - if (err != ErrorCode.NoError) - Trace.WriteLine("Vertex Shader: " + err); - - string LogInfo; - GL.GetShaderInfoLog(VertexShaderObject, out LogInfo); - if (LogInfo.Length > 0 && !LogInfo.Contains("hardware")) - Trace.WriteLine("Vertex Shader failed!\nLog:\n" + LogInfo); - else - Trace.WriteLine("Vertex Shader compiled without complaint."); - - // Load&Compile Fragment Shader - - using (StreamReader sr = new StreamReader("Data/Shaders/Picking_FS.glsl")) - { - FragmentShaderObject = GL.CreateShader(ShaderType.FragmentShader); - GL.ShaderSource(FragmentShaderObject, sr.ReadToEnd()); - GL.CompileShader(FragmentShaderObject); - } - GL.GetShaderInfoLog(FragmentShaderObject, out LogInfo); - - err = GL.GetError(); - if (err != ErrorCode.NoError) - Trace.WriteLine("Fragment Shader: " + err); - - if (LogInfo.Length > 0 && !LogInfo.Contains("hardware")) - Trace.WriteLine("Fragment Shader failed!\nLog:\n" + LogInfo); - else - Trace.WriteLine("Fragment Shader compiled without complaint."); - - // Link the Shaders to a usable Program - ProgramObject = GL.CreateProgram(); - GL.AttachShader(ProgramObject, VertexShaderObject); - GL.AttachShader(ProgramObject, FragmentShaderObject); - - // link it all together - GL.LinkProgram(ProgramObject); - - err = GL.GetError(); - if (err != ErrorCode.NoError) - Trace.WriteLine("LinkProgram: " + err); - - GL.UseProgram(ProgramObject); - - err = GL.GetError(); - if (err != ErrorCode.NoError) - Trace.WriteLine("UseProgram: " + err); - - // flag ShaderObjects for delete when not used anymore - GL.DeleteShader(VertexShaderObject); - GL.DeleteShader(FragmentShaderObject); - - int temp; - GL.GetProgram(ProgramObject, ProgramParameter.LinkStatus, out temp); - Trace.WriteLine("Linking Program (" + ProgramObject + ") " + ((temp == 1) ? "succeeded." : "FAILED!")); - if (temp != 1) - { - GL.GetProgramInfoLog(ProgramObject, out LogInfo); - Trace.WriteLine("Program Log:\n" + LogInfo); - } - - Trace.WriteLine("End of Shader build. GL Error: " + GL.GetError()); - - GL.UseProgram(0); -*/ - #endregion Shader - } - - protected override void OnUnload(EventArgs e) - { - GL.BindBuffer(BufferTarget.ArrayBuffer, 0); - GL.DeleteBuffers(1, ref VBO_Handle); - - base.OnUnload(e); - } - - /// - /// Called when your window is resized. Set your viewport here. It is also - /// a good place to set up your projection matrix (which probably changes - /// along when the aspect ratio of your window). - /// - /// Contains information on the new Width and Size of the GameWindow. - protected override void OnResize(EventArgs e) - { - GL.Viewport(ClientRectangle); - - Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, this.Width / (float)this.Height, 0.1f, 10.0f); - GL.MatrixMode(MatrixMode.Projection); - GL.LoadMatrix(ref projection); - } - - /// - /// Called when it is time to setup the next frame. Add you game logic here. - /// - /// Contains timing information for framerate independent logic. - protected override void OnUpdateFrame(FrameEventArgs e) - { - var keyboard = OpenTK.Input.Keyboard.GetState(); - if (keyboard[Key.Escape]) - Exit(); - } - - /// - /// Called when it is time to render the next frame. Add your rendering code here. - /// - /// Contains timing information. - protected override void OnRenderFrame(FrameEventArgs e) - { - GL.Color3(Color.White); - GL.EnableClientState(ArrayCap.ColorArray); - - #region Pass 1: Draw Object and pick Triangle - GL.ClearColor(1f, 1f, 1f, 1f); // clears to uint.MaxValue - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - Matrix4 modelview = Matrix4.LookAt(Vector3.UnitZ, Vector3.Zero, Vector3.UnitY); - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadMatrix(ref modelview); - GL.Translate(0f, 0f, -3f); - GL.Rotate(angle, Vector3.UnitX); - GL.Rotate(angle, Vector3.UnitY); - angle += (float)e.Time * 3.0f; - - // You may re-enable the shader, but it works perfectly without and will run on intel HW too - // GL.UseProgram(ProgramObject); - GL.DrawArrays(VBO_PrimMode, 0, VBO_Array.Length); - // GL.UseProgram(0); - - // Read Pixel under mouse cursor - Byte4 Pixel = new Byte4(); - GL.ReadPixels(mouse_x, this.Height - mouse_y, 1, 1, PixelFormat.Rgba, PixelType.UnsignedByte, ref Pixel); - SelectedTriangle = Pixel.ToUInt32(); - #endregion Pass 1: Draw Object and pick Triangle - - GL.Color3(Color.White); - GL.DisableClientState(ArrayCap.ColorArray); - - #region Pass 2: Draw Shape - if (SelectedTriangle == uint.MaxValue) - GL.ClearColor(.2f, .1f, .3f, 1f); // purple - else - GL.ClearColor(0f, .2f, .3f, 1f); // cyan - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - GL.Color3(1f, 1f, 1f); - GL.DrawArrays(VBO_PrimMode, 0, VBO_Array.Length); - - GL.PolygonMode(MaterialFace.Front, PolygonMode.Line); - GL.Color3(Color.Red); - GL.DrawArrays(VBO_PrimMode, 0, VBO_Array.Length); - GL.PolygonMode(MaterialFace.Front, PolygonMode.Fill); - - if (SelectedTriangle != uint.MaxValue) - { - GL.Disable(EnableCap.DepthTest); - GL.Color3(Color.Green); - GL.DrawArrays(VBO_PrimMode, (int)SelectedTriangle * 3, 3); - GL.Enable(EnableCap.DepthTest); - } - #endregion Pass 2: Draw Shape - - this.SwapBuffers(); - - ErrorCode err = GL.GetError(); - if (err != ErrorCode.NoError) - Trace.WriteLine("Error at Swapbuffers: " + err); - } - - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() - { - // The 'using' idiom guarantees proper resource cleanup. - // We request 30 UpdateFrame events per second, and unlimited - // RenderFrame events (as fast as the computer can handle). - using (Picking example = new Picking()) - { - // Get the title and category of this example using reflection. - ExampleAttribute info = ((ExampleAttribute)example.GetType().GetCustomAttributes(false)[0]); - example.Title = String.Format("OpenTK | {0} {1}: {2} (use the mouse to pick)", info.Category, info.Difficulty, info.Title); - example.Run(30.0); - } - } - } -} \ No newline at end of file diff --git a/Source/Examples/OpenGL/1.x/Picking.rtf b/Source/Examples/OpenGL/1.x/Picking.rtf deleted file mode 100644 index 763dd773..00000000 Binary files a/Source/Examples/OpenGL/1.x/Picking.rtf and /dev/null differ diff --git a/Source/Examples/OpenGL/1.x/StencilCSG.cs b/Source/Examples/OpenGL/1.x/StencilCSG.cs deleted file mode 100644 index 242be0d7..00000000 --- a/Source/Examples/OpenGL/1.x/StencilCSG.cs +++ /dev/null @@ -1,311 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Drawing; -using System.Drawing.Imaging; -using System.Diagnostics; - -using OpenTK; -using OpenTK.Input; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; - -using Examples.Shapes; - -namespace Examples.Tutorial -{ - - [Example("Stencil CSG", ExampleCategory.OpenGL, "1.x", Documentation = "StencilCSG")] - partial class StencilCSG : GameWindow - { - #region Model Related - DrawableShape OperandB; - DrawableShape OperandA; - float MySphereZOffset = 0f; - float MySphereXOffset = 0f; - - int Texture; - #endregion Model Related - - string WindowTitle; - bool ShowDebugWireFrame = true; - - float CameraZoom; - float CameraRotX; - float CameraRotY; - Vector3 EyePosition = new Vector3(0f, 0f, 15f); - - #region Window - public StencilCSG() - : base(800, 600, new GraphicsMode(new ColorFormat(8, 8, 8, 8), 24, 8)) // request 8-bit stencil buffer - { - base.VSync = VSyncMode.Off; - KeyDown += delegate(object sender, KeyboardKeyEventArgs e) - { - switch (e.Key) - { - case Key.Escape: this.Exit(); break; - case Key.Space: ShowDebugWireFrame = !ShowDebugWireFrame; break; - } - }; - } - - protected override void OnResize(EventArgs e) - { - GL.Viewport(0, 0, Width, Height); - GL.MatrixMode(MatrixMode.Projection); - Matrix4 p = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, Width / (float)Height, 0.1f, 64.0f); - GL.LoadMatrix(ref p); - } - #endregion Window - - protected override void OnLoad(EventArgs e) - { - #region Abort on platforms which will not be able to execute the ops properly - /* - if (!GL.SupportsExtension("VERSION_1_2")) - { - Trace.WriteLine("Aborting. OpenGL 1.2 or later required."); - this.Exit(); - } - - int[] t = new int[2]; - GL.GetInteger(GetPName.MajorVersion, out t[0]); - GL.GetInteger(GetPName.MinorVersion, out t[1]); - Trace.WriteLine("OpenGL Context Version: " + t[0] + "." + t[1]); - - GL.GetInteger(GetPName.DepthBits, out t[0]); - Trace.WriteLine("Depth Bits: " + t[0]); - GL.GetInteger(GetPName.StencilBits, out t[1]); - Trace.WriteLine("Stencil Bits: " + t[1]); - - if (t[0] < 16) - { - Trace.WriteLine("Aborting. Need at least 16 depth bits, only " + t[0] + " available."); - this.Exit(); - } - - if (t[1] < 1) - { - Trace.WriteLine("Aborting. Need at least 1 stencil bit, only " + t[1] + " available."); - this.Exit(); - } - */ - #endregion Abort on platforms which will not be able to execute the ops properly - - WindowTitle = "Cube-Sphere Stencil CSG " + GL.GetString(StringName.Renderer) + " (GL " + GL.GetString(StringName.Version) + ")"; - - #region GL States - GL.ClearColor(.08f, .12f, .16f, 1f); - - GL.Enable(EnableCap.DepthTest); - GL.DepthFunc(DepthFunction.Less); - GL.ClearDepth(1.0); - - GL.Enable(EnableCap.StencilTest); - GL.ClearStencil(0); - GL.StencilMask(0xFFFFFFFF); // read&write - - GL.Enable(EnableCap.CullFace); - GL.FrontFace(FrontFaceDirection.Ccw); - GL.CullFace(CullFaceMode.Back); - - GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill); - - GL.Color4(1f, 1f, 1f, 1f); - - GL.Enable(EnableCap.Lighting); - GL.Enable(EnableCap.Light0); - GL.ShadeModel(ShadingModel.Smooth); - - #endregion GL States - - #region Load Texture - Bitmap bitmap = new Bitmap("Data/Textures/logo-dark.jpg"); - bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY); - - GL.GenTextures(1, out Texture); - GL.BindTexture(TextureTarget.Texture2D, Texture); - - BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); - GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); - GL.Finish(); - bitmap.UnlockBits(data); - #endregion Load Texture - - OperandA = new ChamferCube(1.5, 2.0, 2.5, ChamferCube.SubDivs.Four, 0.42, true); - OperandB = new SlicedSphere(2.0f, Vector3d.Zero, - SlicedSphere.eSubdivisions.Three, - new SlicedSphere.eDir[] { SlicedSphere.eDir.All }, - true); - - #region Invert Operand B's Normals - // only the inside of the operand is ever drawn to color buffers and lighting requires this. - PrimitiveType tempPrimMode; - VertexT2dN3dV3d[] tempVertices; - uint[] tempIndices; - - OperandB.GetArraysforVBO(out tempPrimMode, out tempVertices, out tempIndices); - OperandB.Dispose(); - - for (int i = 0; i < tempVertices.Length; i++) - { - tempVertices[i].Normal *= -1.0; - tempVertices[i].Normal.Normalize(); - } - - OperandB = new VboShape(ref tempPrimMode, ref tempVertices, ref tempIndices, true); - #endregion Invert Operand B's Normals - } - - protected override void OnUnload(EventArgs e) - { - GL.DeleteTextures(1, ref Texture); - - OperandA.Dispose(); - OperandB.Dispose(); - - base.OnUnload(e); - } - - protected override void OnUpdateFrame(FrameEventArgs e) - { - var mouse = OpenTK.Input.Mouse.GetState(); - CameraRotX = -mouse.X * .5f; - CameraRotY = mouse.Y * .5f; - CameraZoom = mouse.Wheel * .2f; - } - - public void DrawOperandB() - { - GL.PushMatrix(); - GL.Translate(Math.Cos(MySphereXOffset), -1f, Math.Cos(MySphereZOffset)); - OperandB.Draw(); - GL.PopMatrix(); - } - - public void DrawOperandA() - { - GL.Enable(EnableCap.Texture2D); - OperandA.Draw(); - GL.Disable(EnableCap.Texture2D); - } - - public void RenderCsg() - { - // first pass - GL.Disable(EnableCap.StencilTest); - - GL.ColorMask(false, false, false, false); - GL.CullFace(CullFaceMode.Front); - DrawOperandB();// draw front-faces into depth buffer - - // use stencil plane to find parts of b in a - GL.DepthMask(false); - GL.Enable(EnableCap.StencilTest); - GL.StencilFunc(StencilFunction.Always, 0, 0); - - GL.StencilOp(StencilOp.Keep, StencilOp.Keep, StencilOp.Incr); - GL.CullFace(CullFaceMode.Back); - DrawOperandA(); // increment the stencil where the front face of a is drawn - - GL.StencilOp(StencilOp.Keep, StencilOp.Keep, StencilOp.Decr); - GL.CullFace(CullFaceMode.Front); - DrawOperandA(); // decrement the stencil buffer where the back face of a is drawn - - GL.DepthMask(true); - GL.Disable(EnableCap.DepthTest); - - GL.ColorMask(true, true, true, true); - GL.StencilFunc(StencilFunction.Notequal, 0, 1); - DrawOperandB(); // draw the part of b that's in a - - // fix depth - GL.ColorMask(false, false, false, false); - GL.Enable(EnableCap.DepthTest); - GL.Disable(EnableCap.StencilTest); - GL.DepthFunc(DepthFunction.Always); - DrawOperandA(); - GL.DepthFunc(DepthFunction.Less); - - // second pass - GL.CullFace(CullFaceMode.Back); - DrawOperandA(); - - GL.DepthMask(false); - GL.Enable(EnableCap.StencilTest); - - GL.StencilFunc(StencilFunction.Always, 0, 0); - GL.StencilOp(StencilOp.Keep, StencilOp.Keep, StencilOp.Incr); - DrawOperandB(); // increment the stencil where the front face of b is drawn - - GL.StencilOp(StencilOp.Keep, StencilOp.Keep, StencilOp.Decr); - GL.CullFace(CullFaceMode.Front); - DrawOperandB(); // decrement the stencil buffer where the back face of b is drawn - - GL.DepthMask(true); - GL.Disable(EnableCap.DepthTest); - - GL.ColorMask(true, true, true, true); - GL.StencilFunc(StencilFunction.Equal, 0, 1); - GL.CullFace(CullFaceMode.Back); - DrawOperandA(); // draw the part of a that's in b - - GL.Enable(EnableCap.DepthTest); - } - - protected override void OnRenderFrame(FrameEventArgs e) - { - this.Title = WindowTitle + " FPS: " + (1f / e.Time).ToString("0."); - - MySphereZOffset += (float)(e.Time * 3.1); - MySphereXOffset += (float)(e.Time * 4.2); - - #region Transform setup - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit | ClearBufferMask.StencilBufferBit); - - // Camera - GL.MatrixMode(MatrixMode.Modelview); - Matrix4 mv = Matrix4.LookAt(EyePosition, Vector3.Zero, Vector3.UnitY); - GL.LoadMatrix(ref mv); - - GL.Translate(0f, 0f, CameraZoom); - GL.Rotate(CameraRotX, Vector3.UnitY); - GL.Rotate(CameraRotY, Vector3.UnitX); - #endregion Transform setup - - RenderCsg(); - - // --------------------------------- - - if (ShowDebugWireFrame) - { - GL.Color3(System.Drawing.Color.LightGray); - GL.Disable(EnableCap.StencilTest); - GL.Disable(EnableCap.Lighting); - //GL.Disable( EnableCap.DepthTest ); - GL.PolygonMode(MaterialFace.Front, PolygonMode.Line); - DrawOperandB(); - GL.PolygonMode(MaterialFace.Front, PolygonMode.Fill); - GL.Enable(EnableCap.DepthTest); - GL.Enable(EnableCap.Lighting); - GL.Enable(EnableCap.StencilTest); - } - this.SwapBuffers(); - } - - [STAThread] - static void Main() - { - using (StencilCSG example = new StencilCSG()) - { - Utilities.SetWindowTitle(example); - example.Run(30.0, 0.0); - } - } - } -} diff --git a/Source/Examples/OpenGL/1.x/StencilCSG.rtf b/Source/Examples/OpenGL/1.x/StencilCSG.rtf deleted file mode 100644 index a60c31c8..00000000 Binary files a/Source/Examples/OpenGL/1.x/StencilCSG.rtf and /dev/null differ diff --git a/Source/Examples/OpenGL/1.x/TextRendering.cs b/Source/Examples/OpenGL/1.x/TextRendering.cs deleted file mode 100644 index 016ff54a..00000000 --- a/Source/Examples/OpenGL/1.x/TextRendering.cs +++ /dev/null @@ -1,265 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Text; -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; - -namespace Examples.Tutorial -{ - [Example("Text Rendering (2D)", ExampleCategory.OpenGL, "1.x", Documentation = "TextRendering")] - class TextRendering : GameWindow - { - TextRenderer renderer; - Font serif = new Font(FontFamily.GenericSerif, 24); - Font sans = new Font(FontFamily.GenericSansSerif, 24); - Font mono = new Font(FontFamily.GenericMonospace, 24); - - /// - /// Uses System.Drawing for 2d text rendering. - /// - public class TextRenderer : IDisposable - { - Bitmap bmp; - Graphics gfx; - int texture; - Rectangle dirty_region; - bool disposed; - - #region Constructors - - /// - /// Constructs a new instance. - /// - /// The width of the backing store in pixels. - /// The height of the backing store in pixels. - public TextRenderer(int width, int height) - { - if (width <= 0) - throw new ArgumentOutOfRangeException("width"); - if (height <= 0) - throw new ArgumentOutOfRangeException("height "); - if (GraphicsContext.CurrentContext == null) - throw new InvalidOperationException("No GraphicsContext is current on the calling thread."); - - bmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); - gfx = Graphics.FromImage(bmp); - gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; - - texture = GL.GenTexture(); - GL.BindTexture(TextureTarget.Texture2D, texture); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); - GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, width, height, 0, - PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero); - } - - #endregion - - #region Public Members - - /// - /// Clears the backing store to the specified color. - /// - /// A . - public void Clear(Color color) - { - gfx.Clear(color); - dirty_region = new Rectangle(0, 0, bmp.Width, bmp.Height); - } - - /// - /// Draws the specified string to the backing store. - /// - /// The to draw. - /// The that will be used. - /// The that will be used. - /// The location of the text on the backing store, in 2d pixel coordinates. - /// The origin (0, 0) lies at the top-left corner of the backing store. - public void DrawString(string text, Font font, Brush brush, PointF point) - { - gfx.DrawString(text, font, brush, point); - - SizeF size = gfx.MeasureString(text, font); - dirty_region = Rectangle.Round(RectangleF.Union(dirty_region, new RectangleF(point, size))); - dirty_region = Rectangle.Intersect(dirty_region, new Rectangle(0, 0, bmp.Width, bmp.Height)); - } - - /// - /// Gets a that represents an OpenGL 2d texture handle. - /// The texture contains a copy of the backing store. Bind this texture to TextureTarget.Texture2d - /// in order to render the drawn text on screen. - /// - public int Texture - { - get - { - UploadBitmap(); - return texture; - } - } - - #endregion - - #region Private Members - - // Uploads the dirty regions of the backing store to the OpenGL texture. - void UploadBitmap() - { - if (dirty_region != RectangleF.Empty) - { - System.Drawing.Imaging.BitmapData data = bmp.LockBits(dirty_region, - System.Drawing.Imaging.ImageLockMode.ReadOnly, - System.Drawing.Imaging.PixelFormat.Format32bppArgb); - - GL.BindTexture(TextureTarget.Texture2D, texture); - GL.TexSubImage2D(TextureTarget.Texture2D, 0, - dirty_region.X, dirty_region.Y, dirty_region.Width, dirty_region.Height, - PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0); - - bmp.UnlockBits(data); - - dirty_region = Rectangle.Empty; - } - } - - #endregion - - #region IDisposable Members - - void Dispose(bool manual) - { - if (!disposed) - { - if (manual) - { - bmp.Dispose(); - gfx.Dispose(); - if (GraphicsContext.CurrentContext != null) - GL.DeleteTexture(texture); - } - - disposed = true; - } - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - ~TextRenderer() - { - Console.WriteLine("[Warning] Resource leaked: {0}.", typeof(TextRenderer)); - } - - #endregion - } - - #region Constructor - - public TextRendering() - : base(800, 600) - { - } - - #endregion - - #region OnLoad - - protected override void OnLoad(EventArgs e) - { - renderer = new TextRenderer(Width, Height); - PointF position = PointF.Empty; - - renderer.Clear(Color.MidnightBlue); - renderer.DrawString("The quick brown fox jumps over the lazy dog", serif, Brushes.White, position); - position.Y += serif.Height; - renderer.DrawString("The quick brown fox jumps over the lazy dog", sans, Brushes.White, position); - position.Y += sans.Height; - renderer.DrawString("The quick brown fox jumps over the lazy dog", mono, Brushes.White, position); - position.Y += mono.Height; - } - - #endregion - - #region OnUnload - - protected override void OnUnload(EventArgs e) - { - renderer.Dispose(); - } - - #endregion - - #region OnResize - - protected override void OnResize(EventArgs e) - { - GL.Viewport(ClientRectangle); - - GL.MatrixMode(MatrixMode.Projection); - GL.LoadIdentity(); - GL.Ortho(-1.0, 1.0, -1.0, 1.0, 0.0, 4.0); - } - - #endregion - - #region OnUpdateFrame - - protected override void OnUpdateFrame(FrameEventArgs e) - { - var keyboard = OpenTK.Input.Keyboard.GetState(); - if (keyboard[OpenTK.Input.Key.Escape]) - { - this.Exit(); - } - } - - #endregion - - #region OnRenderFrame - - protected override void OnRenderFrame(FrameEventArgs e) - { - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadIdentity(); - - GL.Enable(EnableCap.Texture2D); - GL.BindTexture(TextureTarget.Texture2D, renderer.Texture); - GL.Begin(PrimitiveType.Quads); - - GL.TexCoord2(0.0f, 1.0f); GL.Vertex2(-1f, -1f); - GL.TexCoord2(1.0f, 1.0f); GL.Vertex2(1f, -1f); - GL.TexCoord2(1.0f, 0.0f); GL.Vertex2(1f, 1f); - GL.TexCoord2(0.0f, 0.0f); GL.Vertex2(-1f, 1f); - - GL.End(); - - SwapBuffers(); - } - - #endregion - - #region Main - - public static void Main() - { - using (TextRendering example = new TextRendering()) - { - Utilities.SetWindowTitle(example); - example.Run(30.0); - } - } - - #endregion - } -} diff --git a/Source/Examples/OpenGL/1.x/TextRendering.rtf b/Source/Examples/OpenGL/1.x/TextRendering.rtf deleted file mode 100644 index bcd19623..00000000 Binary files a/Source/Examples/OpenGL/1.x/TextRendering.rtf and /dev/null differ diff --git a/Source/Examples/OpenGL/1.x/TextureMatrix.cs b/Source/Examples/OpenGL/1.x/TextureMatrix.cs deleted file mode 100644 index 6b5c6d11..00000000 --- a/Source/Examples/OpenGL/1.x/TextureMatrix.cs +++ /dev/null @@ -1,175 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Drawing; -using System.Drawing.Imaging; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; -using OpenTK.Input; - -namespace Examples.Tutorial -{ - - [Example("Texture Matrix Wormhole", ExampleCategory.OpenGL, "1.x", Documentation = "TextureMatrix")] - - class TextureMatrix : GameWindow - { - Vector2 orientation; - - public TextureMatrix() - : base(800, 600, new GraphicsMode(32, 16, 0, 4)) - { - VSync = VSyncMode.On; - } - - int Texture; - int list; - - protected override void OnLoad(EventArgs e) - { - GL.ClearColor(0f, 0f, 0f, 0f); - GL.Enable(EnableCap.DepthTest); - GL.Enable(EnableCap.CullFace); - - Texture = LoadTexture("Data/Textures/logo-dark.jpg"); - - GL.Enable(EnableCap.Texture2D); - - list = GL.GenLists(1); - - GL.NewList(list, ListMode.Compile); - { - const int slices = 32; - const float distance = 0.25f; - - GL.Begin(PrimitiveType.Quads); - - for (float scale = 0.26f; scale < 5f; scale += distance) - for (int i = 0; i < slices; i++) - { - Vector3 MiddleCenter = new Vector3((float)(Math.Sin((double)i / slices * 2 * Math.PI) * scale), - (float)(Math.Cos((double)i / slices * 2 * Math.PI) * scale), - (float)(1f / scale)); - Vector3 MiddleRight = new Vector3((float)(Math.Sin((double)(i + 1) / slices * 2 * Math.PI) * scale), - (float)(Math.Cos((double)(i + 1) / slices * 2 * Math.PI) * scale), - (float)(1f / scale)); - Vector3 BottomRight = new Vector3((float)(Math.Sin((double)(i + 1) / slices * 2 * Math.PI) * (scale - distance)), - (float)(Math.Cos((double)(i + 1) / slices * 2 * Math.PI) * (scale - distance)), - (float)(1f / (scale - distance))); - Vector3 BottomCenter = new Vector3((float)(Math.Sin((double)i / slices * 2 * Math.PI) * (scale - distance)), - (float)(Math.Cos((double)i / slices * 2 * Math.PI) * (scale - distance)), - (float)(1f / (scale - distance))); - - GL.TexCoord2(1f, 0f); - GL.Vertex3(MiddleCenter); - GL.TexCoord2(0f, 0f); - GL.Vertex3(MiddleRight); - GL.TexCoord2(0f, 1f); - GL.Vertex3(BottomRight); - GL.TexCoord2(1f, 1f); - GL.Vertex3(BottomCenter); - } - - GL.End(); - } - GL.EndList(); - } - - protected override void OnResize(EventArgs e) - { - GL.Viewport(this.ClientRectangle); - - Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, Width / (float)Height, 1.0f, 50.0f); - GL.MatrixMode(MatrixMode.Projection); - GL.LoadMatrix(ref projection); - } - - protected override void OnUpdateFrame(FrameEventArgs e) - { - var keyboard = OpenTK.Input.Keyboard.GetState(); - if (keyboard[Key.Escape]) - Exit(); - - var mouse = OpenTK.Input.Mouse.GetState(); - orientation = new Vector2(mouse.X, mouse.Y); - } - - protected override void OnRenderFrame(FrameEventArgs e) - { - GL.Clear(ClearBufferMask.ColorBufferBit | - ClearBufferMask.DepthBufferBit); - - GL.MatrixMode(MatrixMode.Texture); - GL.Translate(e.Time / 2, -e.Time, 0f); - - Matrix4 modelview = Matrix4.LookAt(Vector3.Zero, Vector3.UnitZ, Vector3.UnitY); - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadMatrix(ref modelview); - - GL.Translate(0f, 0f, 1.5f); - - GL.Rotate(orientation.X, Vector3.UnitY); - GL.Rotate(orientation.Y, Vector3.UnitX); - - GL.BindTexture(TextureTarget.Texture2D, Texture); - GL.CallList(list); - - SwapBuffers(); - } - - public static int LoadTexture(string filename) - { - TextureTarget Target = TextureTarget.Texture2D; - - int texture; - GL.GenTextures(1, out texture); - GL.BindTexture(Target, texture); - - Version version = new Version(GL.GetString(StringName.Version).Substring(0, 3)); - Version target = new Version(1, 4); - if (version >= target) - { - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.GenerateMipmap, (int)All.True); - GL.TexParameter(Target, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear); - } - else - { - GL.TexParameter(Target, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); - } - GL.TexParameter(Target, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); - - GL.TexParameter(Target, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat); - GL.TexParameter(Target, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat); - - Bitmap bitmap = new Bitmap(filename); - BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); - GL.TexImage2D(Target, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0); - GL.Finish(); - bitmap.UnlockBits(data); - - if (GL.GetError() != ErrorCode.NoError) - throw new Exception("Error loading texture " + filename); - - return texture; - } - - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() - { - using (TextureMatrix example = new TextureMatrix()) - { - // Get the title and category of this example using reflection. - ExampleAttribute info = ((ExampleAttribute)example.GetType().GetCustomAttributes(false)[0]); - example.Title = String.Format("OpenTK | {0} {1}: {2}", info.Category, info.Difficulty, info.Title); - example.Run(30.0, 0.0); - } - } - } -} \ No newline at end of file diff --git a/Source/Examples/OpenGL/1.x/TextureMatrix.rtf b/Source/Examples/OpenGL/1.x/TextureMatrix.rtf deleted file mode 100644 index c2621c0d..00000000 Binary files a/Source/Examples/OpenGL/1.x/TextureMatrix.rtf and /dev/null differ diff --git a/Source/Examples/OpenGL/1.x/Textures.cs b/Source/Examples/OpenGL/1.x/Textures.cs deleted file mode 100644 index edfc85c0..00000000 --- a/Source/Examples/OpenGL/1.x/Textures.cs +++ /dev/null @@ -1,151 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Collections.Generic; -using System.Text; -using System.Diagnostics; -using System.IO; - -using System.Drawing; -using System.Drawing.Imaging; - -using OpenTK; -using OpenTK.Graphics.OpenGL; -using OpenTK.Graphics; - -namespace Examples.Tutorial -{ - /// - /// Demonstrates simple OpenGL Texturing. - /// - [Example("Texture mapping", ExampleCategory.OpenGL, "1.x", 5, Documentation = "Textures")] - public class Textures : GameWindow - { - Bitmap bitmap = new Bitmap("Data/Textures/logo.jpg"); - int texture; - - public Textures() : base(800, 600) { } - - #region OnLoad - - /// - /// Setup OpenGL and load resources here. - /// - /// Not used. - protected override void OnLoad(EventArgs e) - { - GL.ClearColor(Color.MidnightBlue); - GL.Enable(EnableCap.Texture2D); - - GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest); - - GL.GenTextures(1, out texture); - GL.BindTexture(TextureTarget.Texture2D, texture); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); - - BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), - ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); - - GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0, - OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0); - - bitmap.UnlockBits(data); - } - - #endregion - - #region OnUnload - - protected override void OnUnload(EventArgs e) - { - GL.DeleteTextures(1, ref texture); - } - - #endregion - - #region OnResize - - /// - /// Respond to resize events here. - /// - /// Contains information on the new GameWindow size. - /// There is no need to call the base implementation. - protected override void OnResize(EventArgs e) - { - GL.Viewport(0, 0, Width, Height); - - GL.MatrixMode(MatrixMode.Projection); - GL.LoadIdentity(); - GL.Ortho(-1.0, 1.0, -1.0, 1.0, 0.0, 4.0); - } - - #endregion - - #region OnUpdateFrame - - /// - /// Add your game logic here. - /// - /// Contains timing information. - /// There is no need to call the base implementation. - protected override void OnUpdateFrame(FrameEventArgs e) - { - var keyboard = OpenTK.Input.Keyboard.GetState(); - if (keyboard[OpenTK.Input.Key.Escape]) - this.Exit(); - } - - #endregion - - #region OnRenderFrame - - /// - /// Add your game rendering code here. - /// - /// Contains timing information. - /// There is no need to call the base implementation. - protected override void OnRenderFrame(FrameEventArgs e) - { - GL.Clear(ClearBufferMask.ColorBufferBit); - - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadIdentity(); - GL.BindTexture(TextureTarget.Texture2D, texture); - - GL.Begin(PrimitiveType.Quads); - - GL.TexCoord2(0.0f, 1.0f); GL.Vertex2(-0.6f, -0.4f); - GL.TexCoord2(1.0f, 1.0f); GL.Vertex2(0.6f, -0.4f); - GL.TexCoord2(1.0f, 0.0f); GL.Vertex2(0.6f, 0.4f); - GL.TexCoord2(0.0f, 0.0f); GL.Vertex2(-0.6f, 0.4f); - - GL.End(); - - SwapBuffers(); - } - - #endregion - - #region public static void Main() - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - using (Textures example = new Textures()) - { - // Get the title and category of this example using reflection. - ExampleAttribute info = ((ExampleAttribute)typeof(Textures).GetCustomAttributes(false)[0]); - example.Title = String.Format("OpenTK | {0} {1}: {2}", info.Category, info.Difficulty, info.Title); - example.Run(30.0, 0.0); - } - } - - #endregion - } -} diff --git a/Source/Examples/OpenGL/1.x/Textures.rtf b/Source/Examples/OpenGL/1.x/Textures.rtf deleted file mode 100644 index 38351156..00000000 Binary files a/Source/Examples/OpenGL/1.x/Textures.rtf and /dev/null differ diff --git a/Source/Examples/OpenGL/1.x/VBODynamic.cs b/Source/Examples/OpenGL/1.x/VBODynamic.cs deleted file mode 100644 index 3b0fc0b0..00000000 --- a/Source/Examples/OpenGL/1.x/VBODynamic.cs +++ /dev/null @@ -1,212 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; -using OpenTK.Input; - -namespace Examples.Tutorial -{ - - [Example("VBO Dynamic", ExampleCategory.OpenGL, "1.x", 4, Documentation = "VBODynamic")] - class T09_VBO_Dynamic : GameWindow - { - /// Creates a 800x600 window with the specified title. - public T09_VBO_Dynamic() - : base(800, 600) - { - this.VSync = VSyncMode.Off; - } - - #region Particles - static int MaxParticleCount = 2000; - int VisibleParticleCount; - VertexC4ubV3f[] VBO = new VertexC4ubV3f[MaxParticleCount]; - ParticleAttribut[] ParticleAttributes = new ParticleAttribut[MaxParticleCount]; - - // this struct is used for drawing - struct VertexC4ubV3f - { - public byte R, G, B, A; - public Vector3 Position; - - public static int SizeInBytes = 16; - } - - // this struct is used for updates - struct ParticleAttribut - { - public Vector3 Direction; - public uint Age; - // more stuff could be here: Rotation, Radius, whatever - } - - uint VBOHandle; - #endregion Particles - - /// Load resources here. - /// Not used. - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - Version version = new Version(GL.GetString(StringName.Version).Substring(0, 3)); - Version target = new Version(1, 5); - if (version < target) - { - throw new NotSupportedException(String.Format( - "OpenGL {0} is required (you only have {1}).", target, version)); - } - - GL.ClearColor(.1f, 0f, .1f, 0f); - GL.Enable(EnableCap.DepthTest); - - // Setup parameters for Points - GL.PointSize(5f); - GL.Enable(EnableCap.PointSmooth); - GL.Hint(HintTarget.PointSmoothHint, HintMode.Nicest); - - // Setup VBO state - GL.EnableClientState(ArrayCap.ColorArray); - GL.EnableClientState(ArrayCap.VertexArray); - - GL.GenBuffers(1, out VBOHandle); - - // Since there's only 1 VBO in the app, might aswell setup here. - GL.BindBuffer(BufferTarget.ArrayBuffer, VBOHandle); - GL.ColorPointer(4, ColorPointerType.UnsignedByte, VertexC4ubV3f.SizeInBytes, (IntPtr)0); - GL.VertexPointer(3, VertexPointerType.Float, VertexC4ubV3f.SizeInBytes, (IntPtr)(4 * sizeof(byte))); - - Random rnd = new Random(); - Vector3 temp = Vector3.Zero; - - // generate some random stuff for the particle system - for (uint i = 0; i < MaxParticleCount; i++) - { - VBO[i].R = (byte)rnd.Next(0, 256); - VBO[i].G = (byte)rnd.Next(0, 256); - VBO[i].B = (byte)rnd.Next(0, 256); - VBO[i].A = (byte)rnd.Next(0, 256); // isn't actually used - VBO[i].Position = Vector3.Zero; // all particles are born at the origin - - // generate direction vector in the range [-0.25f...+0.25f] - // that's slow enough so you can see particles 'disappear' when they are respawned - temp.X = (float)((rnd.NextDouble() - 0.5) * 0.5f); - temp.Y = (float)((rnd.NextDouble() - 0.5) * 0.5f); - temp.Z = (float)((rnd.NextDouble() - 0.5) * 0.5f); - ParticleAttributes[i].Direction = temp; // copy - ParticleAttributes[i].Age = 0; - } - - VisibleParticleCount = 0; - - } - - protected override void OnUnload(EventArgs e) - { - GL.DeleteBuffers(1, ref VBOHandle); - } - - /// - /// Called when your window is resized. Set your viewport here. It is also - /// a good place to set up your projection matrix (which probably changes - /// along when the aspect ratio of your window). - /// - /// Contains information on the new Width and Size of the GameWindow. - protected override void OnResize(EventArgs e) - { - GL.Viewport(0, 0, Width, Height); - - GL.MatrixMode(MatrixMode.Projection); - Matrix4 p = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, Width / (float)Height, 0.1f, 50.0f); - GL.LoadMatrix(ref p); - - GL.MatrixMode(MatrixMode.Modelview); - Matrix4 mv = Matrix4.LookAt(Vector3.UnitZ, Vector3.Zero, Vector3.UnitY); - GL.LoadMatrix(ref mv); - } - - /// - /// Called when it is time to setup the next frame. Add you game logic here. - /// - /// Contains timing information for framerate independent logic. - protected override void OnUpdateFrame(FrameEventArgs e) - { - var keyboard = OpenTK.Input.Keyboard.GetState(); - if (keyboard[Key.Escape]) - { - Exit(); - } - - // will update particles here. When using a Physics SDK, it's update rate is much higher than - // the framerate and it would be a waste of cycles copying to the VBO more often than drawing it. - if (VisibleParticleCount < MaxParticleCount) - VisibleParticleCount++; - - Vector3 temp; - - for (int i = MaxParticleCount - VisibleParticleCount; i < MaxParticleCount; i++) - { - if (ParticleAttributes[i].Age >= MaxParticleCount) - { - // reset particle - ParticleAttributes[i].Age = 0; - VBO[i].Position = Vector3.Zero; - } - else - { - ParticleAttributes[i].Age += (uint)Math.Max(ParticleAttributes[i].Direction.LengthFast * 10, 1); - Vector3.Multiply(ref ParticleAttributes[i].Direction, (float)e.Time, out temp); - Vector3.Add(ref VBO[i].Position, ref temp, out VBO[i].Position); - } - } - } - - /// - /// Called when it is time to render the next frame. Add your rendering code here. - /// - /// Contains timing information. - protected override void OnRenderFrame(FrameEventArgs e) - { - this.Title = VisibleParticleCount + " Points. FPS: " + string.Format("{0:F}", 1.0 / e.Time); - - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - GL.PushMatrix(); - - GL.Translate(0f, 0f, -5f); - - // Tell OpenGL to discard old VBO when done drawing it and reserve memory _now_ for a new buffer. - // without this, GL would wait until draw operations on old VBO are complete before writing to it - GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(VertexC4ubV3f.SizeInBytes * MaxParticleCount), IntPtr.Zero, BufferUsageHint.StreamDraw); - // Fill newly allocated buffer - GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(VertexC4ubV3f.SizeInBytes * MaxParticleCount), VBO, BufferUsageHint.StreamDraw); - // Only draw particles that are alive - GL.DrawArrays(PrimitiveType.Points, MaxParticleCount - VisibleParticleCount, VisibleParticleCount); - - GL.PopMatrix(); - - SwapBuffers(); - } - - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() - { - // The 'using' idiom guarantees proper resource cleanup. - // We request 30 UpdateFrame events per second, and unlimited - // RenderFrame events (as fast as the computer can handle). - using (T09_VBO_Dynamic example = new T09_VBO_Dynamic()) - { - Utilities.SetWindowTitle(example); - example.Run(60.0, 0.0); - } - } - } -} \ No newline at end of file diff --git a/Source/Examples/OpenGL/1.x/VBODynamic.rtf b/Source/Examples/OpenGL/1.x/VBODynamic.rtf deleted file mode 100644 index c44774a2..00000000 Binary files a/Source/Examples/OpenGL/1.x/VBODynamic.rtf and /dev/null differ diff --git a/Source/Examples/OpenGL/1.x/VBOStatic.cs b/Source/Examples/OpenGL/1.x/VBOStatic.cs deleted file mode 100644 index 0ae2ea0b..00000000 --- a/Source/Examples/OpenGL/1.x/VBOStatic.cs +++ /dev/null @@ -1,178 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -#region --- Using directives --- - -using System; -using System.Collections.Generic; -using System.Text; -using System.Runtime.InteropServices; -using System.Threading; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; -using OpenTK.Platform; -using System.Drawing; - -#endregion - -namespace Examples.Tutorial -{ - [Example("VBO Static", ExampleCategory.OpenGL, "1.x", 3, Documentation = "VBOStatic")] - public class T08_VBO : GameWindow - { - const float rotation_speed = 180.0f; - float angle; - - struct Vbo { public int VboID, EboID, NumElements; } - Vbo[] vbo = new Vbo[2]; - - VertexPositionColor[] CubeVertices = new VertexPositionColor[] - { - new VertexPositionColor(-1.0f, -1.0f, 1.0f, Color.DarkRed), - new VertexPositionColor( 1.0f, -1.0f, 1.0f, Color.DarkRed), - new VertexPositionColor( 1.0f, 1.0f, 1.0f, Color.Gold), - new VertexPositionColor(-1.0f, 1.0f, 1.0f, Color.Gold), - new VertexPositionColor(-1.0f, -1.0f, -1.0f, Color.DarkRed), - new VertexPositionColor( 1.0f, -1.0f, -1.0f, Color.DarkRed), - new VertexPositionColor( 1.0f, 1.0f, -1.0f, Color.Gold), - new VertexPositionColor(-1.0f, 1.0f, -1.0f, Color.Gold) - }; - - readonly short[] CubeElements = new short[] - { - 0, 1, 2, 2, 3, 0, // front face - 3, 2, 6, 6, 7, 3, // top face - 7, 6, 5, 5, 4, 7, // back face - 4, 0, 3, 3, 7, 4, // left face - 0, 1, 5, 5, 4, 0, // bottom face - 1, 5, 6, 6, 2, 1, // right face - }; - - public T08_VBO() : base(800, 600) { } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - Version version = new Version(GL.GetString(StringName.Version).Substring(0, 3)); - Version target = new Version(1, 5); - if (version < target) - { - throw new NotSupportedException(String.Format( - "OpenGL {0} is required (you only have {1}).", target, version)); - } - - GL.ClearColor(System.Drawing.Color.MidnightBlue); - GL.Enable(EnableCap.DepthTest); - - vbo[0] = LoadVBO(CubeVertices, CubeElements); - vbo[1] = LoadVBO(CubeVertices, CubeElements); - } - - protected override void OnResize(EventArgs e) - { - base.OnResize(e); - - GL.Viewport(0, 0, Width, Height); - - float aspect_ratio = Width / (float)Height; - Matrix4 perpective = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspect_ratio, 1, 64); - GL.MatrixMode(MatrixMode.Projection); - GL.LoadMatrix(ref perpective); - } - - protected override void OnUpdateFrame(FrameEventArgs e) - { - base.OnUpdateFrame(e); - - var keyboard = OpenTK.Input.Keyboard.GetState(); - if (keyboard[OpenTK.Input.Key.Escape]) - this.Exit(); - } - - protected override void OnRenderFrame(FrameEventArgs e) - { - base.OnRenderFrame(e); - - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - Matrix4 lookat = Matrix4.LookAt(0, 5, 5, 0, 0, 0, 0, 1, 0); - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadMatrix(ref lookat); - - angle += rotation_speed * (float)e.Time; - GL.Rotate(angle, 0.0f, 1.0f, 0.0f); - - Draw(vbo[0]); - - SwapBuffers(); - } - - Vbo LoadVBO(TVertex[] vertices, short[] elements) where TVertex : struct - { - Vbo handle = new Vbo(); - int size; - - // To create a VBO: - // 1) Generate the buffer handles for the vertex and element buffers. - // 2) Bind the vertex buffer handle and upload your vertex data. Check that the buffer was uploaded correctly. - // 3) Bind the element buffer handle and upload your element data. Check that the buffer was uploaded correctly. - - GL.GenBuffers(1, out handle.VboID); - GL.BindBuffer(BufferTarget.ArrayBuffer, handle.VboID); - GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vertices.Length * BlittableValueType.StrideOf(vertices)), vertices, - BufferUsageHint.StaticDraw); - GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out size); - if (vertices.Length * BlittableValueType.StrideOf(vertices) != size) - throw new ApplicationException("Vertex data not uploaded correctly"); - - GL.GenBuffers(1, out handle.EboID); - GL.BindBuffer(BufferTarget.ElementArrayBuffer, handle.EboID); - GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(elements.Length * sizeof(short)), elements, - BufferUsageHint.StaticDraw); - GL.GetBufferParameter(BufferTarget.ElementArrayBuffer, BufferParameterName.BufferSize, out size); - if (elements.Length * sizeof(short) != size) - throw new ApplicationException("Element data not uploaded correctly"); - - handle.NumElements = elements.Length; - return handle; - } - - void Draw(Vbo handle) - { - // To draw a VBO: - // 1) Ensure that the VertexArray client state is enabled. - // 2) Bind the vertex and element buffer handles. - // 3) Set up the data pointers (vertex, normal, color) according to your vertex format. - // 4) Call DrawElements. (Note: the last parameter is an offset into the element buffer - // and will usually be IntPtr.Zero). - - GL.EnableClientState(ArrayCap.ColorArray); - GL.EnableClientState(ArrayCap.VertexArray); - - GL.BindBuffer(BufferTarget.ArrayBuffer, handle.VboID); - GL.BindBuffer(BufferTarget.ElementArrayBuffer, handle.EboID); - - GL.VertexPointer(3, VertexPointerType.Float, BlittableValueType.StrideOf(CubeVertices), new IntPtr(0)); - GL.ColorPointer(4, ColorPointerType.UnsignedByte, BlittableValueType.StrideOf(CubeVertices), new IntPtr(12)); - - GL.DrawElements(PrimitiveType.Triangles, handle.NumElements, DrawElementsType.UnsignedShort, IntPtr.Zero); - } - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - using (T08_VBO example = new T08_VBO()) - { - Utilities.SetWindowTitle(example); - example.Run(30.0, 0.0); - } - } - } -} diff --git a/Source/Examples/OpenGL/1.x/VBOStatic.rtf b/Source/Examples/OpenGL/1.x/VBOStatic.rtf deleted file mode 100644 index 12f3488c..00000000 Binary files a/Source/Examples/OpenGL/1.x/VBOStatic.rtf and /dev/null differ diff --git a/Source/Examples/OpenGL/1.x/VertexArrays.cs b/Source/Examples/OpenGL/1.x/VertexArrays.cs deleted file mode 100644 index 4fe29c88..00000000 --- a/Source/Examples/OpenGL/1.x/VertexArrays.cs +++ /dev/null @@ -1,205 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; -using System.Threading; - -using OpenTK; -using System.Diagnostics; -using OpenTK.Input; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; - -namespace Examples.Tutorial -{ - /// - /// Demonstrates Vertex Arrays (in system memory). Example is incomplete (documentation). - /// Broken since release 0.3.12. - /// - [Example("Vertex Arrays", ExampleCategory.OpenGL, "1.x", 5, false)] - class T02_Vertex_Arrays : GameWindow - { - float rotation_speed = 3.0f; - float angle = 0.0f; - - Shapes.Shape shape = new Examples.Shapes.Plane(16, 16, 2.0f, 2.0f); - //TextureFont sans = new TextureFont(new Font(FontFamily.GenericSansSerif, 32, FontStyle.Regular, - // GraphicsUnit.Pixel)); - - #region Constructor - - public T02_Vertex_Arrays() - : base(800, 600) - { - //this.VSync = VSyncMode.On; - KeyUp += Keyboard_KeyUp; - } - - void Keyboard_KeyUp(object sender, KeyboardKeyEventArgs e) - { - // F4 cycles between available VSync modes. - if (e.Key == Key.F4) - { - if (this.VSync == VSyncMode.Off) - this.VSync = VSyncMode.On; - else if (this.VSync == VSyncMode.On) - this.VSync = VSyncMode.Adaptive; - else - this.VSync = VSyncMode.Off; - } - } - - #endregion - - #region OnLoad - - protected override void OnLoad(EventArgs e) - { - GL.Enable(EnableCap.Texture2D); - - GL.ClearColor(Color.CadetBlue); - GL.Enable(EnableCap.DepthTest); - - GL.EnableClientState(ArrayCap.VertexArray); - //GL.EnableClientState(GL.Enums.EnableCap.COLOR_ARRAY); - GL.VertexPointer(3, VertexPointerType.Float, 0, shape.Vertices); - //GL.ColorPointer(4, GL.Enums.ColorPointerType.UNSIGNED_BYTE, 0, shape.Colors); - } - - #endregion - - #region OnResize - - /// - /// Called when the user resizes the window. - /// - /// Contains the new width/height of the window. - /// - /// You want the OpenGL viewport to match the window. This is the place to do it! - /// - protected override void OnResize(EventArgs e) - { - base.OnResize(e); - - GL.Viewport(0, 0, Width, Height); - - double aspect_ratio = Width / (double)Height; - - OpenTK.Matrix4 perspective = OpenTK.Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, (float)aspect_ratio, 1, 64); - GL.MatrixMode(MatrixMode.Projection); - GL.LoadMatrix(ref perspective); - } - - #endregion - - #region OnUpdateFrame - - /// - /// Prepares the next frame for rendering. - /// - /// - /// Place your control logic here. This is the place to respond to user input, - /// update object positions etc. - /// - protected override void OnUpdateFrame(FrameEventArgs e) - { - var keyboard = OpenTK.Input.Keyboard.GetState(); - - if (keyboard[Key.Escape]) - { - this.Exit(); - return; - } - - if (keyboard[Key.F11]) - if (WindowState != WindowState.Fullscreen) - WindowState = WindowState.Fullscreen; - else - WindowState = WindowState.Normal; - - // Plus/Minus change the target render frequency. - // PageUp/PageDown change the target update frequency. - if (keyboard[Key.Plus] || keyboard[Key.KeypadAdd]) TargetRenderFrequency++; - if (keyboard[Key.Minus] || keyboard[Key.KeypadSubtract]) TargetRenderFrequency--; - if (keyboard[Key.PageUp]) TargetUpdateFrequency++; - if (keyboard[Key.PageDown]) TargetUpdateFrequency--; - - // Right/Left control the rotation speed and direction. - if (keyboard[Key.Right]) rotation_speed += 0.5f; - if (keyboard[Key.Left]) rotation_speed -= 0.5f; - } - - #endregion - - #region OnRenderFrame - - /// - /// Place your rendering code here. - /// - protected override void OnRenderFrame(FrameEventArgs e) - { - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - Matrix4 lookat = Matrix4.LookAt(0, 5, 5, 0, 0, 0, 0, 1, 0); - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadMatrix(ref lookat); - - angle += rotation_speed * (float)e.Time; - - if (angle >= 360.0f) - angle -= 360.0f; - GL.Rotate(angle, 0.0f, 1.0f, 0.0f); - - GL.DrawElements(PrimitiveType.Triangles, shape.Indices.Length, - DrawElementsType.UnsignedInt, shape.Indices); - - //GL.Begin(GL.Enums.BeginMode.TRIANGLES); - - //GL.Vertex3(-1.0, -1.0, 5.0); - //GL.Vertex3(1.0, -1.0, 5.0); - //GL.Vertex3(1.0, 1.0, 5.0); - - //GL.End(); - - GL.PushMatrix(); - - GL.MatrixMode(MatrixMode.Projection); - GL.LoadIdentity(); - GL.Ortho(-1.0, 1.0, -1.0, 1.0, 0.0, 1.0); - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadIdentity(); - - //GL.Translate(0.7f, 1.0f, 0.0f); - //sans.Print(String.format("{0:f1}", RenderFrequency)); - - GL.PopMatrix(); - - SwapBuffers(); - } - - #endregion - - #region public void Launch() - - /// - /// Launches this example. - /// - /// - /// Provides a simple way for the example launcher to launch the examples. - /// - public void Launch() - { - // Lock UpdateFrame rate at 30Hz and RenderFrame rate 85Hz. - //Run(60.0, 85.0); - Run(30.0, 85.0); - } - - #endregion - - public static readonly int order = 2; - } -} diff --git a/Source/Examples/OpenGL/1.x/VertexLighting.cs b/Source/Examples/OpenGL/1.x/VertexLighting.cs deleted file mode 100644 index 2b31bc94..00000000 --- a/Source/Examples/OpenGL/1.x/VertexLighting.cs +++ /dev/null @@ -1,181 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; - -using OpenTK; -using OpenTK.Graphics.OpenGL; -using Examples.Shapes; - -namespace Examples.Tutorial -{ - /// - /// Demonstrates fixed-function OpenGL lighting. Example is incomplete (documentation). - /// - [Example("Vertex Lighting", ExampleCategory.OpenGL, "1.x", false)] - public class T04_Vertex_Lighting : GameWindow - { - float x_angle, zoom; - Shape shape = new Plane(16, 16, 4.0f, 4.0f); - - #region Constructor - - public T04_Vertex_Lighting() : base(800, 600) - { - } - - #endregion - - #region OnLoad - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - GL.ClearColor(Color.MidnightBlue); - GL.Enable(EnableCap.DepthTest); - //GL.Enable(GL.Enums.EnableCap.CULL_FACE); - - GL.EnableClientState(ArrayCap.VertexArray); - GL.EnableClientState(ArrayCap.NormalArray); - GL.VertexPointer(3, VertexPointerType.Float, 0, shape.Vertices); - GL.NormalPointer(NormalPointerType.Float, 0, shape.Normals); - - // Enable Light 0 and set its parameters. - GL.Light(LightName.Light0, LightParameter.Position, new float[] { 1.0f, 1.0f, -0.5f }); - GL.Light(LightName.Light0, LightParameter.Ambient, new float[] { 0.3f, 0.3f, 0.3f, 1.0f }); - GL.Light(LightName.Light0, LightParameter.Diffuse, new float[] { 1.0f, 1.0f, 1.0f, 1.0f }); - GL.Light(LightName.Light0, LightParameter.Specular, new float[] { 1.0f, 1.0f, 1.0f, 1.0f }); - GL.Light(LightName.Light0, LightParameter.SpotExponent, new float[] { 1.0f, 1.0f, 1.0f, 1.0f }); - GL.LightModel(LightModelParameter.LightModelAmbient, new float[] { 0.2f, 0.2f, 0.2f, 1.0f }); - GL.LightModel(LightModelParameter.LightModelTwoSide, 1); - GL.LightModel(LightModelParameter.LightModelLocalViewer, 1); - GL.Enable(EnableCap.Lighting); - GL.Enable(EnableCap.Light0); - - // Use GL.Material to set your object's material parameters. - GL.Material(MaterialFace.Front, MaterialParameter.Ambient, new float[] { 0.3f, 0.3f, 0.3f, 1.0f }); - GL.Material(MaterialFace.Front, MaterialParameter.Diffuse, new float[] { 1.0f, 1.0f, 1.0f, 1.0f }); - GL.Material(MaterialFace.Front, MaterialParameter.Specular, new float[] { 1.0f, 1.0f, 1.0f, 1.0f }); - GL.Material(MaterialFace.Front, MaterialParameter.Emission, new float[] { 0.0f, 0.0f, 0.0f, 1.0f }); - } - - #endregion - - #region OnResize - - /// - /// Called when the user resizes the window. - /// - /// Contains the new width/height of the window. - /// - /// You want the OpenGL viewport to match the window. This is the place to do it! - /// - protected override void OnResize(EventArgs e) - { - base.OnResize(e); - - GL.Viewport(0, 0, Width, Height); - - float aspect_ratio = Width / (float)Height; - Matrix4 perpective = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspect_ratio, 1, 64); - GL.MatrixMode(MatrixMode.Projection); - GL.LoadMatrix(ref perpective); - } - - #endregion - - #region OnUpdateFrame - - /// - /// Prepares the next frame for rendering. - /// - /// - /// Place your control logic here. This is the place to respond to user input, - /// update object positions etc. - /// - protected override void OnUpdateFrame(FrameEventArgs e) - { - var keyboard = OpenTK.Input.Keyboard.GetState(); - var mouse = OpenTK.Input.Mouse.GetState(); - - if (keyboard[OpenTK.Input.Key.Escape]) - { - this.Exit(); - return; - } - - if (keyboard[OpenTK.Input.Key.F11]) - if (WindowState != WindowState.Fullscreen) - WindowState = WindowState.Fullscreen; - else - WindowState = WindowState.Normal; - - if (mouse[OpenTK.Input.MouseButton.Left]) - x_angle = mouse.X; - else - x_angle += 0.5f; - - zoom = mouse.Wheel * 0.5f; // Mouse.Wheel is broken on both Linux and Windows. - - // Do not leave x_angle drift too far away, as this will cause inaccuracies. - if (x_angle > 360.0f) - x_angle -= 360.0f; - else if (x_angle < -360.0f) - x_angle += 360.0f; - } - - #endregion - - #region OnRenderFrame - - /// - /// Place your rendering code here. - /// - protected override void OnRenderFrame(FrameEventArgs e) - { - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - Matrix4 lookat = Matrix4.LookAt(0, 0, -7.5f + zoom, 0, 0, 0, 0, 1, 0); - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadMatrix(ref lookat); - - GL.Rotate(x_angle, 0.0f, 1.0f, 0.0f); - - GL.Begin(PrimitiveType.Triangles); - foreach (int index in shape.Indices) - { - GL.Normal3(shape.Normals[index]); - GL.Vertex3(shape.Vertices[index]); - } - GL.End(); - - SwapBuffers(); - } - - #endregion - - #region public void Launch() - - /// - /// Launches this example. - /// - /// - /// Provides a simple way for the example launcher to launch the examples. - /// - public static void Main() - { - using (T04_Vertex_Lighting example = new T04_Vertex_Lighting()) - { - Utilities.SetWindowTitle(example); - example.Run(30.0, 0.0); - } - } - - #endregion - } -} diff --git a/Source/Examples/OpenGL/2.x/DDSCubeMap.cs b/Source/Examples/OpenGL/2.x/DDSCubeMap.cs deleted file mode 100644 index d8334bc9..00000000 --- a/Source/Examples/OpenGL/2.x/DDSCubeMap.cs +++ /dev/null @@ -1,273 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Drawing; -using System.Collections.Generic; -using System.Diagnostics; -using System.Windows.Forms; -using System.IO; -using System.Text; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; - -using Examples.Shapes; -using Examples.TextureLoaders; - -namespace Examples.Tutorial -{ - [Example("DDS Cube Map", ExampleCategory.OpenGL, "2.x", Documentation = "DDSCubeMap")] - public class T13_GLSL_Earth: GameWindow - { - public T13_GLSL_Earth( ) - : base( 800, 800 ) - { - } - - #region internal Fields - - // Shader - int VertexShaderObject, FragmentShaderObject, ProgramObject; - const string VertexShaderFilename = "Data/Shaders/CubeMap_VS.glsl"; - const string FragmentShaderFilename = "Data/Shaders/CubeMap_FS.glsl"; - - // Textures - const TextureUnit TMU0_Unit = TextureUnit.Texture0; - const int TMU0_UnitInteger = 0; - const string TMU0_Filename = "Data/Textures/earth-cubemap.dds"; - uint TMU0_Handle; - TextureTarget TMU0_Target; - - // DL - DrawableShape sphere; - - // Camera - Vector3 EyePos = new Vector3( 0.0f, 0.0f, 6.0f ); - Vector3 Trackball = Vector3.Zero; - - #endregion internal Fields - - /// Setup OpenGL and load resources here. - /// Not used. - protected override void OnLoad(EventArgs e) - { - this.VSync = VSyncMode.Off; - - // Check for necessary capabilities: - string extensions = GL.GetString(StringName.Extensions); - if (!GL.GetString(StringName.Extensions).Contains("GL_ARB_shading_language")) - { - throw new NotSupportedException(String.Format("This example requires OpenGL 2.0. Found {0}. Aborting.", - GL.GetString(StringName.Version).Substring(0, 3))); - } - - if (!extensions.Contains("GL_ARB_texture_compression") || - !extensions.Contains("GL_EXT_texture_compression_s3tc")) - { - throw new NotSupportedException("This example requires support for texture compression. Aborting."); - } - - #region GL State - - GL.ClearColor( 0f, 0f, 0f, 0f ); - - GL.Disable( EnableCap.Dither ); - - GL.Enable( EnableCap.CullFace ); - GL.FrontFace( FrontFaceDirection.Ccw ); - GL.PolygonMode( MaterialFace.Front, PolygonMode.Fill ); - // GL.PolygonMode( MaterialFace.Back, PolygonMode.Line ); - - #endregion GL State - - #region Shaders - - string LogInfo; - - // Load&Compile Vertex Shader - - using ( StreamReader sr = new StreamReader( VertexShaderFilename ) ) - { - VertexShaderObject = GL.CreateShader( ShaderType.VertexShader ); - GL.ShaderSource( VertexShaderObject, sr.ReadToEnd( ) ); - GL.CompileShader( VertexShaderObject ); - } - - GL.GetShaderInfoLog( VertexShaderObject, out LogInfo ); - if ( LogInfo.Length > 0 && !LogInfo.Contains( "hardware" ) ) - Trace.WriteLine( "Vertex Shader failed!\nLog:\n" + LogInfo ); - else - Trace.WriteLine( "Vertex Shader compiled without complaint." ); - - // Load&Compile Fragment Shader - - using ( StreamReader sr = new StreamReader( FragmentShaderFilename ) ) - { - FragmentShaderObject = GL.CreateShader( ShaderType.FragmentShader ); - GL.ShaderSource( FragmentShaderObject, sr.ReadToEnd( ) ); - GL.CompileShader( FragmentShaderObject ); - } - GL.GetShaderInfoLog( FragmentShaderObject, out LogInfo ); - - if ( LogInfo.Length > 0 && !LogInfo.Contains( "hardware" ) ) - Trace.WriteLine( "Fragment Shader failed!\nLog:\n" + LogInfo ); - else - Trace.WriteLine( "Fragment Shader compiled without complaint." ); - - // Link the Shaders to a usable Program - ProgramObject = GL.CreateProgram( ); - GL.AttachShader( ProgramObject, VertexShaderObject ); - GL.AttachShader( ProgramObject, FragmentShaderObject ); - - // link it all together - GL.LinkProgram( ProgramObject ); - - // flag ShaderObjects for delete when not used anymore - GL.DeleteShader( VertexShaderObject ); - GL.DeleteShader( FragmentShaderObject ); - - int[] temp = new int[1]; - GL.GetProgram(ProgramObject, GetProgramParameterName.LinkStatus, out temp[0]); - Trace.WriteLine( "Linking Program (" + ProgramObject + ") " + ( ( temp[0] == 1 ) ? "succeeded." : "FAILED!" ) ); - if ( temp[0] != 1 ) - { - GL.GetProgramInfoLog( ProgramObject, out LogInfo ); - Trace.WriteLine( "Program Log:\n" + LogInfo ); - } - - GL.GetProgram(ProgramObject, GetProgramParameterName.ActiveAttributes, out temp[0]); - Trace.WriteLine( "Program registered " + temp[0] + " Attributes. (Should be 4: Pos, UV, Normal, Tangent)" ); - - Trace.WriteLine( "Tangent attribute bind location: " + GL.GetAttribLocation( ProgramObject, "AttributeTangent" ) ); - - Trace.WriteLine( "End of Shader build. GL Error: " + GL.GetError( ) ); - - #endregion Shaders - - #region Textures - - TextureLoaderParameters.FlipImages = false; - TextureLoaderParameters.MagnificationFilter = TextureMagFilter.Linear; - TextureLoaderParameters.MinificationFilter = TextureMinFilter.Linear; - TextureLoaderParameters.WrapModeS = TextureWrapMode.ClampToEdge; - TextureLoaderParameters.WrapModeT = TextureWrapMode.ClampToEdge; - TextureLoaderParameters.EnvMode = TextureEnvMode.Modulate; - - ImageDDS.LoadFromDisk( TMU0_Filename, out TMU0_Handle, out TMU0_Target ); - Trace.WriteLine( "Loaded " + TMU0_Filename + " with handle " + TMU0_Handle + " as " + TMU0_Target ); - - #endregion Textures - - Trace.WriteLine( "End of Texture Loading. GL Error: " + GL.GetError( ) ); - Trace.WriteLine( ""); - - sphere = new SlicedSphere(1.5f, Vector3d.Zero, SlicedSphere.eSubdivisions.Four, new SlicedSphere.eDir[] { SlicedSphere.eDir.All }, true); - - } - - protected override void OnUnload(EventArgs e) - { - sphere.Dispose(); - - GL.DeleteProgram( ProgramObject ); - GL.DeleteTextures( 1, ref TMU0_Handle ); - - base.OnUnload( e ); - } - - /// Respond to resize events here. - /// Contains information on the new GameWindow size. - /// There is no need to call the base implementation. - protected override void OnResize( EventArgs e ) - { - GL.Viewport( 0, 0, Width, Height ); - - GL.MatrixMode( MatrixMode.Projection ); - Matrix4 p = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, Width / (float)Height, 0.1f, 10.0f); - GL.LoadMatrix(ref p); - - GL.MatrixMode( MatrixMode.Modelview ); - GL.LoadIdentity( ); - - base.OnResize( e ); - } - - /// Add your game logic here. - /// Contains timing information. - /// There is no need to call the base implementation. - protected override void OnUpdateFrame(FrameEventArgs e) - { - base.OnUpdateFrame(e); - - var keyboard = OpenTK.Input.Keyboard.GetState(); - var mouse = OpenTK.Input.Mouse.GetState(); - - if (keyboard[OpenTK.Input.Key.Escape]) - this.Exit(); - if (keyboard[OpenTK.Input.Key.Space]) - Trace.WriteLine("GL: " + GL.GetError()); - - Trackball.X = mouse.X; - Trackball.Y = mouse.Y; - Trackball.Z = mouse.Scroll.Y * 0.5f; - } - - /// Add your game rendering code here. - /// Contains timing information. - /// There is no need to call the base implementation. - protected override void OnRenderFrame(FrameEventArgs e) - { - this.Title = "FPS: " + (1 / e.Time).ToString("0."); - - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - GL.UseProgram(ProgramObject); - - #region Textures - - GL.ActiveTexture(TMU0_Unit); - GL.BindTexture(TMU0_Target, TMU0_Handle); - - #endregion Textures - - #region Uniforms - - GL.Uniform1(GL.GetUniformLocation(ProgramObject, "Earth"), TMU0_UnitInteger); - - #endregion Uniforms - - GL.PushMatrix(); - Matrix4 temp = Matrix4.LookAt(EyePos, Vector3.Zero, Vector3.UnitY); - GL.MultMatrix(ref temp); - - GL.Rotate(Trackball.X, Vector3.UnitY); - GL.Rotate(Trackball.Y, Vector3.UnitX); - - #region Draw - - GL.Color3(1f, 1f, 1f); - - sphere.Draw(); - - #endregion Draw - - GL.PopMatrix(); - - this.SwapBuffers(); - } - - /// Entry point - [STAThread] - public static void Main( ) - { - using ( T13_GLSL_Earth example = new T13_GLSL_Earth( ) ) - { - Utilities.SetWindowTitle(example); - example.Run( 30.0, 0.0 ); - } - } - } -} diff --git a/Source/Examples/OpenGL/2.x/GeometryShader.cs b/Source/Examples/OpenGL/2.x/GeometryShader.cs deleted file mode 100644 index 74b625d6..00000000 --- a/Source/Examples/OpenGL/2.x/GeometryShader.cs +++ /dev/null @@ -1,246 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Diagnostics; -using System.Drawing; - -using OpenTK; -using OpenTK.Input; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; - -namespace Examples.Tutorial -{ - [Example("Basic Geometry Shader", ExampleCategory.OpenGL, "2.x", Documentation = "Simple usage of EXT_geometry_shader4")] - public class SimpleGeometryShader : GameWindow - { - public SimpleGeometryShader() - : base(800, 600) - { - } - - int shaderProgram = 0; - - protected override void OnLoad(EventArgs e) - { - if (!GL.GetString(StringName.Extensions).Contains("EXT_geometry_shader4")) - { - System.Windows.Forms.MessageBox.Show( - "Your video card does not support EXT_geometry_shader4. Please update your drivers.", - "EXT_geometry_shader4 not supported", - System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); - Exit(); - throw new NotSupportedException(); - } - - // create a shader object. - shaderProgram = GL.CreateProgram(); - // create shader objects for all three types. - int vert = GL.CreateShader(ShaderType.VertexShader); - int frag = GL.CreateShader(ShaderType.FragmentShader); - int geom = GL.CreateShader(ShaderType.GeometryShaderExt); - - // GLSL for fragment shader. - String fragSource = @" - void main( void ) - { - gl_FragColor = vec4(0, 1, 0, 0); - } - "; - - // GLSL for vertex shader. - String vertSource = @" - void main( void ) - { - gl_Position = ftransform(); - } - "; - - // GLSL for geometry shader. - // Note this is a version 1.20 shader - // Also note GL_EXT_geometry_shader4 must be enabled explicitly, correct - // OpenGL implementations should only have the new tokens, like - // EmitVertex and EndPrimitive, when this extension is enabled. - String geomSource = @" - #version 120 - #extension GL_EXT_geometry_shader4 : enable - - void main(void) - { - // variable to use in for loops - int i; - - // Emit the original vertices without changing, making - // this part exactly the same as if no geometry shader - // was used. - for(i=0; i< gl_VerticesIn; i++) - { - gl_Position = gl_PositionIn[i]; - EmitVertex(); - } - // End the one primitive with the original vertices - EndPrimitive(); - - // Now we generate some more! This translates 0.2 over - // the positive x axis. - for(i=0; i< gl_VerticesIn; i++) - { - gl_Position = gl_PositionIn[i]; - gl_Position.x += 0.2; - EmitVertex(); - } - EndPrimitive(); - } - "; - - // compile shaders. - compileShader(frag, fragSource); - compileShader(vert, vertSource); - compileShader(geom, geomSource); - - // attach shaders and link the program. - GL.AttachShader(shaderProgram, frag); - GL.AttachShader(shaderProgram, vert); - GL.AttachShader(shaderProgram, geom); - - // Set the input type of the primitives we are going to feed the geometry shader, this should be the same as - // the primitive type given to GL.Begin. If the types do not match a GL error will occur (todo: verify GL_INVALID_ENUM, on glBegin) - GL.Ext.ProgramParameter(shaderProgram, AssemblyProgramParameterArb.GeometryInputType, (int)BeginMode.Lines); - // Set the output type of the geometry shader. Becasue we input Lines we will output LineStrip(s). - GL.Ext.ProgramParameter(shaderProgram, AssemblyProgramParameterArb.GeometryOutputType, (int)BeginMode.LineStrip); - - // We must tell the shader program how much vertices the geometry shader will output (at most). - // One simple way is to query the maximum and use that. - // NOTE: Make sure that the number of vertices * sum(components of active varyings) does not - // exceed MaxGeometryTotalOutputComponents. - GL.Ext.ProgramParameter(shaderProgram, AssemblyProgramParameterArb.GeometryVerticesOut, 50); - - // NOTE: calls to ProgramParameter do not take effect until you call LinkProgram. - GL.LinkProgram(shaderProgram); - - // output link info log. - string info; - GL.GetProgramInfoLog(shaderProgram, out info); - Debug.WriteLine(info); - - // Set clearcolor and bind the shader program. - GL.ClearColor(0.1f, 0.1f, 0.1f, 0.1f); - GL.UseProgram(shaderProgram); - // Set color to red. If the shader fails the fixed pipeline will be used and - // the lines will be red, if all is ok the fragment shader is used and they will be green. - GL.Color3(1.0f, 0, 0); - - // Clean up resources. Note the program object is not deleted. - if (frag != 0) - GL.DeleteShader(frag); - if (vert != 0) - GL.DeleteShader(vert); - if (geom != 0) - GL.DeleteShader(geom); - } - - /// - /// Helper method to avoid code duplication. - /// Compiles a shader and prints results using Debug.WriteLine. - /// - /// A shader object, gotten from GL.CreateShader. - /// The GLSL source to compile. - void compileShader(int shader, string source) - { - GL.ShaderSource(shader, source); - GL.CompileShader(shader); - - string info; - GL.GetShaderInfoLog(shader, out info); - Debug.WriteLine(info); - - int compileResult; - GL.GetShader(shader, ShaderParameter.CompileStatus, out compileResult); - if (compileResult != 1) - { - Debug.WriteLine("Compile Error!"); - Debug.WriteLine(source); - } - } - - protected override void OnUnload(EventArgs e) - { - if (shaderProgram != 0) - GL.DeleteProgram(shaderProgram); - base.OnUnload(e); - } - - /// - /// Sets the viewport and projection matrix for orthographic projection. - /// - /// resize event args - protected override void OnResize(EventArgs e) - { - GL.Viewport(ClientRectangle); - - // Set projection matrix - GL.MatrixMode(MatrixMode.Projection); - OpenTK.Matrix4 ortho = OpenTK.Matrix4.CreateOrthographicOffCenter(-1, 1, -1, 1, 1, -1); - GL.LoadMatrix(ref ortho); - - // Set selector state back to matrix mode - GL.MatrixMode(MatrixMode.Modelview); - - base.OnResize(e); - } - - protected override void OnUpdateFrame(FrameEventArgs e) - { - base.OnUpdateFrame(e); - - var keyboard = OpenTK.Input.Keyboard.GetState(); - if (keyboard[Key.Space]) - { - ErrorCode err = GL.GetError(); - //Console.WriteLine(err + " " + Glu.ErrorString((GluErrorCode)err)); - Console.WriteLine("GL error code: {0}", err); - } - - if (keyboard[Key.Escape]) - this.Exit(); - } - - protected override void OnRenderFrame(FrameEventArgs e) - { - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - // draw two vertical lines - GL.Begin(PrimitiveType.Lines); - { - // line one - GL.Vertex2(-0.5f, -0.5f); - GL.Vertex2(-0.5f, 0.5f); - // line two - GL.Vertex2(0.5f, 0.5f); - GL.Vertex2(0.5f, -0.5f); - } - GL.End(); - - this.SwapBuffers(); - } - - #region public static void Main() - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - using (SimpleGeometryShader example = new SimpleGeometryShader()) - { - Utilities.SetWindowTitle(example); - example.Run(30.0, 0.0); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/Source/Examples/OpenGL/2.x/GeometryShaderAdvanced.cs b/Source/Examples/OpenGL/2.x/GeometryShaderAdvanced.cs deleted file mode 100644 index 69d1f17f..00000000 --- a/Source/Examples/OpenGL/2.x/GeometryShaderAdvanced.cs +++ /dev/null @@ -1,1061 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Diagnostics; -using System.Drawing; - -using OpenTK; -using OpenTK.Input; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; - -/* - * The idea is to make a simple scene: A box with a checker texture with a sphere inside it. The - * camera will be inside the box looking at the sphere. - * - * Rendering will be done in two passes. The first pass will render the box from within the - * sphere, looking in along all three axes in the positive and negative directions. These six - * different camara orientations will be rendered to individual faces of a cubemap, in one - * single pass using the gl_Layer token in the geometry shader. This cubemap will be used the - * the second pass. - * - * The second pass will render both the box and the sphere. The box will have the checker - * texture, and the sphere will use the cubemap from the first pass. - * - * Keys: - * F1 - switch to cubemap cross texture view - * F2 - switch to the normal scene render - * - * F5 - Polygon mode points - * F6 - Polygon mode lines - * F7 - Polygon mode fill - * - * References: - * http://www.opengl.org/wiki/GL_EXT_framebuffer_object#Quick_example.2C_render_to_texture_.28Cubemap.29 - * http://www.opengl.org/registry/specs/EXT/framebuffer_object.txt - * http://www.opengl.org/registry/specs/EXT/geometry_shader4.txt - */ - -namespace Examples.Tutorial -{ - [Example("Advanced Geometry Shader", ExampleCategory.OpenGL, "2.x", Documentation = "Advanced usage of EXT_geometry_shader4")] - public class SimpleGeometryShader2 : GameWindow - { - public SimpleGeometryShader2() - : base(800, 600) - { - KeyDown += Keyboard_KeyDown; - } - - enum ViewMode - { - CubemapCross, - Scene, - } - - struct VertexPositionNormalTexture - { - public Vector3 Position, Normal; - public Vector2 Texture; - - public VertexPositionNormalTexture(Vector3 position, Vector3 normal, Vector2 texture) - { - Position = position; - Normal = normal; - Texture = texture; - } - } - - #region Fields - - int shaderProgramBox; - int shaderProgramSphere; - int shaderProgramCubemap; - - int textureCubeColor; - int textureCubeDepth; - int textureCubeFBO; - - int vboCube; - int vboCubeStride; - int vboSphere; - int vboSphereStride = BlittableValueType.Stride; - int eboSphere; - - ViewMode mode = ViewMode.Scene; - Vector3 eyePos = new Vector3(0, -8, 0); - Vector3 eyeLookat = new Vector3(0, -9, -0); - Vector3 spherePos = new Vector3(0, -9, 0); - DateTime startTime = DateTime.Now; - - #endregion - - #region keyboard handler - - void Keyboard_KeyDown(object sender, KeyboardKeyEventArgs e) - { - switch (e.Key) - { - case Key.F1: - switchToMode(ViewMode.CubemapCross); - break; - case Key.F2: - switchToMode(ViewMode.Scene); - break; - case Key.F5: - GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Point); - break; - case Key.F6: - GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line); - break; - case Key.F7: - GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill); - break; - case Key.Escape: - this.Exit(); - break; - default: - break; - } - } - - #endregion - - #region init methods - - void initShaderProgramBox() - { - // create a program object. - shaderProgramBox = GL.CreateProgram(); - // create shader objects. - int vert = GL.CreateShader(ShaderType.VertexShader); - int frag = GL.CreateShader(ShaderType.FragmentShader); - - // GLSL for fragment shader. - // diagonal checker - String fragSource = @" - varying vec3 normal; - void main( void ) - { - float s = gl_TexCoord[0].s * 6.28 * 8.0; - float t = gl_TexCoord[0].t * 6.28 * 8.0; - gl_FragColor = gl_TexCoord[1] * vec4(sign(cos(s)+cos(t))); - //gl_FragColor = vec4(normal*vec3(0.5)+vec3(0.5), 1); - } - "; - - // GLSL for vertex shader. - String vertSource = @" - varying vec3 normal; - void main( void ) - { - gl_Position = ftransform(); - normal = gl_Normal; - gl_TexCoord[0] = gl_MultiTexCoord0; - gl_TexCoord[1] = normalize(gl_Vertex)*0.5+0.5; - } - "; - - // compile shaders. - compileShader(frag, fragSource); - compileShader(vert, vertSource); - - // attach shaders and link the program. - GL.AttachShader(shaderProgramBox, frag); - GL.AttachShader(shaderProgramBox, vert); - GL.LinkProgram(shaderProgramBox); - - // output link info log. - string info; - GL.GetProgramInfoLog(shaderProgramBox, out info); - Debug.WriteLine(info); - - // Clean up resources. Note the program object is not deleted. - if (frag != 0) - GL.DeleteShader(frag); - if (vert != 0) - GL.DeleteShader(vert); - } - - void initShaderProgramSphere() - { - // create a program object. - shaderProgramSphere = GL.CreateProgram(); - // create shader objects. - int vert = GL.CreateShader(ShaderType.VertexShader); - int frag = GL.CreateShader(ShaderType.FragmentShader); - - // GLSL for fragment shader. - String fragSource = @" - varying vec3 normal; - varying vec3 eyevec; - uniform samplerCube tex; - - void main( void ) - { - gl_FragColor = textureCube(tex, reflect(normalize(-eyevec), normalize(normal))); - } - "; - - // GLSL for vertex shader. - String vertSource = @" - varying vec3 normal; - varying vec3 eyevec; - - void main( void ) - { - gl_Position = ftransform(); - eyevec = -gl_Vertex.xyz; - normal = gl_Normal; - } - "; - - // compile shaders. - compileShader(frag, fragSource); - compileShader(vert, vertSource); - - // attach shaders and link the program. - GL.AttachShader(shaderProgramSphere, frag); - GL.AttachShader(shaderProgramSphere, vert); - GL.LinkProgram(shaderProgramSphere); - - // output link info log. - string info; - GL.GetProgramInfoLog(shaderProgramSphere, out info); - Debug.WriteLine(info); - - // Clean up resources. Note the program object is not deleted. - if (frag != 0) - GL.DeleteShader(frag); - if (vert != 0) - GL.DeleteShader(vert); - } - - void initShaderProgramCubemap() - { - // create a program object. - shaderProgramCubemap = GL.CreateProgram(); - // create shader objects. - int vert = GL.CreateShader(ShaderType.VertexShader); - int frag = GL.CreateShader(ShaderType.FragmentShader); - int geom = GL.CreateShader(ShaderType.GeometryShaderExt); - - // GLSL for fragment shader. - // Checkerboard :) - String fragSource = @" - #version 120 - #extension GL_EXT_gpu_shader4 : enable - - void main( void ) - { - float s = gl_TexCoord[0].s * 6.28 * 8.0; - float t = gl_TexCoord[0].t * 6.28 * 8.0; - gl_FragColor = gl_TexCoord[2] * vec4(sign(cos(s)+cos(t)))/* * gl_TexCoord[1]*/; -// gl_FragColor = gl_TexCoord[1]; - } - "; - - // GLSL for vertex shader. - String vertSource = @" - #version 120 - #extension GL_EXT_gpu_shader4 : enable - - //varying vec4 p[2]; - //varying vec4 nx; - - void main( void ) - { - gl_Position = gl_Vertex; - gl_TexCoord[2] = normalize(gl_Vertex)*0.5+0.5; - gl_TexCoord[0] = gl_MultiTexCoord0; - } - "; - - // GLSL for geometry shader. - String geomSource = @" - #version 120 - #extension GL_EXT_geometry_shader4 : enable - #extension GL_EXT_gpu_shader4 : enable - uniform mat4 matrixPX; - uniform mat4 matrixNX; - uniform mat4 matrixPY; - uniform mat4 matrixNY; - uniform mat4 matrixPZ; - uniform mat4 matrixNZ; - - void main(void) { - int i, layer; - gl_Layer = 0; - gl_TexCoord[1] = vec4(1, 0, 0, 1); - for (i = 0; i < gl_VerticesIn; i++) { - gl_Position = matrixPX * gl_PositionIn[i]; - gl_TexCoord[0] = gl_TexCoordIn[i][0]; - gl_TexCoord[2] = gl_TexCoordIn[i][2]; - EmitVertex(); - } - EndPrimitive(); - gl_Layer = 1; - gl_TexCoord[1] = vec4(0, 0, 1, 1); - for (i = 0; i < gl_VerticesIn; i++) { - gl_Position = matrixNX * gl_PositionIn[i]; - gl_TexCoord[0] = gl_TexCoordIn[i][0]; - gl_TexCoord[2] = gl_TexCoordIn[i][2]; - EmitVertex(); - } - EndPrimitive(); - gl_Layer = 2; - gl_TexCoord[1] = vec4(0, 1, 0, 1); - for (i = 0; i < gl_VerticesIn; i++) { - gl_Position = matrixPY* gl_PositionIn[i]; - gl_TexCoord[0] = gl_TexCoordIn[i][0]; - gl_TexCoord[2] = gl_TexCoordIn[i][2]; - EmitVertex(); - } - EndPrimitive(); - gl_Layer = 3; - gl_TexCoord[1] = vec4(1, 1, 0, 1); - for (i = 0; i < gl_VerticesIn; i++) { - gl_Position = matrixNY * gl_PositionIn[i]; - gl_TexCoord[0] = gl_TexCoordIn[i][0]; - gl_TexCoord[2] = gl_TexCoordIn[i][2]; - EmitVertex(); - } - EndPrimitive(); - gl_Layer = 4; - gl_TexCoord[1] = vec4(1, 1, 1, 1); - for (i = 0; i < gl_VerticesIn; i++) { - gl_Position = matrixPZ * gl_PositionIn[i]; - gl_TexCoord[0] = gl_TexCoordIn[i][0]; - gl_TexCoord[2] = gl_TexCoordIn[i][2]; - EmitVertex(); - } - EndPrimitive(); - gl_Layer = 5; - gl_TexCoord[1] = vec4(1, 0, 1, 1); - for (i = 0; i < gl_VerticesIn; i++) { - gl_Position = matrixNZ * gl_PositionIn[i]; - gl_TexCoord[0] = gl_TexCoordIn[i][0]; - gl_TexCoord[2] = gl_TexCoordIn[i][2]; - EmitVertex(); - } - EndPrimitive(); - } - "; - - // compile shaders. - compileShader(frag, fragSource); - compileShader(vert, vertSource); - compileShader(geom, geomSource); - - int tmp; - GL.GetInteger((GetPName)ExtGeometryShader4.MaxGeometryOutputVerticesExt, out tmp); - GL.Ext.ProgramParameter(shaderProgramCubemap, AssemblyProgramParameterArb.GeometryVerticesOut, 18); - - GL.Ext.ProgramParameter(shaderProgramCubemap, AssemblyProgramParameterArb.GeometryInputType, (int)All.Triangles); - GL.Ext.ProgramParameter(shaderProgramCubemap, AssemblyProgramParameterArb.GeometryOutputType, (int)All.TriangleStrip); - - // attach shaders and link the program. - GL.AttachShader(shaderProgramCubemap, frag); - GL.AttachShader(shaderProgramCubemap, vert); - GL.AttachShader(shaderProgramCubemap, geom); - GL.LinkProgram(shaderProgramCubemap); - - // output link info log. - string info; - GL.GetProgramInfoLog(shaderProgramCubemap, out info); - Debug.WriteLine(info); - - // Clean up resources. Note the program object is not deleted. - if (frag != 0) - GL.DeleteShader(frag); - if (vert != 0) - GL.DeleteShader(vert); - if (geom != 0) - GL.DeleteShader(geom); - } - - /// - /// Helper method to avoid code duplication. - /// Compiles a shader and prints results using Debug.WriteLine. - /// - /// A shader object, gotten from GL.CreateShader. - /// The GLSL source to compile. - void compileShader(int shader, string source) - { - GL.ShaderSource(shader, source); - GL.CompileShader(shader); - - string info; - GL.GetShaderInfoLog(shader, out info); - Debug.WriteLine(info); - - int compileResult; - GL.GetShader(shader, ShaderParameter.CompileStatus, out compileResult); - if (compileResult != 1) - { - Debug.WriteLine("Compile Error!"); - Debug.WriteLine(source); - } - } - - void initTextureCube() - { - textureCubeColor = GL.GenTexture(); - GL.BindTexture(TextureTarget.TextureCubeMap, textureCubeColor); - GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); - GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); - GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); - GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); - GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapR, (int)TextureWrapMode.ClampToEdge); - foreach (TextureTarget target in new TextureTarget[] { - TextureTarget.TextureCubeMapPositiveX, - TextureTarget.TextureCubeMapNegativeX, - TextureTarget.TextureCubeMapPositiveY, - TextureTarget.TextureCubeMapNegativeY, - TextureTarget.TextureCubeMapPositiveZ, - TextureTarget.TextureCubeMapNegativeZ, - }) - { - GL.TexImage2D(target, 0, PixelInternalFormat.Rgba8, 512, 512, 0, PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero); - } - - /* - GL.BindTexture(TextureTarget.TextureCubeMap, textureCubeDepth); - GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); - GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); - GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); - GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); - GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapR, (int)TextureWrapMode.ClampToEdge); - foreach (TextureTarget target in new TextureTarget[] { - TextureTarget.TextureCubeMapPositiveX, - TextureTarget.TextureCubeMapNegativeX, - TextureTarget.TextureCubeMapPositiveY, - TextureTarget.TextureCubeMapNegativeY, - TextureTarget.TextureCubeMapPositiveZ, - TextureTarget.TextureCubeMapNegativeZ, - }) { - GL.TexImage2D(target, 0, (PixelInternalFormat)All.DepthComponent32, 512, 512, 0, PixelFormat.DepthComponent, PixelType.UnsignedInt, IntPtr.Zero); - } - */ - GL.Ext.GenFramebuffers(1, out textureCubeFBO); - GL.Ext.GenRenderbuffers(1, out textureCubeDepth); - - GL.Ext.BindFramebuffer(FramebufferTarget.FramebufferExt, textureCubeFBO); - GL.Ext.FramebufferTexture(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, textureCubeColor, 0); - - //GL.Ext.BindRenderbuffer(RenderbufferTarget.RenderbufferExt, textureCubeDepth); - //GL.Ext.RenderbufferStorage(RenderbufferTarget.RenderbufferExt, (RenderbufferStorage)All.DepthComponent24, 512, 512); - //GL.Ext.FramebufferRenderbuffer(FramebufferTarget.FramebufferExt, FramebufferAttachment.DepthAttachmentExt, RenderbufferTarget.RenderbufferExt, textureCubeDepth); - - #region Test for Error - FramebufferErrorCode e = GL.Ext.CheckFramebufferStatus(FramebufferTarget.FramebufferExt); - switch (e) - { - case FramebufferErrorCode.FramebufferCompleteExt: - { - Console.WriteLine("FBO: The framebuffer is complete and valid for rendering."); - break; - } - case FramebufferErrorCode.FramebufferIncompleteAttachmentExt: - { - Console.WriteLine("FBO: One or more attachment points are not framebuffer attachment complete. This could mean there’s no texture attached or the format isn’t renderable. For color textures this means the base format must be RGB or RGBA and for depth textures it must be a DEPTH_COMPONENT format. Other causes of this error are that the width or height is zero or the z-offset is out of range in case of render to volume."); - break; - } - case FramebufferErrorCode.FramebufferIncompleteMissingAttachmentExt: - { - Console.WriteLine("FBO: There are no attachments."); - break; - } - /* case FramebufferErrorCode.GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT_EXT: - { - Console.WriteLine("FBO: An object has been attached to more than one attachment point."); - break; - }*/ - case FramebufferErrorCode.FramebufferIncompleteDimensionsExt: - { - Console.WriteLine("FBO: Attachments are of different size. All attachments must have the same width and height."); - break; - } - case FramebufferErrorCode.FramebufferIncompleteFormatsExt: - { - Console.WriteLine("FBO: The color attachments have different format. All color attachments must have the same format."); - break; - } - case FramebufferErrorCode.FramebufferIncompleteDrawBufferExt: - { - Console.WriteLine("FBO: An attachment point referenced by GL.DrawBuffers() doesn’t have an attachment."); - break; - } - case FramebufferErrorCode.FramebufferIncompleteReadBufferExt: - { - Console.WriteLine("FBO: The attachment point referenced by GL.ReadBuffers() doesn’t have an attachment."); - break; - } - case FramebufferErrorCode.FramebufferUnsupportedExt: - { - Console.WriteLine("FBO: This particular FBO configuration is not supported by the implementation."); - break; - } - case (FramebufferErrorCode)All.FramebufferIncompleteLayerTargetsExt: - { - Console.WriteLine("FBO: Framebuffer Incomplete Layer Targets."); - break; - } - case (FramebufferErrorCode)All.FramebufferIncompleteLayerCountExt: - { - Console.WriteLine("FBO: Framebuffer Incomplete Layer Count."); - break; - } - default: - { - Console.WriteLine("FBO: Status unknown. (yes, this is really bad.)"); - break; - } - } - - // using FBO might have changed states, e.g. the FBO might not support stereoscopic views or double buffering - int[] queryinfo = new int[6]; - GL.GetInteger(GetPName.MaxColorAttachmentsExt, out queryinfo[0]); - GL.GetInteger(GetPName.AuxBuffers, out queryinfo[1]); - GL.GetInteger(GetPName.MaxDrawBuffers, out queryinfo[2]); - GL.GetInteger(GetPName.Stereo, out queryinfo[3]); - GL.GetInteger(GetPName.Samples, out queryinfo[4]); - GL.GetInteger(GetPName.Doublebuffer, out queryinfo[5]); - Console.WriteLine("max. ColorBuffers: " + queryinfo[0] + " max. AuxBuffers: " + queryinfo[1] + " max. DrawBuffers: " + queryinfo[2] + - "\nStereo: " + queryinfo[3] + " Samples: " + queryinfo[4] + " DoubleBuffer: " + queryinfo[5]); - - Console.WriteLine("Last GL Error: " + GL.GetError()); - - #endregion Test for Error - - GL.Ext.BindFramebuffer(FramebufferTarget.FramebufferExt, 0); // disable rendering into the FBO - } - - void initVBOCube() - { - GL.GenBuffers(1, out vboCube); - // vertex 3 floats - // normal 3 floats - // texcoord 2 floats - // 3+3+2=8 floats = 8*4 = 32 bytes - vboCubeStride = 32; - GL.BindBuffer(BufferTarget.ArrayBuffer, vboCube); - GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(cubeData.Length * vboCubeStride), cubeData, BufferUsageHint.StaticDraw); - GL.BindBuffer(BufferTarget.ArrayBuffer, 0); - } - - void initVBOSpere() - { - VertexPositionNormalTexture[] sphereVertices = CalculateSphereVertices(1, 1, 16, 16); - ushort[] sphereElements = CalculateSphereElements(1, 1, 16, 16); - - GL.GenBuffers(1, out vboSphere); - GL.BindBuffer(BufferTarget.ArrayBuffer, vboSphere); - GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(BlittableValueType.StrideOf(sphereVertices) * sphereVertices.Length), sphereVertices, BufferUsageHint.StaticDraw); - - GL.GenBuffers(1, out eboSphere); - GL.BindBuffer(BufferTarget.ElementArrayBuffer, eboSphere); - GL.BufferData(BufferTarget.ElementArrayBuffer, new IntPtr(BlittableValueType.StrideOf(sphereElements) * sphereElements.Length), sphereElements, BufferUsageHint.StaticDraw); - - GL.BindBuffer(BufferTarget.ArrayBuffer, 0); - } - - #endregion - - #region perspective - - void setOrtho() - { - OpenTK.Matrix4 proj; - proj = OpenTK.Matrix4.CreateOrthographicOffCenter(-1, 1, -1, 1, 1, -1); - GL.LoadMatrix(ref proj); - } - - void setPerspective() - { - OpenTK.Matrix4 proj; - proj = OpenTK.Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, Width / (float)Height, 0.1f, 200f); - GL.LoadMatrix(ref proj); - } - - void switchToMode(ViewMode m) - { - mode = m; - // force update of projection matrix by calling OnResize - this.OnResize(EventArgs.Empty); - } - - #endregion - - #region render methods - - void drawCubemapCross() - { - GL.ClearColor(0.1f, 0.1f, 0.1f, 0.1f); - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - GL.PushAttrib(AttribMask.PolygonBit); - GL.Enable(EnableCap.TextureCubeMap); - GL.BindTexture(TextureTarget.TextureCubeMap, textureCubeColor); - GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill); - - /* - * - * +---+ - * | 4 | - * +---+---+---+---+ - * | 0 | 1 | 2 | 3 | - * +---+---+---+---+ - * | 5 | - * +---+ - * 0 -x - * 1 +z - * 2 +x - * 3 -z - * 4 +y - * 5 -y - */ - - - GL.PushMatrix(); - GL.LoadIdentity(); - GL.Begin(PrimitiveType.Quads); - - // 0 -x - GL.TexCoord3(-1.0f, +1.0f, -1.0f); - GL.Vertex2(-1.0f, +0.3333f); - GL.TexCoord3(-1.0f, +1.0f, +1.0f); - GL.Vertex2(-0.5f, +0.3333f); - GL.TexCoord3(-1.0f, -1.0f, +1.0f); - GL.Vertex2(-0.5f, -0.3333f); - GL.TexCoord3(-1.0f, -1.0f, -1.0f); - GL.Vertex2(-1.0f, -0.3333f); - - // 1 +z - GL.TexCoord3(-1.0f, +1.0f, +1.0f); - GL.Vertex2(-0.5f, +0.3333f); - GL.TexCoord3(+1.0f, +1.0f, +1.0f); - GL.Vertex2(+0.0f, +0.3333f); - GL.TexCoord3(+1.0f, -1.0f, +1.0f); - GL.Vertex2(+0.0f, -0.3333f); - GL.TexCoord3(-1.0f, -1.0f, +1.0f); - GL.Vertex2(-0.5f, -0.3333f); - - // 2 +x - GL.TexCoord3(+1.0f, +1.0f, +1.0f); - GL.Vertex2(+0.0f, +0.3333f); - GL.TexCoord3(+1.0f, +1.0f, -1.0f); - GL.Vertex2(+0.5f, +0.3333f); - GL.TexCoord3(+1.0f, -1.0f, -1.0f); - GL.Vertex2(+0.5f, -0.3333f); - GL.TexCoord3(+1.0f, -1.0f, +1.0f); - GL.Vertex2(+0.0f, -0.3333f); - - // 3 -z - GL.TexCoord3(+1.0f, +1.0f, -1.0f); - GL.Vertex2(+0.5f, +0.3333f); - GL.TexCoord3(-1.0f, +1.0f, -1.0f); - GL.Vertex2(+1.0f, +0.3333f); - GL.TexCoord3(-1.0f, -1.0f, -1.0f); - GL.Vertex2(+1.0f, -0.3333f); - GL.TexCoord3(+1.0f, -1.0f, -1.0f); - GL.Vertex2(+0.5f, -0.3333f); - - // 4 +y - GL.TexCoord3(-1.0f, +1.0f, -1.0f); - GL.Vertex2(-0.5f, +1.0f); - GL.TexCoord3(+1.0f, +1.0, -1.0f); - GL.Vertex2(+0.0f, +1.0); - GL.TexCoord3(+1.0f, +1.0f, +1.0f); - GL.Vertex2(+0.0f, +0.3333f); - GL.TexCoord3(-1.0f, +1.0f, +1.0f); - GL.Vertex2(-0.5f, +0.3333f); - - // 5 -y - GL.TexCoord3(-1.0f, -1.0f, +1.0f); - GL.Vertex2(-0.5f, -0.3333f); - GL.TexCoord3(+1.0f, -1.0, +1.0f); - GL.Vertex2(+0.0f, -0.3333f); - GL.TexCoord3(+1.0f, -1.0f, -1.0f); - GL.Vertex2(+0.0f, -1.0f); - GL.TexCoord3(-1.0f, -1.0f, -1.0f); - GL.Vertex2(-0.5f, -1.0f); - - GL.End(); - GL.PopMatrix(); - - GL.Disable(EnableCap.TextureCubeMap); - GL.PopAttrib(); - } - - void renderCubeVBO() - { - GL.EnableClientState(ArrayCap.VertexArray); - GL.EnableClientState(ArrayCap.NormalArray); - GL.EnableClientState(ArrayCap.TextureCoordArray); - //GL.ClientActiveTexture(TextureUnit.Texture0 + 0); - - GL.BindBuffer(BufferTarget.ArrayBuffer, vboCube); - GL.VertexPointer(3, VertexPointerType.Float, vboCubeStride, new IntPtr(0)); - GL.NormalPointer(NormalPointerType.Float, vboCubeStride, new IntPtr(Vector3.SizeInBytes)); - GL.TexCoordPointer(2, TexCoordPointerType.Float, vboCubeStride, new IntPtr(Vector3.SizeInBytes + Vector3.SizeInBytes)); - - //GL.Arb.DrawArraysInstanced(BeginMode.Triangles, 0, cubeData.Length/8, 1); - GL.DrawArrays(PrimitiveType.Triangles, 0, cubeData.Length / (vboCubeStride / sizeof(float))); - - GL.DisableClientState(ArrayCap.VertexArray); - GL.DisableClientState(ArrayCap.NormalArray); - GL.DisableClientState(ArrayCap.TextureCoordArray); - } - - void renderSphereVBO() - { - GL.EnableClientState(ArrayCap.VertexArray); - GL.EnableClientState(ArrayCap.NormalArray); - GL.EnableClientState(ArrayCap.TextureCoordArray); - //GL.ClientActiveTexture(TextureUnit.Texture0 + 0); - - GL.BindBuffer(BufferTarget.ArrayBuffer, vboSphere); - GL.VertexPointer(3, VertexPointerType.Float, vboSphereStride, new IntPtr(0)); - GL.NormalPointer(NormalPointerType.Float, vboSphereStride, new IntPtr(Vector3.SizeInBytes)); - GL.TexCoordPointer(2, TexCoordPointerType.Float, vboSphereStride, new IntPtr(Vector3.SizeInBytes + Vector3.SizeInBytes)); - - GL.BindBuffer(BufferTarget.ElementArrayBuffer, eboSphere); - GL.DrawElements(PrimitiveType.Triangles, 16 * 16 * 6, DrawElementsType.UnsignedShort, IntPtr.Zero); - - //GL.Arb.DrawArraysInstanced(BeginMode.Triangles, 0, cubeData.Length/8, 1); - //GL.DrawArrays(BeginMode.Triangles, 0, sphereData.Length / (vboSphereStride / sizeof(float))); - - GL.DisableClientState(ArrayCap.VertexArray); - GL.DisableClientState(ArrayCap.NormalArray); - GL.DisableClientState(ArrayCap.TextureCoordArray); - } - - void renderCubemap() - { - GL.Disable(EnableCap.DepthTest); - - // draw onto cubemap FBO using geometry shader - GL.Ext.BindFramebuffer(FramebufferTarget.FramebufferExt, textureCubeFBO); - GL.UseProgram(shaderProgramCubemap); - GL.PushAttrib(AttribMask.ViewportBit); - { - GL.Viewport(0, 0, 512, 512); - - // clear all cubemap faces to blue - GL.ClearColor(0f, 0f, 1f, 0f); - for (int i = 0; i < 6; i++) - { - GL.Ext.FramebufferTexture2D(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0, TextureTarget.TextureCubeMapPositiveX + i, textureCubeColor, 0); - //todo select depth renderbuffer face and trun depth_test on again - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - } - GL.Ext.FramebufferTexture(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0, textureCubeColor, 0); - // Create 6 ModelViewProjection matrices, one to look in each direction - // proj with 90 degrees (1/2 pi) fov - // translate negative to place cam insize sphere - Matrix4 model = Matrix4.CreateScale(-1) * Matrix4.CreateTranslation(spherePos); - Matrix4 proj = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver2, 1, 0.1f, 100f); - - Matrix4[] m = new Matrix4[6]; - - m[0] = model * Matrix4.LookAt(Vector3.Zero, Vector3.UnitX, -Vector3.UnitY) * proj; - m[1] = model * Matrix4.LookAt(Vector3.Zero, -Vector3.UnitX, -Vector3.UnitY) * proj; - m[2] = model * Matrix4.LookAt(Vector3.Zero, Vector3.UnitY, Vector3.UnitZ) * proj; - m[3] = model * Matrix4.LookAt(Vector3.Zero, -Vector3.UnitY, -Vector3.UnitZ) * proj; - m[4] = model * Matrix4.LookAt(Vector3.Zero, Vector3.UnitZ, -Vector3.UnitY) * proj; - m[5] = model * Matrix4.LookAt(Vector3.Zero, -Vector3.UnitZ, -Vector3.UnitY) * proj; - GL.UniformMatrix4(GL.GetUniformLocation(shaderProgramCubemap, "matrixPX"), false, ref m[0]); - GL.UniformMatrix4(GL.GetUniformLocation(shaderProgramCubemap, "matrixNX"), false, ref m[1]); - GL.UniformMatrix4(GL.GetUniformLocation(shaderProgramCubemap, "matrixPY"), false, ref m[2]); - GL.UniformMatrix4(GL.GetUniformLocation(shaderProgramCubemap, "matrixNY"), false, ref m[3]); - GL.UniformMatrix4(GL.GetUniformLocation(shaderProgramCubemap, "matrixPZ"), false, ref m[4]); - GL.UniformMatrix4(GL.GetUniformLocation(shaderProgramCubemap, "matrixNZ"), false, ref m[5]); - - - renderCubeVBO(); - } - GL.PopAttrib(); - GL.Ext.BindFramebuffer(FramebufferTarget.FramebufferExt, 0); - GL.UseProgram(0); - GL.Enable(EnableCap.DepthTest); - } - - void renderScene() - { - GL.MatrixMode(MatrixMode.Projection); - GL.PushMatrix(); - setPerspective(); - GL.MatrixMode(MatrixMode.Modelview); - GL.PushMatrix(); - Matrix4 lookat = Matrix4.LookAt(eyePos, eyeLookat, Vector3.UnitY); - GL.LoadMatrix(ref lookat); - - - GL.UseProgram(shaderProgramBox); - renderCubeVBO(); - GL.UseProgram(shaderProgramSphere); - GL.BindTexture(TextureTarget.TextureCubeMap, textureCubeColor); - GL.Uniform1(GL.GetUniformLocation(shaderProgramSphere, "tex"), 0); - GL.Translate(spherePos); - GL.Enable(EnableCap.DepthTest); - renderSphereVBO(); - GL.UseProgram(0); - - GL.MatrixMode(MatrixMode.Projection); - GL.PopMatrix(); - GL.MatrixMode(MatrixMode.Modelview); - GL.PopMatrix(); - } - - #endregion - - #region overrides - - protected override void OnLoad(EventArgs e) - { - if (!GL.GetString(StringName.Extensions).Contains("EXT_geometry_shader4")) - { - System.Windows.Forms.MessageBox.Show( - "Your video card does not support EXT_geometry_shader4. Please update your drivers.", - "EXT_geometry_shader4 not supported", - System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); - Exit(); - } - - //int tmp; - //GL.GetInteger(GetPName.MaxVertexUniformComponents, out tmp); - //0x0400 - // 6 * 4x4 mat (0x10) = 0x60 - - // init shaders - initShaderProgramBox(); - initShaderProgramSphere(); - initShaderProgramCubemap(); - // init textures / fbos - initTextureCube(); - // init vbos - initVBOCube(); - initVBOSpere(); - - //switchToMode(ViewMode.Scene); - - } - - protected override void OnUnload(EventArgs e) - { - if (shaderProgramBox != 0) - GL.DeleteProgram(shaderProgramBox); - if (shaderProgramSphere != 0) - GL.DeleteProgram(shaderProgramSphere); - if (shaderProgramCubemap != 0) - GL.DeleteProgram(shaderProgramCubemap); - if (textureCubeColor != 0) - GL.DeleteTexture(textureCubeColor); - if (textureCubeDepth != 0) - GL.DeleteTexture(textureCubeDepth); - if (textureCubeFBO != 0) - GL.DeleteFramebuffers(1, ref textureCubeFBO); - base.OnUnload(e); - } - - protected override void OnResize(EventArgs e) - { - GL.Viewport(0, 0, Width, Height); - - // Set projection matrix - GL.MatrixMode(MatrixMode.Projection); - switch (mode) - { - case ViewMode.CubemapCross: - setOrtho(); - break; - case ViewMode.Scene: - setPerspective(); - break; - default: - GL.LoadIdentity(); - break; - } - - // Set selector state back to ModelView matrix mode - GL.MatrixMode(MatrixMode.Modelview); - base.OnResize(e); - - } - - protected override void OnUpdateFrame(FrameEventArgs e) - { - base.OnUpdateFrame(e); - - // elapsed time in ms since last start - double elapsed = (DateTime.Now - startTime).TotalMilliseconds; - - spherePos.X = (float)Math.Sin(elapsed / 5000) * 3; - spherePos.Z = (float)Math.Cos(elapsed / 5000) * 3; - eyePos.X = (float)Math.Cos(elapsed / 3000) * 8; - eyePos.Z = (float)Math.Sin(elapsed / 2000) * 8; - - var keyboard = OpenTK.Input.Keyboard.GetState(); - if (keyboard[Key.Space]) - { - ErrorCode err = GL.GetError(); - //Console.WriteLine(err + " " + Glu.ErrorString((GluErrorCode)err)); - Console.WriteLine("GL error code: {0}", err); - } - } - - protected override void OnRenderFrame(FrameEventArgs e) - { - if (mode == ViewMode.CubemapCross) - { - renderCubemap(); - drawCubemapCross(); - } - if (mode == ViewMode.Scene) - { - renderCubemap(); - GL.ClearColor(0.1f, 0.1f, 0.1f, 0.1f); - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - renderScene(); - } - - this.SwapBuffers(); - } - - #endregion - - #region public static void Main() - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - using (SimpleGeometryShader2 example = new SimpleGeometryShader2()) - { - Utilities.SetWindowTitle(example); - example.Run(60.0, 0.0); - } - } - - #endregion - - #region data - //structure: vec3 pos, vec3 normal, vec2 texcoord - static float[] cubeData = { - -10,-10,-10, 0,0,-10, 1.0f,0.0f, - -10,10,-10, 0,0,-10, 1.0f,1.0f, - 10,10,-10, 0,0,-10, 0.0f,1.0f, - - 10,10,-10, 0,0,-10, 0.0f,1.0f, - 10,-10,-10, 0,0,-10, 0.0f,0.0f, - -10,-10,-10, 0,0,-10, 1.0f,0.0f, - - -10,-10,10, 0,0,10, 0.0f,0.0f, - 10,-10,10, 0,0,10, 1.0f,0.0f, - 10,10,10, 0,0,10, 1.0f,1.0f, - - 10,10,10, 0,0,10, 1.0f,1.0f, - -10,10,10, 0,0,10, 0.0f,1.0f, - -10,-10,10, 0,0,10, 0.0f,0.0f, - - -10,-10,-10, 0,-10,0, 0.0f,0.0f, - 10,-10,-10, 0,-10,0, 1.0f,0.0f, - 10,-10,10, 0,-10,0, 1.0f,1.0f, - - 10,-10,10, 0,-10,0, 1.0f,1.0f, - -10,-10,10, 0,-10,0, 0.0f,1.0f, - -10,-10,-10, 0,-10,0, 0.0f,0.0f, - - 10,-10,-10, 10,0,0, 0.0f,0.0f, - 10,10,-10, 10,0,0, 1.0f,0.0f, - 10,10,10, 10,0,0, 1.0f,1.0f, - - 10,10,10, 10,0,0, 1.0f,1.0f, - 10,-10,10, 10,0,0, 0.0f,1.0f, - 10,-10,-10, 10,0,0, 0.0f,0.0f, - - 10,10,-10, 0,10,0, 0.0f,0.0f, - -10,10,-10, 0,10,0, 1.0f,0.0f, - -10,10,10, 0,10,0, 1.0f,1.0f, - - -10,10,10, 0,10,0, 1.0f,1.0f, - 10,10,10, 0,10,0, 0.0f,1.0f, - 10,10,-10, 0,10,0, 0.0f,0.0f, - - -10,10,-10, -10,0,0, 0.0f,0.0f, - -10,-10,-10, -10,0,0, 1.0f,0.0f, - -10,-10,10, -10,0,0, 1.0f,1.0f, - - -10,-10,10, -10,0,0, 1.0f,1.0f, - -10,10,10, -10,0,0, 0.0f,1.0f, - -10,10,-10, -10,0,0, 0.0f,0.0f, - }; - - static VertexPositionNormalTexture[] CalculateSphereVertices(float radius, float height, byte segments, byte rings) - { - VertexPositionNormalTexture[] data = new VertexPositionNormalTexture[segments * rings]; - - int i = 0; - - for (double y = 0; y < rings; y++) - { - double phi = (y / (rings - 1)) * Math.PI; - for (double x = 0; x < segments; x++) - { - double theta = (x / (segments - 1)) * 2 * Math.PI; - - Vector3 v = new Vector3( - (float)(radius * Math.Sin(phi) * Math.Cos(theta)), - (float)(height * Math.Cos(phi)), - (float)(radius * Math.Sin(phi) * Math.Sin(theta))); - Vector3 n = Vector3.Normalize(v); - Vector2 uv = new Vector2( - (float)(x / (segments - 1)), - (float)(y / (rings - 1))); - // Using data[i++] causes i to be incremented multiple times in Mono 2.2 (bug #479506). - data[i] = new VertexPositionNormalTexture(v, n, uv); - i++; - } - - } - - return data; - } - - static ushort[] CalculateSphereElements(float radius, float height, byte segments, byte rings) - { - int num_vertices = segments * rings; - ushort[] data = new ushort[num_vertices * 6]; - - ushort i = 0; - - for (byte y = 0; y < rings - 1; y++) - { - for (byte x = 0; x < segments - 1; x++) - { - data[i++] = (ushort)((y + 0) * segments + x); - data[i++] = (ushort)((y + 1) * segments + x); - data[i++] = (ushort)((y + 1) * segments + x + 1); - - data[i++] = (ushort)((y + 1) * segments + x + 1); - data[i++] = (ushort)((y + 0) * segments + x + 1); - data[i++] = (ushort)((y + 0) * segments + x); - } - } - - // Verify that we don't access any vertices out of bounds: - foreach (int index in data) - if (index >= segments * rings) - throw new IndexOutOfRangeException(); - - return data; - } - - #endregion - } -} \ No newline at end of file diff --git a/Source/Examples/OpenGL/2.x/JuliaSetFractal.cs b/Source/Examples/OpenGL/2.x/JuliaSetFractal.cs deleted file mode 100644 index c896c217..00000000 --- a/Source/Examples/OpenGL/2.x/JuliaSetFractal.cs +++ /dev/null @@ -1,307 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Windows.Forms; -using System.Diagnostics; -using System.Drawing; -using System.Drawing.Imaging; -using System.IO; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; -using OpenTK.Input; - -namespace Examples.Tutorial -{ - /// - /// Demonstrates how to render an animated Julia Set in real-time. Quality is sacrificed for speed. - /// Info about the fractal: http://en.wikipedia.org/wiki/Julia_set - /// One more major optimization could be applied (exploit the symmetry of the image with RTT), but - /// that would make the program alot more complicated to follow. You can do this as an exercise. - /// - [Example("Julia Set Fractal", ExampleCategory.OpenGL, "2.x", Documentation = "JuliaSetFractal")] - public class JuliaSetFractal : GameWindow - { - public JuliaSetFractal() - : base(512, 512) - { - } - - #region Private Fields - - // GLSL Objects - int VertexShaderObject, FragmentShaderObject, ProgramObject; - int TextureObject; - - // Julia Variables for animation - float AnimOffsetX = 0.213f; // using non-zero as starting point to make it more interesting - float AnimOffsetY = 0.63f; - - const double AnimSpeedX = 0.65; // anim speed scaling is solely used to make the anim more interesting - const double AnimSpeedY = 1.05; - const double AnimCosinusPercent = 0.85f; // scales the cosinus down to 85% to avoid the (boring) borders - - float UniformScaleFactorX; // fractal horizontal scaling is only affected by window resize - float UniformScaleFactorY; // fractal vertical scaling is only affected by window resize - float UniformOffsetX = 1.8f; // fractal horizontal offset - float UniformOffsetY = 1.8f; // fractal vertical offset - - #endregion private Fields - - #region OnLoad - - /// - /// Setup OpenGL and load resources here. - /// - /// Not used. - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - // Check for necessary capabilities: - Version version = new Version(GL.GetString(StringName.Version).Substring(0, 3)); - Version target = new Version(2, 0); - if (version < target) - { - throw new NotSupportedException(String.Format( - "OpenGL {0} is required (you only have {1}).", target, version)); - } - - this.VSync = VSyncMode.On; - - GL.Disable(EnableCap.Dither); - GL.ClearColor(0.2f, 0f, 0.4f, 0f); - - // declare some variables for tracking which shader did compile, and which texture to use - string[] ShaderFilenames = new string[2]; - ShaderFilenames[0] = "Data/Shaders/JuliaSet_SM3_FS.glsl"; - ShaderFilenames[1] = "Data/Shaders/JuliaSet_SM2_FS.glsl"; - - string LogInfo; - int status = 0; - - #region Shaders - // Load&Compile Vertex Shader - using (StreamReader sr = new StreamReader("Data/Shaders/JuliaSet_VS.glsl")) - { - VertexShaderObject = GL.CreateShader(ShaderType.VertexShader); - GL.ShaderSource(VertexShaderObject, sr.ReadToEnd()); - GL.CompileShader(VertexShaderObject); - } - - GL.GetShaderInfoLog(VertexShaderObject, out LogInfo); - if (LogInfo.Length > 0 && !LogInfo.Contains("hardware")) - Trace.WriteLine("Vertex Shader Log:\n" + LogInfo); - else - Trace.WriteLine("Vertex Shader compiled without complaint."); - - // Load&Compile Fragment Shader - FragmentShaderObject = GL.CreateShader(ShaderType.FragmentShader); - foreach (var shader in ShaderFilenames) - { - using (StreamReader sr = new StreamReader(shader)) - { - GL.ShaderSource(FragmentShaderObject, sr.ReadToEnd()); - GL.CompileShader(FragmentShaderObject); - } - GL.GetShader(FragmentShaderObject, ShaderParameter.CompileStatus, out status); - if (status != 1) - { - GL.GetShaderInfoLog(FragmentShaderObject, out LogInfo); - Trace.WriteLine("Compiling " + shader + " failed!\nLog:\n" + LogInfo); - } - else - { - Trace.WriteLine("Fragment Shader compiled without complaint."); - break; - } - } - if (status != 1) - { - MessageBox.Show("Shader compilation failed"); - Exit(); - } - - // Link the Shaders to a usable Program - ProgramObject = GL.CreateProgram(); - GL.AttachShader(ProgramObject, VertexShaderObject); - GL.AttachShader(ProgramObject, FragmentShaderObject); - GL.LinkProgram(ProgramObject); - - // make current - GL.UseProgram(ProgramObject); - - // Flag ShaderObjects for delete when app exits - GL.DeleteShader(VertexShaderObject); - GL.DeleteShader(FragmentShaderObject); - #endregion Shaders - - #region Textures - - // Load&Bind the 1D texture for color lookups - GL.ActiveTexture(TextureUnit.Texture0); // select TMU0 - GL.GenTextures(1, out TextureObject); - GL.TexParameter(TextureTarget.Texture1D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); - GL.TexParameter(TextureTarget.Texture1D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); - GL.TexParameter(TextureTarget.Texture1D, TextureParameterName.TextureWrapS, (int)(TextureWrapMode)All.ClampToEdge); - - using (Bitmap bitmap = new Bitmap("Data/Textures/JuliaColorTable.bmp")) - { - BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, - System.Drawing.Imaging.PixelFormat.Format24bppRgb); - GL.TexImage1D(TextureTarget.Texture1D, 0, PixelInternalFormat.Rgb8, data.Width, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgr, - PixelType.UnsignedByte, data.Scan0); - bitmap.UnlockBits(data); - } - #endregion Textures - - KeyUp += Keyboard_KeyUp; - } - - int i = 0; - void Keyboard_KeyUp(object sender, KeyboardKeyEventArgs e) - { - if (e.Key == Key.F12) - { - Bitmap bmp = new Bitmap(this.Width, this.Height); - System.Drawing.Imaging.BitmapData data = - bmp.LockBits(new System.Drawing.Rectangle(0, 0, this.Width, this.Height), - System.Drawing.Imaging.ImageLockMode.WriteOnly, - System.Drawing.Imaging.PixelFormat.Format24bppRgb); - GL.ReadPixels(0, 0, this.Width, this.Height, - OpenTK.Graphics.OpenGL.PixelFormat.Bgr, - OpenTK.Graphics.OpenGL.PixelType.UnsignedByte, - data.Scan0); - bmp.UnlockBits(data); - bmp.RotateFlip(RotateFlipType.RotateNoneFlipY); - bmp.Save("Screenshot" + (i++).ToString() + ".png", ImageFormat.Png); - } - } - - #endregion - - #region OnUnload - - protected override void OnUnload(EventArgs e) - { - if (TextureObject != 0) - GL.DeleteTextures(1, ref TextureObject); - - if (ProgramObject != 0) - GL.DeleteProgram(ProgramObject); // implies deleting the previously flagged ShaderObjects - } - - #endregion - - #region OnResize - - /// - /// Respond to resize events here. - /// - /// Contains information on the new GameWindow size. - /// There is no need to call the base implementation. - protected override void OnResize(EventArgs e) - { - // Magic numbers so the fractal almost fits inside the window. - // If changing this, also change the -1.6f offset in the fragment shader accordingly. - UniformScaleFactorX = Width / (UniformOffsetX * 2f); - UniformScaleFactorY = Height / (UniformOffsetY * 2f); - - GL.Viewport(0, 0, Width, Height); - - GL.MatrixMode(MatrixMode.Projection); - GL.LoadIdentity(); - GL.Ortho(-1.0, 1.0, -1.0, 1.0, 0.0, 1.0); // 2D setup - - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadIdentity(); - } - - #endregion - - #region OnUpdateFrame - - /// - /// Add your game logic here. - /// - /// Contains timing information. - /// There is no need to call the base implementation. - protected override void OnUpdateFrame(FrameEventArgs e) - { - base.OnUpdateFrame(e); - - var keyboard = OpenTK.Input.Keyboard.GetState(); - if (keyboard[OpenTK.Input.Key.Escape]) - { - this.Exit(); - } - } - - #endregion - - #region OnRenderFrame - - /// - /// Add your game rendering code here. - /// - /// Contains timing information. - /// There is no need to call the base implementation. - protected override void OnRenderFrame(FrameEventArgs e) - { - //this.Title = "FPS: " + 1 / e.Time; - GL.Clear(ClearBufferMask.ColorBufferBit); - - // First, render the next frame of the Julia fractal. - GL.UseProgram(ProgramObject); - - // advance the animation by elapsed time, scaling is solely used to make the anim more interesting - AnimOffsetX += (float)(e.Time * AnimSpeedX); - AnimOffsetY += (float)(e.Time * AnimSpeedY); - - // pass uniforms into the fragment shader - // first the texture - GL.Uniform1(GL.GetUniformLocation(ProgramObject, "COLORTABLE"), TextureObject); - // the rest are floats - GL.Uniform1(GL.GetUniformLocation(ProgramObject, "CETX"), (float)(Math.Cos(AnimOffsetX) * AnimCosinusPercent)); - GL.Uniform1(GL.GetUniformLocation(ProgramObject, "CETY"), (float)(Math.Cos(AnimOffsetY) * AnimCosinusPercent)); - GL.Uniform1(GL.GetUniformLocation(ProgramObject, "SCALINGX"), UniformScaleFactorX); - GL.Uniform1(GL.GetUniformLocation(ProgramObject, "SCALINGY"), UniformScaleFactorY); - GL.Uniform1(GL.GetUniformLocation(ProgramObject, "OFFSETX"), UniformOffsetX); - GL.Uniform1(GL.GetUniformLocation(ProgramObject, "OFFSETY"), UniformOffsetY); - - // Fullscreen quad. Using immediate mode, since this app is fragment shader limited anyways. - GL.Begin(PrimitiveType.Quads); - { - GL.Vertex2(-1.0f, -1.0f); - GL.Vertex2(1.0f, -1.0f); - GL.Vertex2(1.0f, 1.0f); - GL.Vertex2(-1.0f, 1.0f); - } - GL.End(); - - SwapBuffers(); - } - - #endregion - - #region public static void Main() - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - using (JuliaSetFractal example = new JuliaSetFractal()) - { - Utilities.SetWindowTitle(example); - example.Run(30.0); - } - } - - #endregion - } -} diff --git a/Source/Examples/OpenGL/2.x/SimpleGLSL.cs b/Source/Examples/OpenGL/2.x/SimpleGLSL.cs deleted file mode 100644 index 3835ff77..00000000 --- a/Source/Examples/OpenGL/2.x/SimpleGLSL.cs +++ /dev/null @@ -1,293 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -#region --- Using Directives --- - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.Threading; -using System.Diagnostics; -using System.IO; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; - -#endregion --- Using Directives --- - -namespace Examples.Tutorial -{ - /// - /// Demonstrates how to load and use a simple OpenGL shader program. Example is incomplete (documentation). - /// - [Example("First shader", ExampleCategory.OpenGL, "2.x", Documentation = "SimpleGLSL")] - public class T10_GLSL_Cube : GameWindow - { - #region --- Fields --- - - static float angle = 0.0f, rotation_speed = 3.0f; - int vertex_shader_object, fragment_shader_object, shader_program; - int vertex_buffer_object, color_buffer_object, element_buffer_object; - - Shapes.Shape shape = new Examples.Shapes.Cube(); - - #endregion - - #region --- Constructors --- - - public T10_GLSL_Cube() - : base(800, 600, GraphicsMode.Default) - { } - - #endregion - - #region OnLoad - - /// - /// This is the place to load resources that change little - /// during the lifetime of the GameWindow. In this case, we - /// check for GLSL support, and load the shaders. - /// - /// Not used. - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - // Check for necessary capabilities: - Version version = new Version(GL.GetString(StringName.Version).Substring(0, 3)); - Version target = new Version(2, 0); - if (version < target) - { - throw new NotSupportedException(String.Format( - "OpenGL {0} is required (you only have {1}).", target, version)); - } - - GL.ClearColor(Color.MidnightBlue); - GL.Enable(EnableCap.DepthTest); - - CreateVBO(); - - using (StreamReader vs = new StreamReader("Data/Shaders/Simple_VS.glsl")) - using (StreamReader fs = new StreamReader("Data/Shaders/Simple_FS.glsl")) - CreateShaders(vs.ReadToEnd(), fs.ReadToEnd(), - out vertex_shader_object, out fragment_shader_object, - out shader_program); - } - - #endregion - - #region CreateShaders - - void CreateShaders(string vs, string fs, - out int vertexObject, out int fragmentObject, - out int program) - { - int status_code; - string info; - - vertexObject = GL.CreateShader(ShaderType.VertexShader); - fragmentObject = GL.CreateShader(ShaderType.FragmentShader); - - // Compile vertex shader - GL.ShaderSource(vertexObject, vs); - GL.CompileShader(vertexObject); - GL.GetShaderInfoLog(vertexObject, out info); - GL.GetShader(vertexObject, ShaderParameter.CompileStatus, out status_code); - - if (status_code != 1) - throw new ApplicationException(info); - - // Compile vertex shader - GL.ShaderSource(fragmentObject, fs); - GL.CompileShader(fragmentObject); - GL.GetShaderInfoLog(fragmentObject, out info); - GL.GetShader(fragmentObject, ShaderParameter.CompileStatus, out status_code); - - if (status_code != 1) - throw new ApplicationException(info); - - program = GL.CreateProgram(); - GL.AttachShader(program, fragmentObject); - GL.AttachShader(program, vertexObject); - - GL.LinkProgram(program); - GL.UseProgram(program); - } - - #endregion - - #region private void CreateVBO() - - void CreateVBO() - { - int size; - - GL.GenBuffers(1, out vertex_buffer_object); - GL.GenBuffers(1, out color_buffer_object); - GL.GenBuffers(1, out element_buffer_object); - - // Upload the vertex buffer. - GL.BindBuffer(BufferTarget.ArrayBuffer, vertex_buffer_object); - GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(shape.Vertices.Length * 3 * sizeof(float)), shape.Vertices, - BufferUsageHint.StaticDraw); - GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out size); - if (size != shape.Vertices.Length * 3 * sizeof(Single)) - throw new ApplicationException(String.Format( - "Problem uploading vertex buffer to VBO (vertices). Tried to upload {0} bytes, uploaded {1}.", - shape.Vertices.Length * 3 * sizeof(Single), size)); - - // Upload the color buffer. - GL.BindBuffer(BufferTarget.ArrayBuffer, color_buffer_object); - GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(shape.Colors.Length * sizeof(int)), shape.Colors, - BufferUsageHint.StaticDraw); - GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out size); - if (size != shape.Colors.Length * sizeof(int)) - throw new ApplicationException(String.Format( - "Problem uploading vertex buffer to VBO (colors). Tried to upload {0} bytes, uploaded {1}.", - shape.Colors.Length * sizeof(int), size)); - - // Upload the index buffer (elements inside the vertex buffer, not color indices as per the IndexPointer function!) - GL.BindBuffer(BufferTarget.ElementArrayBuffer, element_buffer_object); - GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(shape.Indices.Length * sizeof(Int32)), shape.Indices, - BufferUsageHint.StaticDraw); - GL.GetBufferParameter(BufferTarget.ElementArrayBuffer, BufferParameterName.BufferSize, out size); - if (size != shape.Indices.Length * sizeof(int)) - throw new ApplicationException(String.Format( - "Problem uploading vertex buffer to VBO (offsets). Tried to upload {0} bytes, uploaded {1}.", - shape.Indices.Length * sizeof(int), size)); - } - - #endregion - - #region OnUnload - - protected override void OnUnload(EventArgs e) - { - if (shader_program != 0) - GL.DeleteProgram(shader_program); - if (fragment_shader_object != 0) - GL.DeleteShader(fragment_shader_object); - if (vertex_shader_object != 0) - GL.DeleteShader(vertex_shader_object); - if (vertex_buffer_object != 0) - GL.DeleteBuffers(1, ref vertex_buffer_object); - if (element_buffer_object != 0) - GL.DeleteBuffers(1, ref element_buffer_object); - } - - #endregion - - #region OnResize - - /// - /// Called when the user resizes the window. - /// - /// Contains the new width/height of the window. - /// - /// You want the OpenGL viewport to match the window. This is the place to do it! - /// - protected override void OnResize(EventArgs e) - { - GL.Viewport(0, 0, Width, Height); - - float aspect_ratio = Width / (float)Height; - Matrix4 perpective = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspect_ratio, 1, 64); - GL.MatrixMode(MatrixMode.Projection); - GL.LoadMatrix(ref perpective); - } - - #endregion - - #region OnUpdateFrame - - /// - /// Prepares the next frame for rendering. - /// - /// - /// Place your control logic here. This is the place to respond to user input, - /// update object positions etc. - /// - protected override void OnUpdateFrame(FrameEventArgs e) - { - var keyboard = OpenTK.Input.Keyboard.GetState(); - if (keyboard[OpenTK.Input.Key.Escape]) - this.Exit(); - - if (keyboard[OpenTK.Input.Key.F11]) - if (WindowState != WindowState.Fullscreen) - WindowState = WindowState.Fullscreen; - else - WindowState = WindowState.Normal; - } - - #endregion - - #region OnRenderFrame - - /// - /// Place your rendering code here. - /// - protected override void OnRenderFrame(FrameEventArgs e) - { - GL.Clear(ClearBufferMask.ColorBufferBit | - ClearBufferMask.DepthBufferBit); - - Matrix4 lookat = Matrix4.LookAt(0, 5, 5, 0, 0, 0, 0, 1, 0); - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadMatrix(ref lookat); - - angle += rotation_speed * (float)e.Time; - GL.Rotate(angle, 0.0f, 1.0f, 0.0f); - - GL.EnableClientState(ArrayCap.VertexArray); - GL.EnableClientState(ArrayCap.ColorArray); - - GL.BindBuffer(BufferTarget.ArrayBuffer, vertex_buffer_object); - GL.VertexPointer(3, VertexPointerType.Float, 0, IntPtr.Zero); - GL.BindBuffer(BufferTarget.ArrayBuffer, color_buffer_object); - GL.ColorPointer(4, ColorPointerType.UnsignedByte, 0, IntPtr.Zero); - GL.BindBuffer(BufferTarget.ElementArrayBuffer, element_buffer_object); - - GL.DrawElements(PrimitiveType.Triangles, shape.Indices.Length, - DrawElementsType.UnsignedInt, IntPtr.Zero); - - //GL.DrawArrays(GL.Enums.BeginMode.POINTS, 0, shape.Vertices.Length); - - GL.DisableClientState(ArrayCap.VertexArray); - GL.DisableClientState(ArrayCap.ColorArray); - - - //int error = GL.GetError(); - //if (error != 0) - // Debug.Print(Glu.ErrorString(Glu.Enums.ErrorCode.INVALID_OPERATION)); - - SwapBuffers(); - } - - #endregion - - #region public static void Main() - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - using (T10_GLSL_Cube example = new T10_GLSL_Cube()) - { - // Get the title and category of this example using reflection. - ExampleAttribute info = ((ExampleAttribute)example.GetType().GetCustomAttributes(false)[0]); - example.Title = String.Format("OpenTK | {0} {1}: {2}", info.Category, info.Difficulty, info.Title); - example.Run(30.0, 0.0); - } - } - - #endregion - } -} diff --git a/Source/Examples/OpenGL/2.x/SwizzledParallax.cs b/Source/Examples/OpenGL/2.x/SwizzledParallax.cs deleted file mode 100644 index 09dd5d25..00000000 --- a/Source/Examples/OpenGL/2.x/SwizzledParallax.cs +++ /dev/null @@ -1,380 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Diagnostics; -using System.Drawing; -using System.IO; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; - -using Examples.TextureLoaders; - -namespace Examples.Tutorial -{ - /// Demonstrates Swizzled DXT5 Parallax Mapping - /// The idea is described in more detail right here: http://www.opentk.com/node/394 - /// - [Example("Swizzled Parallax Mapping", ExampleCategory.OpenGL, "2.x", Documentation = "SwizzledParallax")] - public class T12_GLSL_Parallax: GameWindow - { - public T12_GLSL_Parallax( ) - : base( 800, 600 ) - { - } - - #region internal Fields - - // Shader - int VertexShaderObject, FragmentShaderObject, ProgramObject; - const string VertexShaderFilename = "Data/Shaders/Parallax_VS.glsl"; - const string FragmentShaderFilename = "Data/Shaders/Parallax_FS.glsl"; - - const int AttribTangent = 5; // slot where to pass tangents to VS, not sure which are reserved besides 0 - Vector3 Tangent = new Vector3( 1f, 0f, 0f ); - Vector3 Normal = new Vector3( 0f, 0f, 1f ); - - // Material parameter - //Vector3 MaterialScaleAndBiasAndShininess = new Vector3( 0.07f, 0.0f, 38.0f ); // for Metal tex - Vector3 MaterialScaleAndBiasAndShininess = new Vector3( 0.04f, 0.0f, 92.0f ); // for Rock tex - - // Textures - const TextureUnit TMU0_Unit = TextureUnit.Texture0; - const int TMU0_UnitInteger = 0; - const string TMU0_Filename = "Data/Textures/swizzled-rock-diffuse-height.dds"; - uint TMU0_Handle; - TextureTarget TMU0_Target; - - const TextureUnit TMU1_Unit = TextureUnit.Texture1; - const int TMU1_UnitInteger = 1; - const string TMU1_Filename = "Data/Textures/swizzled-rock-normal-gloss.dds"; - uint TMU1_Handle; - TextureTarget TMU1_Target; - - // Camera - Vector3 EyePos = new Vector3( 0.0f, 0.0f, 3.0f ); - - // Light - Vector3 LightPosition = new Vector3( 0.0f, 1.0f, 1.0f ); - Vector3 LightDiffuse = new Vector3( 0.5f, 0.5f, 0.5f ); - Vector3 LightSpecular = new Vector3( 1f, 1f, 1f ); - - #endregion internal Fields - - /// Setup OpenGL and load resources here. - /// Not used. - protected override void OnLoad(EventArgs e) - { - this.VSync = VSyncMode.Off; - - // Check for necessary capabilities: - string extensions = GL.GetString(StringName.Extensions); - if ( !GL.GetString(StringName.Extensions).Contains("GL_ARB_shading_language")) - { - throw new NotSupportedException(String.Format("This example requires OpenGL 2.0. Found {0}. Aborting.", - GL.GetString(StringName.Version).Substring(0, 3))); - } - - if (!extensions.Contains("GL_ARB_texture_compression") || - !extensions.Contains("GL_EXT_texture_compression_s3tc")) - { - throw new NotSupportedException("This example requires support for texture compression. Aborting."); - } - - int[] temp = new int[1]; - GL.GetInteger( GetPName.MaxTextureImageUnits, out temp[0] ); - Trace.WriteLine( temp[0] + " TMU's for Fragment Shaders found. (2 required)" ); - - GL.GetInteger( GetPName.MaxVaryingFloats, out temp[0] ); - Trace.WriteLine( temp[0] + " varying floats between VS and FS allowed. (6 required)" ); - - GL.GetInteger( GetPName.MaxVertexUniformComponents, out temp[0] ); - Trace.WriteLine( temp[0] + " uniform components allowed in Vertex Shader. (6 required)" ); - - GL.GetInteger( GetPName.MaxFragmentUniformComponents, out temp[0] ); - Trace.WriteLine( temp[0] + " uniform components allowed in Fragment Shader. (11 required)" ); - Trace.WriteLine("" ); - - #region GL State - - GL.ClearColor( 0.2f, 0f, 0.4f, 0f ); - - GL.PointSize( 10f ); - - GL.Disable( EnableCap.Dither ); - - GL.FrontFace( FrontFaceDirection.Ccw ); - GL.PolygonMode( MaterialFace.Front, PolygonMode.Fill ); - GL.PolygonMode( MaterialFace.Back, PolygonMode.Line ); - - #endregion GL State - - #region Shaders - - string LogInfo; - - // Load&Compile Vertex Shader - - using ( StreamReader sr = new StreamReader( VertexShaderFilename ) ) - { - VertexShaderObject = GL.CreateShader( ShaderType.VertexShader ); - GL.ShaderSource( VertexShaderObject, sr.ReadToEnd( ) ); - GL.CompileShader( VertexShaderObject ); - } - - GL.GetShaderInfoLog( VertexShaderObject, out LogInfo ); - if ( LogInfo.Length > 0 && !LogInfo.Contains( "hardware" ) ) - Trace.WriteLine( "Vertex Shader failed!\nLog:\n" + LogInfo ); - else - Trace.WriteLine( "Vertex Shader compiled without complaint." ); - - // Load&Compile Fragment Shader - - using ( StreamReader sr = new StreamReader( FragmentShaderFilename ) ) - { - FragmentShaderObject = GL.CreateShader( ShaderType.FragmentShader ); - GL.ShaderSource( FragmentShaderObject, sr.ReadToEnd( ) ); - GL.CompileShader( FragmentShaderObject ); - } - GL.GetShaderInfoLog( FragmentShaderObject, out LogInfo ); - - if ( LogInfo.Length > 0 && !LogInfo.Contains( "hardware" ) ) - Trace.WriteLine( "Fragment Shader failed!\nLog:\n" + LogInfo ); - else - Trace.WriteLine( "Fragment Shader compiled without complaint." ); - - // Link the Shaders to a usable Program - ProgramObject = GL.CreateProgram( ); - GL.AttachShader( ProgramObject, VertexShaderObject ); - GL.AttachShader( ProgramObject, FragmentShaderObject ); - - // must bind the attribute before linking - GL.BindAttribLocation( ProgramObject, AttribTangent, "AttributeTangent" ); - - // link it all together - GL.LinkProgram( ProgramObject ); - - // flag ShaderObjects for delete when not used anymore - GL.DeleteShader( VertexShaderObject ); - GL.DeleteShader( FragmentShaderObject ); - - GL.GetProgram(ProgramObject, GetProgramParameterName.LinkStatus, out temp[0]); - Trace.WriteLine( "Linking Program (" + ProgramObject + ") " + ( ( temp[0] == 1 ) ? "succeeded." : "FAILED!" ) ); - if ( temp[0] != 1 ) - { - GL.GetProgramInfoLog( ProgramObject, out LogInfo ); - Trace.WriteLine( "Program Log:\n" + LogInfo ); - } - - GL.GetProgram(ProgramObject, GetProgramParameterName.ActiveAttributes, out temp[0]); - Trace.WriteLine( "Program registered " + temp[0] + " Attributes. (Should be 4: Pos, UV, Normal, Tangent)" ); - - Trace.WriteLine( "Tangent attribute bind location: " + GL.GetAttribLocation( ProgramObject, "AttributeTangent" ) ); - - Trace.WriteLine( "End of Shader build. GL Error: " + GL.GetError( ) ); - - #endregion Shaders - - #region Textures - - TextureLoaderParameters.MagnificationFilter = TextureMagFilter.Linear; - TextureLoaderParameters.MinificationFilter = TextureMinFilter.LinearMipmapLinear; - TextureLoaderParameters.WrapModeS = TextureWrapMode.ClampToBorder; - TextureLoaderParameters.WrapModeT = TextureWrapMode.ClampToBorder; - TextureLoaderParameters.EnvMode = TextureEnvMode.Modulate; - - ImageDDS.LoadFromDisk( TMU0_Filename, out TMU0_Handle, out TMU0_Target ); - Trace.WriteLine( "Loaded " + TMU0_Filename + " with handle " + TMU0_Handle + " as " + TMU0_Target ); - - ImageDDS.LoadFromDisk( TMU1_Filename, out TMU1_Handle, out TMU1_Target ); - Trace.WriteLine( "Loaded " + TMU1_Filename + " with handle " + TMU1_Handle + " as " + TMU1_Target ); - - #endregion Textures - - Trace.WriteLine( "End of Texture Loading. GL Error: " + GL.GetError( ) ); - Trace.WriteLine( ""); - } - - protected override void OnUnload(EventArgs e) - { - GL.DeleteProgram( ProgramObject ); - GL.DeleteTextures( 1, ref TMU0_Handle ); - GL.DeleteTextures( 1, ref TMU1_Handle ); - - base.OnUnload( e ); - } - - /// Respond to resize events here. - /// Contains information on the new GameWindow size. - /// There is no need to call the base implementation. - protected override void OnResize( EventArgs e ) - { - GL.Viewport( 0, 0, Width, Height ); - - GL.MatrixMode( MatrixMode.Projection ); - Matrix4 p = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, Width / (float)Height, 0.1f, 100.0f); - GL.LoadMatrix(ref p); - - GL.MatrixMode( MatrixMode.Modelview ); - GL.LoadIdentity( ); - - base.OnResize( e ); - } - - protected override void OnKeyDown(OpenTK.Input.KeyboardKeyEventArgs e) - { - base.OnKeyDown(e); - - if (e.Keyboard[OpenTK.Input.Key.Escape]) - this.Exit(); - if (e.Keyboard[OpenTK.Input.Key.Space]) - Trace.WriteLine("GL: " + GL.GetError()); - if (e.Keyboard[OpenTK.Input.Key.Q]) - { - MaterialScaleAndBiasAndShininess.X += 0.01f; - Trace.WriteLine("Scale: " + MaterialScaleAndBiasAndShininess.X + " Bias: " + MaterialScaleAndBiasAndShininess.Y); - } - if (e.Keyboard[OpenTK.Input.Key.A]) - { - MaterialScaleAndBiasAndShininess.X -= 0.01f; - Trace.WriteLine("Scale: " + MaterialScaleAndBiasAndShininess.X + " Bias: " + MaterialScaleAndBiasAndShininess.Y); - } - if (e.Keyboard[OpenTK.Input.Key.W]) - { - MaterialScaleAndBiasAndShininess.Y += 0.01f; - Trace.WriteLine("Scale: " + MaterialScaleAndBiasAndShininess.X + " Bias: " + MaterialScaleAndBiasAndShininess.Y); - } - if (e.Keyboard[OpenTK.Input.Key.S]) - { - MaterialScaleAndBiasAndShininess.Y -= 0.01f; - Trace.WriteLine("Scale: " + MaterialScaleAndBiasAndShininess.X + " Bias: " + MaterialScaleAndBiasAndShininess.Y); - } - if (e.Keyboard[OpenTK.Input.Key.E]) - { - MaterialScaleAndBiasAndShininess.Z += 1f; - Trace.WriteLine("Shininess: " + MaterialScaleAndBiasAndShininess.Z); - } - if (e.Keyboard[OpenTK.Input.Key.D]) - { - MaterialScaleAndBiasAndShininess.Z -= 1f; - Trace.WriteLine("Shininess: " + MaterialScaleAndBiasAndShininess.Z); - } - } - - protected override void OnMouseMove(OpenTK.Input.MouseMoveEventArgs e) - { - base.OnMouseMove(e); - - LightPosition.X = (-(this.Width / 2) + e.Mouse.X) / 100f; - LightPosition.Y = ((this.Height / 2) - e.Mouse.Y) / 100f; - - EyePos.Y = e.Mouse.Wheel * 0.5f; - } - - /// Add your game logic here. - /// Contains timing information. - /// There is no need to call the base implementation. - protected override void OnUpdateFrame( FrameEventArgs e ) - { - base.OnUpdateFrame( e ); - } - - /// Add your game rendering code here. - /// Contains timing information. - /// There is no need to call the base implementation. - protected override void OnRenderFrame( FrameEventArgs e ) - { - this.Title = "FPS: " + (1 / e.Time).ToString("0."); - - GL.Clear( ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit ); - - GL.UseProgram( ProgramObject ); - - #region Textures - - GL.ActiveTexture( TMU0_Unit ); - GL.BindTexture( TMU0_Target, TMU0_Handle ); - GL.ActiveTexture( TMU1_Unit ); - GL.BindTexture( TMU1_Target, TMU1_Handle ); - - #endregion Textures - - #region Uniforms - - // first Material's uniforms - GL.Uniform1( GL.GetUniformLocation( ProgramObject, "Material_DiffuseAndHeight" ), TMU0_UnitInteger ); - GL.Uniform1( GL.GetUniformLocation( ProgramObject, "Material_NormalAndGloss" ), TMU1_UnitInteger ); - GL.Uniform3( GL.GetUniformLocation( ProgramObject, "Material_ScaleBiasShininess" ), MaterialScaleAndBiasAndShininess.X, MaterialScaleAndBiasAndShininess.Y, MaterialScaleAndBiasAndShininess.Z ); - - // the rest are vectors - GL.Uniform3( GL.GetUniformLocation( ProgramObject, "Camera_Position" ), EyePos.X, EyePos.Y, EyePos.Z ); - GL.Uniform3( GL.GetUniformLocation( ProgramObject, "Light_Position" ), LightPosition.X, LightPosition.Y, LightPosition.Z ); - GL.Uniform3( GL.GetUniformLocation( ProgramObject, "Light_DiffuseColor" ), LightDiffuse.X, LightDiffuse.Y, LightDiffuse.Z ); - GL.Uniform3( GL.GetUniformLocation( ProgramObject, "Light_SpecularColor" ), LightSpecular.X, LightSpecular.Y, LightSpecular.Z ); - - #endregion Uniforms - - GL.PushMatrix( ); - Matrix4 t = Matrix4.LookAt( EyePos, Vector3.Zero, Vector3.UnitY ); - GL.MultMatrix(ref t); - - #region Draw Quad - - GL.Color3( 1f, 1f, 1f ); - - GL.Begin(PrimitiveType.Quads); - { - GL.Normal3( Normal ); - GL.VertexAttrib3( AttribTangent, ref Tangent ); - GL.MultiTexCoord2( TextureUnit.Texture0, 0f, 1f ); - GL.Vertex3( -1.0f, 1.0f, 0.0f ); - - GL.Normal3( Normal ); - GL.VertexAttrib3( AttribTangent, ref Tangent ); - GL.MultiTexCoord2( TextureUnit.Texture0, 0f, 0f ); - GL.Vertex3( -1.0f, -1.0f, 0.0f ); - - GL.Normal3( Normal ); - GL.VertexAttrib3( AttribTangent, ref Tangent ); - GL.MultiTexCoord2( TextureUnit.Texture0, 1f, 0f ); - GL.Vertex3( 1.0f, -1.0f, 0.0f ); - - GL.Normal3( Normal ); - GL.VertexAttrib3( AttribTangent, ref Tangent ); - GL.MultiTexCoord2( TextureUnit.Texture0, 1f, 1f ); - GL.Vertex3( 1.0f, 1.0f, 0.0f ); - } - GL.End( ); - - #endregion Draw Quad - - GL.UseProgram( 0 ); - - // visualize the light position 'somehow' - GL.Begin(PrimitiveType.Points); - { - GL.Color3( LightSpecular ); - GL.Vertex3( LightPosition ); - } - GL.End( ); - - GL.PopMatrix( ); - - this.SwapBuffers( ); - } - - /// Entry point - [STAThread] - public static void Main( ) - { - using ( T12_GLSL_Parallax example = new T12_GLSL_Parallax( ) ) - { - Utilities.SetWindowTitle( example ); - example.Run( 30.0, 0.0 ); - } - } - } -} diff --git a/Source/Examples/OpenGL/3.x/HelloGL3.cs b/Source/Examples/OpenGL/3.x/HelloGL3.cs deleted file mode 100644 index 0a9877a1..00000000 --- a/Source/Examples/OpenGL/3.x/HelloGL3.cs +++ /dev/null @@ -1,233 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Diagnostics; -using System.IO; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; - -namespace Examples.Tutorial -{ - [Example("OpenGL 3.0", ExampleCategory.OpenGL, "3.x", Documentation="HelloGL3")] - public class HelloGL3 : GameWindow - { - string vertexShaderSource = @" -#version 140 - -precision highp float; - -uniform mat4 projection_matrix; -uniform mat4 modelview_matrix; - -in vec3 in_position; -in vec3 in_normal; - -out vec3 normal; - -void main(void) -{ - //works only for orthogonal modelview - normal = (modelview_matrix * vec4(in_normal, 0)).xyz; - - gl_Position = projection_matrix * modelview_matrix * vec4(in_position, 1); -}"; - - string fragmentShaderSource = @" -#version 140 - -precision highp float; - -const vec3 ambient = vec3(0.1, 0.1, 0.1); -const vec3 lightVecNormalized = normalize(vec3(0.5, 0.5, 2.0)); -const vec3 lightColor = vec3(0.9, 0.9, 0.7); - -in vec3 normal; - -out vec4 out_frag_color; - -void main(void) -{ - float diffuse = clamp(dot(lightVecNormalized, normalize(normal)), 0.0, 1.0); - out_frag_color = vec4(ambient + diffuse * lightColor, 1.0); -}"; - - int vertexShaderHandle, - fragmentShaderHandle, - shaderProgramHandle, - modelviewMatrixLocation, - projectionMatrixLocation, - vaoHandle, - positionVboHandle, - normalVboHandle, - eboHandle; - - Vector3[] positionVboData = new Vector3[]{ - new Vector3(-1.0f, -1.0f, 1.0f), - new Vector3( 1.0f, -1.0f, 1.0f), - new Vector3( 1.0f, 1.0f, 1.0f), - new Vector3(-1.0f, 1.0f, 1.0f), - new Vector3(-1.0f, -1.0f, -1.0f), - new Vector3( 1.0f, -1.0f, -1.0f), - new Vector3( 1.0f, 1.0f, -1.0f), - new Vector3(-1.0f, 1.0f, -1.0f) }; - - int[] indicesVboData = new int[]{ - // front face - 0, 1, 2, 2, 3, 0, - // top face - 3, 2, 6, 6, 7, 3, - // back face - 7, 6, 5, 5, 4, 7, - // left face - 4, 0, 3, 3, 7, 4, - // bottom face - 0, 1, 5, 5, 4, 0, - // right face - 1, 5, 6, 6, 2, 1, }; - - Matrix4 projectionMatrix, modelviewMatrix; - - public HelloGL3() - : base(640, 480, - new GraphicsMode(), "OpenGL 3 Example", 0, - DisplayDevice.Default, 3, 2, - GraphicsContextFlags.ForwardCompatible | GraphicsContextFlags.Debug) - { } - - protected override void OnLoad (System.EventArgs e) - { - VSync = VSyncMode.On; - - CreateShaders(); - CreateVBOs(); - CreateVAOs(); - - // Other state - GL.Enable(EnableCap.DepthTest); - GL.ClearColor(System.Drawing.Color.MidnightBlue); - } - - void CreateShaders() - { - vertexShaderHandle = GL.CreateShader(ShaderType.VertexShader); - fragmentShaderHandle = GL.CreateShader(ShaderType.FragmentShader); - - GL.ShaderSource(vertexShaderHandle, vertexShaderSource); - GL.ShaderSource(fragmentShaderHandle, fragmentShaderSource); - - GL.CompileShader(vertexShaderHandle); - GL.CompileShader(fragmentShaderHandle); - - Debug.WriteLine(GL.GetShaderInfoLog(vertexShaderHandle)); - Debug.WriteLine(GL.GetShaderInfoLog(fragmentShaderHandle)); - - // Create program - shaderProgramHandle = GL.CreateProgram(); - - GL.AttachShader(shaderProgramHandle, vertexShaderHandle); - GL.AttachShader(shaderProgramHandle, fragmentShaderHandle); - - GL.BindAttribLocation(shaderProgramHandle, 0, "in_position"); - GL.BindAttribLocation(shaderProgramHandle, 1, "in_normal"); - - GL.LinkProgram(shaderProgramHandle); - Debug.WriteLine(GL.GetProgramInfoLog(shaderProgramHandle)); - GL.UseProgram(shaderProgramHandle); - - // Set uniforms - projectionMatrixLocation = GL.GetUniformLocation(shaderProgramHandle, "projection_matrix"); - modelviewMatrixLocation = GL.GetUniformLocation(shaderProgramHandle, "modelview_matrix"); - - float aspectRatio = ClientSize.Width / (float)(ClientSize.Height); - Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, aspectRatio, 1, 100, out projectionMatrix); - modelviewMatrix = Matrix4.LookAt(new Vector3(0, 3, 5), new Vector3(0, 0, 0), new Vector3(0, 1, 0)); - - GL.UniformMatrix4(projectionMatrixLocation, false, ref projectionMatrix); - GL.UniformMatrix4(modelviewMatrixLocation, false, ref modelviewMatrix); - } - - void CreateVBOs() - { - positionVboHandle = GL.GenBuffer(); - GL.BindBuffer(BufferTarget.ArrayBuffer, positionVboHandle); - GL.BufferData(BufferTarget.ArrayBuffer, - new IntPtr(positionVboData.Length * Vector3.SizeInBytes), - positionVboData, BufferUsageHint.StaticDraw); - - normalVboHandle = GL.GenBuffer(); - GL.BindBuffer(BufferTarget.ArrayBuffer, normalVboHandle); - GL.BufferData(BufferTarget.ArrayBuffer, - new IntPtr(positionVboData.Length * Vector3.SizeInBytes), - positionVboData, BufferUsageHint.StaticDraw); - - eboHandle = GL.GenBuffer(); - GL.BindBuffer(BufferTarget.ElementArrayBuffer, eboHandle); - GL.BufferData(BufferTarget.ElementArrayBuffer, - new IntPtr(sizeof(uint) * indicesVboData.Length), - indicesVboData, BufferUsageHint.StaticDraw); - - GL.BindBuffer(BufferTarget.ArrayBuffer, 0); - GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); - } - - void CreateVAOs() - { - // GL3 allows us to store the vertex layout in a "vertex array object" (VAO). - // This means we do not have to re-issue VertexAttribPointer calls - // every time we try to use a different vertex layout - these calls are - // stored in the VAO so we simply need to bind the correct VAO. - vaoHandle = GL.GenVertexArray(); - GL.BindVertexArray(vaoHandle); - - GL.EnableVertexAttribArray(0); - GL.BindBuffer(BufferTarget.ArrayBuffer, positionVboHandle); - GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, true, Vector3.SizeInBytes, 0); - - GL.EnableVertexAttribArray(1); - GL.BindBuffer(BufferTarget.ArrayBuffer, normalVboHandle); - GL.VertexAttribPointer(1, 3, VertexAttribPointerType.Float, true, Vector3.SizeInBytes, 0); - - GL.BindBuffer(BufferTarget.ElementArrayBuffer, eboHandle); - - GL.BindVertexArray(0); - } - - protected override void OnUpdateFrame(FrameEventArgs e) - { - Matrix4 rotation = Matrix4.CreateRotationY((float)e.Time); - Matrix4.Mult(ref rotation, ref modelviewMatrix, out modelviewMatrix); - GL.UniformMatrix4(modelviewMatrixLocation, false, ref modelviewMatrix); - - var keyboard = OpenTK.Input.Keyboard.GetState(); - if (keyboard[OpenTK.Input.Key.Escape]) - Exit(); - } - - protected override void OnRenderFrame(FrameEventArgs e) - { - GL.Viewport(0, 0, Width, Height); - - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - GL.BindVertexArray(vaoHandle); - GL.DrawElements(PrimitiveType.Triangles, indicesVboData.Length, - DrawElementsType.UnsignedInt, IntPtr.Zero); - - SwapBuffers(); - } - - [STAThread] - public static void Main() - { - using (HelloGL3 example = new HelloGL3()) - { - Utilities.SetWindowTitle(example); - example.Run(30); - } - } - } -} \ No newline at end of file diff --git a/Source/Examples/OpenGLES/1.1/SimpleWindow.cs b/Source/Examples/OpenGLES/1.1/SimpleWindow.cs deleted file mode 100644 index c599f023..00000000 --- a/Source/Examples/OpenGLES/1.1/SimpleWindow.cs +++ /dev/null @@ -1,186 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -#region Using Directives - -using System; -using System.Collections.Generic; -using System.Windows.Forms; -using System.Threading; -using System.Drawing; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.ES11; - -#endregion - -namespace Examples.Tutorial -{ -#if EXPERIMENTAL - [Example("Immediate mode", ExampleCategory.OpenGLES, "1.1", Documentation = "SimpleES11Window")] - public class SimpleES11Window : GameWindow - { - #region --- Fields --- - - float rotation_speed = 3.0f; - float angle; - - #endregion - - #region --- Constructor --- - - public SimpleES11Window() - : base(800, 600, new GraphicsMode(16, 16), "", GameWindowFlags.Default, DisplayDevice.Default, 2, 0, GraphicsContextFlags.Embedded) - { } - - #endregion - - #region OnLoad - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - Color4 color = Color4.MidnightBlue; - GL.ClearColor(color.R, color.G, color.B, color.A); - GL.Enable((All)EnableCap.DepthTest); - } - - #endregion - - #region OnResize - - /// - /// Called when the user resizes the window. - /// - /// Contains the new width/height of the window. - /// - /// You want the OpenGL viewport to match the window. This is the place to do it! - /// - protected override void OnResize(EventArgs e) - { - GL.Viewport(0, 0, Width, Height); - - double aspect_ratio = Width / (double)Height; - - OpenTK.Matrix4 perspective = OpenTK.Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, (float)aspect_ratio, 1, 64); - GL.MatrixMode((All)MatrixMode.Projection); - GL.LoadMatrix(ref perspective.Row0.X); - } - - #endregion - - #region OnUpdateFrame - - /// - /// Prepares the next frame for rendering. - /// - /// - /// Place your control logic here. This is the place to respond to user input, - /// update object positions etc. - /// - protected override void OnUpdateFrame(FrameEventArgs e) - { - if (Keyboard[OpenTK.Input.Key.Escape]) - { - this.Exit(); - return; - } - } - - #endregion - - #region OnRenderFrame - - /// - /// Place your rendering code here. - /// - protected override void OnRenderFrame(FrameEventArgs e) - { - GL.Clear((uint)(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit)); - - Matrix4 lookat = Matrix4.LookAt(0, 5, 5, 0, 0, 0, 0, 1, 0); - GL.MatrixMode((All)MatrixMode.Modelview); - GL.LoadMatrix(ref lookat.Row0.X); - - angle += rotation_speed * (float)e.Time; - GL.Rotate(angle, 0.0f, 1.0f, 0.0f); - - DrawCube(); - - this.SwapBuffers(); - } - - #endregion - - #region private void DrawCube() - - private void DrawCube() - { -#if false - GL.Begin(BeginMode.Quads); - - GL.Color3(Color.Silver); - GL.Vertex3(-1.0f, -1.0f, -1.0f); - GL.Vertex3(-1.0f, 1.0f, -1.0f); - GL.Vertex3(1.0f, 1.0f, -1.0f); - GL.Vertex3(1.0f, -1.0f, -1.0f); - - GL.Color3(Color.Honeydew); - GL.Vertex3(-1.0f, -1.0f, -1.0f); - GL.Vertex3(1.0f, -1.0f, -1.0f); - GL.Vertex3(1.0f, -1.0f, 1.0f); - GL.Vertex3(-1.0f, -1.0f, 1.0f); - - GL.Color3(Color.Moccasin); - - GL.Vertex3(-1.0f, -1.0f, -1.0f); - GL.Vertex3(-1.0f, -1.0f, 1.0f); - GL.Vertex3(-1.0f, 1.0f, 1.0f); - GL.Vertex3(-1.0f, 1.0f, -1.0f); - - GL.Color3(Color.IndianRed); - GL.Vertex3(-1.0f, -1.0f, 1.0f); - GL.Vertex3(1.0f, -1.0f, 1.0f); - GL.Vertex3(1.0f, 1.0f, 1.0f); - GL.Vertex3(-1.0f, 1.0f, 1.0f); - - GL.Color3(Color.PaleVioletRed); - GL.Vertex3(-1.0f, 1.0f, -1.0f); - GL.Vertex3(-1.0f, 1.0f, 1.0f); - GL.Vertex3(1.0f, 1.0f, 1.0f); - GL.Vertex3(1.0f, 1.0f, -1.0f); - - GL.Color3(Color.ForestGreen); - GL.Vertex3(1.0f, -1.0f, -1.0f); - GL.Vertex3(1.0f, 1.0f, -1.0f); - GL.Vertex3(1.0f, 1.0f, 1.0f); - GL.Vertex3(1.0f, -1.0f, 1.0f); - - GL.End(); -#endif - } - - #endregion - - #region public static void Main() - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - using (SimpleES11Window example = new SimpleES11Window()) - { - Utilities.SetWindowTitle(example); - example.Run(30.0, 0.0); - } - } - - #endregion - } -#endif -} diff --git a/Source/Examples/OpenGLES/2.0/SimpleWindow20.cs b/Source/Examples/OpenGLES/2.0/SimpleWindow20.cs deleted file mode 100644 index c1470705..00000000 --- a/Source/Examples/OpenGLES/2.0/SimpleWindow20.cs +++ /dev/null @@ -1,134 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -#region Using Directives - -using System; -using System.Collections.Generic; -using System.Windows.Forms; -using System.Threading; -using System.Drawing; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.ES20; - -#endregion - -namespace Examples.Tutorial -{ - [Example("Simple ES 2.0", ExampleCategory.OpenGLES, "2.0", Documentation = "SimpleES20Window")] - public class SimpleES20Window : GameWindow - { - #region Constructor - - public SimpleES20Window(GraphicsContextFlags flags) - : base(800, 600, GraphicsMode.Default, "", GameWindowFlags.Default, DisplayDevice.Default, 2, 0, flags) - { } - - #endregion - - #region OnLoad - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - Color4 color = Color4.MidnightBlue; - GL.ClearColor(color.R, color.G, color.B, color.A); - GL.Enable(EnableCap.DepthTest); - } - - #endregion - - #region OnResize - - /// - /// Called when the user resizes the window. - /// - /// Contains the new width/height of the window. - /// - /// You want the OpenGL viewport to match the window. This is the place to do it! - /// - protected override void OnResize(EventArgs e) - { - GL.Viewport(0, 0, Width, Height); - } - - #endregion - - #region OnUpdateFrame - - /// - /// Prepares the next frame for rendering. - /// - /// - /// Place your control logic here. This is the place to respond to user input, - /// update object positions etc. - /// - protected override void OnUpdateFrame(FrameEventArgs e) - { - var keyboard = OpenTK.Input.Keyboard.GetState(); - if (keyboard[OpenTK.Input.Key.Escape]) - { - this.Exit(); - return; - } - } - - #endregion - - #region OnRenderFrame - - /// - /// Place your rendering code here. - /// - protected override void OnRenderFrame(FrameEventArgs e) - { - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - this.SwapBuffers(); - } - - #endregion - - #region private void DrawCube() - - private void DrawCube() - { - } - - #endregion - - #region public static void Main() - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - SimpleES20Window example; - try - { - example = new SimpleES20Window(GraphicsContextFlags.Embedded); - } - catch - { - example = new SimpleES20Window(GraphicsContextFlags.Default); - } - - if (example != null) - { - using (example) - { - Utilities.SetWindowTitle(example); - example.Run(30.0, 0.0); - } - } - } - - #endregion - } -} diff --git a/Source/Examples/OpenGLES/SimpleWindow20.cs b/Source/Examples/OpenGLES/SimpleWindow20.cs deleted file mode 100644 index e69de29b..00000000 diff --git a/Source/Examples/OpenTK.Examples.csproj b/Source/Examples/OpenTK.Examples.csproj deleted file mode 100644 index 68cf447d..00000000 --- a/Source/Examples/OpenTK.Examples.csproj +++ /dev/null @@ -1,688 +0,0 @@ - - - - Local - 8.0.30703 - 2.0 - {868E37B3-0000-0000-0000-000000000000} - Debug - AnyCPU - Resources\App.ico - - - Examples - JScript - Grid - IE50 - false - WinExe - - - OpenTK.Examples - Examples.Program - - - - - 2.0 - - false - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - true - - - True - 285212672 - - - DEBUG;TRACE; - True - 4096 - False - ..\..\Binaries\OpenTK\Debug\ - False - False - 4 - AllRules.ruleset - full - - - True - 285212672 - - - TRACE; - 4096 - True - ..\..\Binaries\OpenTK\Release\ - False - False - 4 - AllRules.ruleset - pdbonly - true - - - ..\..\Binaries\OpenTK\Release\ - none - 4 - True - TRACE; - true - - - True - 285212672 - - - TRACE; - 4096 - True - ..\..\Binaries\OpenTK\Release\ - False - False - 4 - AllRules.ruleset - none - - - True - - - ..\..\OpenTK.snk - - - app.manifest - - - - System - - - System.Data - - - System.Drawing - - - System.Windows.Forms - - - System.Xml - - - - - - - - - - OpenTK - {A37A7E14-0000-0000-0000-000000000000} - - - {A625BE88-0000-0000-0000-000000000000} - OpenTK.GLControl - - - {A625BE87-0000-0000-0000-000000000000} - OpenTK.GLWidget - - - - - Properties\GlobalAssemblyInfo.cs - - - - Code - - - - Code - - - - - - Code - - - Code - - - Code - - - Code - - - Form - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Form - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Form - - - Code - - - Form - - - UserControl - - - Form - - - Form - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Form - - - Code - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ExampleBrowser.cs - - - ExampleBrowser.cs - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - True - - - Parrot.cs - - - Parrot.cs - - - FontRenderingBasic.cs - - - FontRenderingBasic.cs - - - MultipleGLControls.cs - - - MultipleGLControls.cs - - - GLControlGameLoop.cs - - - GLControlGameLoop.cs - - - GLControlSimple.cs - - - GLControlSimple.cs - - - DerivedGLControl.cs - - - DerivedGLControl.cs - - - Extensions.cs - - - Extensions.cs - - - OpenTK.snk - - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - - - - - - - Always - - - Code - - - - Dependencies\x86\libSDL2.dylib - - - Dependencies\x64\libSDL2.dylib - - - - - - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Dependencies\openal.COPYING.txt - - - Dependencies\SDL2.COPYING.txt - - - Dependencies\x64\openal32.dll - SDL2.dll - - - Dependencies\x64\SDL2.dll - - - Dependencies\x86\openal32.dll - - - Dependencies\x86\SDL2.dll - - - - - - - - - - - true - full - false - ..\..\Binaries\OpenTK\Debug\ - DEBUG;TRACE; - 4 - true - AllRules.ruleset - False - 285212672 - 4096 - False - - - - - true - pdbonly - true - ..\..\Binaries\OpenTK\Release\ - TRACE; - 4 - true - AllRules.ruleset - False - 285212672 - 4096 - False - - - - - - - \ No newline at end of file diff --git a/Source/Examples/OpenTK/Fonts/FontRenderingAdvanced.cs b/Source/Examples/OpenTK/Fonts/FontRenderingAdvanced.cs deleted file mode 100644 index cf82eb21..00000000 --- a/Source/Examples/OpenTK/Fonts/FontRenderingAdvanced.cs +++ /dev/null @@ -1,161 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Collections.Generic; -using System.Text; -using System.IO; -using System.Drawing; -using System.Diagnostics; - -using OpenTK; -using OpenTK.Graphics.OpenGL; -using OpenTK.Input; - -namespace Examples.Tutorial -{ -#if false - /// - /// Shows how to render and scroll large amounts of text. - /// - [Example("Font rendering (advanced)", ExampleCategory.OpenTK, "Fonts", 2, Documentation="FontRenderingAdvanced")] - public class FontRenderingAdvanced : GameWindow - { - Font serif = new Font(FontFamily.GenericSerif, 16.0f); - Font sans = new Font(FontFamily.GenericSansSerif, 18.0f); - TextPrinter text = new TextPrinter(); - - string poem = new StreamReader("Data/Poem.txt").ReadToEnd(); - int lines; // How many lines the poem contains. - - float scroll_speed; - float initial_position; - float wraparound_position; - float current_position; - - public FontRenderingAdvanced() - : base(800, 600) - { } - - #region OnLoad - - protected override void OnLoad(EventArgs e) - { - GL.ClearColor(Color.MidnightBlue); - - current_position = initial_position; - scroll_speed = -1.0f; - - // Count the amount of lines in the text, to find out the correct - // warparound position. We want the text to scroll until the last - // line moves outside the screen, then warp it around from the - // other side of the screen. - foreach (char c in poem) - if (c == '\n') - lines++; - - wraparound_position = -(lines + 1) * serif.Height; - } - - #endregion - - #region OnUnload - - public override void OnUnload(EventArgs e) - { - if (serif != null) - serif.Dispose(); - if (sans != null) - sans.Dispose(); - } - - #endregion - - #region OnResize - - protected override void OnResize(EventArgs e) - { - GL.Viewport(0, 0, Width, Height); - - initial_position = Height + serif.Height; // Start one line below the screen. - wraparound_position = -(lines + 1) * serif.Height; - } - - #endregion - - #region OnUpdateFrame - - protected override void OnUpdateFrame(FrameEventArgs e) - { - if (Keyboard[Key.Space]) - scroll_speed = 0; - if (Keyboard[Key.Down]) - scroll_speed += 10; - if (Keyboard[Key.Up]) - scroll_speed -= 10; - if (Keyboard[Key.Escape]) - this.Exit(); - } - - #endregion - - #region OnRenderFrame - - protected override void OnRenderFrame(FrameEventArgs e) - { - GL.Clear(ClearBufferMask.ColorBufferBit); - - // We'll start printing from the lower left corner of the screen. The text - // will slowly move updwards - the user can control the movement speed with - // the keyboard arrows and the space bar. - current_position += scroll_speed * (float)e.Time; - if (scroll_speed > 0.0f && current_position > initial_position) - current_position = wraparound_position; - else if (scroll_speed < 0.0f && current_position < wraparound_position) - current_position = initial_position; - - // TextPrinter.Begin() sets up a 2d orthographic projection, with the x axis - // moving from 0 to viewport.Width (left to right) and the y axis from - // 0 to viewport.Height (top to bottom). This is the typical coordinate system - // used in 2d graphics, and is necessary for achieving pixel-perfect glyph rendering. - // TextPrinter.End() restores your previous projection/modelview matrices. - text.Begin(); - - // Print FPS counter. Since the counter changes per frame, - // it shouldn't be cached (TextPrinterOptions.NoCache). - text.Print((1.0 / e.Time).ToString("F2"), sans, Color.SpringGreen, new RectangleF(0, 0, Width, 0), TextPrinterOptions.NoCache, TextAlignment.Far); - - // Print the actual text. - GL.Translate(0, current_position, 0); - text.Print(poem, serif, Color.White, new RectangleF(Width / 2, 0, Width / 2, 0), TextPrinterOptions.Default, TextAlignment.Far); - text.Print(poem, serif, Color.White, new RectangleF(0, 0, Width / 2, 0)); - - text.End(); - - SwapBuffers(); - } - - #endregion - - #region public static void Main() - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - using (FontRenderingAdvanced example = new FontRenderingAdvanced()) - { - // Get the title and category of this example using reflection. - ExampleAttribute info = ((ExampleAttribute)example.GetType().GetCustomAttributes(false)[0]); - example.Title = String.Format("OpenTK | {0} {1}: {2}", info.Category, info.Difficulty, info.Title); - example.Run(30.0, 0.0); - } - } - - #endregion - } -#endif -} diff --git a/Source/Examples/OpenTK/Fonts/FontRenderingBasic.Designer.cs b/Source/Examples/OpenTK/Fonts/FontRenderingBasic.Designer.cs deleted file mode 100644 index 2217ad7b..00000000 --- a/Source/Examples/OpenTK/Fonts/FontRenderingBasic.Designer.cs +++ /dev/null @@ -1,96 +0,0 @@ -namespace Examples.WinForms -{ - partial class FontRenderingBasic - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.glControl1 = new OpenTK.GLControl(); - this.changeFont = new System.Windows.Forms.Button(); - this.textBox1 = new System.Windows.Forms.TextBox(); - this.fontDialog = new System.Windows.Forms.FontDialog(); - this.SuspendLayout(); - // - // glControl1 - // - this.glControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.glControl1.BackColor = System.Drawing.Color.Black; - this.glControl1.Location = new System.Drawing.Point(0, 40); - this.glControl1.Name = "glControl1"; - this.glControl1.Size = new System.Drawing.Size(700, 521); - this.glControl1.TabIndex = 0; - this.glControl1.VSync = false; - this.glControl1.Load += new System.EventHandler(this.glControl1_Load); - this.glControl1.Paint += new System.Windows.Forms.PaintEventHandler(this.glControl1_Paint); - this.glControl1.Resize += new System.EventHandler(this.glControl1_Resize); - // - // changeFont - // - this.changeFont.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.changeFont.Location = new System.Drawing.Point(568, 10); - this.changeFont.Name = "changeFont"; - this.changeFont.Size = new System.Drawing.Size(120, 23); - this.changeFont.TabIndex = 1; - this.changeFont.Text = "Change Font"; - this.changeFont.UseVisualStyleBackColor = true; - this.changeFont.Click += new System.EventHandler(this.changeFont_Click); - // - // textBox1 - // - this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.textBox1.Location = new System.Drawing.Point(12, 11); - this.textBox1.Name = "textBox1"; - this.textBox1.Size = new System.Drawing.Size(550, 22); - this.textBox1.TabIndex = 2; - this.textBox1.Text = "The quick brown fox jumped over the lazy dogs. 0123456789"; - this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged); - // - // FontRendering - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(700, 561); - this.Controls.Add(this.textBox1); - this.Controls.Add(this.changeFont); - this.Controls.Add(this.glControl1); - this.Name = "FontRendering"; - this.Text = "FontRendering"; - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private OpenTK.GLControl glControl1; - private System.Windows.Forms.Button changeFont; - private System.Windows.Forms.TextBox textBox1; - private System.Windows.Forms.FontDialog fontDialog; - } -} \ No newline at end of file diff --git a/Source/Examples/OpenTK/Fonts/FontRenderingBasic.cs b/Source/Examples/OpenTK/Fonts/FontRenderingBasic.cs deleted file mode 100644 index ad6de379..00000000 --- a/Source/Examples/OpenTK/Fonts/FontRenderingBasic.cs +++ /dev/null @@ -1,132 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; - -namespace Examples.WinForms -{ - [Example("Font rendering (basic)", ExampleCategory.OpenTK, "Fonts", Difficulty = 1, Documentation = "FontRenderingBasic", Visible=false)] - public partial class FontRenderingBasic : Form - { - #region Fields - - float[] sizes = new float[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 24 }; - List fonts = new List(); - - //TextPrinter printer = new TextPrinter(); - - #endregion - - #region Constructors - - public FontRenderingBasic() - { - InitializeComponent(); - ResizeRedraw = true; - - glControl1.Width = ClientSize.Width; - glControl1.Height = ClientSize.Height; - - UpdateFontList(fontDialog.Font); - glControl1_Resize(this, EventArgs.Empty); - } - - #endregion - - #region Private Members - - void UpdateFontList(Font base_font) - { - //printer.Clear(); - - foreach (Font font in fonts) - font.Dispose(); - fonts.Clear(); - foreach (float size in sizes) - fonts.Add(new Font(base_font.Name, base_font.SizeInPoints + size, base_font.Style)); - } - - #endregion - - #region Events - - private void glControl1_Load(object sender, EventArgs e) - { - glControl1.MakeCurrent(); - } - - private void changeFont_Click(object sender, EventArgs e) - { - if (fontDialog.ShowDialog() == DialogResult.OK) - { - UpdateFontList(fontDialog.Font); - glControl1.Invalidate(); - } - } - - private void textBox1_TextChanged(object sender, EventArgs e) - { - glControl1.Invalidate(); - } - - private void glControl1_Paint(object sender, PaintEventArgs e) - { - glControl1.MakeCurrent(); - GL.ClearColor(Color.MidnightBlue); - GL.Clear(ClearBufferMask.ColorBufferBit); - - GL.MatrixMode(MatrixMode.Projection); - GL.LoadIdentity(); - GL.Ortho(0, glControl1.ClientSize.Width, glControl1.ClientSize.Height, 0, -1, 1); - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadIdentity(); - - foreach (Font font in fonts) - { - //printer.Print(textBox1.Text, font, Color.White); - GL.Translate(0, font.Height + 5, 0); - } - - glControl1.SwapBuffers(); - } - - private void glControl1_Resize(object sender, EventArgs e) - { - glControl1.MakeCurrent(); - - if (glControl1.ClientSize.Height == 0) - glControl1.ClientSize = new System.Drawing.Size(glControl1.ClientSize.Width, 1); - - GL.Viewport(0, 0, glControl1.ClientSize.Width, glControl1.ClientSize.Height); - } - - #endregion - - #region public static void Main() - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - using (FontRenderingBasic example = new FontRenderingBasic()) - { - Utilities.SetWindowTitle(example); - example.ShowDialog(); - } - } - - #endregion - } -} diff --git a/Source/Examples/OpenTK/Fonts/FontRenderingBasic.resx b/Source/Examples/OpenTK/Fonts/FontRenderingBasic.resx deleted file mode 100644 index cf80c422..00000000 --- a/Source/Examples/OpenTK/Fonts/FontRenderingBasic.resx +++ /dev/null @@ -1,123 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - \ No newline at end of file diff --git a/Source/Examples/OpenTK/Fonts/FontRenderingBasic.rtf b/Source/Examples/OpenTK/Fonts/FontRenderingBasic.rtf deleted file mode 100644 index c0233ee2..00000000 Binary files a/Source/Examples/OpenTK/Fonts/FontRenderingBasic.rtf and /dev/null differ diff --git a/Source/Examples/OpenTK/GLControl/DerivedGLControl.Designer.cs b/Source/Examples/OpenTK/GLControl/DerivedGLControl.Designer.cs deleted file mode 100644 index 3c6aecad..00000000 --- a/Source/Examples/OpenTK/GLControl/DerivedGLControl.Designer.cs +++ /dev/null @@ -1,37 +0,0 @@ -namespace Examples.WinForms -{ - partial class DerivedGLControl - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Component Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - components = new System.ComponentModel.Container(); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - } - - #endregion - } -} diff --git a/Source/Examples/OpenTK/GLControl/DerivedGLControl.cs b/Source/Examples/OpenTK/GLControl/DerivedGLControl.cs deleted file mode 100644 index 9ea8e6e2..00000000 --- a/Source/Examples/OpenTK/GLControl/DerivedGLControl.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Data; -using System.Text; -using System.Windows.Forms; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; - -namespace Examples.WinForms -{ - public partial class DerivedGLControl : GLControl - { - Color clearColor; - - public DerivedGLControl() - { - this.InitializeComponent(); - } - - public Color ClearColor - { - get { return clearColor; } - set - { - clearColor = value; - - if (!this.DesignMode) - { - MakeCurrent(); - GL.ClearColor(clearColor); - } - } - } - - protected override void OnPaint(PaintEventArgs e) - { - base.OnPaint(e); - - if (!this.DesignMode) - { - MakeCurrent(); - GL.Clear(ClearBufferMask.ColorBufferBit); - SwapBuffers(); - } - } - } -} diff --git a/Source/Examples/OpenTK/GLControl/DerivedGLControl.resx b/Source/Examples/OpenTK/GLControl/DerivedGLControl.resx deleted file mode 100644 index 19dc0dd8..00000000 --- a/Source/Examples/OpenTK/GLControl/DerivedGLControl.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/Source/Examples/OpenTK/GLControl/GLControlGameLoop.Designer.cs b/Source/Examples/OpenTK/GLControl/GLControlGameLoop.Designer.cs deleted file mode 100644 index c84b7444..00000000 --- a/Source/Examples/OpenTK/GLControl/GLControlGameLoop.Designer.cs +++ /dev/null @@ -1,60 +0,0 @@ -namespace Examples.WinForms -{ - partial class GameLoopForm - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.glControl = new OpenTK.GLControl(); - this.SuspendLayout(); - // - // glControl - // - this.glControl.BackColor = System.Drawing.Color.Black; - this.glControl.Dock = System.Windows.Forms.DockStyle.Fill; - this.glControl.Location = new System.Drawing.Point(0, 0); - this.glControl.Name = "glControl"; - this.glControl.Size = new System.Drawing.Size(784, 564); - this.glControl.TabIndex = 0; - this.glControl.VSync = false; - // - // W02_Immediate_Mode_Cube - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(784, 564); - this.Controls.Add(this.glControl); - this.Name = "W02_Immediate_Mode_Cube"; - this.Text = "Cube"; - this.ResumeLayout(false); - - } - - #endregion - - private OpenTK.GLControl glControl; - } -} \ No newline at end of file diff --git a/Source/Examples/OpenTK/GLControl/GLControlGameLoop.cs b/Source/Examples/OpenTK/GLControl/GLControlGameLoop.cs deleted file mode 100644 index 0ee55fb5..00000000 --- a/Source/Examples/OpenTK/GLControl/GLControlGameLoop.cs +++ /dev/null @@ -1,243 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -#region --- Using directives --- - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.Diagnostics; -using System.Threading; - -using OpenTK.Graphics.OpenGL; -using OpenTK.Platform; -using OpenTK; - -#endregion - -namespace Examples.WinForms -{ - [Example("Simple GLControl Game Loop", ExampleCategory.OpenTK, "GLControl", 2, Documentation="GLControlGameLoop")] - public partial class GameLoopForm : Form - { - static float angle = 0.0f; - - #region --- Constructor --- - - public GameLoopForm() - { - InitializeComponent(); - } - - #endregion - - #region OnLoad - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - glControl.KeyDown += new KeyEventHandler(glControl_KeyDown); - glControl.KeyUp += new KeyEventHandler(glControl_KeyUp); - glControl.Resize += new EventHandler(glControl_Resize); - glControl.Paint += new PaintEventHandler(glControl_Paint); - - Text = - GL.GetString(StringName.Vendor) + " " + - GL.GetString(StringName.Renderer) + " " + - GL.GetString(StringName.Version); - - GL.ClearColor(Color.MidnightBlue); - GL.Enable(EnableCap.DepthTest); - - Application.Idle += Application_Idle; - - // Ensure that the viewport and projection matrix are set correctly. - glControl_Resize(glControl, EventArgs.Empty); - } - - void glControl_KeyUp(object sender, KeyEventArgs e) - { - if (e.KeyCode == Keys.F12) - { - GrabScreenshot().Save("screenshot.png"); - } - } - - #endregion - - #region OnClosing - - protected override void OnClosing(CancelEventArgs e) - { - Application.Idle -= Application_Idle; - - base.OnClosing(e); - } - - #endregion - - #region Application_Idle event - - void Application_Idle(object sender, EventArgs e) - { - while (glControl.IsIdle) - { - Render(); - } - } - - #endregion - - #region GLControl.Resize event handler - - void glControl_Resize(object sender, EventArgs e) - { - OpenTK.GLControl c = sender as OpenTK.GLControl; - - if (c.ClientSize.Height == 0) - c.ClientSize = new System.Drawing.Size(c.ClientSize.Width, 1); - - GL.Viewport(0, 0, c.ClientSize.Width, c.ClientSize.Height); - - float aspect_ratio = Width / (float)Height; - Matrix4 perpective = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspect_ratio, 1, 64); - GL.MatrixMode(MatrixMode.Projection); - GL.LoadMatrix(ref perpective); - } - - #endregion - - #region GLControl.KeyDown event handler - - void glControl_KeyDown(object sender, KeyEventArgs e) - { - switch (e.KeyData) - { - case Keys.Escape: - this.Close(); - break; - } - } - - #endregion - - #region GLControl.Paint event handler - - void glControl_Paint(object sender, PaintEventArgs e) - { - Render(); - } - - #endregion - - #region private void Render() - - private void Render() - { - Matrix4 lookat = Matrix4.LookAt(0, 5, 5, 0, 0, 0, 0, 1, 0); - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadMatrix(ref lookat); - - GL.Rotate(angle, 0.0f, 1.0f, 0.0f); - angle += 0.5f; - - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - DrawCube(); - - glControl.SwapBuffers(); - } - - #endregion - - #region private void DrawCube() - - private void DrawCube() - { - GL.Begin(PrimitiveType.Quads); - - GL.Color3(Color.Silver); - GL.Vertex3(-1.0f, -1.0f, -1.0f); - GL.Vertex3(-1.0f, 1.0f, -1.0f); - GL.Vertex3(1.0f, 1.0f, -1.0f); - GL.Vertex3(1.0f, -1.0f, -1.0f); - - GL.Color3(Color.Honeydew); - GL.Vertex3(-1.0f, -1.0f, -1.0f); - GL.Vertex3(1.0f, -1.0f, -1.0f); - GL.Vertex3(1.0f, -1.0f, 1.0f); - GL.Vertex3(-1.0f, -1.0f, 1.0f); - - GL.Color3(Color.Moccasin); - - GL.Vertex3(-1.0f, -1.0f, -1.0f); - GL.Vertex3(-1.0f, -1.0f, 1.0f); - GL.Vertex3(-1.0f, 1.0f, 1.0f); - GL.Vertex3(-1.0f, 1.0f, -1.0f); - - GL.Color3(Color.IndianRed); - GL.Vertex3(-1.0f, -1.0f, 1.0f); - GL.Vertex3(1.0f, -1.0f, 1.0f); - GL.Vertex3(1.0f, 1.0f, 1.0f); - GL.Vertex3(-1.0f, 1.0f, 1.0f); - - GL.Color3(Color.PaleVioletRed); - GL.Vertex3(-1.0f, 1.0f, -1.0f); - GL.Vertex3(-1.0f, 1.0f, 1.0f); - GL.Vertex3(1.0f, 1.0f, 1.0f); - GL.Vertex3(1.0f, 1.0f, -1.0f); - - GL.Color3(Color.ForestGreen); - GL.Vertex3(1.0f, -1.0f, -1.0f); - GL.Vertex3(1.0f, 1.0f, -1.0f); - GL.Vertex3(1.0f, 1.0f, 1.0f); - GL.Vertex3(1.0f, -1.0f, 1.0f); - - GL.End(); - } - - #endregion - - #region private void GrabScreenshot() - - Bitmap GrabScreenshot() - { - Bitmap bmp = new Bitmap(this.ClientSize.Width, this.ClientSize.Height); - System.Drawing.Imaging.BitmapData data = - bmp.LockBits(this.ClientRectangle, System.Drawing.Imaging.ImageLockMode.WriteOnly, - System.Drawing.Imaging.PixelFormat.Format24bppRgb); - GL.ReadPixels(0, 0, this.ClientSize.Width, this.ClientSize.Height, PixelFormat.Bgr, PixelType.UnsignedByte, - data.Scan0); - bmp.UnlockBits(data); - bmp.RotateFlip(RotateFlipType.RotateNoneFlipY); - return bmp; - } - - #endregion - - #region public static void Main() - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - using (GameLoopForm example = new GameLoopForm()) - { - // Get the title and category of this example using reflection. - ExampleAttribute info = ((ExampleAttribute)example.GetType().GetCustomAttributes(false)[0]); - example.Text = String.Format("OpenTK | {0} {1}: {2}", info.Category, info.Difficulty, info.Title); - example.ShowDialog(); - } - } - - #endregion - } -} diff --git a/Source/Examples/OpenTK/GLControl/GLControlGameLoop.resx b/Source/Examples/OpenTK/GLControl/GLControlGameLoop.resx deleted file mode 100644 index 19dc0dd8..00000000 --- a/Source/Examples/OpenTK/GLControl/GLControlGameLoop.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/Source/Examples/OpenTK/GLControl/GLControlSimple.Designer.cs b/Source/Examples/OpenTK/GLControl/GLControlSimple.Designer.cs deleted file mode 100644 index 2d520900..00000000 --- a/Source/Examples/OpenTK/GLControl/GLControlSimple.Designer.cs +++ /dev/null @@ -1,110 +0,0 @@ -namespace Examples.WinForms -{ - partial class SimpleForm - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.redButton = new System.Windows.Forms.Button(); - this.greenButton = new System.Windows.Forms.Button(); - this.blueButton = new System.Windows.Forms.Button(); - this.glControl1 = new OpenTK.GLControl(); - this.SuspendLayout(); - // - // redButton - // - this.redButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.redButton.Location = new System.Drawing.Point(1278, 25); - this.redButton.Margin = new System.Windows.Forms.Padding(6); - this.redButton.Name = "redButton"; - this.redButton.Size = new System.Drawing.Size(266, 44); - this.redButton.TabIndex = 1; - this.redButton.Text = "Red"; - this.redButton.UseVisualStyleBackColor = true; - this.redButton.Click += new System.EventHandler(this.redButton_Click); - // - // greenButton - // - this.greenButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.greenButton.Location = new System.Drawing.Point(1278, 83); - this.greenButton.Margin = new System.Windows.Forms.Padding(6); - this.greenButton.Name = "greenButton"; - this.greenButton.Size = new System.Drawing.Size(266, 44); - this.greenButton.TabIndex = 2; - this.greenButton.Text = "Green"; - this.greenButton.UseVisualStyleBackColor = true; - this.greenButton.Click += new System.EventHandler(this.greenButton_Click); - // - // blueButton - // - this.blueButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.blueButton.Location = new System.Drawing.Point(1278, 140); - this.blueButton.Margin = new System.Windows.Forms.Padding(6); - this.blueButton.Name = "blueButton"; - this.blueButton.Size = new System.Drawing.Size(266, 44); - this.blueButton.TabIndex = 3; - this.blueButton.Text = "Blue"; - this.blueButton.UseVisualStyleBackColor = true; - this.blueButton.Click += new System.EventHandler(this.blueButton_Click); - // - // glControl1 - // - this.glControl1.BackColor = System.Drawing.SystemColors.ControlDark; - this.glControl1.Dock = System.Windows.Forms.DockStyle.Fill; - this.glControl1.Location = new System.Drawing.Point(0, 0); - this.glControl1.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); - this.glControl1.Name = "glControl1"; - this.glControl1.Size = new System.Drawing.Size(1562, 1085); - this.glControl1.TabIndex = 4; - this.glControl1.VSync = false; - this.glControl1.Paint += new System.Windows.Forms.PaintEventHandler(this.glControl1_Paint); - this.glControl1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.glControl1_KeyDown); - this.glControl1.Resize += new System.EventHandler(this.glControl1_Resize); - // - // SimpleForm - // - this.AutoScaleDimensions = new System.Drawing.SizeF(12F, 25F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(1562, 1085); - this.Controls.Add(this.blueButton); - this.Controls.Add(this.greenButton); - this.Controls.Add(this.redButton); - this.Controls.Add(this.glControl1); - this.Margin = new System.Windows.Forms.Padding(6); - this.Name = "SimpleForm"; - this.Text = "OpenTK Windows Forms Tutorial 01 - Your first window"; - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.Button redButton; - private System.Windows.Forms.Button greenButton; - private System.Windows.Forms.Button blueButton; - private OpenTK.GLControl glControl1; - } -} diff --git a/Source/Examples/OpenTK/GLControl/GLControlSimple.cs b/Source/Examples/OpenTK/GLControl/GLControlSimple.cs deleted file mode 100644 index f73b2e0b..00000000 --- a/Source/Examples/OpenTK/GLControl/GLControlSimple.cs +++ /dev/null @@ -1,94 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Drawing; -using System.Windows.Forms; - -using OpenTK.Graphics.OpenGL; - -namespace Examples.WinForms -{ - [Example("GLControl Simple", ExampleCategory.OpenTK, "GLControl", 1, Documentation="GLControlSimple")] - public partial class SimpleForm : Form - { - public SimpleForm() - { - InitializeComponent(); - } - - #region Events - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - glControl1_Resize(this, EventArgs.Empty); // Ensure the Viewport is set up correctly - GL.ClearColor(Color.Crimson); - } - - private void redButton_Click(object sender, EventArgs e) - { - GL.ClearColor(Color.Crimson); - glControl1.Invalidate(); - } - - private void greenButton_Click(object sender, EventArgs e) - { - GL.ClearColor(Color.ForestGreen); - glControl1.Invalidate(); - } - - private void blueButton_Click(object sender, EventArgs e) - { - GL.ClearColor(Color.RoyalBlue); - glControl1.Invalidate(); - } - - private void glControl1_Paint(object sender, PaintEventArgs e) - { - glControl1.MakeCurrent(); - - GL.Clear(ClearBufferMask.ColorBufferBit); - glControl1.SwapBuffers(); - } - - private void glControl1_Resize(object sender, EventArgs e) - { - if (glControl1.ClientSize.Height == 0) - glControl1.ClientSize = new System.Drawing.Size(glControl1.ClientSize.Width, 1); - - GL.Viewport(0, 0, glControl1.ClientSize.Width, glControl1.ClientSize.Height); - } - - private void glControl1_KeyDown(object sender, KeyEventArgs e) - { - switch (e.KeyData) - { - case Keys.Escape: - this.Close(); - break; - } - } - - #endregion - - #region public static void Main() - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - using (SimpleForm example = new SimpleForm()) - { - Utilities.SetWindowTitle(example); - example.ShowDialog(); - } - } - - #endregion - } -} diff --git a/Source/Examples/OpenTK/GLControl/GLControlSimple.resx b/Source/Examples/OpenTK/GLControl/GLControlSimple.resx deleted file mode 100644 index 19dc0dd8..00000000 --- a/Source/Examples/OpenTK/GLControl/GLControlSimple.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/Source/Examples/OpenTK/GLControl/GLControlSimple.rtf b/Source/Examples/OpenTK/GLControl/GLControlSimple.rtf deleted file mode 100644 index 425d8844..00000000 Binary files a/Source/Examples/OpenTK/GLControl/GLControlSimple.rtf and /dev/null differ diff --git a/Source/Examples/OpenTK/GLControl/MultipleGLControls.Designer.cs b/Source/Examples/OpenTK/GLControl/MultipleGLControls.Designer.cs deleted file mode 100644 index 4238de8e..00000000 --- a/Source/Examples/OpenTK/GLControl/MultipleGLControls.Designer.cs +++ /dev/null @@ -1,74 +0,0 @@ -namespace Examples.WinForms -{ - partial class MultipleGLControlsForm - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.derivedGLControl1 = new Examples.WinForms.DerivedGLControl(); - this.derivedGLControl2 = new Examples.WinForms.DerivedGLControl(); - this.SuspendLayout(); - // - // derivedGLControl1 - // - this.derivedGLControl1.BackColor = System.Drawing.Color.Black; - this.derivedGLControl1.ClearColor = System.Drawing.Color.Blue; - this.derivedGLControl1.Location = new System.Drawing.Point(12, 12); - this.derivedGLControl1.Name = "derivedGLControl1"; - this.derivedGLControl1.Size = new System.Drawing.Size(300, 225); - this.derivedGLControl1.TabIndex = 0; - this.derivedGLControl1.VSync = false; - // - // derivedGLControl2 - // - this.derivedGLControl2.BackColor = System.Drawing.Color.Black; - this.derivedGLControl2.ClearColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); - this.derivedGLControl2.Location = new System.Drawing.Point(319, 13); - this.derivedGLControl2.Name = "derivedGLControl2"; - this.derivedGLControl2.Size = new System.Drawing.Size(293, 224); - this.derivedGLControl2.TabIndex = 1; - this.derivedGLControl2.VSync = false; - // - // W04_Multiple_GLControls - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(624, 444); - this.Controls.Add(this.derivedGLControl2); - this.Controls.Add(this.derivedGLControl1); - this.Name = "W04_Multiple_GLControls"; - this.Text = "W04_Multiple_GLControls"; - this.ResumeLayout(false); - - } - - #endregion - - private DerivedGLControl derivedGLControl1; - private DerivedGLControl derivedGLControl2; - - } -} \ No newline at end of file diff --git a/Source/Examples/OpenTK/GLControl/MultipleGLControls.cs b/Source/Examples/OpenTK/GLControl/MultipleGLControls.cs deleted file mode 100644 index 993a607c..00000000 --- a/Source/Examples/OpenTK/GLControl/MultipleGLControls.cs +++ /dev/null @@ -1,35 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace Examples.WinForms -{ - [Example("Multiple GLControls", ExampleCategory.OpenTK, "GLControl", 3, Documentation="MultipleGLControls")] - public partial class MultipleGLControlsForm : Form - { - public MultipleGLControlsForm() - { - InitializeComponent(); - } - - public static void Main() - { - using (MultipleGLControlsForm example = new MultipleGLControlsForm()) - { - Utilities.SetWindowTitle(example); - example.ShowDialog(); - } - } - } -} \ No newline at end of file diff --git a/Source/Examples/OpenTK/GLControl/MultipleGLControls.resx b/Source/Examples/OpenTK/GLControl/MultipleGLControls.resx deleted file mode 100644 index 19dc0dd8..00000000 --- a/Source/Examples/OpenTK/GLControl/MultipleGLControls.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/Source/Examples/OpenTK/GLWidget/GLWidgetSimple.cs b/Source/Examples/OpenTK/GLWidget/GLWidgetSimple.cs deleted file mode 100644 index 0cbc2b6a..00000000 --- a/Source/Examples/OpenTK/GLWidget/GLWidgetSimple.cs +++ /dev/null @@ -1,152 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Drawing; -using System.Threading; - -using Gtk; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; - -namespace Examples.GLWidget -{ - [Example("GLWidget Simple", ExampleCategory.OpenTK, "GLWidget", 1, Documentation="GLWidgetSimple")] - public class SimpleWindow : Window - { - VBox vbox1; - HBox hbox1; - Button button_red, button_green, button_blue; - OpenTK.GLWidget glwidget1; - - public SimpleWindow() - : base(WindowType.Toplevel) - { - Build(); - } - - private void Build() - { - this.Title = "Sample GLWidget Example"; - this.DefaultWidth = 800; - this.DefaultHeight = 600; - - vbox1 = new VBox(); - - glwidget1 = new OpenTK.GLWidget(); - glwidget1.Initialized += Glwidget1_Initialized; - - // do note that if you are placing the widget inside a container you have to do it after initalization - var t = new Thread(new ThreadStart(delegate { - Thread.Sleep(50); - - Application.Invoke(delegate { - vbox1.PackStart(glwidget1, true, true, 1); - glwidget1.Show(); - }); - })); - t.Start(); - - hbox1 = new HBox(); - - button_blue = new Button("Clear Blue"); - button_blue.Clicked += Button_blue_Clicked; - hbox1.PackStart(button_blue, true, true, 0); - - button_green = new Button("Clear Green"); - button_green.Clicked += Button_green_Clicked; - hbox1.PackStart(button_green, true, true, 1); - - button_red = new Button("Clear Red"); - button_red.Clicked += Button_red_Clicked; - hbox1.PackStart(button_red, true, true, 2); - - vbox1.PackStart(hbox1, false, false, 0); - - this.Add(vbox1); - this.ShowAll(); - - this.DeleteEvent += OnDeleteEvent; - } - - #region Events - - protected void Glwidget1_Initialized(object sender, EventArgs e) - { - GL.ClearColor(1.0f, 1.0f, 1.0f, 1.0f); - - GL.MatrixMode(MatrixMode.Projection); - GL.LoadIdentity(); - GL.Ortho(-1.0, 1.0, -1.0, 1.0, 0.0, 4.0); - - glwidget1.SizeAllocated += Glwidget1_SizeAllocated; - glwidget1.RenderFrame += Glwidget1_RenderFrame; - } - - protected void Glwidget1_SizeAllocated(object o, SizeAllocatedArgs args) - { - GL.Viewport(0, 0, args.Allocation.Width, args.Allocation.Height); - } - - protected void Glwidget1_RenderFrame(object sender, EventArgs e) - { - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - GL.Begin(PrimitiveType.Triangles); - - GL.Color3(Color.MidnightBlue); - GL.Vertex2(-1.0f, 1.0f); - GL.Color3(Color.SpringGreen); - GL.Vertex2(0.0f, -1.0f); - GL.Color3(Color.Ivory); - GL.Vertex2(1.0f, 1.0f); - - GL.End(); - - GraphicsContext.CurrentContext.SwapBuffers(); - } - - protected void Button_blue_Clicked(object sender, EventArgs e) - { - GL.ClearColor(Color.RoyalBlue); - glwidget1.QueueDraw(); - } - - protected void Button_green_Clicked(object sender, EventArgs e) - { - GL.ClearColor(Color.ForestGreen); - glwidget1.QueueDraw(); - } - - protected void Button_red_Clicked(object sender, EventArgs e) - { - GL.ClearColor(Color.Crimson); - glwidget1.QueueDraw(); - } - - protected void OnDeleteEvent(object sender, DeleteEventArgs a) - { - Application.Quit(); - a.RetVal = true; - } - - #endregion - - #region public static void Main() - - public static void Main(string[] args) - { - Application.Init(); - - SimpleWindow win = new SimpleWindow(); - win.Show(); - - Application.Run(); - } - - #endregion - } -} diff --git a/Source/Examples/OpenTK/GameWindow/GameWindowMsaa.cs b/Source/Examples/OpenTK/GameWindow/GameWindowMsaa.cs deleted file mode 100644 index 38c4ae63..00000000 --- a/Source/Examples/OpenTK/GameWindow/GameWindowMsaa.cs +++ /dev/null @@ -1,136 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Drawing; -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; -using OpenTK.Input; - -namespace Examples -{ - [Example("GameWindow MSAA", ExampleCategory.OpenTK, "GameWindow", 2, Documentation = "GameWindowMsaa")] - public class FullscreenAntialias : GameWindow - { - public FullscreenAntialias() - : base(800, 600, new GraphicsMode(32, 0, 0, 4)) - { - KeyDown += Keyboard_KeyDown; - } - - #region Keyboard_KeyDown - - /// - /// Occurs when a key is pressed. - /// - /// The KeyboardDevice which generated this event. - /// The key that was pressed. - void Keyboard_KeyDown(object sender, KeyboardKeyEventArgs e) - { - if (e.Key == Key.Escape) - this.Exit(); - - if (e.Key == Key.F11) - if (this.WindowState == WindowState.Fullscreen) - this.WindowState = WindowState.Normal; - else - this.WindowState = WindowState.Fullscreen; - } - - #endregion - - #region OnLoad - - /// - /// Setup OpenGL and load resources here. - /// - /// Not used. - protected override void OnLoad(EventArgs e) - { - GL.ClearColor(Color.MidnightBlue); - } - - #endregion - - #region OnResize - - /// - /// Respond to resize events here. - /// - /// Contains information on the new GameWindow size. - /// There is no need to call the base implementation. - protected override void OnResize(EventArgs e) - { - GL.Viewport(0, 0, Width, Height); - - GL.MatrixMode(MatrixMode.Projection); - GL.LoadIdentity(); - GL.Ortho(-1.0, 1.0, -1.0, 1.0, 0.0, 4.0); - - base.OnResize(e); - } - - #endregion - - #region OnUpdateFrame - - /// - /// Add your game logic here. - /// - /// Contains timing information. - /// There is no need to call the base implementation. - protected override void OnUpdateFrame(FrameEventArgs e) - { - // Nothing to do! - } - - #endregion - - #region OnRenderFrame - - /// - /// Add your game rendering code here. - /// - /// Contains timing information. - /// There is no need to call the base implementation. - protected override void OnRenderFrame(FrameEventArgs e) - { - GL.Clear(ClearBufferMask.ColorBufferBit); - - GL.Begin(PrimitiveType.Triangles); - - GL.Color3(Color.MidnightBlue); - GL.Vertex2(-1.0f, 1.0f); - GL.Color3(Color.SpringGreen); - GL.Vertex2(0.0f, -1.0f); - GL.Color3(Color.Ivory); - GL.Vertex2(1.0f, 1.0f); - - GL.End(); - - this.SwapBuffers(); - } - - #endregion - - #region public static void Main() - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - using (FullscreenAntialias example = new FullscreenAntialias()) - { - // Get the title and category of this example using reflection. - Utilities.SetWindowTitle(example); - example.Run(30.0, 0.0); - } - } - - #endregion - } -} diff --git a/Source/Examples/OpenTK/GameWindow/GameWindowMsaa.rtf b/Source/Examples/OpenTK/GameWindow/GameWindowMsaa.rtf deleted file mode 100644 index 36643be2..00000000 Binary files a/Source/Examples/OpenTK/GameWindow/GameWindowMsaa.rtf and /dev/null differ diff --git a/Source/Examples/OpenTK/GameWindow/GameWindowSimple.cs b/Source/Examples/OpenTK/GameWindow/GameWindowSimple.cs deleted file mode 100644 index 697e9622..00000000 --- a/Source/Examples/OpenTK/GameWindow/GameWindowSimple.cs +++ /dev/null @@ -1,135 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Drawing; -using OpenTK; -using OpenTK.Graphics.OpenGL; -using OpenTK.Input; - -namespace Examples.Tutorial -{ - /// - /// Demonstrates the GameWindow class. - /// - [Example("GameWindow Simple", ExampleCategory.OpenTK, "GameWindow", 1, Documentation = "GameWindowSimple")] - public class SimpleWindow : GameWindow - { - public SimpleWindow() : base(800, 600) - { - KeyDown += Keyboard_KeyDown; - } - - #region Keyboard_KeyDown - - /// - /// Occurs when a key is pressed. - /// - /// The KeyboardDevice which generated this event. - /// The key that was pressed. - void Keyboard_KeyDown(object sender, KeyboardKeyEventArgs e) - { - if (e.Key == Key.Escape) - this.Exit(); - - if (e.Key == Key.F11) - if (this.WindowState == WindowState.Fullscreen) - this.WindowState = WindowState.Normal; - else - this.WindowState = WindowState.Fullscreen; - } - - #endregion - - #region OnLoad - - /// - /// Setup OpenGL and load resources here. - /// - /// Not used. - protected override void OnLoad(EventArgs e) - { - GL.ClearColor(Color.MidnightBlue); - } - - #endregion - - #region OnResize - - /// - /// Respond to resize events here. - /// - /// Contains information on the new GameWindow size. - /// There is no need to call the base implementation. - protected override void OnResize(EventArgs e) - { - GL.Viewport(0, 0, Width, Height); - - GL.MatrixMode(MatrixMode.Projection); - GL.LoadIdentity(); - GL.Ortho(-1.0, 1.0, -1.0, 1.0, 0.0, 4.0); - } - - #endregion - - #region OnUpdateFrame - - /// - /// Add your game logic here. - /// - /// Contains timing information. - /// There is no need to call the base implementation. - protected override void OnUpdateFrame(FrameEventArgs e) - { - // Nothing to do! - } - - #endregion - - #region OnRenderFrame - - /// - /// Add your game rendering code here. - /// - /// Contains timing information. - /// There is no need to call the base implementation. - protected override void OnRenderFrame(FrameEventArgs e) - { - GL.Clear(ClearBufferMask.ColorBufferBit); - - GL.Begin(PrimitiveType.Triangles); - - GL.Color3(Color.MidnightBlue); - GL.Vertex2(-1.0f, 1.0f); - GL.Color3(Color.SpringGreen); - GL.Vertex2(0.0f, -1.0f); - GL.Color3(Color.Ivory); - GL.Vertex2(1.0f, 1.0f); - - GL.End(); - - this.SwapBuffers(); - } - - #endregion - - #region public static void Main() - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - using (SimpleWindow example = new SimpleWindow()) - { - // Get the title and category of this example using reflection. - Utilities.SetWindowTitle(example); - example.Run(30.0, 0.0); - } - } - - #endregion - } -} diff --git a/Source/Examples/OpenTK/GameWindow/GameWindowSimple.rtf b/Source/Examples/OpenTK/GameWindow/GameWindowSimple.rtf deleted file mode 100644 index c360c26d..00000000 Binary files a/Source/Examples/OpenTK/GameWindow/GameWindowSimple.rtf and /dev/null differ diff --git a/Source/Examples/OpenTK/GameWindow/GameWindowThreaded.cs b/Source/Examples/OpenTK/GameWindow/GameWindowThreaded.cs deleted file mode 100644 index c60f0afa..00000000 --- a/Source/Examples/OpenTK/GameWindow/GameWindowThreaded.cs +++ /dev/null @@ -1,319 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Drawing; -using System.Threading; -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; -using OpenTK.Input; - -namespace Examples.Tutorial -{ - /// - /// Demonstrates how to decouple rendering from the main thread. - /// Note that all OpenGL function calls should take place at the rendering thread - - /// OpenGL will not be available on the main thread at all! - /// - [Example("GameWindow Threaded", ExampleCategory.OpenTK, "GameWindow", 3, Documentation = "GameWindowThreaded")] - public class ThreadedRendering : GameWindow - { - bool viewport_changed = true; - int viewport_width, viewport_height; - bool position_changed = true; - int position_x, position_y; - float position_dx, position_dy; - bool exit = false; - Thread rendering_thread; - object update_lock = new object(); - const float GravityAccel = -9.81f; - struct Particle - { - public Vector2 Position; - public Vector2 Velocity; - public Color4 Color; - } - List Particles = new List(); - Random rand = new Random(); - - public ThreadedRendering() - : base(800, 600) - { - KeyDown += delegate(object sender, KeyboardKeyEventArgs e) - { - if (e.Key == Key.Escape) - this.Exit(); - }; - - KeyUp += delegate(object sender, KeyboardKeyEventArgs e) - { - if (e.Key == Key.F11) - if (this.WindowState == WindowState.Fullscreen) - this.WindowState = WindowState.Normal; - else - this.WindowState = WindowState.Fullscreen; - }; - - Resize += delegate(object sender, EventArgs e) - { - // Note that we cannot call any OpenGL methods directly. What we can do is set - // a flag and respond to it from the rendering thread. - lock (update_lock) - { - viewport_changed = true; - viewport_width = Width; - viewport_height = Height; - } - }; - - Move += delegate(object sender, EventArgs e) - { - // Note that we cannot call any OpenGL methods directly. What we can do is set - // a flag and respond to it from the rendering thread. - lock (update_lock) - { - position_changed = true; - position_dx = (position_x - X) / (float)Width; - position_dy = (position_y - Y) / (float)Height; - position_x = X; - position_y = Y; - } - }; - - // Make sure initial position are correct, otherwise we'll give a huge - // initial velocity to the balls. - position_x = X; - position_y = Y; - } - - #region OnLoad - - /// - /// Setup OpenGL and load resources here. - /// - /// Not used. - protected override void OnLoad(EventArgs e) - { - Context.MakeCurrent(null); // Release the OpenGL context so it can be used on the new thread. - - rendering_thread = new Thread(RenderLoop); - rendering_thread.IsBackground = true; - rendering_thread.Start(); - } - - #endregion - - #region OnUnload - - /// - /// Release resources here. - /// - /// Not used. - protected override void OnUnload(EventArgs e) - { - exit = true; // Set a flag that the rendering thread should stop running. - rendering_thread.Join(); - - base.OnUnload(e); - } - - #endregion - - #region OnUpdateFrame - - /// - /// Add your game logic here. - /// - /// Contains timing information. - /// There is no need to call the base implementation. - protected override void OnUpdateFrame(FrameEventArgs e) - { - // Nothing to do! - } - - #endregion - - #region OnRenderFrame - - /// - /// Ignored. All rendering is performed on our own rendering function. - /// - /// Contains timing information. - /// There is no need to call the base implementation. - protected override void OnRenderFrame(FrameEventArgs e) - { - // Nothing to do. Release the CPU to other threads. - Thread.Sleep(1); - } - - #endregion - - #region RenderLoop - - void RenderLoop() - { - MakeCurrent(); // The context now belongs to this thread. No other thread may use it! - - VSync = VSyncMode.On; - - for (int i = 0; i < 64; i++) - { - Particle p = new Particle(); - p.Position = new Vector2((float)rand.NextDouble() * 2 - 1, (float)rand.NextDouble() * 2 - 1); - p.Color.R = (float)rand.NextDouble(); - p.Color.G = (float)rand.NextDouble(); - p.Color.B = (float)rand.NextDouble(); - Particles.Add(p); - } - - // Since we don't use OpenTK's timing mechanism, we need to keep time ourselves; - Stopwatch render_watch = new Stopwatch(); - Stopwatch update_watch = new Stopwatch(); - update_watch.Start(); - render_watch.Start(); - - GL.ClearColor(Color.MidnightBlue); - GL.Enable(EnableCap.DepthTest); - GL.Enable(EnableCap.PointSmooth); - GL.PointSize(16); - - while (!exit) - { - Update(update_watch.Elapsed.TotalSeconds); - update_watch.Reset(); - update_watch.Start(); - - Render(render_watch.Elapsed.TotalSeconds); - render_watch.Reset(); // Stopwatch may be inaccurate over larger intervals. - render_watch.Start(); // Plus, timekeeping is easier if we always start counting from 0. - - SwapBuffers(); - } - - Context.MakeCurrent(null); - } - - #endregion - - #region Update - - void Update(double time) - { - lock (update_lock) - { - // When the user moves the window we make the particles react to - // this movement. The reaction is semi-random and not physically - // correct. It looks quite good, however. - if (position_changed) - { - for (int i = 0; i < Particles.Count; i++) - { - Particle p = Particles[i]; - p.Velocity += new Vector2( - 16 * (position_dx + 0.05f * (float)(rand.NextDouble() - 0.5)), - 32 * (position_dy + 0.05f * (float)(rand.NextDouble() - 0.5))); - Particles[i] = p; - } - - position_changed = false; - } - } - - // For simplicity, we use simple Euler integration to simulate particle movement. - // This is not accurate, especially under varying timesteps (as is the case here). - // A better solution would have been time-corrected Verlet integration, as - // described here: - // http://www.gamedev.net/reference/programming/features/verlet/ - for (int i = 0; i < Particles.Count; i++) - { - Particle p = Particles[i]; - - p.Velocity.X = Math.Abs(p.Position.X) >= 1 ?-p.Velocity.X * 0.92f : p.Velocity.X * 0.97f; - p.Velocity.Y = Math.Abs(p.Position.Y) >= 1 ? -p.Velocity.Y * 0.92f : p.Velocity.Y * 0.97f; - if (p.Position.Y > -0.99) - { - p.Velocity.Y += (float)(GravityAccel * time); - } - else - { - if (Math.Abs(p.Velocity.Y) < 0.02) - { - p.Velocity.Y = 0; - p.Position.Y = -1; - } - else - { - p.Velocity.Y *= 0.9f; - } - } - - p.Position += p.Velocity * (float)time; - if (p.Position.Y <= -1) - p.Position.Y = -1; - - Particles[i] = p; - } - } - - #endregion - - #region Render - - /// - /// This is our main rendering function, which executes on the rendering thread. - /// - public void Render(double time) - { - lock (update_lock) - { - if (viewport_changed) - { - GL.Viewport(0, 0, viewport_width, viewport_height); - viewport_changed = false; - } - } - - Matrix4 perspective = - Matrix4.CreateOrthographic(2, 2, -1, 1); - GL.MatrixMode(MatrixMode.Projection); - GL.LoadMatrix(ref perspective); - - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadIdentity(); - - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - GL.Begin(PrimitiveType.Points); - foreach (Particle p in Particles) - { - GL.Color4(p.Color); - GL.Vertex2(p.Position); - } - GL.End(); - } - - #endregion - - #region public static void Main() - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - using (GameWindow example = new ThreadedRendering()) - { - // Get the title and category of this example using reflection. - Utilities.SetWindowTitle(example); - example.Run(); - } - } - - #endregion - } -} diff --git a/Source/Examples/OpenTK/GameWindow/GameWindowThreaded.rtf b/Source/Examples/OpenTK/GameWindow/GameWindowThreaded.rtf deleted file mode 100644 index a2d12660..00000000 Binary files a/Source/Examples/OpenTK/GameWindow/GameWindowThreaded.rtf and /dev/null differ diff --git a/Source/Examples/OpenTK/GameWindow/MouseCursorSimple.cs b/Source/Examples/OpenTK/GameWindow/MouseCursorSimple.cs deleted file mode 100644 index c3276581..00000000 --- a/Source/Examples/OpenTK/GameWindow/MouseCursorSimple.cs +++ /dev/null @@ -1,224 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Collections.Generic; -using System.Drawing; -using OpenTK; -using OpenTK.Graphics.OpenGL; -using OpenTK.Input; - -namespace Examples.Tutorial -{ - /// - /// Demonstrates the MouseCursor class. - /// - [Example("Custom MouseCursor", ExampleCategory.OpenTK, "GameWindow", 1, Documentation = "MouseCursorSimple")] - public class MouseCursorSimple : GameWindow - { - readonly MouseCursor MyCursor; - List lines = new List(); - - public MouseCursorSimple() - : base(800, 600) - { - KeyDown += Keyboard_KeyDown; - - using (Bitmap bitmap = new Bitmap("Data/Textures/cursor.png")) - { - var data = bitmap.LockBits( - new Rectangle(0, 0, bitmap.Width, bitmap.Height), - System.Drawing.Imaging.ImageLockMode.ReadOnly, - System.Drawing.Imaging.PixelFormat.Format32bppPArgb); - - MyCursor = new OpenTK.MouseCursor( - 2, 21, data.Width, data.Height, data.Scan0); - Cursor = MyCursor; - } - - MouseMove += Mouse_Move; - MouseDown += Mouse_ButtonDown; - } - - void AddLine(float x, float y) - { - // Scale mouse coordinates from - // (0, 0):(Width, Height) to - // (-1, -1):(+1, +1) - // Note, we must flip the y-coordinate - // since mouse is reported with (0, 0) - // at top-left and our projection uses - // (-1, -1) at bottom left. - x = (x- Width) / (float)Width; - y = (Height - y) / (float)Height; - lines.Add(new Vector2(2 * x + 1, 2 * y - 1)); - } - - #region Mouse_ButtonDown - - void Mouse_ButtonDown(object sender, MouseButtonEventArgs e) - { - if (e.Button == MouseButton.Left) - { - AddLine(e.X, e.Y); - } - } - - #endregion - - #region Mouse_Move - - void Mouse_Move(object sender, MouseMoveEventArgs e) - { - if (e.Mouse[MouseButton.Left]) - { - AddLine(e.X, e.Y); - } - } - - #endregion - - #region Keyboard_KeyDown - - /// - /// Occurs when a key is pressed. - /// - /// The KeyboardDevice which generated this event. - /// The key that was pressed. - void Keyboard_KeyDown(object sender, KeyboardKeyEventArgs e) - { - if (e.Key == Key.Escape) - { - this.Exit(); - } - - if (e.Key == Key.Enter && e.Alt) - { - if (this.WindowState == WindowState.Fullscreen) - this.WindowState = WindowState.Normal; - else - this.WindowState = WindowState.Fullscreen; - } - else if (e.Key == Key.Enter) - { - CursorVisible = !CursorVisible; - } - - if (e.Key == Key.Space) - { - if (Cursor == MouseCursor.Default) - { - Cursor = MyCursor; - } - else if (Cursor == MyCursor) - { - Cursor = MouseCursor.Empty; - } - else - { - Cursor = MouseCursor.Default; - } - } - } - - #endregion - - #region OnLoad - - /// - /// Setup OpenGL and load resources here. - /// - /// Not used. - protected override void OnLoad(EventArgs e) - { - GL.ClearColor(Color.MidnightBlue); - } - - #endregion - - #region OnResize - - /// - /// Respond to resize events here. - /// - /// Contains information on the new GameWindow size. - /// There is no need to call the base implementation. - protected override void OnResize(EventArgs e) - { - GL.Viewport(0, 0, Width, Height); - - GL.MatrixMode(MatrixMode.Projection); - GL.LoadIdentity(); - GL.Ortho(-1.0, 1.0, -1.0, 1.0, 0.0, 4.0); - } - - #endregion - - #region OnUpdateFrame - - /// - /// Add your game logic here. - /// - /// Contains timing information. - /// There is no need to call the base implementation. - protected override void OnUpdateFrame(FrameEventArgs e) - { - } - - #endregion - - #region OnRenderFrame - - /// - /// Add your game rendering code here. - /// - /// Contains timing information. - /// There is no need to call the base implementation. - protected override void OnRenderFrame(FrameEventArgs e) - { - GL.Clear(ClearBufferMask.ColorBufferBit); - - GL.Begin(PrimitiveType.Triangles); - - GL.Color3(Color.MidnightBlue); - GL.Vertex2(-1.0f, 1.0f); - GL.Color3(Color.SpringGreen); - GL.Vertex2(0.0f, -1.0f); - GL.Color3(Color.Ivory); - GL.Vertex2(1.0f, 1.0f); - - GL.End(); - - GL.Begin(PrimitiveType.LineStrip); - foreach (var p in lines) - { - GL.Color4(Color.White); - GL.Vertex2(p); - } - GL.End(); - - this.SwapBuffers(); - } - - #endregion - - #region public static void Main() - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - using (MouseCursorSimple example = new MouseCursorSimple()) - { - // Get the title and category of this example using reflection. - Utilities.SetWindowTitle(example); - example.Run(30.0, 0.0); - } - } - - #endregion - } -} diff --git a/Source/Examples/OpenTK/GameWindow/MouseCursorSimple.rtf b/Source/Examples/OpenTK/GameWindow/MouseCursorSimple.rtf deleted file mode 100644 index 18c0bdb6..00000000 Binary files a/Source/Examples/OpenTK/GameWindow/MouseCursorSimple.rtf and /dev/null differ diff --git a/Source/Examples/OpenTK/Test/BasicMouseInput.cs b/Source/Examples/OpenTK/Test/BasicMouseInput.cs deleted file mode 100644 index b40d94c3..00000000 --- a/Source/Examples/OpenTK/Test/BasicMouseInput.cs +++ /dev/null @@ -1,123 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain by Andy Korth -// It is provided "as is" without express or implied warranty of any kind. - -#region --- Using Directives --- - -using System; -using System.Collections.Generic; -using System.Drawing; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; -using OpenTK.Input; - -#endregion --- Using Directives --- - -namespace Examples.Tests -{ - /// - /// Demonstrates basic recommended mouse input, and to see if it actually works - /// - [Example("Basic Mouse Input", ExampleCategory.OpenTK,"Basic Mouse Input")] - public class BasicMouseInput : GameWindow - { - List lines = new List(); - - public BasicMouseInput() - : base(800, 600) - { - MouseMove += (sender, e) => - { - if (e.Mouse[MouseButton.Left]) - { - // Scale mouse coordinates from - // (0, 0):(Width, Height) to - // (-1, -1):(+1, +1) - // Note, we must flip the y-coordinate - // since mouse is reported with (0, 0) - // at top-left and our projection uses - // (-1, -1) at bottom left. - float x = (e.X - Width) / (float)Width; - float y = (Height- e.Y) / (float)Height; - lines.Add(new Vector2(2 * x + 1, 2 * y - 1)); - } - }; - } - - protected override void OnLoad(EventArgs e) - { - MouseUp += (object sender, MouseButtonEventArgs buttonEvent) => { - Console.WriteLine("Mouse button up: " + buttonEvent.Button + " at: " + buttonEvent.Position); - }; - } - - protected override void OnUpdateFrame(FrameEventArgs e) - { - // Here's the big test! - if(OpenTK.Input.Mouse.GetState()[MouseButton.Left]){ - Console.WriteLine("The left mouse button is down!"); - } - - // While we are here, test keyboard. - if(OpenTK.Input.Keyboard.GetState()[Key.A]){ - Console.WriteLine("The A key is down!"); - } - - var keyboard = OpenTK.Input.Keyboard.GetState(); - - if (keyboard[OpenTK.Input.Key.Escape]) - this.Exit(); - - if (keyboard[OpenTK.Input.Key.F11]) - if (WindowState != WindowState.Fullscreen) - WindowState = WindowState.Fullscreen; - else - WindowState = WindowState.Normal; - } - - protected override void OnRenderFrame(FrameEventArgs e) - { - GL.ClearColor(Color.MidnightBlue); - GL.Clear(ClearBufferMask.ColorBufferBit); - - GL.Viewport(ClientRectangle); - GL.MatrixMode(MatrixMode.Projection); - GL.LoadIdentity(); - GL.Ortho(-1, 1, -1, 1, -1, 1); - - GL.Begin(PrimitiveType.LineStrip); - foreach (var p in lines) - { - GL.Color4(Color.White); - GL.Vertex2(p); - } - GL.End(); - - SwapBuffers(); - - var keyboard = OpenTK.Input.Keyboard.GetState(); - if (keyboard[Key.Space]) - { - // Simulate high load (4 fps) to check - // mouse input behavior - System.Threading.Thread.Sleep(250); - } - } - - [STAThread] - public static void Main() - { - using (BasicMouseInput example = new BasicMouseInput()) - { - // Get the title and category of this example using reflection. - ExampleAttribute info = ((ExampleAttribute)example.GetType().GetCustomAttributes(false)[0]); - example.Title = String.Format("OpenTK | {0} {1}: {2}", info.Category, info.Difficulty, info.Title); - - example.Run(30.0); - } - } - - } -} diff --git a/Source/Examples/OpenTK/Test/BlittableValueTypes.cs b/Source/Examples/OpenTK/Test/BlittableValueTypes.cs deleted file mode 100644 index 8ac895d7..00000000 --- a/Source/Examples/OpenTK/Test/BlittableValueTypes.cs +++ /dev/null @@ -1,79 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Diagnostics; -using System.Reflection; -using OpenTK; - -#pragma warning disable 0649 // Do not warn about unitialized fields, this is on purpose - -namespace Examples.Tests -{ - struct Simple { public int Value; } - struct Generic { public T Value; } - enum Enum { First, Second } - struct Complex { public Simple Value; } - struct Complex { public Generic Value; } - struct Complex2 { public Enum Value; } - struct Complex3 { public Class Value; } - struct Complex4 : Interface { public Class Value; } - class Class { public int Value; } - class Class { public T Value; } - interface Interface { } - - [Example("Blittable Value Types", ExampleCategory.OpenTK, "Test", Documentation="BlittableValueTypes")] - public class BlittableValueTypes - { - public static void Main() - { - TestType(new Simple()); - TestType(new Generic()); - TestType(new Generic()); - TestType(new Complex()); - TestType(new Complex()); - TestType(new Complex2()); - TestType(new Complex3()); - TestType(new Complex4()); - TestType(new Class()); - TestType(new Class()); - } - - // Tests whether specified type is blittable and prints its marshalled size if so. - static void TestType(T instance) - { - PrintType(); - - Trace.Write(BlittableValueType.Check(instance) ? "is blittable " : "is not blittable "); - - try - { - // StrideOf() will throw an ArgumentException if the type is not blittable. - Trace.Write(String.Format("({0} bytes)", BlittableValueType.StrideOf(instance))); - } - catch (Exception e) - { - Trace.Write(String.Format("({0})", e.GetType().Name)); - } - - Trace.WriteLine(""); - } - - // Prints a simple description for the type. - static void PrintType() - { - Type type = typeof(T); - string typename = type.GetFields()[0].FieldType.ToString(); - - Trace.Write(type.IsClass ? "class " : type.IsEnum ? "enum " : type.IsInterface ? "interface " : "struct "); - Trace.Write(type.Name); - if (type.IsGenericType) - Trace.Write(String.Format("<{0}>", type.GetGenericArguments()[0].Name)); - Trace.Write(" { "); - - Trace.Write(typename.Substring(typename.LastIndexOf('.') + 1)); - Trace.Write(" } "); - } - } -} diff --git a/Source/Examples/OpenTK/Test/BlittableValueTypes.rtf b/Source/Examples/OpenTK/Test/BlittableValueTypes.rtf deleted file mode 100644 index d6f3715d..00000000 Binary files a/Source/Examples/OpenTK/Test/BlittableValueTypes.rtf and /dev/null differ diff --git a/Source/Examples/OpenTK/Test/Color4Serialization.cs b/Source/Examples/OpenTK/Test/Color4Serialization.cs deleted file mode 100644 index 168da1aa..00000000 --- a/Source/Examples/OpenTK/Test/Color4Serialization.cs +++ /dev/null @@ -1,32 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System.Diagnostics; -using System.IO; -using System.Xml.Serialization; -using OpenTK.Graphics; - -namespace Examples.Tests -{ - [Example("Color4 Serialization", ExampleCategory.OpenTK, "Test", Documentation="Color4Serialization")] - public class Color4Serialization - { - public static void Main() - { - Color4 color = System.Drawing.Color.MidnightBlue; - Color4 color2 = new Color4(); - - using (MemoryStream stream = new MemoryStream()) - { - XmlSerializer xs = new XmlSerializer(typeof(Color4)); - xs.Serialize(stream, color); - stream.Seek(0, SeekOrigin.Begin); - color2 = (Color4)xs.Deserialize(stream); - Trace.WriteLine(color); - Trace.WriteLine(color2); - Trace.WriteLine(color.Equals(color2)); - } - } - } -} diff --git a/Source/Examples/OpenTK/Test/Extensions.Designer.cs b/Source/Examples/OpenTK/Test/Extensions.Designer.cs deleted file mode 100644 index 9cadd734..00000000 --- a/Source/Examples/OpenTK/Test/Extensions.Designer.cs +++ /dev/null @@ -1,236 +0,0 @@ -namespace Examples.WinForms -{ - partial class Extensions - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker(); - this.dataGridView1 = new System.Windows.Forms.DataGridView(); - this.LabelVendor = new System.Windows.Forms.Label(); - this.LabelRenderer = new System.Windows.Forms.Label(); - this.LabelVersion = new System.Windows.Forms.Label(); - this.TextBoxVendor = new System.Windows.Forms.TextBox(); - this.TextBoxRenderer = new System.Windows.Forms.TextBox(); - this.TextBoxVersion = new System.Windows.Forms.TextBox(); - this.LabelSupport = new System.Windows.Forms.Label(); - this.TextBoxSupport = new System.Windows.Forms.TextBox(); - this.SupportedColumn = new System.Windows.Forms.DataGridViewCheckBoxColumn(); - this.NameColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); - this.CategoryColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); - this.Version = new System.Windows.Forms.DataGridViewTextBoxColumn(); - this.ExtensionColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); - this.UnmanagedName = new System.Windows.Forms.DataGridViewTextBoxColumn(); - ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); - this.SuspendLayout(); - // - // backgroundWorker1 - // - this.backgroundWorker1.WorkerReportsProgress = true; - this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork); - this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted); - // - // dataGridView1 - // - this.dataGridView1.AllowUserToAddRows = false; - this.dataGridView1.AllowUserToDeleteRows = false; - this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; - this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { - this.SupportedColumn, - this.NameColumn, - this.CategoryColumn, - this.Version, - this.ExtensionColumn, - this.UnmanagedName}); - this.dataGridView1.Location = new System.Drawing.Point(0, 110); - this.dataGridView1.Name = "dataGridView1"; - this.dataGridView1.ReadOnly = true; - this.dataGridView1.Size = new System.Drawing.Size(939, 397); - this.dataGridView1.TabIndex = 1; - // - // LabelVendor - // - this.LabelVendor.AutoSize = true; - this.LabelVendor.Location = new System.Drawing.Point(12, 9); - this.LabelVendor.Name = "LabelVendor"; - this.LabelVendor.Size = new System.Drawing.Size(41, 13); - this.LabelVendor.TabIndex = 2; - this.LabelVendor.Text = "Vendor"; - // - // LabelRenderer - // - this.LabelRenderer.AutoSize = true; - this.LabelRenderer.Location = new System.Drawing.Point(12, 35); - this.LabelRenderer.Name = "LabelRenderer"; - this.LabelRenderer.Size = new System.Drawing.Size(51, 13); - this.LabelRenderer.TabIndex = 3; - this.LabelRenderer.Text = "Renderer"; - // - // LabelVersion - // - this.LabelVersion.AutoSize = true; - this.LabelVersion.Location = new System.Drawing.Point(12, 61); - this.LabelVersion.Name = "LabelVersion"; - this.LabelVersion.Size = new System.Drawing.Size(42, 13); - this.LabelVersion.TabIndex = 4; - this.LabelVersion.Text = "Version"; - // - // TextBoxVendor - // - this.TextBoxVendor.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.TextBoxVendor.Location = new System.Drawing.Point(70, 6); - this.TextBoxVendor.Name = "TextBoxVendor"; - this.TextBoxVendor.ReadOnly = true; - this.TextBoxVendor.Size = new System.Drawing.Size(856, 20); - this.TextBoxVendor.TabIndex = 5; - // - // TextBoxRenderer - // - this.TextBoxRenderer.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.TextBoxRenderer.Location = new System.Drawing.Point(70, 32); - this.TextBoxRenderer.Name = "TextBoxRenderer"; - this.TextBoxRenderer.ReadOnly = true; - this.TextBoxRenderer.Size = new System.Drawing.Size(856, 20); - this.TextBoxRenderer.TabIndex = 6; - // - // TextBoxVersion - // - this.TextBoxVersion.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.TextBoxVersion.Location = new System.Drawing.Point(70, 58); - this.TextBoxVersion.Name = "TextBoxVersion"; - this.TextBoxVersion.ReadOnly = true; - this.TextBoxVersion.Size = new System.Drawing.Size(856, 20); - this.TextBoxVersion.TabIndex = 7; - // - // LabelSupport - // - this.LabelSupport.AutoSize = true; - this.LabelSupport.Location = new System.Drawing.Point(12, 87); - this.LabelSupport.Name = "LabelSupport"; - this.LabelSupport.Size = new System.Drawing.Size(44, 13); - this.LabelSupport.TabIndex = 8; - this.LabelSupport.Text = "Support"; - // - // TextBoxSupport - // - this.TextBoxSupport.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.TextBoxSupport.Location = new System.Drawing.Point(70, 84); - this.TextBoxSupport.Name = "TextBoxSupport"; - this.TextBoxSupport.ReadOnly = true; - this.TextBoxSupport.Size = new System.Drawing.Size(856, 20); - this.TextBoxSupport.TabIndex = 9; - // - // SupportedColumn - // - this.SupportedColumn.HeaderText = ""; - this.SupportedColumn.Name = "SupportedColumn"; - this.SupportedColumn.ReadOnly = true; - this.SupportedColumn.Width = 24; - // - // NameColumn - // - this.NameColumn.HeaderText = "Name"; - this.NameColumn.Name = "NameColumn"; - this.NameColumn.ReadOnly = true; - this.NameColumn.Width = 852; - // - // CategoryColumn - // - this.CategoryColumn.HeaderText = "Category"; - this.CategoryColumn.Name = "CategoryColumn"; - this.CategoryColumn.ReadOnly = true; - this.CategoryColumn.Width = 5; - // - // Version - // - this.Version.HeaderText = "Introduced"; - this.Version.Name = "Version"; - this.Version.ReadOnly = true; - this.Version.Width = 5; - // - // ExtensionColumn - // - this.ExtensionColumn.HeaderText = "Extension"; - this.ExtensionColumn.Name = "ExtensionColumn"; - this.ExtensionColumn.ReadOnly = true; - this.ExtensionColumn.Width = 5; - // - // UnmanagedName - // - this.UnmanagedName.HeaderText = "Unmanaged Name"; - this.UnmanagedName.Name = "UnmanagedName"; - this.UnmanagedName.ReadOnly = true; - this.UnmanagedName.Width = 5; - // - // Extensions - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.ClientSize = new System.Drawing.Size(938, 508); - this.Controls.Add(this.TextBoxSupport); - this.Controls.Add(this.LabelSupport); - this.Controls.Add(this.TextBoxVersion); - this.Controls.Add(this.TextBoxRenderer); - this.Controls.Add(this.TextBoxVendor); - this.Controls.Add(this.LabelVersion); - this.Controls.Add(this.LabelRenderer); - this.Controls.Add(this.LabelVendor); - this.Controls.Add(this.dataGridView1); - this.Name = "Extensions"; - this.Text = "W03_Extensions"; - ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.ComponentModel.BackgroundWorker backgroundWorker1; - private System.Windows.Forms.DataGridView dataGridView1; - private System.Windows.Forms.Label LabelVendor; - private System.Windows.Forms.Label LabelRenderer; - private System.Windows.Forms.Label LabelVersion; - private System.Windows.Forms.TextBox TextBoxVendor; - private System.Windows.Forms.TextBox TextBoxRenderer; - private System.Windows.Forms.TextBox TextBoxVersion; - private System.Windows.Forms.Label LabelSupport; - private System.Windows.Forms.TextBox TextBoxSupport; - private System.Windows.Forms.DataGridViewCheckBoxColumn SupportedColumn; - private System.Windows.Forms.DataGridViewTextBoxColumn NameColumn; - private System.Windows.Forms.DataGridViewTextBoxColumn CategoryColumn; - private System.Windows.Forms.DataGridViewTextBoxColumn Version; - private System.Windows.Forms.DataGridViewTextBoxColumn ExtensionColumn; - private System.Windows.Forms.DataGridViewTextBoxColumn UnmanagedName; - } -} \ No newline at end of file diff --git a/Source/Examples/OpenTK/Test/Extensions.cs b/Source/Examples/OpenTK/Test/Extensions.cs deleted file mode 100644 index b6f4c2c7..00000000 --- a/Source/Examples/OpenTK/Test/Extensions.cs +++ /dev/null @@ -1,250 +0,0 @@ -#region --- License --- -/* Copyright (c) 2006, 2007 Stefanos Apostolopoulos - * See license.txt for license info - */ -#endregion - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.Threading; -using System.Reflection; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; -using System.Text.RegularExpressions; - -namespace Examples.WinForms -{ - [Example("OpenGL Extensions", ExampleCategory.OpenTK, "Test", Documentation="Extensions", Visible = false)] - public partial class Extensions : Form - { - #region Fields - - int supported_count, opengl_function_count; // Number of supported extensions. - SortedDictionary functions = new SortedDictionary(); - - #endregion - - #region Constructors - - public Extensions() - { - this.Font = SystemFonts.MessageBoxFont; - InitializeComponent(); - - Application.Idle += StartAsync; - - // Workaround for missing Idle event on Mono/Windows. - if (Configuration.RunningOnMono && Configuration.RunningOnWindows) - Application.RaiseIdle(EventArgs.Empty); - } - - #endregion - - #region Private Members - - // Creates a context and starts processing the GL class. - // The processing takes place in the background to avoid hanging the GUI. - void StartAsync(object sender, EventArgs e) - { - Application.Idle -= StartAsync; - - // Create a context to load all GL entry points. - // The loading part is handled automatically by OpenTK. - using (INativeWindow window = new OpenTK.NativeWindow()) - using (IGraphicsContext context = new GraphicsContext(GraphicsMode.Default, window.WindowInfo, 3, 0, GraphicsContextFlags.Default)) - { - window.ProcessEvents(); - context.MakeCurrent(window.WindowInfo); - (context as IGraphicsContextInternal).LoadAll(); - - TextBoxVendor.Text = GL.GetString(StringName.Vendor); - TextBoxRenderer.Text = GL.GetString(StringName.Renderer); - TextBoxVersion.Text = GL.GetString(StringName.Version); - } - - backgroundWorker1.RunWorkerAsync(); - TextBoxSupport.Text = "processing... (please be patient)"; - } - - void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) - { - Type delegates = typeof(GL).GetNestedType("Delegates", BindingFlags.NonPublic | BindingFlags.Static); - - foreach (Function f in LoadFunctionsFromType(typeof(GL))) - { - FieldInfo @delegate = delegates.GetField(f.EntryPoint, - BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); - - // Only show a function as supported when all relevant overloads are supported. - if (!functions.ContainsKey(f)) - functions.Add(f, @delegate != null && @delegate.GetValue(null) != null); - else - functions[f] &= @delegate != null && @delegate.GetValue(null) != null; - } - - // Count supported functions using the delegates directly. - foreach (FieldInfo f in typeof(GL).GetNestedType("Delegates", BindingFlags.NonPublic) - .GetFields(BindingFlags.Static | BindingFlags.NonPublic)) - { - if (f.GetValue(null) != null) - supported_count++; - - opengl_function_count++; - } - } - - // Recursively load all functions marked with [AutoGenerated] in the specified Type. - IEnumerable LoadFunctionsFromType(Type type) - { - foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) - { - // Functions in GLHelper.cs are not autogenerated and should be skipped. - AutoGeneratedAttribute[] attr = (AutoGeneratedAttribute[]) - method.GetCustomAttributes(typeof(AutoGeneratedAttribute), false); - if (attr.Length == 0) - continue; - string returnType = method.ReturnParameter.ToString(); - List args = new List(); - foreach (ParameterInfo item in method.GetParameters()) - { - args.Add(item.ToString()); - } - - string argsStr = String.Join(", ", args.ToArray()); - string fullMethodName = String.Format("{0} {1}({2})", returnType, method.Name, argsStr); - - yield return new Function(fullMethodName, type.Name, - attr[0].EntryPoint, attr[0].Version, attr[0].Category); - } - - foreach (Type nested_type in type.GetNestedTypes(BindingFlags.Public | BindingFlags.Static)) - foreach (Function f in LoadFunctionsFromType(nested_type)) - yield return f; - } - - // Update the DataGridView with our findings. - private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) - { - TextBoxSupport.Text = String.Format("{0} of {1} functions supported.", - supported_count, opengl_function_count); - - foreach (Function f in functions.Keys) - { - dataGridView1.Rows.Add(functions[f], f.Name, f.Category, f.Version, f.Extension, f.EntryPoint); - int index = dataGridView1.Rows.Count - 1; - - // Some simple coloring to make the GridView easier on the eyes. - // Supported functions are green, unsupported are redish. - dataGridView1.Rows[index].DefaultCellStyle.BackColor = - functions[f] ? - (index % 2 != 0 ? Color.FromArgb(128, 255, 192) : Color.FromArgb(192, 255, 192)) : - (index % 2 != 0 ? Color.FromArgb(255, 192, 160) : Color.FromArgb(255, 200, 160)); - } - - // Change the width of our Form to make every DataGridView column visible. - dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader); - dataGridView1.Columns[1].Width = 450; - this.Size = dataGridView1.GetPreferredSize(new System.Drawing.Size(2000, Height)); - } - - #endregion - - #region public static void Main() - - /// - /// Entry point of this example. - /// - [STAThread] - public static void Main() - { - using (Extensions example = new Extensions()) - { - Utilities.SetWindowTitle(example); - example.ShowDialog(); - } - } - - #endregion - } - - #region class Function - - // A simple class where we store information from OpenTK.Graphics.GL. - sealed class Function : IEquatable, IComparable - { - #region Fields - - // We use these fields to distinguish between functions. - public readonly string Name; - public readonly string Category; - // These fields just provide some extra (cosmetic) information. - public readonly string EntryPoint; - public readonly string Version; - public readonly string Extension; - - #endregion - - #region Constructors - - public Function(string name, string category, string entryPoint, string version, string extension) - { - Name = name; - Category = category == "GL" ? String.Empty : category; - EntryPoint = entryPoint; - Version = version; - Extension = extension; - } - - #endregion - - #region Public Members - - public override bool Equals(object obj) - { - if (obj is Function) - return this.Equals((Function)obj); - - return false; - } - - public override int GetHashCode() - { - return Name.GetHashCode() ^ Category.GetHashCode(); - } - - #endregion - - #region IEquatable Members - - public bool Equals(Function other) - { - return - Category == other.Category && - Name == other.Name; - } - - #endregion - - #region IComparable Members - - public int CompareTo(Function other) - { - int order = Category.CompareTo(other.Category); - if (order == 0) - order = Name.CompareTo(other.Name); - - return order; - } - - #endregion - } - - #endregion -} \ No newline at end of file diff --git a/Source/Examples/OpenTK/Test/Extensions.resx b/Source/Examples/OpenTK/Test/Extensions.resx deleted file mode 100644 index ecf172ae..00000000 --- a/Source/Examples/OpenTK/Test/Extensions.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - True - - - True - - \ No newline at end of file diff --git a/Source/Examples/OpenTK/Test/ExternalContext.cs b/Source/Examples/OpenTK/Test/ExternalContext.cs deleted file mode 100644 index 77a6fadb..00000000 --- a/Source/Examples/OpenTK/Test/ExternalContext.cs +++ /dev/null @@ -1,111 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Runtime.InteropServices; -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; - -namespace Examples.Tests -{ - [Example("External Context Test", ExampleCategory.OpenTK, "OpenGL")] - class ExternalContext - { - public static void Main() - { - using (Toolkit.Init(new ToolkitOptions { Backend = PlatformBackend.PreferNative })) - { - // Create a window and context using a third-party toolkit - // (in this case SDL2) - var window = SDL.CreateWindow("Test", 0, 0, 640, 480, - WindowFlags.AllowHighDpi | WindowFlags.OpenGL); - var context = SDL.GL.CreateContext(window); - - // The external context must be made current, - // in order to correctly initialize OpenTK.Graphics - SDL.GL.MakeCurrent(window, context); - - // Now we need to initialize OpenTK.Graphics using - // the external context. This can be achieved in - // two ways: - // - // var dummy = new GraphicsContext(ContextHandle.Zero, null); - // -- or -- - // var dummy = new GraphicsContext( - // new ContextHandle(context), - // (name) => SDL.GL.GetAddress(name), - // () => new ContextHandle(SDL.GL.GetCurrentContext())); - // - // The first approach works only on Windows, Mac and Linux/X11. - // - // The second approach will work on all platforms supported - // by the external toolkit. This means that you can use - // OpenTK.Graphics everywhere, even on platforms not directly - // supported by OpenTK. - - using (var dummy = new GraphicsContext( - new ContextHandle(context), - SDL.GL.GetAddress, - () => new ContextHandle(SDL.GL.GetCurrentContext()))) - { - for (int i = 0; i < 100; i++) - { - SDL.PumpEvents(); - GL.ClearColor(i / 100.0f, i / 100.0f, i / 100.0f, i / 100.0f); - GL.Clear(ClearBufferMask.ColorBufferBit); - - SDL.GL.SwapWindow(window); - } - - SDL.DestroyWindow(window); - } - } - } - } - - #region SDL2 bindings - - public enum WindowFlags - { - Default = 0, - OpenGL = 0x00000002, - AllowHighDpi = 0x00002000, - } - - static class SDL - { - const string lib = "SDL2.dll"; - - [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_CreateWindow", ExactSpelling = true)] - public static extern IntPtr CreateWindow(string title, int x, int y, int w, int h, WindowFlags flags); - - [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_DestroyWindow", ExactSpelling = true)] - public static extern void DestroyWindow(IntPtr window); - - [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_PumpEvents", ExactSpelling = true)] - public static extern void PumpEvents(); - - public static class GL - { - [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_GL_CreateContext", ExactSpelling = true)] - public static extern IntPtr CreateContext(IntPtr window); - - [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_GL_GetCurrentContext", ExactSpelling = true)] - public static extern IntPtr GetCurrentContext(); - - [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_GL_GetProcAddress", ExactSpelling = true)] - public static extern IntPtr GetAddress(string name); - - [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_GL_MakeCurrent", ExactSpelling = true)] - public static extern int MakeCurrent(IntPtr window, IntPtr context); - - [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_GL_SwapWindow", ExactSpelling = true)] - public static extern void SwapWindow(IntPtr window); - } - } - - #endregion - -} diff --git a/Source/Examples/OpenTK/Test/GameWindowStates.cs b/Source/Examples/OpenTK/Test/GameWindowStates.cs deleted file mode 100644 index 66057787..00000000 --- a/Source/Examples/OpenTK/Test/GameWindowStates.cs +++ /dev/null @@ -1,731 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Collections.Generic; -using System.Text; -using System.Diagnostics; -using System.Drawing; -using System.Threading; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; -using OpenTK.Input; - -#pragma warning disable 612,618 // disable obsolete warnings - we need to access these functions - -namespace Examples.Tests -{ - [Example("GameWindow States", ExampleCategory.OpenTK, "GameWindow", 4, Documentation = "GameWindowStates")] - public class GameWindowStates : GameWindow - { - static readonly Font TextFont = new Font(FontFamily.GenericSansSerif, 11); - Bitmap TextBitmap = new Bitmap(1024, 1024); - StringBuilder TypedText = new StringBuilder(); - int texture; - bool mouse_in_window = false; - bool viewport_changed = true; - - MouseCursor Pencil; - - // legacy GameWindow.Mouse.* events - Vector4 mousedevice_pos; - int mousedevice_buttons; - MouseState mousedevice_state; - - // new GameWindow.Mouse* events - Vector4 mouse_pos; - int mouse_buttons; - MouseState mouse_state; - - // legacy GameWindow.Keyboard.Key* events - Dictionary legacy_keyboard_keys = new Dictionary(); - KeyboardState legacy_keyboard_state; - KeyModifiers legacy_keyboard_modifiers; - - //new GameWindow.Key* events - Dictionary keyboard_keys = new Dictionary(); - KeyboardState keyboard_state; - KeyModifiers keyboard_modifiers; - - // time drift - Stopwatch watch = new Stopwatch(); - double update_time, render_time; - - // timing information - double timestamp; - int update_count; - int update_fps; - int render_count; - int render_fps; - - // position of moving objects on screen - double variable_update_timestep_pos = -1; - double variable_refresh_timestep_pos = -1; - double fixed_update_timestep_pos = -1; - - public GameWindowStates() - : base(800, 600, GraphicsMode.Default) - { - VSync = VSyncMode.On; - Keyboard.KeyRepeat = false; - KeyDown += KeyDownHandler; - KeyUp += KeyUpHandler; - KeyPress += KeyPressHandler; - Keyboard.KeyDown += KeyboardDeviceDownHandler; - Keyboard.KeyUp += KeyboardDeviceUpHandler; - - MouseEnter += delegate { mouse_in_window = true; }; - MouseLeave += delegate { mouse_in_window = false; }; - - Mouse.Move += MouseDeviceMoveHandler; - Mouse.WheelChanged += MouseDeviceWheelHandler; - Mouse.ButtonDown += MouseDeviceButtonHandler; - Mouse.ButtonUp += MouseDeviceButtonHandler; - - MouseMove += MouseMoveHandler; - MouseWheel += MouseWheelHandler; - MouseDown += MouseButtonHandler; - MouseUp += MouseButtonHandler; - } - - #region Keyboard Events - - void KeyPressHandler(object sender, KeyPressEventArgs e) - { - if (TypedText.Length > 32) - TypedText.Remove(0, 1); - - TypedText.Append(e.KeyChar); - } - - void KeyDownHandler(object sender, KeyboardKeyEventArgs e) - { - switch (e.Key) - { - case OpenTK.Input.Key.Escape: - if (!CursorVisible) - CursorVisible = true; - else - Exit(); - break; - - case Key.Number1: WindowState = WindowState.Normal; break; - case Key.Number2: WindowState = WindowState.Maximized; break; - case Key.Number3: WindowState = WindowState.Fullscreen; break; - case Key.Number4: WindowState = WindowState.Minimized; break; - - case Key.Number5: WindowBorder = WindowBorder.Resizable; break; - case Key.Number6: WindowBorder = WindowBorder.Fixed; break; - case Key.Number7: WindowBorder = WindowBorder.Hidden; break; - - case Key.Left: X = X - 16; break; - case Key.Right: X = X + 16; break; - case Key.Up: Y = Y - 16; break; - case Key.Down: Y = Y + 16; break; - - case Key.KeypadPlus: - case Key.Plus: Size += new Size(16, 16); break; - - case Key.KeypadMinus: - case Key.Minus: Size -= new Size(16, 16); break; - - case Key.V: - VSync = VSync == VSyncMode.On ? VSyncMode.Off : VSyncMode.On; - break; - - case Key.BracketLeft: TargetUpdateFrequency--; break; - case Key.BracketRight: TargetUpdateFrequency++; break; - case Key.Comma: TargetRenderFrequency--; break; - case Key.Period: TargetRenderFrequency++; break; - - case Key.Enter: - CursorVisible = !CursorVisible; - break; - - case Key.C: - if (Cursor == MouseCursor.Default) - Cursor = Pencil; - else if (Cursor == Pencil) - Cursor = MouseCursor.Empty; - else - Cursor = MouseCursor.Default; - break; - - case Key.Space: - Point p = new Point(Width / 2, Height / 2); - p = PointToScreen(p); - OpenTK.Input.Mouse.SetPosition(p.X, p.Y); - break; - - case Key.R: - Keyboard.KeyRepeat = !Keyboard.KeyRepeat; - break; - } - - if (!keyboard_keys.ContainsKey(e.Key)) - { - keyboard_keys.Add(e.Key, 0); - } - keyboard_keys[e.Key] = keyboard_keys[e.Key] + 1; - keyboard_modifiers = e.Modifiers; - keyboard_state = e.Keyboard; - } - - void KeyUpHandler(object sender, KeyboardKeyEventArgs e) - { - keyboard_keys.Remove(e.Key); - keyboard_modifiers = e.Modifiers; - keyboard_state = e.Keyboard; - } - - void KeyboardDeviceDownHandler(object sender, KeyboardKeyEventArgs e) - { - if (!legacy_keyboard_keys.ContainsKey(e.Key)) - { - legacy_keyboard_keys.Add(e.Key, 0); - } - legacy_keyboard_keys[e.Key] = legacy_keyboard_keys[e.Key] + 1; - legacy_keyboard_modifiers = e.Modifiers; - legacy_keyboard_state = e.Keyboard; - } - - void KeyboardDeviceUpHandler(object sender, KeyboardKeyEventArgs e) - { - legacy_keyboard_keys.Remove(e.Key); - legacy_keyboard_modifiers = e.Modifiers; - legacy_keyboard_state = e.Keyboard; - } - - #endregion - - #region MouseDevice events - - void MouseDeviceMoveHandler(object sender, MouseMoveEventArgs e) - { - mousedevice_pos.X = e.X; - mousedevice_pos.Y = e.Y; - mousedevice_pos.Z = e.Mouse.Scroll.X; - mousedevice_pos.W = e.Mouse.Scroll.Y; - mousedevice_state = e.Mouse; - } - - void MouseDeviceButtonHandler(object sender, MouseButtonEventArgs e) - { - if (e.IsPressed) - { - mousedevice_buttons |= 1 << (int)e.Button; - Cursor = Pencil; - } - else - { - mousedevice_buttons &= ~(1 << (int)e.Button); - Cursor = MouseCursor.Default; - } - mousedevice_state = e.Mouse; - } - - void MouseDeviceWheelHandler(object sender, MouseWheelEventArgs e) - { - mousedevice_pos.Z = e.Mouse.Scroll.X; - mousedevice_pos.W = e.Mouse.Scroll.Y; - mousedevice_state = e.Mouse; - } - - #endregion - - #region Mouse events - - void MouseMoveHandler(object sender, MouseMoveEventArgs e) - { - mouse_pos.X = e.X; - mouse_pos.Y = e.Y; - mouse_pos.Z = e.Mouse.Scroll.X; - mouse_pos.W = e.Mouse.Scroll.Y; - mouse_state = e.Mouse; - } - - void MouseButtonHandler(object sender, MouseButtonEventArgs e) - { - if (e.IsPressed) - { - mouse_buttons |= 1 << (int)e.Button; - } - else - { - mouse_buttons &= ~(1 << (int)e.Button); - } - mouse_state = e.Mouse; - } - - void MouseWheelHandler(object sender, MouseWheelEventArgs e) - { - mouse_pos.Z = e.Mouse.Scroll.X; - mouse_pos.W = e.Mouse.Scroll.Y; - mouse_state = e.Mouse; - } - - #endregion - - #region Private Members - - static int Clamp(int val, int min, int max) - { - return val > max ? max : val < min ? min : val; - } - - static float DrawString(Graphics gfx, string str, int line) - { - return DrawString(gfx, str, line, 0); - } - - static float DrawString(Graphics gfx, string str, int line, float offset) - { - gfx.DrawString(str, TextFont, Brushes.White, new PointF(offset, line * TextFont.Height)); - return offset + gfx.MeasureString(str, TextFont).Width; - } - - static void KeyboardStateToString(KeyboardState state, StringBuilder sb) - { - for (int key_index = 0; key_index < (int)Key.LastKey; key_index++) - { - Key k = (Key)key_index; - if (state[k]) - { - sb.Append(k); - sb.Append(" "); - } - } - } - - int DrawKeyboards(Graphics gfx, int line) - { - line++; - DrawString(gfx, "Keyboard:", line++); - for (int i = 0; i < 4; i++) - { - var state = OpenTK.Input.Keyboard.GetState(i); - if (state.IsConnected) - { - StringBuilder sb = new StringBuilder(); - sb.Append(i); - sb.Append(": "); - KeyboardStateToString(state, sb); - DrawString(gfx, sb.ToString(), line++); - } - } - return line; - } - - static int DrawMice(Graphics gfx, int line) - { - line++; - DrawString(gfx, String.Format("Cursor: {0}", OpenTK.Input.Mouse.GetCursorState()), line++); - DrawString(gfx, "Mouse:", line++); - for (int i = 0; i < 4; i++) - { - var state = OpenTK.Input.Mouse.GetState(i); - if (state.IsConnected) - { - DrawString(gfx, state.ToString(), line++); - } - } - return line; - } - - int DrawKeyboardDevice(Graphics gfx, int line) - { - StringBuilder sb = new StringBuilder(); - sb.Append("KeyboardDevice: "); - for (Key key = 0; key < Key.LastKey; key++) - { - if (Keyboard[key]) - { - sb.Append(key); - sb.Append(" "); - } - } - DrawString(gfx, sb.ToString(), line++); - - sb.Remove(0, sb.Length); - sb.Append("KeyboardDevice events: ["); - sb.Append(legacy_keyboard_modifiers); - sb.Append("] "); - foreach (var pair in legacy_keyboard_keys) - { - sb.Append(pair.Key); - sb.Append(":"); - sb.Append(pair.Value); - sb.Append(" "); - } - DrawString(gfx, sb.ToString(), line++); - - sb.Remove(0, sb.Length); - sb.Append("KeyboardDevice state: "); - KeyboardStateToString(legacy_keyboard_state, sb); - DrawString(gfx, sb.ToString(), line++); - - sb.Remove(0, sb.Length); - sb.Append("Keyboard events: ["); - sb.Append(keyboard_modifiers); - sb.Append("] "); - foreach (var pair in keyboard_keys) - { - sb.Append(pair.Key); - sb.Append(":"); - sb.Append(pair.Value); - sb.Append(" "); - } - DrawString(gfx, sb.ToString(), line++); - - sb.Remove(0, sb.Length); - sb.Append("Keyboard state: "); - KeyboardStateToString(keyboard_state, sb); - DrawString(gfx, sb.ToString(), line++); - - return line; - } - - int DrawMouseDevice(Graphics gfx, int line) - { - StringBuilder sb = new StringBuilder(); - sb.Append("MouseDevice: "); - sb.AppendFormat("[{0}, {1}, {2:0.00}] ", - Mouse.X, Mouse.Y, Mouse.WheelPrecise); - for (var i = MouseButton.Left; i < MouseButton.LastButton; i++) - { - if (Mouse[i]) - { - sb.Append(i); - sb.Append(" "); - } - } - sb.AppendLine(); - DrawString(gfx, sb.ToString(), line++); - - sb.Remove(0, sb.Length); - sb.Append("MouseDevice events: "); - sb.AppendFormat("[{0}, {1}, {2:0.00}, {3:0.00}] ", - mousedevice_pos.X, mousedevice_pos.Y, - mousedevice_pos.Z, mousedevice_pos.W); - for (var i = MouseButton.Left; i < MouseButton.LastButton; i++) - { - if ((mousedevice_buttons & (1 << (int)i)) != 0) - { - sb.Append(i); - sb.Append(" "); - } - } - sb.Append(" "); - sb.AppendLine(mousedevice_state.ToString()); - DrawString(gfx, sb.ToString(), line++); - - sb.Remove(0, sb.Length); - sb.Append("Mouse events: "); - sb.AppendFormat("[{0}, {1}, {2:0.00}, {3:0.00}] ", - mouse_pos.X, mouse_pos.Y, - mouse_pos.Z, mouse_pos.W); - for (var i = MouseButton.Left; i < MouseButton.LastButton; i++) - { - if ((mouse_buttons & (1 << (int)i)) != 0) - { - sb.Append(i); - sb.Append(" "); - } - } - sb.Append(" "); - sb.AppendLine(mouse_state.ToString()); - DrawString(gfx, sb.ToString(), line++); - return line; - } - - static int DrawLegacyJoysticks(Graphics gfx, IList joysticks, int line) - { - line++; - DrawString(gfx, "Legacy Joystick:", line++); - - int joy_index = -1; - foreach (var joy in joysticks) - { - joy_index++; - if (!String.IsNullOrEmpty(joy.Description)) - { - StringBuilder sb = new StringBuilder(); - sb.Append(joy_index); - sb.Append(": '"); - sb.Append(joy.Description); - sb.Append("' "); - - for (int i = 0; i < joy.Axis.Count; i++) - { - sb.Append(joy.Axis[i]); - sb.Append(" "); - } - - for (int i = 0; i < joy.Button.Count; i++) - { - sb.Append(joy.Button[i]); - sb.Append(" "); - } - DrawString(gfx, sb.ToString(), line++); - } - } - - return line; - } - - #endregion - - protected override void OnUpdateFrame(FrameEventArgs e) - { - double clock_time = watch.Elapsed.TotalSeconds; - update_time += e.Time; - timestamp += e.Time; - update_count++; - - using (Graphics gfx = Graphics.FromImage(TextBitmap)) - { - int line = 0; - - gfx.Clear(Color.Black); - gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; - - // OpenGL information - DrawString(gfx, GL.GetString(StringName.Renderer), line++); - DrawString(gfx, GL.GetString(StringName.Version), line++); - DrawString(gfx, Context.GraphicsMode.ToString(), line++); - - // GameWindow information - line++; - DrawString(gfx, "GameWindow:", line++); - DrawString(gfx, String.Format("[1 - 4]:[5 - 7]: WindowState.{0}:WindowBorder.{1}", - this.WindowState, this.WindowBorder), line++); - DrawString(gfx, String.Format("[V]: VSync.{0}.", VSync), line++); - DrawString(gfx, String.Format("Bounds: {0}", Bounds), line++); - DrawString(gfx, String.Format("ClientRectangle: {0}", ClientRectangle), line++); - DrawString(gfx, String.Format("Mouse {0} and {1}. {2}.", - mouse_in_window ? "inside" : "outside", - CursorVisible ? "visible" : "hidden", - Focused ? "Focused" : "Not focused"), line++); - - line = DrawKeyboardDevice(gfx, line); - line = DrawMouseDevice(gfx, line); - - // Timing information - line++; - DrawString(gfx, "Timing:", line++); - DrawString(gfx, - String.Format("Frequency: update {4} ({0:f2}/{1:f2}); render {5} ({2:f2}/{3:f2})", - UpdateFrequency, TargetUpdateFrequency, - RenderFrequency, TargetRenderFrequency, - update_fps, render_fps), - line++); - DrawString(gfx, - String.Format("Period: update {4:N4} ({0:f4}/{1:f4}); render {5:N4} ({2:f4}/{3:f4})", - UpdatePeriod, TargetUpdatePeriod, - RenderPeriod, TargetRenderPeriod, - 1.0 / update_fps, 1.0 / render_fps), - line++); - DrawString(gfx, String.Format("Time: update {0:f4}; render {1:f4}", - UpdateTime, RenderTime), line++); - DrawString(gfx, String.Format("Drift: clock {0:f4}; update {1:f4}; render {2:f4}", - clock_time, clock_time - update_time, clock_time - render_time), line++); - DrawString(gfx, String.Format("Text: {0}", TypedText.ToString()), line++); - - if (timestamp >= 1) - { - timestamp -= 1; - update_fps = update_count; - render_fps = render_count; - update_count = 0; - render_count = 0; - - } - - // Input information - line = DrawKeyboards(gfx, line); - line = DrawMice(gfx, line); - line = DrawJoysticks(gfx, line); - line = DrawLegacyJoysticks(gfx, Joysticks, line); - } - - fixed_update_timestep_pos += TargetUpdatePeriod; - variable_update_timestep_pos += e.Time; - if (fixed_update_timestep_pos >= 1) - fixed_update_timestep_pos -= 2; - if (variable_update_timestep_pos >= 1) - variable_update_timestep_pos -= 2; - } - - int DrawJoysticks(Graphics gfx, int line) - { - line++; - DrawString(gfx, "GamePad:", line++); - for (int i = 0; i < 4; i++) - { - GamePadCapabilities caps = GamePad.GetCapabilities(i); - GamePadState state = GamePad.GetState(i); - if (state.IsConnected) - { - DrawString(gfx, String.Format("{0}: {1}", i, caps), line++); - DrawString(gfx, state.ToString(), line++); - } - } - - line++; - DrawString(gfx, "Joystick:", line++); - for (int i = 0; i < 4; i++) - { - JoystickCapabilities caps = Joystick.GetCapabilities(i); - JoystickState state = Joystick.GetState(i); - if (state.IsConnected) - { - DrawString(gfx, String.Format("{0}: {1}", i, caps), line++); - DrawString(gfx, state.ToString(), line++); - } - } - - return line; - } - - protected override void OnLoad(EventArgs e) - { - watch.Start(); - - using (var bitmap = new Bitmap("Data/Textures/cursor.png")) - { - var data = bitmap.LockBits( - new Rectangle(0, 0, bitmap.Width, bitmap.Height), - System.Drawing.Imaging.ImageLockMode.ReadOnly, - System.Drawing.Imaging.PixelFormat.Format32bppPArgb); - - Pencil = new OpenTK.MouseCursor( - 2, 21, data.Width, data.Height, data.Scan0); - } - - GL.ClearColor(Color.MidnightBlue); - - GL.Enable(EnableCap.Texture2D); - GL.Enable(EnableCap.Blend); - GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.OneMinusSrcColor); - - texture = GL.GenTexture(); - GL.BindTexture(TextureTarget.Texture2D, texture); - GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, TextBitmap.Width, TextBitmap.Height, - 0, PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Nearest); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Nearest); - } - - protected override void OnResize(EventArgs e) - { - base.OnResize(e); - viewport_changed = true; - } - - protected override void OnRenderFrame(FrameEventArgs e) - { - render_time += e.Time; - render_count++; - - GL.Clear(ClearBufferMask.ColorBufferBit); - - if (viewport_changed) - { - viewport_changed = false; - GL.Viewport(0, 0, Width, Height); - } - - DrawText(); - - DrawMovingObjects(); - - variable_refresh_timestep_pos += e.Time; - if (variable_refresh_timestep_pos >= 1) - variable_refresh_timestep_pos -= 2; - - SwapBuffers(); - } - - // Uploads our text Bitmap to an OpenGL texture - // and displays is to screen. - private void DrawText() - { - System.Drawing.Imaging.BitmapData data = TextBitmap.LockBits( - new System.Drawing.Rectangle(0, 0, TextBitmap.Width, TextBitmap.Height), - System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); - GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, TextBitmap.Width, TextBitmap.Height, PixelFormat.Bgra, - PixelType.UnsignedByte, data.Scan0); - TextBitmap.UnlockBits(data); - - Matrix4 text_projection = Matrix4.CreateOrthographicOffCenter(0, Width, Height, 0, -1, 1); - GL.MatrixMode(MatrixMode.Projection); - GL.LoadMatrix(ref text_projection); - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadIdentity(); - - GL.Color4(Color4.White); - GL.Enable(EnableCap.Texture2D); - GL.Begin(PrimitiveType.Quads); - GL.TexCoord2(0, 0); GL.Vertex2(0, 0); - GL.TexCoord2(1, 0); GL.Vertex2(TextBitmap.Width, 0); - GL.TexCoord2(1, 1); GL.Vertex2(TextBitmap.Width, TextBitmap.Height); - GL.TexCoord2(0, 1); GL.Vertex2(0, TextBitmap.Height); - GL.End(); - GL.Disable(EnableCap.Texture2D); - } - - // Draws three moving objects, using three different timing methods: - // 1. fixed framerate based on TargetUpdatePeriod - // 2. variable framerate based on UpdateFrame e.Time - // 3. variable framerate based on RenderFrame e.Time - // If the timing implementation is correct, all three objects - // should be moving at the same speed, regardless of the current - // UpdatePeriod and RenderPeriod. - void DrawMovingObjects() - { - Matrix4 thing_projection = Matrix4.CreateOrthographic(2, 2, -1, 1); - GL.MatrixMode(MatrixMode.Projection); - GL.LoadMatrix(ref thing_projection); - - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadIdentity(); - GL.Translate(fixed_update_timestep_pos, -0.2, 0); - GL.Color4(Color4.Red); - DrawRectangle(); - - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadIdentity(); - GL.Translate(variable_update_timestep_pos, -0.4, 0); - GL.Color4(Color4.DarkGoldenrod); - DrawRectangle(); - - GL.MatrixMode(MatrixMode.Modelview); - GL.LoadIdentity(); - GL.Translate(variable_refresh_timestep_pos, -0.8, 0); - GL.Color4(Color4.DarkGreen); - DrawRectangle(); - } - - private void DrawRectangle() - { - GL.Begin(PrimitiveType.Quads); - GL.Vertex2(-0.05, -0.05); - GL.Vertex2(+0.05, -0.05); - GL.Vertex2(+0.05, +0.05); - GL.Vertex2(-0.05, +0.05); - GL.End(); - } - - public static void Main() - { - using (GameWindowStates ex = new GameWindowStates()) - { - Utilities.SetWindowTitle(ex); - ex.Run(30.0); - } - } - } -} diff --git a/Source/Examples/OpenTK/Test/GameWindowStates.rtf b/Source/Examples/OpenTK/Test/GameWindowStates.rtf deleted file mode 100644 index f4c9a1dd..00000000 Binary files a/Source/Examples/OpenTK/Test/GameWindowStates.rtf and /dev/null differ diff --git a/Source/Examples/OpenTK/Test/MathSerialization.cs b/Source/Examples/OpenTK/Test/MathSerialization.cs deleted file mode 100644 index 08994eda..00000000 --- a/Source/Examples/OpenTK/Test/MathSerialization.cs +++ /dev/null @@ -1,68 +0,0 @@ -#region --- License --- -/* Licensed under the MIT/X11 license. - * Copyright (c) 2006-2008 the OpenTK team. - * This notice may not be removed. - * See license.txt for licensing detailed licensing details. - */ -#endregion - -using System; -using System.Collections.Generic; -using System.Text; -using System.IO; -using System.Xml; - -#if false - -using System.Xml.Serialization; - - -namespace Examples.Tests -{ - [Example("Serialization", ExampleCategory.Test)] - public class MathSerialization - { - public static void Main() - { - using (MemoryStream stream = new MemoryStream()) - { - XmlSerializer xs = new XmlSerializer(typeof(Matrix4)); - - { - XmlWriterSettings settings = new XmlWriterSettings(); - settings.NewLineHandling = NewLineHandling.Entitize; - settings.Indent = true; - XmlWriter xw = XmlTextWriter.Create(stream, settings); - - xs.Serialize(xw, Matrix4.Identity); - - xw.Close(); - } - - stream.Position = 0; - byte[] text = new byte[stream.Length]; - int pos = 0; - do - { - pos += stream.Read(text, pos, (int)stream.Length); - } - while (pos != stream.Length); - - Console.WriteLine(System.Text.Encoding.Default.GetChars(text)); - - stream.Position = 0; - Matrix4 matrix = (Matrix4)xs.Deserialize(stream); - - if (Matrix4.Identity == matrix) - Console.WriteLine("Matrix deserialized correctly."); - else - Console.WriteLine("Error deserializing matrix."); - - Console.WriteLine("Press any key to continue..."); - Console.ReadKey(false); - } - } - } -} - -#endif \ No newline at end of file diff --git a/Source/Examples/OpenTK/Test/MathSpeed.cs b/Source/Examples/OpenTK/Test/MathSpeed.cs deleted file mode 100644 index 0da9c2d1..00000000 --- a/Source/Examples/OpenTK/Test/MathSpeed.cs +++ /dev/null @@ -1,91 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Collections.Generic; -using System.Text; -using System.Diagnostics; - -namespace Examples.Tests -{ - [Example("Math speed test", ExampleCategory.OpenTK, "Test", Visible = false)] - public class MathSpeed - { - public static void Main() - { - /* - Stopwatch watch = new Stopwatch(); - - Vector3 a = new Vector3(0.0f, 0.0f, 0.0f); - Vector3 b = new Vector3(1.0f, 1.0f, 1.0f); - Vector3 c = new Vector3(3.0f, 3.0f, 3.0f); - Vector3 d = new Vector3(4.0f, 4.0f, 4.0f); - Vector3 e = Vector3.Zero; - Vector3 res; - - // Force the JIT to compile the functions. - Vector3.Add(a, b); - Vector3.Add(ref a, ref b, out res); - res = a + b; - res = Vector3.Zero; - - watch.Reset(); - watch.Start(); - for (int i = 100000000; --i != 0; ) - ; - watch.Stop(); - Trace.WriteLine(String.format("Noop\t\t\t\t\t\t{0}ns", (watch.Elapsed.TotalSeconds / 10.0).ToString())); - - watch.Reset(); - watch.Start(); - for (int i = 100000000; --i != 0; ) - res = Vector3.Add(res, a); - watch.Stop(); - res += res; // To make sure the whole for-loop isn't optimized-out - Trace.WriteLine(String.format("res = Vector3.Add(a, b)\t\t\t{0}ns", (watch.Elapsed.TotalSeconds / 10.0).ToString())); - res = Vector3.Zero; - - watch.Reset(); - watch.Start(); - for (int i = 100000000; --i != 0; ) - res = res + a; - watch.Stop(); - res += res; // To make sure the whole for-loop isn't optimized-out - Trace.WriteLine(String.format("res = a + b\t\t\t\t\t{0}ns", (watch.Elapsed.TotalSeconds / 10.0).ToString())); - - watch.Reset(); - watch.Start(); - for (int i = 100000000; --i != 0; ) - Vector3.Add(ref res, ref a, out res); - watch.Stop(); - res += res; // To make sure the whole for-loop isn't optimized-out - Trace.WriteLine(String.format("Vector3.Add(ref a, ref b, out res)\t{0}ns", (watch.Elapsed.TotalSeconds / 10.0).ToString())); -*/ - /* - a = Vector3.UnitX; - b = Vector3.UnitY; - res = Vector3.Add(ref a, ref b); - Trace.WriteLine(res.ToString()); - - a = Vector3.UnitX; - b = Vector3.UnitY; - Vector3.Add(a, b, out res); - Trace.WriteLine(res.ToString()); - - Vector2Im q = new Vector2(0.0f, 1.0f); - Vector2Im p = new Vector2(2.0f, 3.0f); - Vector2Im s = Vector2.Add(p, q); - p = s + q; - */ - } - - //static Vector3 pos = new Vector3(); - - //static Vector3 Pos - //{ - // get { return pos; } - // set { pos = value; } - //} - } -} diff --git a/Source/Examples/OpenTK/Test/MatrixTest.cs b/Source/Examples/OpenTK/Test/MatrixTest.cs deleted file mode 100644 index e19646b6..00000000 --- a/Source/Examples/OpenTK/Test/MatrixTest.cs +++ /dev/null @@ -1,32 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Collections.Generic; -using System.Text; -using System.Diagnostics; -using OpenTK; - -namespace Examples.Tests -{ - [Example("Matrix math test", ExampleCategory.OpenTK, "Test", Visible = false)] - public class MatrixTest - { - public static void Main() - { - float x = 1.0f; - float y = 1.0f; - float z = 1.0f; - - Matrix4 translation = new Matrix4(new Vector4(1, 0, 0, 2), new Vector4(0, 1, 0, 3), new Vector4(0, 0, 1, -1), new Vector4(0, 0, 0, 1)); - Vector4 point = new Vector4(x, y, z, 1); - - Vector4 result = Vector4.Transform(point, translation); - - Trace.WriteLine("Result should be: (3, 4, 0, 1) : " + result); - - } - } -} - diff --git a/Source/Examples/OpenTK/Test/Multithreading.cs b/Source/Examples/OpenTK/Test/Multithreading.cs deleted file mode 100644 index 7e8383be..00000000 --- a/Source/Examples/OpenTK/Test/Multithreading.cs +++ /dev/null @@ -1,56 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; - -namespace Examples.Tests -{ - [Example("Multithreading Test", ExampleCategory.OpenTK, "Test")] - class Multithreading - { - public static void Main() - { - const int ThreadCount = 2; - List threads = new List(); - - // launch threads - for (int i = 0; i < ThreadCount; i++) - { - Thread t = new Thread(RunGame); - t.IsBackground = true; - t.Priority = ThreadPriority.BelowNormal; - t.Start(); - threads.Add(t); - } - - // wait for exit - foreach (Thread t in threads) - { - t.Join(); - } - } - - static void RunGame() - { - using (Tutorial.T03_Immediate_Mode_Cube game = new Examples.Tutorial.T03_Immediate_Mode_Cube()) - { - Utilities.SetWindowTitle(game); - game.KeyUp += delegate(object sender, OpenTK.Input.KeyboardKeyEventArgs e) - { - if (e.Key == OpenTK.Input.Key.F11) - { - if (game.WindowState == OpenTK.WindowState.Fullscreen) - game.WindowState = OpenTK.WindowState.Normal; - else - game.WindowState = OpenTK.WindowState.Fullscreen; - } - }; - game.Run(30.0); - } - } - } -} diff --git a/Source/Examples/OpenTK/Test/PointToClient.cs b/Source/Examples/OpenTK/Test/PointToClient.cs deleted file mode 100644 index 78e281b6..00000000 --- a/Source/Examples/OpenTK/Test/PointToClient.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; -using System.Diagnostics; -using System.Drawing; -using OpenTK; - -namespace Examples.Tests -{ - [Example("PointToClient Test", ExampleCategory.OpenTK, "NativeWindow")] - public class PointToClientTest - { - public static void Main() - { - using (var window = new NativeWindow()) - { - Trace.WriteLine(String.Format("Window bounds: {0}", window.Bounds)); - Trace.WriteLine(String.Format("Window client: {0}", window.ClientRectangle)); - - Point pclient = new Point(100, 100); - Point pscreen = window.PointToScreen(pclient); - Point ptest = window.PointToClient(pscreen); - Trace.WriteLine(String.Format("Client: {0} -> Screen: {1} -> Client: {2}", - pclient, pscreen, ptest)); - Trace.WriteLine(String.Format("Test {0}", - ptest == pclient ? "succeeded" : "failed")); - - pscreen = new Point(100, 100); - pclient = window.PointToClient(pscreen); - ptest = window.PointToScreen(pclient); - Trace.WriteLine(String.Format("Screen: {0} -> Client: {1} -> Screen: {2}", - pscreen, pclient, ptest)); - Trace.WriteLine(String.Format("Test {0}", - ptest == pscreen ? "succeeded" : "failed")); - } - } - } -} - diff --git a/Source/Examples/OpenTK/Test/TestGraphicsModes.cs b/Source/Examples/OpenTK/Test/TestGraphicsModes.cs deleted file mode 100644 index 4af88c45..00000000 --- a/Source/Examples/OpenTK/Test/TestGraphicsModes.cs +++ /dev/null @@ -1,49 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Collections.Generic; -using System.Text; -using System.Diagnostics; -using OpenTK.Graphics; -using OpenTK; -using System.Windows.Forms; - -namespace Examples.Tests -{ - [Example("Test GraphicsModes", ExampleCategory.OpenTK, "Test", Documentation = "TestGraphicsModes")] - public class TestGraphicsModes - { - static void Main() - { - Dictionary modes = new Dictionary(); - Trace.WriteLine("Cl (RGBA): Color format (total bits and bits per channel)."); - Trace.WriteLine("Dp : Depth buffer bits."); - Trace.WriteLine("St : Stencil buffer bits."); - Trace.WriteLine("AA : Sample count for anti-aliasing."); - Trace.WriteLine("Stereo : Stereoscoping rendering supported."); - Trace.WriteLine(""); - Trace.WriteLine("Cl (RGBA), Dp, St, AA, Stereo"); - Trace.WriteLine("-----------------------------"); - foreach (ColorFormat color in new ColorFormat[] { 32, 24, 16, 8 }) - foreach (int depth in new int[] { 24, 16 }) - foreach (int stencil in new int[] { 8, 0 }) - foreach (int samples in new int[] { 0, 2, 4, 6, 8, 16 }) - foreach (bool stereo in new bool[] { false, true }) - { - try - { - GraphicsMode mode = new GraphicsMode(color, depth, stencil, samples, 0, 2, stereo); - if (!modes.ContainsKey(mode)) - modes.Add(mode, mode); - } - catch - { } - } - - foreach (GraphicsMode mode in modes.Keys) - Trace.WriteLine(String.Format("{0}, {1:00}, {2:00}, {3:00}, {4}", mode.ColorFormat, mode.Depth, mode.Stencil, mode.Samples, mode.Stereo)); - } - } -} diff --git a/Source/Examples/OpenTK/Test/TestResolutionChanges.cs b/Source/Examples/OpenTK/Test/TestResolutionChanges.cs deleted file mode 100644 index 740f60f4..00000000 --- a/Source/Examples/OpenTK/Test/TestResolutionChanges.cs +++ /dev/null @@ -1,57 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows.Forms; -using System.Diagnostics; -using System.Threading; - -using OpenTK; - -namespace Examples.Tests -{ - [Example("Test Resolution Changes", ExampleCategory.OpenTK, "Test", Documentation="TestResolutionChanges")] - public class TestResolutionChanges - { - public static void Main() - { - for (int i = 0; i < 6; i++) - { - DisplayDevice dev = DisplayDevice.GetDisplay(DisplayIndex.First + i); - if (dev != null) - { - Print(dev.ToString()); - - dev.ChangeResolution(dev.SelectResolution(640, 480, 32, 60.0f)); - Thread.Sleep(1000); - Print(dev.ToString()); - - dev.RestoreResolution(); - Thread.Sleep(1000); - Print(dev.ToString()); - } - } - } - - static void Print(string msg) - { - Trace.WriteLine(msg); - - // Also display a MessageBox when running on a platform - // with WinForms support. - try - { - if (Configuration.RunningOnWindows || Configuration.RunningOnX11 || Configuration.RunningOnMacOS) - { - MessageBox.Show(msg); - } - } - catch - { - } - } - } -} diff --git a/Source/Examples/OpenTK/Test/TestShaderUtf8Support.cs b/Source/Examples/OpenTK/Test/TestShaderUtf8Support.cs deleted file mode 100644 index f61a3b2b..00000000 --- a/Source/Examples/OpenTK/Test/TestShaderUtf8Support.cs +++ /dev/null @@ -1,238 +0,0 @@ -// This code was written for the OpenTK library and has been released -// to the Public Domain. -// It is provided "as is" without express or implied warranty of any kind. - -using System; -using System.Diagnostics; -using System.IO; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; - -namespace Examples.Tutorial -{ - [Example("Shader UTF8 support", ExampleCategory.OpenTK, "OpenGL")] - public class TestShaderUtf8Support : GameWindow - { - string vertexShaderSource = @" -#version 130 - -precision highp float;//日本語文字 Japanese Characters - -uniform mat4 projection_matrix; -uniform mat4 modelview_matrix; - -in vec3 in_position; -in vec3 in_normal; - -out vec3 normal; - -void main(void) -{ - //works only for orthogonal modelview - normal = (modelview_matrix * vec4(in_normal, 0)).xyz; - - gl_Position = projection_matrix * modelview_matrix * vec4(in_position, 1); -}"; - - string fragmentShaderSource = @" -#version 130 - -precision highp float; - -const vec3 ambient = vec3(0.1, 0.1, 0.1); -const vec3 lightVecNormalized = normalize(vec3(0.5, 0.5, 2.0)); -const vec3 lightColor = vec3(0.9, 0.9, 0.7); - -in vec3 normal; - -out vec4 out_frag_color; - -void main(void) -{ - float diffuse = clamp(dot(lightVecNormalized, normalize(normal)), 0.0, 1.0); - out_frag_color = vec4(ambient + diffuse * lightColor, 1.0); -}"; - - int vertexShaderHandle, - fragmentShaderHandle, - shaderProgramHandle, - modelviewMatrixLocation, - projectionMatrixLocation, - vaoHandle, - positionVboHandle, - normalVboHandle, - eboHandle; - - Vector3[] positionVboData = new Vector3[]{ - new Vector3(-1.0f, -1.0f, 1.0f), - new Vector3( 1.0f, -1.0f, 1.0f), - new Vector3( 1.0f, 1.0f, 1.0f), - new Vector3(-1.0f, 1.0f, 1.0f), - new Vector3(-1.0f, -1.0f, -1.0f), - new Vector3( 1.0f, -1.0f, -1.0f), - new Vector3( 1.0f, 1.0f, -1.0f), - new Vector3(-1.0f, 1.0f, -1.0f) }; - - int[] indicesVboData = new int[]{ - // front face - 0, 1, 2, 2, 3, 0, - // top face - 3, 2, 6, 6, 7, 3, - // back face - 7, 6, 5, 5, 4, 7, - // left face - 4, 0, 3, 3, 7, 4, - // bottom face - 0, 1, 5, 5, 4, 0, - // right face - 1, 5, 6, 6, 2, 1, }; - - Matrix4 projectionMatrix, modelviewMatrix; - - public TestShaderUtf8Support() - : base(640, 480, - new GraphicsMode(), "OpenGL 3 Example", 0, - DisplayDevice.Default, 3, 0, - GraphicsContextFlags.ForwardCompatible | GraphicsContextFlags.Debug) - { } - - protected override void OnLoad (System.EventArgs e) - { - VSync = VSyncMode.On; - - CreateShaders(); - CreateVBOs(); - CreateVAOs(); - - // Other state - GL.Enable(EnableCap.DepthTest); - GL.ClearColor(System.Drawing.Color.MidnightBlue); - } - - void CreateShaders() - { - vertexShaderHandle = GL.CreateShader(ShaderType.VertexShader); - fragmentShaderHandle = GL.CreateShader(ShaderType.FragmentShader); - - GL.ShaderSource(vertexShaderHandle, vertexShaderSource); - GL.ShaderSource(fragmentShaderHandle, fragmentShaderSource); - - GL.CompileShader(vertexShaderHandle); - string log = GL.GetShaderInfoLog(vertexShaderHandle); - if (log.Length != 0) { - Debug.Print(log); - } - GL.CompileShader(fragmentShaderHandle); - - Debug.WriteLine(GL.GetShaderInfoLog(vertexShaderHandle)); - Debug.WriteLine(GL.GetShaderInfoLog(fragmentShaderHandle)); - - // Create program - shaderProgramHandle = GL.CreateProgram(); - - GL.AttachShader(shaderProgramHandle, vertexShaderHandle); - GL.AttachShader(shaderProgramHandle, fragmentShaderHandle); - - GL.LinkProgram(shaderProgramHandle); - - Debug.WriteLine(GL.GetProgramInfoLog(shaderProgramHandle)); - - GL.UseProgram(shaderProgramHandle); - - // Set uniforms - projectionMatrixLocation = GL.GetUniformLocation(shaderProgramHandle, "projection_matrix"); - modelviewMatrixLocation = GL.GetUniformLocation(shaderProgramHandle, "modelview_matrix"); - - float aspectRatio = ClientSize.Width / (float)(ClientSize.Height); - Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, aspectRatio, 1, 100, out projectionMatrix); - modelviewMatrix = Matrix4.LookAt(new Vector3(0, 3, 5), new Vector3(0, 0, 0), new Vector3(0, 1, 0)); - - GL.UniformMatrix4(projectionMatrixLocation, false, ref projectionMatrix); - GL.UniformMatrix4(modelviewMatrixLocation, false, ref modelviewMatrix); - } - - void CreateVBOs() - { - GL.GenBuffers(1, out positionVboHandle); - GL.BindBuffer(BufferTarget.ArrayBuffer, positionVboHandle); - GL.BufferData(BufferTarget.ArrayBuffer, - new IntPtr(positionVboData.Length * Vector3.SizeInBytes), - positionVboData, BufferUsageHint.StaticDraw); - - GL.GenBuffers(1, out normalVboHandle); - GL.BindBuffer(BufferTarget.ArrayBuffer, normalVboHandle); - GL.BufferData(BufferTarget.ArrayBuffer, - new IntPtr(positionVboData.Length * Vector3.SizeInBytes), - positionVboData, BufferUsageHint.StaticDraw); - - GL.GenBuffers(1, out eboHandle); - GL.BindBuffer(BufferTarget.ElementArrayBuffer, eboHandle); - GL.BufferData(BufferTarget.ElementArrayBuffer, - new IntPtr(sizeof(uint) * indicesVboData.Length), - indicesVboData, BufferUsageHint.StaticDraw); - - GL.BindBuffer(BufferTarget.ArrayBuffer, 0); - GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); - } - - void CreateVAOs() - { - // GL3 allows us to store the vertex layout in a "vertex array object" (VAO). - // This means we do not have to re-issue VertexAttribPointer calls - // every time we try to use a different vertex layout - these calls are - // stored in the VAO so we simply need to bind the correct VAO. - GL.GenVertexArrays(1, out vaoHandle); - GL.BindVertexArray(vaoHandle); - - GL.EnableVertexAttribArray(0); - GL.BindBuffer(BufferTarget.ArrayBuffer, positionVboHandle); - GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, true, Vector3.SizeInBytes, 0); - GL.BindAttribLocation(shaderProgramHandle, 0, "in_position"); - - GL.EnableVertexAttribArray(1); - GL.BindBuffer(BufferTarget.ArrayBuffer, normalVboHandle); - GL.VertexAttribPointer(1, 3, VertexAttribPointerType.Float, true, Vector3.SizeInBytes, 0); - GL.BindAttribLocation(shaderProgramHandle, 1, "in_normal"); - - GL.BindBuffer(BufferTarget.ElementArrayBuffer, eboHandle); - - GL.BindVertexArray(0); - } - - protected override void OnUpdateFrame(FrameEventArgs e) - { - Matrix4 rotation = Matrix4.CreateRotationY((float)e.Time); - Matrix4.Mult(ref rotation, ref modelviewMatrix, out modelviewMatrix); - GL.UniformMatrix4(modelviewMatrixLocation, false, ref modelviewMatrix); - - var keyboard = OpenTK.Input.Keyboard.GetState(); - if (keyboard[OpenTK.Input.Key.Escape]) - Exit(); - } - - protected override void OnRenderFrame(FrameEventArgs e) - { - GL.Viewport(0, 0, Width, Height); - - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - - GL.BindVertexArray(vaoHandle); - GL.DrawElements(PrimitiveType.Triangles, indicesVboData.Length, - DrawElementsType.UnsignedInt, IntPtr.Zero); - - SwapBuffers(); - } - - [STAThread] - public static void Main() - { - using (TestShaderUtf8Support example = new TestShaderUtf8Support()) - { - Utilities.SetWindowTitle(example); - example.Run(30); - } - } - } -} \ No newline at end of file diff --git a/Source/Examples/Properties/AssemblyInfo.cs b/Source/Examples/Properties/AssemblyInfo.cs deleted file mode 100644 index f39180d4..00000000 --- a/Source/Examples/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("OpenTK.Examples")] -[assembly: AssemblyDescription("Examples showcasing OpenTK and OpenGL")] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("f236c767-678f-4c20-9282-d051a3c39657")] diff --git a/Source/Examples/Properties/Resources.Designer.cs b/Source/Examples/Properties/Resources.Designer.cs deleted file mode 100644 index d99e79ae..00000000 --- a/Source/Examples/Properties/Resources.Designer.cs +++ /dev/null @@ -1,173 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.18051 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace OpenTK.Examples.Properties { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("OpenTK.Examples.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). - /// - internal static System.Drawing.Icon App { - get { - object obj = ResourceManager.GetObject("App", resourceCulture); - return ((System.Drawing.Icon)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). - /// - internal static System.Drawing.Icon Game { - get { - object obj = ResourceManager.GetObject("Game", resourceCulture); - return ((System.Drawing.Icon)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap OpenAL { - get { - object obj = ResourceManager.GetObject("OpenAL", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap OpenCL { - get { - object obj = ResourceManager.GetObject("OpenCL", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap OpenGL { - get { - object obj = ResourceManager.GetObject("OpenGL", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap OpenGLES { - get { - object obj = ResourceManager.GetObject("OpenGLES", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap OpenTK { - get { - object obj = ResourceManager.GetObject("OpenTK", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap v1x { - get { - object obj = ResourceManager.GetObject("v1x", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap v2x { - get { - object obj = ResourceManager.GetObject("v2x", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap v3x { - get { - object obj = ResourceManager.GetObject("v3x", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap v4x { - get { - object obj = ResourceManager.GetObject("v4x", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - } -} diff --git a/Source/Examples/Properties/Resources.resx b/Source/Examples/Properties/Resources.resx deleted file mode 100644 index 9aa53f94..00000000 --- a/Source/Examples/Properties/Resources.resx +++ /dev/null @@ -1,154 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - - ../Resources/App.ico;System.Drawing.Icon, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\Game.ico;System.Drawing.Icon, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\OpenAL.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\OpenCL.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\OpenGL.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\OpenGLES.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\OpenTK.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\v1x.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\v2x.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\v3x.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\v4x.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - \ No newline at end of file diff --git a/Source/Examples/Resources/App.ico b/Source/Examples/Resources/App.ico deleted file mode 100644 index 8d05ba69..00000000 Binary files a/Source/Examples/Resources/App.ico and /dev/null differ diff --git a/Source/Examples/Resources/Game.ico b/Source/Examples/Resources/Game.ico deleted file mode 100644 index d3605919..00000000 Binary files a/Source/Examples/Resources/Game.ico and /dev/null differ diff --git a/Source/Examples/Resources/OpenAL.png b/Source/Examples/Resources/OpenAL.png deleted file mode 100644 index 0d71bb5d..00000000 Binary files a/Source/Examples/Resources/OpenAL.png and /dev/null differ diff --git a/Source/Examples/Resources/OpenCL.png b/Source/Examples/Resources/OpenCL.png deleted file mode 100644 index 3cebd915..00000000 Binary files a/Source/Examples/Resources/OpenCL.png and /dev/null differ diff --git a/Source/Examples/Resources/OpenGL.png b/Source/Examples/Resources/OpenGL.png deleted file mode 100644 index ddb9126b..00000000 Binary files a/Source/Examples/Resources/OpenGL.png and /dev/null differ diff --git a/Source/Examples/Resources/OpenGLES.png b/Source/Examples/Resources/OpenGLES.png deleted file mode 100644 index 83772bdd..00000000 Binary files a/Source/Examples/Resources/OpenGLES.png and /dev/null differ diff --git a/Source/Examples/Resources/OpenTK.png b/Source/Examples/Resources/OpenTK.png deleted file mode 100644 index 4b8903aa..00000000 Binary files a/Source/Examples/Resources/OpenTK.png and /dev/null differ diff --git a/Source/Examples/Resources/v1x.png b/Source/Examples/Resources/v1x.png deleted file mode 100644 index 9d049df5..00000000 Binary files a/Source/Examples/Resources/v1x.png and /dev/null differ diff --git a/Source/Examples/Resources/v2x.png b/Source/Examples/Resources/v2x.png deleted file mode 100644 index f95d08ad..00000000 Binary files a/Source/Examples/Resources/v2x.png and /dev/null differ diff --git a/Source/Examples/Resources/v3x.png b/Source/Examples/Resources/v3x.png deleted file mode 100644 index 0972589a..00000000 Binary files a/Source/Examples/Resources/v3x.png and /dev/null differ diff --git a/Source/Examples/Resources/v4x.png b/Source/Examples/Resources/v4x.png deleted file mode 100644 index 692170c0..00000000 Binary files a/Source/Examples/Resources/v4x.png and /dev/null differ diff --git a/Source/Examples/SamplesTreeViewSorter.cs b/Source/Examples/SamplesTreeViewSorter.cs deleted file mode 100644 index 0ac1ba0a..00000000 --- a/Source/Examples/SamplesTreeViewSorter.cs +++ /dev/null @@ -1,76 +0,0 @@ -#region License -// -// The Open Toolkit Library License -// -// Copyright (c) 2006 - 2009 the Open Toolkit library. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -// the Software, and to permit persons to whom the Software is furnished to do -// so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// -#endregion - -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows.Forms; -using System.Collections; - -namespace Examples -{ - class SamplesTreeViewSorter : IComparer, IComparer - { - #region IComparer Members - - public int Compare(TreeNode x, TreeNode y) - { - ExampleInfo x_info = x.Tag as ExampleInfo; - ExampleInfo y_info = y.Tag as ExampleInfo; - if (x_info == null || y_info == null) - { - return x.Text.CompareTo(y.Text); - } - else - { - int result = x_info.Attribute.Category.CompareTo(y_info.Attribute.Category); - if (result == 0) - result = x_info.Attribute.Subcategory.CompareTo(y_info.Attribute.Subcategory); - if (result == 0) - result = x_info.Attribute.Difficulty.CompareTo(y_info.Attribute.Difficulty); - if (result == 0) - result = x_info.Attribute.Title.CompareTo(y_info.Attribute.Title); - - return result; - } - } - - #endregion - - #region IComparer Members - - public int Compare(object x, object y) - { - if (x is TreeNode && y is TreeNode) - return Compare(x as TreeNode, y as TreeNode); - else - return 0; - } - - #endregion - } -} diff --git a/Source/Examples/Shapes/Base/DrawableShape.cs b/Source/Examples/Shapes/Base/DrawableShape.cs deleted file mode 100644 index 2c786d15..00000000 --- a/Source/Examples/Shapes/Base/DrawableShape.cs +++ /dev/null @@ -1,181 +0,0 @@ -#region --- License --- -/* Copyright (c) 2006, 2007 Stefanos Apostolopoulos - * See license.txt for license info - */ -#endregion - -using System; - -using OpenTK; -using OpenTK.Graphics.OpenGL; - -namespace Examples.Shapes -{ - // Abstract base class for procedurally generated geometry - // - // All classes derived from it must produce Counter-Clockwise (CCW) primitives. - // Derived classes must create a single VBO and IBO, without primitive restarts for strips. - // Uses an double-precision all-possible-attributes VertexT2dN3dV3d Array internally. - // Cannot directly use VBO, but has Get-methods to retrieve VBO-friendly data. - // Can use a Display List to prevent repeated immediate mode draws. - // - - public abstract class DrawableShape: IDisposable - { - protected PrimitiveType PrimitiveMode; - protected VertexT2dN3dV3d[] VertexArray; - protected uint[] IndexArray; - - public int GetTriangleCount - { - get - { - switch ( PrimitiveMode ) - { - case PrimitiveType.Triangles: - if ( IndexArray != null ) - { - return IndexArray.Length / 3; - } else - { - return VertexArray.Length / 3; - } - // break; - default: throw new NotImplementedException("Unknown primitive type."); - } - } - } - - #region Display List - - private bool UseDisplayList; - private int DisplayListHandle = 0; - - #endregion Display List - - public DrawableShape( bool useDisplayList ) - { - UseDisplayList = useDisplayList; - PrimitiveMode = PrimitiveType.Triangles; - VertexArray = null; - IndexArray = null; - } - - #region Convert to VBO - - public void GetArraysforVBO(out PrimitiveType primitives, out VertexT2dN3dV3d[] vertices, out uint[] indices) - { - primitives = PrimitiveMode; - - vertices = new VertexT2dN3dV3d[VertexArray.Length]; - for (uint i = 0; i < VertexArray.Length; i++) - { - vertices[i].TexCoord = VertexArray[i].TexCoord; - vertices[i].Normal = VertexArray[i].Normal; - vertices[i].Position = VertexArray[i].Position; - } - - indices = IndexArray; - } - - public void GetArraysforVBO(out PrimitiveType primitives, out VertexT2fN3fV3f[] vertices, out uint[] indices) - { - primitives = PrimitiveMode; - - vertices = new VertexT2fN3fV3f[VertexArray.Length]; - for (uint i = 0; i < VertexArray.Length; i++) - { - vertices[i].TexCoord = (Vector2)VertexArray[i].TexCoord; - vertices[i].Normal = (Vector3)VertexArray[i].Normal; - vertices[i].Position = (Vector3)VertexArray[i].Position; - } - - indices = IndexArray; - } - - public void GetArraysforVBO(out PrimitiveType primitives, out VertexT2hN3hV3h[] vertices, out uint[] indices) - { - primitives = PrimitiveMode; - - vertices = new VertexT2hN3hV3h[VertexArray.Length]; - for (uint i = 0; i < VertexArray.Length; i++) - { - vertices[i].TexCoord = (Vector2h)VertexArray[i].TexCoord; - vertices[i].Normal = (Vector3h)VertexArray[i].Normal; - vertices[i].Position = (Vector3h)VertexArray[i].Position; - } - - indices = IndexArray; - } - - #endregion Convert to VBO - - private void DrawImmediateMode() - { - GL.Begin( PrimitiveMode ); - { - if ( IndexArray == null ) - foreach ( VertexT2dN3dV3d v in VertexArray ) - { - GL.TexCoord2( v.TexCoord.X, v.TexCoord.Y ); - GL.Normal3( v.Normal.X, v.Normal.Y, v.Normal.Z ); - GL.Vertex3( v.Position.X, v.Position.Y, v.Position.Z ); - } else - { - for ( uint i = 0; i < IndexArray.Length; i++ ) - { - uint index = IndexArray[i]; - GL.TexCoord2( VertexArray[index].TexCoord.X, VertexArray[index].TexCoord.Y ); - GL.Normal3( VertexArray[index].Normal.X, VertexArray[index].Normal.Y, VertexArray[index].Normal.Z ); - GL.Vertex3( VertexArray[index].Position.X, VertexArray[index].Position.Y, VertexArray[index].Position.Z ); - } - } - } - GL.End(); - } - - /// - /// Does not touch any state/matrices. Does call Begin/End and Vertex&Co. - /// Creates and compiles a display list if not present yet. Requires an OpenGL context. - /// - public void Draw() - { - if ( !UseDisplayList ) - DrawImmediateMode(); - else - if ( DisplayListHandle == 0 ) - { - if ( VertexArray == null ) - throw new Exception("Cannot draw null Vertex Array."); - DisplayListHandle = GL.GenLists( 1 ); - GL.NewList( DisplayListHandle, ListMode.CompileAndExecute ); - DrawImmediateMode(); - GL.EndList(); - } else - GL.CallList( DisplayListHandle ); - } - - #region IDisposable Members - - /// - /// Removes reference to VertexArray and IndexArray. - /// Deletes the Display List, so it requires an OpenGL context. - /// The instance is effectively destroyed. - /// - public void Dispose() - { - if ( VertexArray != null ) - VertexArray = null; - if ( IndexArray != null ) - IndexArray = null; - if ( DisplayListHandle != 0 ) - { - GL.DeleteLists( DisplayListHandle, 1 ); - DisplayListHandle = 0; - } - } - - #endregion - } - -} diff --git a/Source/Examples/Shapes/Base/VertexStructs.cs b/Source/Examples/Shapes/Base/VertexStructs.cs deleted file mode 100644 index 8a3d350b..00000000 --- a/Source/Examples/Shapes/Base/VertexStructs.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; - -using OpenTK; - -namespace Examples.Shapes -{ - public struct VertexT2dN3dV3d - { - public Vector2d TexCoord; - public Vector3d Normal; - public Vector3d Position; - - public VertexT2dN3dV3d( Vector2d texcoord, Vector3d normal, Vector3d position ) - { - TexCoord = texcoord; - Normal = normal; - Position = position; - } - } - - public struct VertexT2fN3fV3f - { - public Vector2 TexCoord; - public Vector3 Normal; - public Vector3 Position; - } - - public struct VertexT2hN3hV3h - { - public Vector2h TexCoord; - public Vector3h Normal; - public Vector3h Position; - } - - -} diff --git a/Source/Examples/Shapes/Capsule.cs b/Source/Examples/Shapes/Capsule.cs deleted file mode 100644 index 3ada2fca..00000000 --- a/Source/Examples/Shapes/Capsule.cs +++ /dev/null @@ -1,110 +0,0 @@ -using System; -using System.Collections.Generic; - -using OpenTK; - -namespace Examples.Shapes -{ - public sealed class Capsule: DrawableShape - { - public enum eSubdivisions - { - None = 0, - One = 1, - Two = 2, - Three = 3, - Four = 4, - } - - - public Capsule( double radius, double height, eSubdivisions subdivs, bool useDL ) - : base( useDL ) - { - uint HoseSubDivs = 0; - SlicedSphere.eSubdivisions spheresubdivs = SlicedSphere.eSubdivisions.Zero; - - switch ( subdivs ) - { - case eSubdivisions.None: - spheresubdivs = SlicedSphere.eSubdivisions.Zero; - HoseSubDivs = 0; - break; - case eSubdivisions.One: - spheresubdivs = SlicedSphere.eSubdivisions.One; - HoseSubDivs = 1; - break; - case eSubdivisions.Two: - spheresubdivs = SlicedSphere.eSubdivisions.Two; - HoseSubDivs = 3; - break; - case eSubdivisions.Three: - spheresubdivs = SlicedSphere.eSubdivisions.Three; - HoseSubDivs = 7; - break; - case eSubdivisions.Four: - spheresubdivs = SlicedSphere.eSubdivisions.Four; - HoseSubDivs = 15; - break; - } - PrimitiveMode = OpenTK.Graphics.OpenGL.PrimitiveType.Triangles; - - OpenTK.Graphics.OpenGL.PrimitiveType TemporaryMode; - VertexT2dN3dV3d[] TemporaryVBO; - uint[] TemporaryIBO; - - List AllChunks = new List(); - Vector3d offset1 = new Vector3d( 0.0, 0.0, height ), - offset2 = new Vector3d( 0.0, 0.0, -height ); - for ( int i = 0; i < 4; i++ ) - { - SlicedHose.eSide tempSide = SlicedHose.eSide.FrontTop; - switch ( i ) - { - case 0: - tempSide = SlicedHose.eSide.FrontBottom; - break; - case 1: - tempSide = SlicedHose.eSide.BackBottom; - break; - case 2: - tempSide = SlicedHose.eSide.BackTop; - break; - case 3: - tempSide = SlicedHose.eSide.FrontTop; - break; - } - SlicedHose tempHose = new SlicedHose( tempSide, HoseSubDivs, radius, offset1, offset2, false ); - tempHose.GetArraysforVBO( out TemporaryMode, out TemporaryVBO, out TemporaryIBO ); - tempHose.Dispose(); - AllChunks.Add( new Chunk( ref TemporaryVBO, ref TemporaryIBO ) ); - } - - SlicedSphere front = new SlicedSphere( radius, offset1, spheresubdivs, - new SlicedSphere.eDir[] { - SlicedSphere.eDir.BackBottomRight, - SlicedSphere.eDir.FrontTopRight, - SlicedSphere.eDir.BackTopRight, - SlicedSphere.eDir.FrontBottomRight, - }, - false ); - - front.GetArraysforVBO( out TemporaryMode, out TemporaryVBO, out TemporaryIBO ); - AllChunks.Add( new Chunk( ref TemporaryVBO, ref TemporaryIBO ) ); - front.Dispose(); - - SlicedSphere back = new SlicedSphere( radius, offset2, spheresubdivs, - new SlicedSphere.eDir[] { - SlicedSphere.eDir.FrontBottomLeft, - SlicedSphere.eDir.FrontTopLeft, - SlicedSphere.eDir.BackTopLeft, - SlicedSphere.eDir.BackBottomLeft }, - false ); - back.GetArraysforVBO( out TemporaryMode, out TemporaryVBO, out TemporaryIBO ); - AllChunks.Add( new Chunk( ref TemporaryVBO, ref TemporaryIBO ) ); - back.Dispose(); - - Chunk.GetArray( ref AllChunks, out VertexArray, out IndexArray ); - AllChunks.Clear(); - } - } -} diff --git a/Source/Examples/Shapes/ChamferCube.cs b/Source/Examples/Shapes/ChamferCube.cs deleted file mode 100644 index 08383af0..00000000 --- a/Source/Examples/Shapes/ChamferCube.cs +++ /dev/null @@ -1,280 +0,0 @@ -using System; -using System.Collections.Generic; - -using OpenTK; - -namespace Examples.Shapes -{ - public sealed class ChamferCube: DrawableShape - { - - public enum SubDivs: byte - { - Zero, - One, - Two, - Three, - Four, - } - - public ChamferCube( double Width, double Height, double Length, SubDivs subdivs, double radius, bool useDL ) - : base( useDL ) - { - SlicedSphere.eSubdivisions sphereSubDivs = SlicedSphere.eSubdivisions.Zero; - uint hoseSubDivs = 0; - - switch ( subdivs ) - { - case SubDivs.Zero: - sphereSubDivs = SlicedSphere.eSubdivisions.Zero; - hoseSubDivs = 0; - break; - case SubDivs.One: - sphereSubDivs = SlicedSphere.eSubdivisions.One; - hoseSubDivs = 1; - break; - case SubDivs.Two: - sphereSubDivs = SlicedSphere.eSubdivisions.Two; - hoseSubDivs = 3; - break; - case SubDivs.Three: - sphereSubDivs = SlicedSphere.eSubdivisions.Three; - hoseSubDivs = 7; - break; - case SubDivs.Four: - sphereSubDivs = SlicedSphere.eSubdivisions.Four; - hoseSubDivs = 15; - break; - } - - #region Temporary Storage - - List AllChunks = new List(); - OpenTK.Graphics.OpenGL.PrimitiveType TemporaryMode; - VertexT2dN3dV3d[] TemporaryVBO; - uint[] TemporaryIBO; - - #endregion Temporary Storage - - Vector3d FrontTopRightEdge = new Vector3d( +Width - radius, +Height - radius, +Length - radius ); - Vector3d FrontTopLeftEdge = new Vector3d( +Width - radius, +Height - radius, -Length + radius ); - Vector3d FrontBottomRightEdge = new Vector3d( +Width - radius, -Height + radius, +Length - radius ); - Vector3d FrontBottomLeftEdge = new Vector3d( +Width - radius, -Height + radius, -Length + radius ); - Vector3d BackTopRightEdge = new Vector3d( -Width + radius, +Height - radius, +Length - radius ); - Vector3d BackTopLeftEdge = new Vector3d( -Width + radius, +Height - radius, -Length + radius ); - Vector3d BackBottomRightEdge = new Vector3d( -Width + radius, -Height + radius, +Length - radius ); - Vector3d BackBottomLeftEdge = new Vector3d( -Width + radius, -Height + radius, -Length + radius ); - - #region 8 sliced Spheres - SlicedSphere tempSphere; - Vector3d tempVector = Vector3d.Zero; - SlicedSphere.eDir[] tempEdge = new SlicedSphere.eDir[1]; - - for ( int i = 0; i < 8; i++ ) - { - switch ( i ) - { - case 0: - tempVector = FrontTopRightEdge; - tempEdge = new SlicedSphere.eDir[] { SlicedSphere.eDir.FrontTopRight }; - break; - case 1: - tempVector = FrontTopLeftEdge; - tempEdge = new SlicedSphere.eDir[] { SlicedSphere.eDir.FrontTopLeft }; - break; - case 2: - tempVector = FrontBottomRightEdge; - tempEdge = new SlicedSphere.eDir[] { SlicedSphere.eDir.FrontBottomRight }; - break; - case 3: - tempVector = FrontBottomLeftEdge; - tempEdge = new SlicedSphere.eDir[] { SlicedSphere.eDir.FrontBottomLeft }; - break; - case 4: - tempVector = BackBottomRightEdge; - tempEdge = new SlicedSphere.eDir[] { SlicedSphere.eDir.BackBottomRight }; - break; - case 5: - tempVector = BackBottomLeftEdge; - tempEdge = new SlicedSphere.eDir[] { SlicedSphere.eDir.BackBottomLeft }; - break; - case 6: - tempVector = BackTopRightEdge; - tempEdge = new SlicedSphere.eDir[] { SlicedSphere.eDir.BackTopRight }; - break; - case 7: - tempVector = BackTopLeftEdge; - tempEdge = new SlicedSphere.eDir[] { SlicedSphere.eDir.BackTopLeft }; - break; - } - tempSphere = new SlicedSphere( radius, - tempVector, - sphereSubDivs, - tempEdge, - false ); - tempSphere.GetArraysforVBO( out TemporaryMode, out TemporaryVBO, out TemporaryIBO ); - tempSphere.Dispose(); - AllChunks.Add( new Chunk( ref TemporaryVBO, ref TemporaryIBO ) ); - } - #endregion 8 sliced Spheres - - #region 12 sliced Hoses - - SlicedHose tempHose; - SlicedHose.eSide tempSide = SlicedHose.eSide.BackBottom; - Vector3d tempHoseStart = Vector3d.Zero; - Vector3d tempHoseEnd = Vector3d.Zero; - - for ( int i = 0; i < 12; i++ ) - { - switch ( i ) - { - #region Around X Axis - case 0: - tempSide = SlicedHose.eSide.BottomRight; - tempHoseStart = BackBottomRightEdge; - tempHoseEnd = FrontBottomRightEdge; - break; - case 1: - tempSide = SlicedHose.eSide.TopRight; - tempHoseStart = BackTopRightEdge; - tempHoseEnd = FrontTopRightEdge; - break; - case 2: - tempSide = SlicedHose.eSide.TopLeft; - tempHoseStart = BackTopLeftEdge; - tempHoseEnd = FrontTopLeftEdge; - break; - case 3: - tempSide = SlicedHose.eSide.BottomLeft; - tempHoseStart = BackBottomLeftEdge; - tempHoseEnd = FrontBottomLeftEdge; - break; - #endregion Around X Axis - #region Around Y Axis - case 4: - tempSide = SlicedHose.eSide.FrontRight; - tempHoseStart = FrontBottomRightEdge; - tempHoseEnd = FrontTopRightEdge; - break; - case 5: - tempSide = SlicedHose.eSide.BackRight; - tempHoseStart = BackBottomRightEdge; - tempHoseEnd = BackTopRightEdge; - break; - case 6: - tempSide = SlicedHose.eSide.BackLeft; - tempHoseStart = BackBottomLeftEdge; - tempHoseEnd = BackTopLeftEdge; - break; - case 7: - tempSide = SlicedHose.eSide.FrontLeft; - tempHoseStart = FrontBottomLeftEdge; - tempHoseEnd = FrontTopLeftEdge; - break; - #endregion Around Y Axis - #region Around Z Axis - case 8: - tempSide = SlicedHose.eSide.FrontTop; - tempHoseStart = FrontTopRightEdge; - tempHoseEnd = FrontTopLeftEdge; - break; - case 9: - tempSide = SlicedHose.eSide.BackTop; - tempHoseStart = BackTopRightEdge; - tempHoseEnd = BackTopLeftEdge; - break; - case 10: - tempSide = SlicedHose.eSide.BackBottom; - tempHoseStart = BackBottomRightEdge; - tempHoseEnd = BackBottomLeftEdge; - break; - case 11: - tempSide = SlicedHose.eSide.FrontBottom; - tempHoseStart = FrontBottomRightEdge; - tempHoseEnd = FrontBottomLeftEdge; - break; - #endregion Around Z Axis - } - tempHose = new SlicedHose( tempSide, - hoseSubDivs, - radius, - tempHoseStart, - tempHoseEnd, - false ); - tempHose.GetArraysforVBO( out TemporaryMode, out TemporaryVBO, out TemporaryIBO ); - tempHose.Dispose(); - AllChunks.Add( new Chunk( ref TemporaryVBO, ref TemporaryIBO ) ); - } - #endregion 12 sliced Hoses - - #region 6 quads for the sides - - VertexT2dN3dV3d[] tempVBO = new VertexT2dN3dV3d[4]; - uint[] tempIBO = new uint[6] { 0, 1, 2, 0, 2, 3 }; // all quads share this IBO - - // all quads use the same texcoords - tempVBO[0].TexCoord = new Vector2d( 0.0, 1.0 ); - tempVBO[1].TexCoord = new Vector2d( 0.0, 0.0 ); - tempVBO[2].TexCoord = new Vector2d( 1.0, 0.0 ); - tempVBO[3].TexCoord = new Vector2d( 1.0, 1.0 ); - - // front face - tempVBO[0].Normal = tempVBO[1].Normal = tempVBO[2].Normal = tempVBO[3].Normal = Vector3d.UnitX; - tempVBO[0].Position = FrontTopRightEdge + new Vector3d( radius, 0.0, 0.0 ); - tempVBO[1].Position = FrontBottomRightEdge + new Vector3d( radius, 0.0, 0.0 ); - tempVBO[2].Position = FrontBottomLeftEdge + new Vector3d( radius, 0.0, 0.0 ); - tempVBO[3].Position = FrontTopLeftEdge + new Vector3d( radius, 0.0, 0.0 ); - AllChunks.Add( new Chunk( ref tempVBO, ref tempIBO ) ); - - // back face - tempVBO[0].Normal = tempVBO[1].Normal = tempVBO[2].Normal = tempVBO[3].Normal = -Vector3d.UnitX; - tempVBO[0].Position = BackTopLeftEdge - new Vector3d( radius, 0.0, 0.0 ); - tempVBO[1].Position = BackBottomLeftEdge - new Vector3d( radius, 0.0, 0.0 ); - tempVBO[2].Position = BackBottomRightEdge - new Vector3d( radius, 0.0, 0.0 ); - tempVBO[3].Position = BackTopRightEdge - new Vector3d( radius, 0.0, 0.0 ); - AllChunks.Add( new Chunk( ref tempVBO, ref tempIBO ) ); - - // top face - tempVBO[0].Normal = tempVBO[1].Normal = tempVBO[2].Normal = tempVBO[3].Normal = Vector3d.UnitY; - tempVBO[0].Position = BackTopRightEdge + new Vector3d( 0.0, radius, 0.0 ); - tempVBO[1].Position = FrontTopRightEdge + new Vector3d( 0.0, radius, 0.0 ); - tempVBO[2].Position = FrontTopLeftEdge + new Vector3d( 0.0, radius, 0.0 ); - tempVBO[3].Position = BackTopLeftEdge + new Vector3d( 0.0, radius, 0.0 ); - AllChunks.Add( new Chunk( ref tempVBO, ref tempIBO ) ); - - // bottom face - tempVBO[0].Normal = tempVBO[1].Normal = tempVBO[2].Normal = tempVBO[3].Normal = -Vector3d.UnitY; - tempVBO[0].Position = BackBottomLeftEdge - new Vector3d( 0.0, radius, 0.0 ); - tempVBO[1].Position = FrontBottomLeftEdge - new Vector3d( 0.0, radius, 0.0 ); - tempVBO[2].Position = FrontBottomRightEdge - new Vector3d( 0.0, radius, 0.0 ); - tempVBO[3].Position = BackBottomRightEdge - new Vector3d( 0.0, radius, 0.0 ); - AllChunks.Add( new Chunk( ref tempVBO, ref tempIBO ) ); - - // right face - tempVBO[0].Normal = tempVBO[1].Normal = tempVBO[2].Normal = tempVBO[3].Normal = Vector3d.UnitZ; - tempVBO[0].Position = BackTopRightEdge + new Vector3d( 0.0, 0.0, radius ); - tempVBO[1].Position = BackBottomRightEdge + new Vector3d( 0.0, 0.0, radius ); - tempVBO[2].Position = FrontBottomRightEdge + new Vector3d( 0.0, 0.0, radius ); - tempVBO[3].Position = FrontTopRightEdge + new Vector3d( 0.0, 0.0, radius ); - AllChunks.Add( new Chunk( ref tempVBO, ref tempIBO ) ); - - // left face - tempVBO[0].Normal = tempVBO[1].Normal = tempVBO[2].Normal = tempVBO[3].Normal = -Vector3d.UnitZ; - tempVBO[0].Position = FrontTopLeftEdge - new Vector3d( 0.0, 0.0, radius ); - tempVBO[1].Position = FrontBottomLeftEdge - new Vector3d( 0.0, 0.0, radius ); - tempVBO[2].Position = BackBottomLeftEdge - new Vector3d( 0.0, 0.0, radius ); - tempVBO[3].Position = BackTopLeftEdge - new Vector3d( 0.0, 0.0, radius ); - AllChunks.Add( new Chunk( ref tempVBO, ref tempIBO ) ); - - - #endregion 6 quads for the sides - - #region Final Assembly of Chunks - PrimitiveMode = OpenTK.Graphics.OpenGL.PrimitiveType.Triangles; - Chunk.GetArray( ref AllChunks, out VertexArray, out IndexArray ); - AllChunks.Clear(); - #endregion Final Assembly of Chunks - } - } -} diff --git a/Source/Examples/Shapes/Helpers/Chunk.cs b/Source/Examples/Shapes/Helpers/Chunk.cs deleted file mode 100644 index 466bff99..00000000 --- a/Source/Examples/Shapes/Helpers/Chunk.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Examples.Shapes -{ - public class Chunk - { - public VertexT2dN3dV3d[] Vertices; - public uint[] Indices; - - public uint VertexCount - { - get - { - return (uint)Vertices.Length; - } - } - public uint IndexCount - { - get - { - return (uint)Indices.Length; - } - } - - public Chunk( uint vertexcount, uint indexcount ) - { - Vertices = new VertexT2dN3dV3d[vertexcount]; - Indices = new uint[indexcount]; - } - - public Chunk( ref VertexT2dN3dV3d[] vbo, ref uint[] ibo ) - { - Vertices = new VertexT2dN3dV3d[vbo.Length]; - for ( int i = 0; i < Vertices.Length; i++ ) - { - Vertices[i] = vbo[i]; - } - Indices = new uint[ibo.Length]; - for ( int i = 0; i < Indices.Length; i++ ) - { - Indices[i] = ibo[i]; - } - } - - public static void GetArray( ref List c, out VertexT2dN3dV3d[] vbo, out uint[] ibo ) - { - - uint VertexCounter = 0; - uint IndexCounter = 0; - - foreach ( Chunk ch in c ) - { - VertexCounter += ch.VertexCount; - IndexCounter += ch.IndexCount; - } - - vbo = new VertexT2dN3dV3d[VertexCounter]; - ibo = new uint[IndexCounter]; - - VertexCounter = 0; - IndexCounter = 0; - - foreach ( Chunk ch in c ) - { - for ( int i = 0; i < ch.Vertices.Length; i++ ) - { - vbo[VertexCounter + i] = ch.Vertices[i]; - } - - for ( int i = 0; i < ch.Indices.Length; i++ ) - { - ibo[IndexCounter + i] = ch.Indices[i] + VertexCounter; - } - - VertexCounter += (uint)ch.VertexCount; - IndexCounter += (uint)ch.IndexCount; - } - } - } -} diff --git a/Source/Examples/Shapes/Helpers/MengerCube.cs b/Source/Examples/Shapes/Helpers/MengerCube.cs deleted file mode 100644 index 763ddc45..00000000 --- a/Source/Examples/Shapes/Helpers/MengerCube.cs +++ /dev/null @@ -1,420 +0,0 @@ -using System; -using System.Collections.Generic; - -using OpenTK; - -namespace Examples.Shapes -{ - public sealed partial class MengerSponge - { - private struct MengerCube - { - private Vector3d Center; - private double SideLength; - private eSides[] VisibleSides; - private eSides[] VisibilityToInherit; - - public void GetArraySizes( out uint vertexcount, out uint indexcount ) - { - vertexcount = (uint)VisibleSides.Length * 8 + 6 * 12; - indexcount = (uint)VisibleSides.Length * 8 * 3 + 6 * 8 * 3; - } - - public MengerCube( Vector3d center, double sidelength, eSides[] visibleSides, eSides[] parentsVisibility ) - { - Center = center; - SideLength = sidelength; - - /* List Sides = new List(); - foreach ( eSides s in visibleSides ) - { - bool isVisible = false; - foreach ( eSides p in parentsVisibility ) - { - if ( (int)p == (int)s ) - { - isVisible = true; - break; - } - } - if ( isVisible ) - { - Sides.Add( s ); - } - } - VisibleSides = Sides.ToArray();*/ - VisibleSides = visibleSides; - VisibilityToInherit = visibleSides; - } - - public void Subdivide( out MengerCube[] cubes ) - { - cubes = new MengerCube[20]; // 8 + 4 + 8 - - double NewLength = this.SideLength / 3.0; - double six = this.SideLength * 2.0 / 3.0; - // we got 3x3x3 cubes. All center cubes who touch the XYZ-Axis are removed. - - // front - cubes[0] = new MengerCube( new Vector3d( Center.X - six, Center.Y + six, Center.Z + six ), NewLength, new eSides[] { eSides.Front, eSides.Left, eSides.Top }, this.VisibilityToInherit ); - cubes[1] = new MengerCube( new Vector3d( Center.X + 0.0, Center.Y + six, Center.Z + six ), NewLength, new eSides[] { eSides.Front, eSides.Bottom, eSides.Back, eSides.Top }, this.VisibilityToInherit ); - cubes[2] = new MengerCube( new Vector3d( Center.X + six, Center.Y + six, Center.Z + six ), NewLength, new eSides[] { eSides.Front, eSides.Right, eSides.Top }, this.VisibilityToInherit ); - - cubes[3] = new MengerCube( new Vector3d( Center.X - six, Center.Y + 0.0, Center.Z + six ), NewLength, new eSides[] { eSides.Front, eSides.Right, eSides.Back, eSides.Left }, this.VisibilityToInherit ); - cubes[4] = new MengerCube( new Vector3d( Center.X + six, Center.Y + 0.0, Center.Z + six ), NewLength, new eSides[] { eSides.Front, eSides.Right, eSides.Back, eSides.Left }, this.VisibilityToInherit ); - - cubes[5] = new MengerCube( new Vector3d( Center.X - six, Center.Y - six, Center.Z + six ), NewLength, new eSides[] { eSides.Front, eSides.Left, eSides.Bottom } , this.VisibilityToInherit ); - cubes[6] = new MengerCube( new Vector3d( Center.X + 0.0, Center.Y - six, Center.Z + six ), NewLength, new eSides[] { eSides.Front, eSides.Top, eSides.Back, eSides.Bottom }, this.VisibilityToInherit ); - cubes[7] = new MengerCube( new Vector3d( Center.X + six, Center.Y - six, Center.Z + six ), NewLength, new eSides[] { eSides.Front, eSides.Right, eSides.Bottom }, this.VisibilityToInherit ); - - // center - cubes[8] = new MengerCube( new Vector3d( Center.X - six, Center.Y + six, Center.Z + 0.0 ), NewLength, new eSides[] { eSides.Top, eSides.Right, eSides.Bottom, eSides.Left }, this.VisibilityToInherit ); - - cubes[9] = new MengerCube( new Vector3d( Center.X + six, Center.Y + six, Center.Z + 0.0 ), NewLength, new eSides[] { eSides.Top, eSides.Right, eSides.Bottom, eSides.Left }, this.VisibilityToInherit ); - - cubes[10] = new MengerCube( new Vector3d( Center.X - six, Center.Y - six, Center.Z + 0.0 ), NewLength, new eSides[] { eSides.Top, eSides.Right, eSides.Bottom, eSides.Left }, this.VisibilityToInherit ); - - cubes[11] = new MengerCube( new Vector3d( Center.X + six, Center.Y - six, Center.Z + 0.0 ), NewLength, new eSides[] { eSides.Top, eSides.Right, eSides.Bottom, eSides.Left }, this.VisibilityToInherit ); - - // back - cubes[12] = new MengerCube( new Vector3d( Center.X - six, Center.Y + six, Center.Z - six ), NewLength, new eSides[] { eSides.Top, eSides.Back, eSides.Left }, this.VisibilityToInherit ); - cubes[13] = new MengerCube( new Vector3d( Center.X + 0.0, Center.Y + six, Center.Z - six ), NewLength, new eSides[] { eSides.Top, eSides.Back, eSides.Bottom, eSides.Front }, this.VisibilityToInherit ); - cubes[14] = new MengerCube( new Vector3d( Center.X + six, Center.Y + six, Center.Z - six ), NewLength, new eSides[] { eSides.Top, eSides.Back, eSides.Right }, this.VisibilityToInherit ); - - cubes[15] = new MengerCube( new Vector3d( Center.X - six, Center.Y + 0.0, Center.Z - six ), NewLength, new eSides[] { eSides.Front, eSides.Right, eSides.Back, eSides.Left } , this.VisibilityToInherit ); - cubes[16] = new MengerCube( new Vector3d( Center.X + six, Center.Y + 0.0, Center.Z - six ), NewLength, new eSides[] { eSides.Front, eSides.Right, eSides.Back, eSides.Left } , this.VisibilityToInherit ); - - cubes[17] = new MengerCube( new Vector3d( Center.X - six, Center.Y - six, Center.Z - six ), NewLength, new eSides[] { eSides.Back, eSides.Bottom, eSides.Left } , this.VisibilityToInherit ); - cubes[18] = new MengerCube( new Vector3d( Center.X + 0.0, Center.Y - six, Center.Z - six ), NewLength, new eSides[] { eSides.Top, eSides.Back, eSides.Bottom, eSides.Front }, this.VisibilityToInherit ); - cubes[19] = new MengerCube( new Vector3d( Center.X + six, Center.Y - six, Center.Z - six ), NewLength, new eSides[] { eSides.Back, eSides.Bottom, eSides.Right }, this.VisibilityToInherit ); - - } - - public enum eSides: byte - { - Front, - Back, - Right, - Left, - Top, - Bottom - } - - internal static readonly eSides[] AllSides = new eSides[] { eSides.Front, eSides.Back, eSides.Right, eSides.Left, eSides.Top, eSides.Bottom }; - - public void GetVboAndIbo( ref List chunks ) - { - foreach ( eSides s in AllSides ) - { - DrawSide( s, ref chunks ); - } - } - - private void DrawSide( eSides side, ref List chunks ) - { - #region Setup constants for current direction - - double _Zero = 0.0; // 0/3 - double _Three = 0.3333333333333; // 1/3 - double _Six = 0.66666666666666; // 2/3 - double _One = 1.0; // 3/3 - - Vector3d C0 = Center + new Vector3d( -SideLength, -SideLength, +SideLength ); - Vector3d C1 = Center + new Vector3d( +SideLength, -SideLength, +SideLength ); - Vector3d C2 = Center + new Vector3d( +SideLength, +SideLength, +SideLength ); - Vector3d C3 = Center + new Vector3d( -SideLength, +SideLength, +SideLength ); - - Vector3d C4 = Center + new Vector3d( -SideLength, -SideLength, -SideLength ); - Vector3d C5 = Center + new Vector3d( +SideLength, -SideLength, -SideLength ); - Vector3d C6 = Center + new Vector3d( +SideLength, +SideLength, -SideLength ); - Vector3d C7 = Center + new Vector3d( -SideLength, +SideLength, -SideLength ); - - Vector3d P0, P1, P2, P3, P4, P5, P6, P7; - - switch ( side ) - { - case eSides.Front: - P0 = C0; - P1 = C1; - P2 = C2; - P3 = C3; - - P4 = C4; - P5 = C5; - P6 = C6; - P7 = C7; - break; - case eSides.Back: - P0 = C5; - P1 = C4; - P2 = C7; - P3 = C6; - - P4 = C1; - P5 = C0; - P6 = C3; - P7 = C2; - break; - case eSides.Right: - P0 = C1; - P1 = C5; - P2 = C6; - P3 = C2; - - P4 = C0; - P5 = C4; - P6 = C7; - P7 = C3; - break; - case eSides.Left: - P0 = C4; - P1 = C0; - P2 = C3; - P3 = C7; - - P4 = C5; - P5 = C1; - P6 = C2; - P7 = C6; - break; - case eSides.Top: - P0 = C3; - P1 = C2; - P2 = C6; - P3 = C7; - - P4 = C0; - P5 = C1; - P6 = C5; - P7 = C4; - break; - case eSides.Bottom: - P0 = C1; - P1 = C0; - P2 = C4; - P3 = C5; - - P4 = C2; - P5 = C3; - P6 = C7; - P7 = C6; - break; - default: - throw new NotImplementedException( "Unknown enum value: " + side ); - } - - #endregion Setup constants for current direction - - #region Set Normal - - Vector3d FaceNormal; - - switch ( side ) - { - case eSides.Front: - FaceNormal = Vector3d.UnitZ; - break; - case eSides.Back: - FaceNormal = -Vector3d.UnitZ; - break; - case eSides.Right: - FaceNormal = Vector3d.UnitX; - break; - case eSides.Left: - FaceNormal = -Vector3d.UnitX; - break; - case eSides.Top: - FaceNormal = Vector3d.UnitY; - break; - case eSides.Bottom: - FaceNormal = -Vector3d.UnitY; - break; - default: - throw new NotImplementedException( "Unknown enum value: " + side ); - } - #endregion Set Normal - - bool FaceIsVisible = false; - foreach ( eSides s in VisibleSides ) - { - if ( s == side ) - { - FaceIsVisible = true; - break; - } - } - - if ( FaceIsVisible ) - { - #region Define Layer1 Vertices - Chunk Layer1 = new Chunk( 8, 8 * 3 ); - - Layer1.Vertices[0].TexCoord = new Vector2d( _Zero, _Zero ); - Layer1.Vertices[0].Normal = FaceNormal; - Layer1.Vertices[0].Position = P0; - - Layer1.Vertices[1].TexCoord = new Vector2d( _One, _Zero ); - Layer1.Vertices[1].Normal = FaceNormal; - Layer1.Vertices[1].Position = P1; - - Layer1.Vertices[2].TexCoord = new Vector2d( _One, _One ); - Layer1.Vertices[2].Normal = FaceNormal; - Layer1.Vertices[2].Position = P2; - - Layer1.Vertices[3].TexCoord = new Vector2d( _Zero, _One ); - Layer1.Vertices[3].Normal = FaceNormal; - Layer1.Vertices[3].Position = P3; - - Layer1.Vertices[4].TexCoord = new Vector2d( _Three, _Three ); - Layer1.Vertices[4].Normal = FaceNormal; - Vector3d.Lerp( ref P0, ref P2, _Three, out Layer1.Vertices[4].Position ); - - Layer1.Vertices[5].TexCoord = new Vector2d( _Six, _Three ); - Layer1.Vertices[5].Normal = FaceNormal; - Vector3d.Lerp( ref P1, ref P3, _Three, out Layer1.Vertices[5].Position ); - - Layer1.Vertices[6].TexCoord = new Vector2d( _Six, _Six ); - Layer1.Vertices[6].Normal = FaceNormal; - Vector3d.Lerp( ref P0, ref P2, _Six, out Layer1.Vertices[6].Position ); - - Layer1.Vertices[7].TexCoord = new Vector2d( _Three, _Six ); - Layer1.Vertices[7].Normal = FaceNormal; - Vector3d.Lerp( ref P1, ref P3, _Six, out Layer1.Vertices[7].Position ); - #endregion Define Layer1 Vertices - - #region Define Layer1 Indices - Layer1.Indices[0] = 0; - Layer1.Indices[1] = 5; - Layer1.Indices[2] = 4; - - Layer1.Indices[3] = 0; - Layer1.Indices[4] = 1; - Layer1.Indices[5] = 5; - - Layer1.Indices[6] = 5; - Layer1.Indices[7] = 1; - Layer1.Indices[8] = 2; - - Layer1.Indices[9] = 6; - Layer1.Indices[10] = 5; - Layer1.Indices[11] = 2; - - Layer1.Indices[12] = 7; - Layer1.Indices[13] = 6; - Layer1.Indices[14] = 2; - - Layer1.Indices[15] = 3; - Layer1.Indices[16] = 7; - Layer1.Indices[17] = 2; - - Layer1.Indices[18] = 0; - Layer1.Indices[19] = 7; - Layer1.Indices[20] = 3; - - Layer1.Indices[21] = 0; - Layer1.Indices[22] = 4; - Layer1.Indices[23] = 7; - - chunks.Add( Layer1 ); - #endregion Define Layer1 Indices - } - - #region Define Layer2 Vertices - Chunk Layer2 = new Chunk( 12, 8 * 3 ); - - Vector3d T0, T1, T2, T3; - Vector3d.Lerp( ref P0, ref P4, _Six, out T0 ); - Vector3d.Lerp( ref P1, ref P5, _Six, out T1 ); - Vector3d.Lerp( ref P2, ref P6, _Six, out T2 ); - Vector3d.Lerp( ref P3, ref P7, _Six, out T3 ); - - Layer2.Vertices[0].TexCoord = new Vector2d( _Three, _Zero ); - Layer2.Vertices[0].Normal = FaceNormal; - Vector3d.Lerp( ref T0, ref T1, _Three, out Layer2.Vertices[0].Position ); - - Layer2.Vertices[1].TexCoord = new Vector2d( _Six, _Zero ); - Layer2.Vertices[1].Normal = FaceNormal; - Vector3d.Lerp( ref T0, ref T1, _Six, out Layer2.Vertices[1].Position ); - - Layer2.Vertices[3].TexCoord = new Vector2d( _One, _Three ); - Layer2.Vertices[3].Normal = FaceNormal; - Vector3d.Lerp( ref T1, ref T2, _Three, out Layer2.Vertices[3].Position ); - - Layer2.Vertices[4].TexCoord = new Vector2d( _One, _Six ); - Layer2.Vertices[4].Normal = FaceNormal; - Vector3d.Lerp( ref T1, ref T2, _Six, out Layer2.Vertices[4].Position ); - - Layer2.Vertices[6].TexCoord = new Vector2d( _Six, _One ); - Layer2.Vertices[6].Normal = FaceNormal; - Vector3d.Lerp( ref T2, ref T3, _Three, out Layer2.Vertices[6].Position ); - - Layer2.Vertices[7].TexCoord = new Vector2d( _Three, _One ); - Layer2.Vertices[7].Normal = FaceNormal; - Vector3d.Lerp( ref T2, ref T3, _Six, out Layer2.Vertices[7].Position ); - - Layer2.Vertices[9].TexCoord = new Vector2d( _Zero, _Six ); - Layer2.Vertices[9].Normal = FaceNormal; - Vector3d.Lerp( ref T3, ref T0, _Three, out Layer2.Vertices[9].Position ); - - Layer2.Vertices[10].TexCoord = new Vector2d( _Zero, _Three ); - Layer2.Vertices[10].Normal = FaceNormal; - Vector3d.Lerp( ref T3, ref T0, _Six, out Layer2.Vertices[10].Position ); - - Layer2.Vertices[2].TexCoord = new Vector2d( _Six, _Three ); - Layer2.Vertices[2].Normal = FaceNormal; - Vector3d.Lerp( ref Layer2.Vertices[1].Position, ref Layer2.Vertices[6].Position, _Three, out Layer2.Vertices[2].Position ); - - Layer2.Vertices[5].TexCoord = new Vector2d( _Six, _Six ); - Layer2.Vertices[5].Normal = FaceNormal; - Vector3d.Lerp( ref Layer2.Vertices[1].Position, ref Layer2.Vertices[6].Position, _Six, out Layer2.Vertices[5].Position ); - - Layer2.Vertices[8].TexCoord = new Vector2d( _Three, _Six ); - Layer2.Vertices[8].Normal = FaceNormal; - Vector3d.Lerp( ref Layer2.Vertices[7].Position, ref Layer2.Vertices[0].Position, _Three, out Layer2.Vertices[8].Position ); - - Layer2.Vertices[11].TexCoord = new Vector2d( _Three, _Three ); - Layer2.Vertices[11].Normal = FaceNormal; - Vector3d.Lerp( ref Layer2.Vertices[7].Position, ref Layer2.Vertices[0].Position, _Six, out Layer2.Vertices[11].Position ); - #endregion Define Layer2 Vertices - - #region Define Layer2 Indices - Layer2.Indices[0] = 0; - Layer2.Indices[1] = 2; - Layer2.Indices[2] = 11; - - Layer2.Indices[3] = 0; - Layer2.Indices[4] = 1; - Layer2.Indices[5] = 2; - - Layer2.Indices[6] = 2; - Layer2.Indices[7] = 3; - Layer2.Indices[8] = 4; - - Layer2.Indices[9] = 2; - Layer2.Indices[10] = 4; - Layer2.Indices[11] = 5; - - Layer2.Indices[12] = 5; - Layer2.Indices[13] = 6; - Layer2.Indices[14] = 8; - - Layer2.Indices[15] = 8; - Layer2.Indices[16] = 6; - Layer2.Indices[17] = 7; - - Layer2.Indices[18] = 11; - Layer2.Indices[19] = 8; - Layer2.Indices[20] = 10; - - Layer2.Indices[21] = 10; - Layer2.Indices[22] = 8; - Layer2.Indices[23] = 9; - - chunks.Add( Layer2 ); - #endregion Define Layer2 Indices - } - } - } - - -} diff --git a/Source/Examples/Shapes/Helpers/TetrahedronFace.cs b/Source/Examples/Shapes/Helpers/TetrahedronFace.cs deleted file mode 100644 index dabfe06f..00000000 --- a/Source/Examples/Shapes/Helpers/TetrahedronFace.cs +++ /dev/null @@ -1,230 +0,0 @@ -using System; - -using OpenTK; - -namespace Examples.Shapes -{ - - /// winding always assumed CCW (Counter-ClockWise) - internal struct TetrahedronFace - { - private Vector3d APosition, BPosition, CPosition; - private Vector3d DPosition, Normal; - private Vector2d ATexCoord, BTexCoord, CTexCoord; - - public TetrahedronFace( ref Vector3d apos, ref Vector2d atc, - ref Vector3d bpos, ref Vector2d btc, - ref Vector3d cpos, ref Vector2d ctc, - ref Vector3d dpos, - ref Vector3d normal ) - { - APosition = apos; ATexCoord = atc; - BPosition = bpos; BTexCoord = btc; - CPosition = cpos; CTexCoord = ctc; - DPosition = dpos; - Normal = normal; - } - - /// Expects CCW triangle order as input, emits 4 new CCW triangles. - /// 1st output Triangle - /// 2nd output Triangle - /// 3rd output Triangle - /// 4th output Triangle - public void SubdivideSierpinski( out TetrahedronFace first, out TetrahedronFace second, out TetrahedronFace third, out TetrahedronFace fourth ) - { - Vector3d temp; - - // find the 3 points AB, BC, CA - Vector3d CenterAB; - Vector3d.Add( ref this.APosition, ref this.BPosition, out temp ); - Vector3d.Multiply( ref temp, 0.5f, out CenterAB ); - - Vector3d CenterBC; - Vector3d.Add( ref this.BPosition, ref this.CPosition, out temp ); - Vector3d.Multiply( ref temp, 0.5f, out CenterBC ); - - Vector3d CenterCA; - Vector3d.Add( ref this.CPosition, ref this.APosition, out temp ); - Vector3d.Multiply( ref temp, 0.5f, out CenterCA ); - - // find the 3 points AD, BD, CD - Vector3d CenterAD; - Vector3d.Lerp( ref this.APosition, ref this.DPosition, 0.5, out CenterAD ); - - Vector3d CenterBD; - Vector3d.Lerp( ref this.BPosition, ref this.DPosition, 0.5, out CenterBD ); - - Vector3d CenterCD; - Vector3d.Lerp( ref this.CPosition, ref this.DPosition, 0.5, out CenterCD ); - - // emit 4 new CCW triangles - first = new TetrahedronFace( ref this.APosition, ref this.ATexCoord, - ref CenterAB, ref this.BTexCoord, - ref CenterCA, ref this.CTexCoord, - ref CenterAD, - ref this.Normal ); - - second = new TetrahedronFace( ref CenterAB, ref this.ATexCoord, - ref this.BPosition, ref this.BTexCoord, - ref CenterBC, ref this.CTexCoord, - ref CenterBD, - ref this.Normal ); - - third = new TetrahedronFace( ref CenterCA, ref this.ATexCoord, - ref CenterBC, ref this.BTexCoord, - ref this.CPosition, ref this.CTexCoord, - ref CenterCD, - ref this.Normal ); - - fourth = new TetrahedronFace( ref CenterAD, ref this.ATexCoord, - ref CenterBD, ref this.BTexCoord, - ref CenterCD, ref this.CTexCoord, - ref this.DPosition, - ref this.Normal ); - } - - - internal void SubdivideKoch( double height, out TetrahedronFace first, out TetrahedronFace second, out TetrahedronFace third, out TetrahedronFace fourth, out TetrahedronFace fifth, out TetrahedronFace sixth ) - { - Vector3d CenterAB, CenterBC, CenterCA, CenterD; - Vector2d TexCoordAB, TexCoordBC, TexCoordCA, TexCoordD; - - Vector3d.Lerp( ref this.APosition, ref this.BPosition, 0.5, out CenterAB ); - Vector3d.Lerp( ref this.BPosition, ref this.CPosition, 0.5, out CenterBC ); - Vector3d.Lerp( ref this.CPosition, ref this.APosition, 0.5, out CenterCA ); - CenterD = CenterAB; - Vector3d.Add(ref CenterD, ref CenterBC, out CenterD); - Vector3d.Add(ref CenterD, ref CenterCA, out CenterD); - CenterD /= 3.0; - Vector3d E = CenterD + ( this.Normal * 0.5 ); - Vector3d temp = this.Normal; - temp *= height; - Vector3d.Add(ref CenterD, ref temp, out CenterD); - - Vector2d.Lerp( ref this.ATexCoord, ref this.BTexCoord, 0.5, out TexCoordAB ); - Vector2d.Lerp( ref this.BTexCoord, ref this.CTexCoord, 0.5, out TexCoordBC ); - Vector2d.Lerp( ref this.CTexCoord, ref this.ATexCoord, 0.5, out TexCoordCA ); - TexCoordD = TexCoordAB; - Vector2d.Add(ref TexCoordD, ref TexCoordBC, out TexCoordD); - Vector2d.Add(ref TexCoordD, ref TexCoordCA, out TexCoordD); - TexCoordD /= 3.0; - #region 1 - first.APosition = this.APosition; - first.ATexCoord = this.ATexCoord; - - first.BPosition = CenterAB; - first.BTexCoord = TexCoordAB; - - first.CPosition = CenterCA; - first.CTexCoord = TexCoordCA; - - first.Normal = this.Normal; - temp = ( this.APosition + CenterAB + CenterCA ); - temp /= 3.0; - temp += this.Normal * -1.0; - first.DPosition = temp; - #endregion 1 - #region 2 - second.APosition = CenterAB; - second.ATexCoord = TexCoordAB; - - second.BPosition = this.BPosition; - second.BTexCoord = this.BTexCoord; - - second.CPosition = CenterBC; - second.CTexCoord = TexCoordBC; - - second.Normal = this.Normal; - - temp = CenterAB + this.BPosition + CenterBC; - temp /= 3.0; - temp += this.Normal * -1.0; - second.DPosition = temp; - - #endregion 2 - #region 3 - third.APosition = CenterBC; - third.ATexCoord = TexCoordBC; - - third.BPosition = this.CPosition; - third.BTexCoord = this.CTexCoord; - - third.CPosition = CenterCA; - third.CTexCoord = TexCoordCA; - - third.Normal = this.Normal; - temp = CenterBC + this.CPosition + CenterCA; - temp /= 3.0; - temp += this.Normal * -1.0; - third.DPosition = temp; - #endregion 3 - #region 4 - fourth.APosition = CenterAB; - fourth.ATexCoord = TexCoordAB; - - fourth.BPosition = CenterD; - fourth.BTexCoord = TexCoordD; - - fourth.CPosition = CenterCA; - fourth.CTexCoord = TexCoordCA; - - SierpinskiTetrahedron.FindNormal( ref CenterAB, ref CenterD, ref CenterCA, out fourth.Normal ); - fourth.DPosition = E; - #endregion 4 - #region 5 - fifth.APosition = CenterAB; - fifth.ATexCoord = TexCoordAB; - - fifth.BPosition = CenterBC; - fifth.BTexCoord = TexCoordBC; - - fifth.CPosition = CenterD; - fifth.CTexCoord = TexCoordD; - - SierpinskiTetrahedron.FindNormal( ref CenterAB, ref CenterBC, ref CenterD, out fifth.Normal ); - fifth.DPosition = E; - - #endregion 5 - #region 6 - sixth.APosition = CenterBC; - sixth.ATexCoord = TexCoordBC; - - sixth.BPosition = CenterCA; - sixth.BTexCoord = TexCoordCA; - - sixth.CPosition = CenterD; - sixth.CTexCoord = TexCoordD; - - SierpinskiTetrahedron.FindNormal( ref CenterBC, ref CenterCA, ref CenterD, out sixth.Normal ); - sixth.DPosition = E; - #endregion 6 - } - - /// Returns 3 Vertices which form a CCW triangle. - public void GetVertices( out VertexT2dN3dV3d first, out VertexT2dN3dV3d second, out VertexT2dN3dV3d third ) - { - first.TexCoord = this.ATexCoord; - first.Normal = this.Normal; - first.Position = this.APosition; - - second.TexCoord = this.BTexCoord; - second.Normal = this.Normal; - second.Position = this.BPosition; - - third.TexCoord = this.CTexCoord; - third.Normal = this.Normal; - third.Position = this.CPosition; - } - - /// Debugging Aid, no real purpose - public override string ToString() - { - return "A= " + this.APosition.ToString() + " TexCoord: " + this.ATexCoord.ToString() + "\n" + - "B= " + this.BPosition.ToString() + " TexCoord: " + this.ATexCoord.ToString() + "\n" + - "C= " + this.CPosition.ToString() + " TexCoord: " + this.ATexCoord.ToString() + "\n" + - "Normal= " + this.Normal.ToString(); - } - } - - -} diff --git a/Source/Examples/Shapes/Helpers/VboShape.cs b/Source/Examples/Shapes/Helpers/VboShape.cs deleted file mode 100644 index 23c4b21a..00000000 --- a/Source/Examples/Shapes/Helpers/VboShape.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Examples.Shapes -{ - public sealed class VboShape: DrawableShape - { - public VboShape(ref OpenTK.Graphics.OpenGL.PrimitiveType primitives, ref VertexT2dN3dV3d[] vertices, ref uint[] indices, bool useDL) - : base( useDL ) - { - PrimitiveMode = primitives; - - VertexArray = new VertexT2dN3dV3d[vertices.Length]; - for ( uint i = 0; i < vertices.Length; i++ ) - { - VertexArray[i] = vertices[i]; - } - - IndexArray = new uint[indices.Length]; - for ( uint i = 0; i < indices.Length; i++ ) - { - IndexArray[i] = indices[i]; - } - } - } -} diff --git a/Source/Examples/Shapes/KochTetrahedron.cs b/Source/Examples/Shapes/KochTetrahedron.cs deleted file mode 100644 index 8d3f2fab..00000000 --- a/Source/Examples/Shapes/KochTetrahedron.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Examples.Shapes -{ - public sealed class KochTetrahedron: DrawableShape - { - - public enum eSubdivisions - { - Zero = 0, - One = 1, - Two = 2, - Three = 3, - Four = 4, - Five=5, - Six=6, - Seven=7, - Eight=8, - } - - public KochTetrahedron( double scale, double extrusionHeight, double extrusionMultiplier, eSubdivisions subdivs, bool useDL ) - : base( useDL ) - { - TetrahedronFace[] Triangles; - - switch ( subdivs ) - { - case eSubdivisions.Zero: - SierpinskiTetrahedron.CreateDefaultTetrahedron( scale, out Triangles ); - break; - case eSubdivisions.One: - case eSubdivisions.Two: - case eSubdivisions.Three: - case eSubdivisions.Four: - case eSubdivisions.Five: - case eSubdivisions.Six: - case eSubdivisions.Seven: - case eSubdivisions.Eight: - SierpinskiTetrahedron.CreateDefaultTetrahedron( scale, out Triangles ); - for ( int i = 0; i < (int)subdivs; i++ ) - { - TetrahedronFace[] temp; - this.SubdivideKoch( extrusionHeight, ref Triangles, out temp ); - Triangles = temp; - extrusionHeight *= extrusionMultiplier; - } - break; - default: throw new ArgumentOutOfRangeException( "Subdivisions other than contained in the enum cause overflows and are not allowed." ); - - } - - PrimitiveMode = OpenTK.Graphics.OpenGL.PrimitiveType.Triangles; - SierpinskiTetrahedron.GetVertexArray( ref Triangles, out VertexArray ); - IndexArray = null; - } - - private void SubdivideKoch( double height, ref TetrahedronFace[] input, out TetrahedronFace[] output ) - { - output = new TetrahedronFace[input.Length * 6]; - - int counter = 0; - for ( int i = 0; i < input.Length; i++ ) - { - input[i].SubdivideKoch(height, out output[counter + 0], out output[counter + 1], out output[counter + 2], out output[counter + 3], out output[counter + 4], out output[counter + 5] ); - counter += 6; // every source triangle emits 6 new triangles - } - - } - } -} diff --git a/Source/Examples/Shapes/MengerSponge.cs b/Source/Examples/Shapes/MengerSponge.cs deleted file mode 100644 index dd78af82..00000000 --- a/Source/Examples/Shapes/MengerSponge.cs +++ /dev/null @@ -1,116 +0,0 @@ -using System; -using System.Collections.Generic; - -using OpenTK; - -namespace Examples.Shapes -{ - public sealed partial class MengerSponge: DrawableShape - { - - public enum eSubdivisions - { - None = 0, - One = 1, - Two = 2, - Three = 3, - } - - public MengerSponge( double scale, eSubdivisions subdivs, bool useDL ) - : base( useDL ) - { - List Cubes; - switch ( subdivs ) - { - case eSubdivisions.None: - CreateDefaultMengerSponge( scale, out Cubes ); - break; - case eSubdivisions.One: - case eSubdivisions.Two: - case eSubdivisions.Three: - CreateDefaultMengerSponge( scale, out Cubes ); - for ( int i = 0; i < (int)subdivs; i++ ) - { - List temp; - SubdivideMengerSponge( ref Cubes, out temp ); - Cubes = temp; - } - break; - default: throw new ArgumentOutOfRangeException( "Subdivisions other than contained in the enum cause overflows and are not allowed." ); - } - - PrimitiveMode = OpenTK.Graphics.OpenGL.PrimitiveType.Triangles; - - #region Get Array Dimensions - uint - VertexCount = 0, - IndexCount = 0; - - foreach ( MengerCube c in Cubes ) - { - uint t1, t2; - c.GetArraySizes( out t1, out t2 ); - VertexCount += t1; - IndexCount += t2; - } - - VertexArray = new VertexT2dN3dV3d[VertexCount]; - IndexArray = new uint[IndexCount]; - #endregion Get Array Dimensions - - List AllChunks = new List(); - - #region Build a temporary List of all loose pieces - foreach ( MengerCube c in Cubes ) - { - c.GetVboAndIbo( ref AllChunks ); - } - #endregion Build a temporary List of all loose pieces - - #region Assemble pieces into a single VBO and IBO - VertexCount = 0; - IndexCount = 0; - - foreach ( Chunk ch in AllChunks ) - { - for ( int i = 0; i < ch.Vertices.Length; i++ ) - { - VertexArray[VertexCount + i] = ch.Vertices[i]; - } - - for ( int i = 0; i < ch.Indices.Length; i++ ) - { - IndexArray[IndexCount + i] = ch.Indices[i] + VertexCount; - } - - VertexCount += (uint)ch.Vertices.Length; - IndexCount += (uint)ch.Indices.Length; - } - - #endregion Assemble pieces into a single VBO and IBO - - AllChunks.Clear(); - } - - private void CreateDefaultMengerSponge( double halfwidth, out List output ) - { - output = new List( 1 ); - output.Add( new MengerCube( Vector3d.Zero, halfwidth, MengerCube.AllSides, MengerCube.AllSides ) ); - } - - private void SubdivideMengerSponge( ref List input, out List output ) - { - output = new List( input.Count * 20 ); - foreach ( MengerCube InputCube in input ) - { - MengerCube[] SubdividedCubes; - InputCube.Subdivide( out SubdividedCubes ); - for ( int i = 0; i < SubdividedCubes.Length; i++ ) - { - output.Add( SubdividedCubes[i] ); - } - } - } - - } -} diff --git a/Source/Examples/Shapes/Old/Cube.cs b/Source/Examples/Shapes/Old/Cube.cs deleted file mode 100644 index a77f888f..00000000 --- a/Source/Examples/Shapes/Old/Cube.cs +++ /dev/null @@ -1,75 +0,0 @@ -#region --- License --- -/* Copyright (c) 2006, 2007 Stefanos Apostolopoulos - * See license.txt for license info - */ -#endregion - -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; - -using System.Runtime.InteropServices; - -using OpenTK; - -namespace Examples.Shapes -{ - public class Cube : Shape - { - public Cube() - { - Vertices = new Vector3[] - { - new Vector3(-1.0f, -1.0f, 1.0f), - new Vector3( 1.0f, -1.0f, 1.0f), - new Vector3( 1.0f, 1.0f, 1.0f), - new Vector3(-1.0f, 1.0f, 1.0f), - new Vector3(-1.0f, -1.0f, -1.0f), - new Vector3( 1.0f, -1.0f, -1.0f), - new Vector3( 1.0f, 1.0f, -1.0f), - new Vector3(-1.0f, 1.0f, -1.0f) - }; - - Indices = new int[] - { - // front face - 0, 1, 2, 2, 3, 0, - // top face - 3, 2, 6, 6, 7, 3, - // back face - 7, 6, 5, 5, 4, 7, - // left face - 4, 0, 3, 3, 7, 4, - // bottom face - 0, 1, 5, 5, 4, 0, - // right face - 1, 5, 6, 6, 2, 1, - }; - - Normals = new Vector3[] - { - new Vector3(-1.0f, -1.0f, 1.0f), - new Vector3( 1.0f, -1.0f, 1.0f), - new Vector3( 1.0f, 1.0f, 1.0f), - new Vector3(-1.0f, 1.0f, 1.0f), - new Vector3(-1.0f, -1.0f, -1.0f), - new Vector3( 1.0f, -1.0f, -1.0f), - new Vector3( 1.0f, 1.0f, -1.0f), - new Vector3(-1.0f, 1.0f, -1.0f), - }; - - Colors = new int[] - { - Utilities.ColorToRgba32(Color.DarkRed), - Utilities.ColorToRgba32(Color.DarkRed), - Utilities.ColorToRgba32(Color.Gold), - Utilities.ColorToRgba32(Color.Gold), - Utilities.ColorToRgba32(Color.DarkRed), - Utilities.ColorToRgba32(Color.DarkRed), - Utilities.ColorToRgba32(Color.Gold), - Utilities.ColorToRgba32(Color.Gold), - }; - } - } -} diff --git a/Source/Examples/Shapes/Old/IsoSphere.cs b/Source/Examples/Shapes/Old/IsoSphere.cs deleted file mode 100644 index 8372af88..00000000 --- a/Source/Examples/Shapes/Old/IsoSphere.cs +++ /dev/null @@ -1,54 +0,0 @@ -#region --- License --- -/* Copyright (c) 2006, 2007 Stefanos Apostolopoulos - * See license.txt for license info - */ -#endregion - -using System; -using System.Collections.Generic; -using System.Text; - -using OpenTK; - -namespace Examples.Shapes -{ - class IsoSphere : Shape - { - const double DoublePI = System.Math.PI * 2.0; - - public IsoSphere(int s_steps, int t_steps, float x_scale, float y_scale, float z_scale) - { - int count = 4 * s_steps * t_steps ; - - Vertices = new Vector3[count]; - Normals = new Vector3[count]; - Texcoords = new Vector2[count]; - Indices = new int[6 * count / 4]; - - int i = 0; - for (double t = -System.Math.PI; (float)t < (float)System.Math.PI - Single.Epsilon; t += System.Math.PI / (double)t_steps) - { - for (double s = 0.0; (float)s < (float)DoublePI; s += System.Math.PI / (double)s_steps) - { - Vertices[i].X = x_scale * (float)(System.Math.Cos(s) * System.Math.Sin(t)); - Vertices[i].Y = y_scale * (float)(System.Math.Sin(s) * System.Math.Sin(t)); - Vertices[i].Z = z_scale * (float)System.Math.Cos(t); - //vertices[i] = vertices[i].Scale(x_scale, y_scale, z_scale); - Normals[i] = Vector3.Normalize(Vertices[i]); - - ++i; - } - } - - for (i = 0; i < 6*count/4; i+=6) - { - Indices[i] = i; - Indices[i + 1] = i + 1; - Indices[i + 2] = i + 2 * s_steps + 1; - Indices[i + 3] = i + 2 * s_steps; - Indices[i + 4] = i; - Indices[i + 5] = i + 2 * s_steps + 1; - } - } - } -} diff --git a/Source/Examples/Shapes/Old/Plane.cs b/Source/Examples/Shapes/Old/Plane.cs deleted file mode 100644 index 633bcb0e..00000000 --- a/Source/Examples/Shapes/Old/Plane.cs +++ /dev/null @@ -1,54 +0,0 @@ -#region --- License --- -/* Copyright (c) 2006, 2007 Stefanos Apostolopoulos - * See license.txt for license info - */ -#endregion - -using System; -using System.Collections.Generic; -using System.Text; - -using OpenTK; - -namespace Examples.Shapes -{ - public class Plane : Shape - { - public Plane(int x_res, int y_res, float x_scale, float y_scale) - { - Vertices = new Vector3[x_res * y_res]; - Normals = new Vector3[x_res * y_res]; - Indices = new int[6 * x_res * y_res]; - Texcoords = new Vector2[x_res * y_res]; - - int i = 0; - for (int y = -y_res / 2; y < y_res / 2; y++) - { - for (int x = -x_res / 2; x < x_res / 2; x++) - { - Vertices[i].X = x_scale * (float)x / (float)x_res; - Vertices[i].Y = y_scale * (float)y / (float)y_res; - Vertices[i].Z = 0; - Normals[i].X = Normals[i].Y = 0; - Normals[i].Z = 1; - i++; - } - } - - i = 0; - for (int y = 0; y < y_res - 1; y++) - { - for (int x = 0; x < x_res - 1; x++) - { - Indices[i++] = (y + 0) * x_res + x; - Indices[i++] = (y + 1) * x_res + x; - Indices[i++] = (y + 0) * x_res + x + 1; - - Indices[i++] = (y + 0) * x_res + x + 1; - Indices[i++] = (y + 1) * x_res + x; - Indices[i++] = (y + 1) * x_res + x + 1; - } - } - } - } -} diff --git a/Source/Examples/Shapes/Old/Shape.cs b/Source/Examples/Shapes/Old/Shape.cs deleted file mode 100644 index faa7d2b7..00000000 --- a/Source/Examples/Shapes/Old/Shape.cs +++ /dev/null @@ -1,70 +0,0 @@ -#region --- License --- -/* Copyright (c) 2006, 2007 Stefanos Apostolopoulos - * See license.txt for license info - */ -#endregion - -using System; -using System.Collections.Generic; -using System.Text; - -using System.Runtime.InteropServices; -using System.Drawing; - -using OpenTK; - -namespace Examples.Shapes -{ - public abstract class Shape - { - private Vector3[] vertices, normals; - private Vector2[] texcoords; - private int[] indices; - private int[] colors; - - public Vector3[] Vertices - { - get { return vertices; } - protected set - { - vertices = value; - } - } - - public Vector3[] Normals - { - get { return normals; } - protected set - { - normals = value; - } - } - - public Vector2[] Texcoords - { - get { return texcoords; } - protected set - { - texcoords = value; - } - } - - public int[] Indices - { - get { return indices; } - protected set - { - indices = value; - } - } - - public int[] Colors - { - get { return colors; } - protected set - { - colors = value; - } - } - } -} diff --git a/Source/Examples/Shapes/Old/SierpinskiTetrahedron.cs b/Source/Examples/Shapes/Old/SierpinskiTetrahedron.cs deleted file mode 100644 index 22f59cfe..00000000 --- a/Source/Examples/Shapes/Old/SierpinskiTetrahedron.cs +++ /dev/null @@ -1,173 +0,0 @@ -using System; -using System.Diagnostics; - -using OpenTK; - -namespace Examples.Shapes -{ - public sealed partial class SierpinskiTetrahedron: DrawableShape - { - - public enum eSubdivisions - { - /// Creates a Sierpinski Tetrahedron using 4 triangles. - Zero = 0, - /// Creates a Sierpinski Tetrahedron using 16 triangles. - One = 1, - /// Creates a Sierpinski Tetrahedron using 64 triangles. - Two = 2, - /// Creates a Sierpinski Tetrahedron using 256 triangles. - Three = 3, - /// Creates a Sierpinski Tetrahedron using 1024 triangles. - Four = 4, - /// Creates a Sierpinski Tetrahedron using 4096 triangles. - Five = 5, - /// Creates a Sierpinski Tetrahedron using 16384 triangles. - Six = 6, - /// Creates a Sierpinski Tetrahedron using 65536 triangles. - Seven = 7, - /// Creates a Sierpinski Tetrahedron using 262144 triangles. - Eight = 8, - /// Creates a Sierpinski Tetrahedron using 1048576 triangles. - Nine = 9, - } - - /// Creates a Sierpinski Tetrahedron which is centered at (0,0,0) and fits into a sphere of radius 1f, or a diameter of 2f - /// Default: 1f. - /// The number of subdivisions of the Tetrahedron. - /// - public SierpinskiTetrahedron( double scale, eSubdivisions subdivs, bool useDL ) - : base( useDL ) - { - TetrahedronFace[] Triangles; - - switch ( subdivs ) - { - case eSubdivisions.Zero: - CreateDefaultTetrahedron( scale, out Triangles ); - break; - case eSubdivisions.One: - case eSubdivisions.Two: - case eSubdivisions.Three: - case eSubdivisions.Four: - case eSubdivisions.Five: - case eSubdivisions.Six: - case eSubdivisions.Seven: - case eSubdivisions.Eight: - case eSubdivisions.Nine: - CreateDefaultTetrahedron( scale, out Triangles ); - for ( int i = 0; i < (int)subdivs; i++ ) - { - TetrahedronFace[] temp; - SubdivideTetrahedron( ref Triangles, out temp ); - Triangles = temp; - } - break; - default: throw new ArgumentOutOfRangeException( "Subdivisions other than contained in the enum cause overflows and are not allowed." ); - } - - PrimitiveMode = OpenTK.Graphics.OpenGL.PrimitiveType.Triangles; - SierpinskiTetrahedron.GetVertexArray( ref Triangles, out VertexArray ); - IndexArray = null; - } - - internal static void GetVertexArray( ref TetrahedronFace[] input, out VertexT2dN3dV3d[] output ) - { - output = new VertexT2dN3dV3d[input.Length * 3]; - int counter = 0; - for ( int i = 0; i < input.Length; i++ ) - { - input[i].GetVertices( out output[counter + 0], out output[counter + 1], out output[counter + 2] ); - counter += 3; - } - } - - /// Generates the lowest subdivision mesh, which consists of 4 Triangles. - internal static void CreateDefaultTetrahedron( double scale, out TetrahedronFace[] array ) - { - Vector3d[] Points = new Vector3d[4]; - Points[0] = new Vector3d( 0.0 * scale, 0.0 * scale, 1.0 * scale ); - Points[1] = new Vector3d( -0.816 * scale, 0.471 * scale, -0.333 * scale ); - Points[2] = new Vector3d( 0.816 * scale, 0.471 * scale, -0.333 * scale ); - Points[3] = new Vector3d( 0.0 * scale, -0.943 * scale, -0.333 * scale ); - - Vector2d[] TexCoords = new Vector2d[4]; - TexCoords[0] = new Vector2d( 0.0, 0.0 ); - TexCoords[1] = new Vector2d( 1.0, 0.0 ); - TexCoords[2] = new Vector2d( 0.0, 1.0 ); - TexCoords[3] = new Vector2d( 1.0, 1.0 ); - - Vector3d Normal; - array = new TetrahedronFace[4]; - - FindNormal( ref Points[0], ref Points[2], ref Points[1], ref Points[3], out Normal ); - array[0] = new TetrahedronFace( ref Points[0], ref TexCoords[2], - ref Points[2], ref TexCoords[0], - ref Points[1], ref TexCoords[1], - ref Points[3], - ref Normal ); - - FindNormal( ref Points[0], ref Points[3], ref Points[2], ref Points[1], out Normal ); - array[1] = new TetrahedronFace( ref Points[0], ref TexCoords[0], - ref Points[3], ref TexCoords[1], - ref Points[2], ref TexCoords[2], - ref Points[1], - ref Normal ); - - FindNormal( ref Points[0], ref Points[1], ref Points[3], ref Points[2], out Normal ); - array[2] = new TetrahedronFace( ref Points[0], ref TexCoords[2], - ref Points[1], ref TexCoords[1], - ref Points[3], ref TexCoords[3], - ref Points[2], - ref Normal ); - - FindNormal( ref Points[1], ref Points[2], ref Points[3], ref Points[0], out Normal ); - array[3] = new TetrahedronFace( ref Points[1], ref TexCoords[3], - ref Points[2], ref TexCoords[2], - ref Points[3], ref TexCoords[1], - ref Points[0], - ref Normal ); - } - - /// Subdivides each triangle into 4 new ones. - private void SubdivideTetrahedron( ref TetrahedronFace[] source, out TetrahedronFace[] output ) - { - - output = new TetrahedronFace[source.Length * 4]; - - int counter = 0; - for ( int i = 0; i < source.Length; i++ ) - { - source[i].SubdivideSierpinski( out output[counter + 0], out output[counter + 1], out output[counter + 2], out output[counter + 3] ); - counter += 4; // every source triangle emits 4 new triangles - } - } - - /// A, B and C are the triangle whos normal is to be determined. D is the 4th Point in the Tetraeder which does not belong to the triangle. - internal static void FindNormal( ref Vector3d A, ref Vector3d B, ref Vector3d C, ref Vector3d D, out Vector3d result ) - { - Vector3d temp1, temp2, temp3; - - Vector3d.Subtract( ref A, ref D, out temp1 ); - Vector3d.Subtract( ref B, ref D, out temp2 ); - Vector3d.Subtract( ref C, ref D, out temp3 ); - - Vector3d.Add( ref temp1, ref temp2, out result ); - Vector3d.Add(ref result, ref temp3, out result); - result.Normalize(); - } - - internal static void FindNormal( ref Vector3d A, ref Vector3d B, ref Vector3d C, out Vector3d result ) - { - Vector3d temp1, temp2; - Vector3d.Subtract( ref A, ref B, out temp1 ); - temp1.Normalize(); - Vector3d.Subtract(ref C, ref B, out temp2); - temp2.Normalize(); - Vector3d.Cross( ref temp1, ref temp2, out result ); - result *= -1.0; - result.Normalize(); - } - - } -} diff --git a/Source/Examples/Shapes/SlicedHose.cs b/Source/Examples/Shapes/SlicedHose.cs deleted file mode 100644 index a27ab67b..00000000 --- a/Source/Examples/Shapes/SlicedHose.cs +++ /dev/null @@ -1,194 +0,0 @@ -using System; -using System.Collections.Generic; -using OpenTK; - -namespace Examples.Shapes -{ - public sealed class SlicedHose : DrawableShape - { - - public enum eSide:byte - { - // Around X Axis - BottomRight, - TopRight, - TopLeft, - BottomLeft, - - // Around Y Axis - - FrontRight, - BackRight, - BackLeft, - FrontLeft, - - // Around Z Axis - FrontBottom, - BackBottom, - BackTop, - FrontTop, - } - - public SlicedHose( eSide side, uint subdivs, double scale, Vector3d offset1, Vector3d offset2, bool useDL ) - : base( useDL ) - { - PrimitiveMode = OpenTK.Graphics.OpenGL.PrimitiveType.Triangles; - - Vector3d start = Vector3d.Zero, - end = Vector3d.Zero; - double TexCoordStart=0f, TexCoordEnd=0f; - - switch ( side ) - { - #region Around X Axis - case eSide.BottomRight: - start = -Vector3d.UnitY; - end = Vector3d.UnitZ; - TexCoordStart = 0.0; - TexCoordEnd = 0.25; - break; - case eSide.TopRight: - start = Vector3d.UnitZ; - end = Vector3d.UnitY; - TexCoordStart = 0.25; - TexCoordEnd = 0.5; - break; - case eSide.TopLeft: - start = Vector3d.UnitY; - end = -Vector3d.UnitZ; - TexCoordStart = 0.5; - TexCoordEnd = 0.75; - break; - case eSide.BottomLeft: - start = -Vector3d.UnitZ; - end = -Vector3d.UnitY; - TexCoordStart = 0.75; - TexCoordEnd = 1.0; - break; - #endregion Around X Axis - #region Around Y Axis - case eSide.FrontRight: - start = Vector3d.UnitX; - end = Vector3d.UnitZ; - TexCoordStart = 0.0; - TexCoordEnd = 0.25; - break; - case eSide.BackRight: - start = Vector3d.UnitZ; - end = -Vector3d.UnitX; - TexCoordStart = 0.25; - TexCoordEnd = 0.5; - break; - case eSide.BackLeft: - start = -Vector3d.UnitX; - end = -Vector3d.UnitZ; - TexCoordStart = 0.5; - TexCoordEnd = 0.75; - break; - case eSide.FrontLeft: - start = -Vector3d.UnitZ; - end = Vector3d.UnitX; - TexCoordStart = 0.75; - TexCoordEnd = 1.0; - break; -#endregion Around Y Axis - #region Around Z Axis - case eSide.FrontBottom: - start = -Vector3d.UnitY; - end = Vector3d.UnitX; - TexCoordStart = 0.0; - TexCoordEnd = 0.25; - break; - case eSide.BackBottom: - start = -Vector3d.UnitX; - end = -Vector3d.UnitY; - TexCoordStart = 0.25; - TexCoordEnd = 0.5; - break; - case eSide.BackTop: - start = Vector3d.UnitY; - end = -Vector3d.UnitX; - TexCoordStart = 0.5; - TexCoordEnd = 0.75; - break; - case eSide.FrontTop: - start = Vector3d.UnitX; - end = Vector3d.UnitY; - TexCoordStart = 0.75; - TexCoordEnd = 1.0; - break; -#endregion Around Z Axis - - } - - VertexT2dN3dV3d[] temp = new VertexT2dN3dV3d[2 + subdivs]; - - double divisor = 1.0/ ((double)temp.Length-1.0); - for ( int i = 0; i < temp.Length; i++ ) - { - float Multiplier = (float)( i * divisor ); - - temp[i].TexCoord.X = TexCoordStart * Multiplier + TexCoordEnd * ( 1.0f- Multiplier); - - Slerp( ref start, ref end, Multiplier, out temp[i].Normal ); - temp[i].Normal.Normalize(); - temp[i].Position = temp[i].Normal; - temp[i].Position *= scale; - } - - VertexArray = new VertexT2dN3dV3d[temp.Length * 2]; - IndexArray = new uint[( temp.Length - 1 ) * 2 * 3]; - - uint VertexCounter = 0, - IndexCounter = 0, - QuadCounter = 0; - - for ( int i = 0; i < temp.Length; i++ ) - { - VertexArray[VertexCounter + 0].TexCoord.X = temp[i].TexCoord.X; - VertexArray[VertexCounter + 0].TexCoord.Y = 0.0; - VertexArray[VertexCounter + 0].Normal = temp[i].Normal; - VertexArray[VertexCounter + 0].Position = temp[i].Position + offset1; - - - VertexArray[VertexCounter + 1].TexCoord.X = temp[i].TexCoord.X; - VertexArray[VertexCounter + 1].TexCoord.Y = 1.0; - VertexArray[VertexCounter + 1].Normal = temp[i].Normal; - VertexArray[VertexCounter + 1].Position = temp[i].Position + offset2; - VertexCounter += 2; - - if ( i < temp.Length - 1 ) - { - IndexArray[IndexCounter + 0] = QuadCounter + 0; - IndexArray[IndexCounter + 1] = QuadCounter + 1; - IndexArray[IndexCounter + 2] = QuadCounter + 2; - - IndexArray[IndexCounter + 3] = QuadCounter + 2; - IndexArray[IndexCounter + 4] = QuadCounter + 1; - IndexArray[IndexCounter + 5] = QuadCounter + 3; - - IndexCounter += 6; - QuadCounter += 2; - } - } - - } - - private void Slerp( ref Vector3d a, ref Vector3d b, double factor, out Vector3d result) - { - double t1; - Vector3d.Dot( ref a, ref b, out t1 ); - double theta = System.Math.Acos( t1 ); - - double temp = 1.0 / System.Math.Sin( theta ); - double t2 = System.Math.Sin( ( 1.0 - factor ) * theta ) * temp; - double t3 = System.Math.Sin( factor * theta ) * temp; - - Vector3d v1 = Vector3d.Multiply( a, t2); - Vector3d v2 = Vector3d.Multiply( b, t3 ); - result = Vector3d.Add( v1, v2 ); - } - - - } -} diff --git a/Source/Examples/Shapes/SlicedSphere.cs b/Source/Examples/Shapes/SlicedSphere.cs deleted file mode 100644 index 818d981c..00000000 --- a/Source/Examples/Shapes/SlicedSphere.cs +++ /dev/null @@ -1,196 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -using OpenTK; - -namespace Examples.Shapes -{ - public sealed class SlicedSphere: DrawableShape - { - public enum eSubdivisions - { - Zero = 0, - One = 1, - Two = 2, - Three = 3, - Four = 4, - Five=5, - Six=6, - Seven=7, - Eight=8, - } - - public enum eDir - { - All, - FrontTopRight, - FrontBottomRight, - FrontBottomLeft, - FrontTopLeft, - BackTopRight, - BackBottomRight, - BackBottomLeft, - BackTopLeft, - - } - - public SlicedSphere( double radius, Vector3d offset, eSubdivisions subdivs, eDir[] sides, bool useDL ) - : base( useDL ) - { - double Diameter = radius; - - PrimitiveMode = OpenTK.Graphics.OpenGL.PrimitiveType.Triangles; - - if ( sides[0] == eDir.All ) - { - sides = new eDir[] { eDir.FrontTopRight, - eDir.FrontBottomRight, - eDir.FrontBottomLeft, - eDir.FrontTopLeft, - eDir.BackTopRight, - eDir.BackBottomRight, - eDir.BackBottomLeft, - eDir.BackTopLeft,}; - } - - VertexArray = new VertexT2dN3dV3d[sides.Length * 3]; - IndexArray = new uint[sides.Length * 3]; - - uint counter = 0; - foreach ( eDir s in sides ) - { - GetDefaultVertices( s, Diameter, out VertexArray[counter + 0], out VertexArray[counter + 1], out VertexArray[counter + 2] ); - IndexArray[counter + 0] = counter + 0; - IndexArray[counter + 1] = counter + 1; - IndexArray[counter + 2] = counter + 2; - counter += 3; - } - - if ( subdivs != eSubdivisions.Zero ) - { - - for ( int s = 0; s < (int)subdivs; s++ ) - { - #region Assemble Chunks and convert to Arrays - List AllChunks = new List(); - for ( uint i = 0; i < IndexArray.Length; i += 3 ) - { - Chunk chu; - Subdivide( Diameter, - ref VertexArray[IndexArray[i + 0]], - ref VertexArray[IndexArray[i + 1]], - ref VertexArray[IndexArray[i + 2]], - out chu ); - AllChunks.Add( chu ); - } - - Chunk.GetArray( ref AllChunks, out VertexArray, out IndexArray ); - AllChunks.Clear(); - #endregion Assemble Chunks and convert to Arrays - } - } - - for (int i=0; i= MINPathSteps, "A Path must have at least " + MINPathSteps + " Steps to form a volume." ); - Trace.Assert( shapevertices >= MINShapeVertices, "A Shape must contain at least " + MINShapeVertices + " Vertices to be considered valid and create a volume." ); - Trace.Assert( TexCount >= 1, "at least 1 Texture set is required." ); - - PrimitiveMode = OpenTK.Graphics.OpenGL.PrimitiveType.TriangleStrip; - - Vector3d[] PathPositions = new Vector3d[pathsteps]; - - #region Find the center Points for each step on the path - - for ( int i = 0; i < pathsteps; i++ ) - { - double Angle = ( i / (double)pathsteps ) * TwoPi; - double AngleTimesP = Angle * p; - double AngleTimesQ = Angle * q; - double r = ( 0.5 * ( 2.0 + System.Math.Sin( AngleTimesQ ) ) ); - - PathPositions[i] = new Vector3d( ( r * System.Math.Cos( AngleTimesP ) ), - ( r * System.Math.Cos( AngleTimesQ ) ), - ( r * System.Math.Sin( AngleTimesP ) ) ); - - } - #endregion Find the center Points for each step on the path - - #region Find the Torus length - Vector3d result; - double[] Lengths = new double[pathsteps]; - Vector3d.Subtract( ref PathPositions[pathsteps - 1], ref PathPositions[0], out result ); - Lengths[0] = result.Length; - double TotalLength = result.Length; - for ( int i = 1; i < pathsteps; i++ ) // skipping - { - Vector3d.Subtract( ref PathPositions[i - 1], ref PathPositions[i], out result ); - Lengths[i] = result.Length; - TotalLength += result.Length; - } - Trace.WriteLine( "the TorusKnot's length is: " + TotalLength + " " ); - #endregion Find the Torus length - - VertexArray = new VertexT2dN3dV3d[pathsteps * shapevertices]; - - #region Loft a circle Shape along the path - double TwoPiThroughVert = TwoPi / shapevertices; // precalc for reuse - for ( uint i = 0; i < pathsteps; i++ ) - { - Vector3d last, next, normal, tangent; - if ( i == pathsteps - 1 ) - next = PathPositions[0]; - else - next = PathPositions[i + 1]; - if ( i == 0 ) - last = PathPositions[pathsteps - 1]; - else - last = PathPositions[i - 1]; - - Vector3d.Subtract( ref next, ref last, out tangent ); // Guesstimate tangent - tangent.Normalize(); - - Vector3d.Add( ref next, ref last, out normal ); // Approximate N - normal.Normalize(); - Vector3d.Multiply( ref normal, radius, out normal );// scale the shape to desired radius - - for ( uint j = 0; j < shapevertices; j++ ) - { - uint index = i * (uint)shapevertices + j; - - // Create a point on the plane and rotate it - Matrix4d RotationMatrix = Matrix4d.Rotate( tangent, -( j * TwoPiThroughVert ) ); - Vector3d point = Vector3d.TransformVector( normal, RotationMatrix ); - Vector3d.Add( ref PathPositions[i], ref point, out VertexArray[index].Position ); - // Since the used shape is a circle, the Vertex normal's heading is easy to find - Vector3d.Subtract( ref VertexArray[index].Position, ref PathPositions[i], out VertexArray[index].Normal ); - VertexArray[index].Normal.Normalize(); - // just generate some semi-useful UVs to fill blanks - VertexArray[index].TexCoord = new Vector2d( (double)( i / TotalLength/ TexCount ), j / ( shapevertices - 1.0 ) ); - } - } - #endregion Loft a circle Shape along the path - - PathPositions = null; // not needed anymore - - uint currentindex = 0; - - #region Build a Triangle strip from the Vertices - IndexArray = new uint[pathsteps * ( shapevertices * 2 + 2 )]; // 2 triangles per vertex, +2 due to added degenerate triangles - for ( uint i = 0; i < pathsteps; i++ ) - { - uint RowCurrent = i * (uint)shapevertices; - uint RowBelow; - if ( i == pathsteps - 1 ) - RowBelow = 0; // for the last row, the first row is the following - else - RowBelow = ( i + 1 ) * (uint)shapevertices; - - // new ring begins here - for ( uint j = 0; j < shapevertices; j++ ) - { - IndexArray[currentindex++] = RowCurrent + j; - IndexArray[currentindex++] = RowBelow + j; - } - // ring ends here, repeat first 2 vertices to insert 2 degenerate triangles to reach following ring - IndexArray[currentindex++] = RowCurrent; - IndexArray[currentindex++] = RowBelow; - } - #endregion Build a Triangle strip from the Vertices - } - - } -} diff --git a/Source/Examples/Shapes/VertexPositionColor.cs b/Source/Examples/Shapes/VertexPositionColor.cs deleted file mode 100644 index 7ad5df57..00000000 --- a/Source/Examples/Shapes/VertexPositionColor.cs +++ /dev/null @@ -1,51 +0,0 @@ -#region License -// -// The Open Toolkit Library License -// -// Copyright (c) 2006 - 2010 the Open Toolkit library, except where noted. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -// the Software, and to permit persons to whom the Software is furnished to do -// so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// -#endregion - -using System.Drawing; -using System.Runtime.InteropServices; -using OpenTK; - -namespace Examples.Tutorial -{ - [StructLayout(LayoutKind.Sequential, Pack = 1)] - struct VertexPositionColor - { - public Vector3 Position; - public uint Color; - - public VertexPositionColor(float x, float y, float z, Color color) - { - Position = new Vector3(x, y, z); - Color = ToRgba(color); - } - - static uint ToRgba(Color color) - { - return (uint)color.A << 24 | (uint)color.B << 16 | (uint)color.G << 8 | (uint)color.R; - } - } -} diff --git a/Source/Examples/TextBoxTraceListener.cs b/Source/Examples/TextBoxTraceListener.cs deleted file mode 100644 index bd4cad21..00000000 --- a/Source/Examples/TextBoxTraceListener.cs +++ /dev/null @@ -1,71 +0,0 @@ -#region License -// -// The Open Toolkit Library License -// -// Copyright (c) 2006 - 2009 the Open Toolkit library. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -// the Software, and to permit persons to whom the Software is furnished to do -// so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// -#endregion - -using System; -using System.Collections.Generic; -using System.Text; -using System.Diagnostics; -using System.Windows.Forms; -using System.Threading; - -namespace Examples -{ - public class TextBoxTraceListener : TraceListener - { - TextBox _target; - StringSendDelegate _invokeWrite; - - public TextBoxTraceListener(TextBox target) - { - _target = target; - _invokeWrite = new StringSendDelegate(SendString); - } - - public override void Write(string message) - { - if (_target.Created) - _target.BeginInvoke(_invokeWrite, new object[] { message }); - } - - public override void WriteLine(string message) - { - if (_target.Created) - _target.BeginInvoke(_invokeWrite, new object[] { message + Environment.NewLine }); - } - - private delegate void StringSendDelegate(string message); - private void SendString(string message) - { - if (_target.Created) - { - // No need to lock text box as this function will only - // ever be executed from the UI thread - _target.Text += message; - } - } - } -} diff --git a/Source/Examples/Utilities.cs b/Source/Examples/Utilities.cs deleted file mode 100644 index 83e64fbd..00000000 --- a/Source/Examples/Utilities.cs +++ /dev/null @@ -1,64 +0,0 @@ -#region --- License --- -/* Licensed under the MIT/X11 license. - * Copyright (c) 2006-2008 the OpenTK Team. - * This notice may not be removed from any source distribution. - * See license.txt for licensing details. - */ -#endregion - -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; - -using OpenTK; -using OpenTK.Input; - -namespace Examples -{ - public static class Utilities - { - /// - /// Converts a System.Drawing.Color to a System.Int32. - /// - /// The System.Drawing.Color to convert. - /// A System.Int32 containing the R, G, B, A values of the - /// given System.Drawing.Color in the Rbga32 format. - public static int ColorToRgba32(Color c) - { - return (int)((c.A << 24) | (c.B << 16) | (c.G << 8) | c.R); - } - - /// - /// Sets the window title to the name of the sample. - /// - /// - public static void SetWindowTitle(GameWindow window) - { - ExampleAttribute info = GetExampleAttribute(window.GetType()); - window.Title = String.Format("OpenTK | {0} {1}: {2}", info.Category, info.Difficulty, info.Title); - window.Icon = OpenTK.Examples.Properties.Resources.Game; - } - - /// - /// Sets the window title to the name of the sample. - /// - /// - public static void SetWindowTitle(System.Windows.Forms.Form window) - { - ExampleAttribute info = GetExampleAttribute(window.GetType()); - window.Text = String.Format("OpenTK | {0} {1}: {2}", info.Category, info.Difficulty, info.Title); - window.Icon = OpenTK.Examples.Properties.Resources.Game; - } - - static ExampleAttribute GetExampleAttribute(Type type) - { - object[] attributes = type.GetCustomAttributes(false); - foreach (object attr in attributes) - if (attr is ExampleAttribute) - return attr as ExampleAttribute; - - return null; - } - } -} diff --git a/Source/Examples/Utilities/LoaderDDS.cs b/Source/Examples/Utilities/LoaderDDS.cs deleted file mode 100644 index 2840ca84..00000000 --- a/Source/Examples/Utilities/LoaderDDS.cs +++ /dev/null @@ -1,711 +0,0 @@ -#region --- License --- -/* Licensed under the MIT/X11 license. - * Copyright (c) 2006-2008 the OpenTK Team. - * This notice may not be removed from any source distribution. - * See license.txt for licensing details. - */ -#endregion - -// #define READALL -// uncomment so ALL fields read from file are interpreted and filled. Necessary to implement uncompressed DDS - -// TODO: Find app that can build compressed dds cubemaps and verify that the import code works. - -using System; -using System.IO; -using System.Diagnostics; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; - -namespace Examples.TextureLoaders -{ - /// - /// Expects the presence of a valid OpenGL Context and Texture Compression Extensions (GL 1.5) and Cube Maps (GL 1.3). - /// You will get what you give. No automatic Mipmap generation or automatic compression is done. (both bad quality) - /// Textures are never rescaled or checked if Power of 2, but you should make the Width and Height a multiple of 4 because DXTn uses 4x4 blocks. - /// (Image displays correctly but runs extremely slow with non-power-of-two Textures on FX5600, Cache misses?) - /// CubeMap support is experimental and the file must specify all 6 faces to work at all. - /// - static class ImageDDS - { - #region Constants - private const byte HeaderSizeInBytes = 128; // all non-image data together is 128 Bytes - private const uint BitMask = 0x00000007; // bits = 00 00 01 11 - - - private static NotImplementedException Unfinished = new NotImplementedException( "ERROR: Only 2 Dimensional DXT1/3/5 compressed images for now. 1D/3D Textures may not be compressed according to spec." ); - #endregion Constants - - #region Simplified In-Memory representation of the Image - private static bool _IsCompressed; - private static int _Width, _Height, _Depth, _MipMapCount; - private static int _BytesForMainSurface; // must be handled with care when implementing uncompressed formats! - private static byte _BytesPerBlock; - private static PixelInternalFormat _PixelInternalFormat; - #endregion Simplified In-Memory representation of the Image - - #region Flag Enums - [Flags] // Surface Description - private enum eDDSD: uint - { - CAPS = 0x00000001, // is always present - HEIGHT = 0x00000002, // is always present - WIDTH = 0x00000004, // is always present - PITCH = 0x00000008, // is set if the image is uncompressed - PIXELFORMAT = 0x00001000, // is always present - MIPMAPCOUNT = 0x00020000, // is set if the image contains MipMaps - LINEARSIZE = 0x00080000, // is set if the image is compressed - DEPTH = 0x00800000 // is set for 3D Volume Textures - } - - [Flags] // Pixelformat - private enum eDDPF: uint - { - NONE = 0x00000000, // not part of DX, added for convenience - ALPHAPIXELS = 0x00000001, - FOURCC = 0x00000004, - RGB = 0x00000040, - RGBA = 0x00000041 - } - - /// This list was derived from nVidia OpenGL SDK - [Flags] // Texture types - private enum eFOURCC: uint - { - UNKNOWN = 0, -#if READALL - R8G8B8 = 20, - A8R8G8B8 = 21, - X8R8G8B8 = 22, - R5G6B5 = 23, - X1R5G5B5 = 24, - A1R5G5B5 = 25, - A4R4G4B4 = 26, - R3G3B2 = 27, - A8 = 28, - A8R3G3B2 = 29, - X4R4G4B4 = 30, - A2B10G10R10 = 31, - A8B8G8R8 = 32, - X8B8G8R8 = 33, - G16R16 = 34, - A2R10G10B10 = 35, - A16B16G16R16 = 36, - - L8 = 50, - A8L8 = 51, - A4L4 = 52, - - D16_LOCKABLE = 70, - D32 = 71, - D24X8 = 77, - D16 = 80, - - D32F_LOCKABLE = 82, - L16 = 81, - - // s10e5 formats (16-bits per channel) - R16F = 111, - G16R16F = 112, - A16B16G16R16F = 113, - - // IEEE s23e8 formats (32-bits per channel) - R32F = 114, - G32R32F = 115, - A32B32G32R32F = 116 -#endif - DXT1 = 0x31545844, - DXT2 = 0x32545844, - DXT3 = 0x33545844, - DXT4 = 0x34545844, - DXT5 = 0x35545844, - } - - [Flags] // dwCaps1 - private enum eDDSCAPS: uint - { - NONE = 0x00000000, // not part of DX, added for convenience - COMPLEX = 0x00000008, // should be set for any DDS file with more than one main surface - TEXTURE = 0x00001000, // should always be set - MIPMAP = 0x00400000 // only for files with MipMaps - } - - [Flags] // dwCaps2 - private enum eDDSCAPS2: uint - { - NONE = 0x00000000, // not part of DX, added for convenience - CUBEMAP = 0x00000200, - CUBEMAP_POSITIVEX = 0x00000400, - CUBEMAP_NEGATIVEX = 0x00000800, - CUBEMAP_POSITIVEY = 0x00001000, - CUBEMAP_NEGATIVEY = 0x00002000, - CUBEMAP_POSITIVEZ = 0x00004000, - CUBEMAP_NEGATIVEZ = 0x00008000, - CUBEMAP_ALL_FACES = 0x0000FC00, - VOLUME = 0x00200000 // for 3D Textures - } - #endregion Flag Enums - - #region Private Members - private static string idString; // 4 bytes, must be "DDS " - private static UInt32 dwSize; // Size of structure is 124 bytes, 128 including all sub-structs and the header - private static UInt32 dwFlags; // Flags to indicate valid fields. - private static UInt32 dwHeight; // Height of the main image in pixels - private static UInt32 dwWidth; // Width of the main image in pixels - private static UInt32 dwPitchOrLinearSize; // For compressed formats, this is the total number of bytes for the main image. - private static UInt32 dwDepth; // For volume textures, this is the depth of the volume. - private static UInt32 dwMipMapCount; // total number of levels in the mipmap chain of the main image. -#if READALL - private static UInt32[] dwReserved1; // 11 UInt32s -#endif - // Pixelformat sub-struct, 32 bytes - private static UInt32 pfSize; // Size of Pixelformat structure. This member must be set to 32. - private static UInt32 pfFlags; // Flags to indicate valid fields. - private static UInt32 pfFourCC; // This is the four-character code for compressed formats. -#if READALL - private static UInt32 pfRGBBitCount; // For RGB formats, this is the total number of bits in the format. dwFlags should include DDpf_RGB in this case. This value is usually 16, 24, or 32. For A8R8G8B8, this value would be 32. - private static UInt32 pfRBitMask; // For RGB formats, these three fields contain the masks for the red, green, and blue channels. For A8R8G8B8, these values would be 0x00ff0000, 0x0000ff00, and 0x000000ff respectively. - private static UInt32 pfGBitMask; // .. - private static UInt32 pfBBitMask; // .. - private static UInt32 pfABitMask; // For RGB formats, this contains the mask for the alpha channel, if any. dwFlags should include DDpf_ALPHAPIXELS in this case. For A8R8G8B8, this value would be 0xff000000. -#endif - // Capabilities sub-struct, 16 bytes - private static UInt32 dwCaps1; // always includes DDSCAPS_TEXTURE. with more than one main surface DDSCAPS_COMPLEX should also be set. - private static UInt32 dwCaps2; // For cubic environment maps, DDSCAPS2_CUBEMAP should be included as well as one or more faces of the map (DDSCAPS2_CUBEMAP_POSITIVEX, DDSCAPS2_CUBEMAP_NEGATIVEX, DDSCAPS2_CUBEMAP_POSITIVEY, DDSCAPS2_CUBEMAP_NEGATIVEY, DDSCAPS2_CUBEMAP_POSITIVEZ, DDSCAPS2_CUBEMAP_NEGATIVEZ). For volume textures, DDSCAPS2_VOLUME should be included. -#if READALL - private static UInt32[] dwReserved2; // 3 = 2 + 1 UInt32 -#endif - #endregion Private Members - - /// - /// This function will generate, bind and fill a Texture Object with a DXT1/3/5 compressed Texture in .dds Format. - /// MipMaps below 4x4 Pixel Size are discarded, because DXTn's smallest unit is a 4x4 block of Pixel data. - /// It will set correct MipMap parameters, Filtering, Wrapping and EnvMode for the Texture. - /// The only call inside this function affecting OpenGL State is GL.BindTexture(); - /// - /// The name of the file you wish to load, including path and file extension. - /// 0 if invalid, otherwise a Texture Object usable with GL.BindTexture(). - /// 0 if invalid, will output what was loaded (typically Texture1D/2D/3D or Cubemap) - public static void LoadFromDisk( string filename, out uint texturehandle, out TextureTarget dimension ) - { - #region Prep data - // invalidate whatever it was before - dimension = (TextureTarget) 0; - texturehandle = TextureLoaderParameters.OpenGLDefaultTexture; - ErrorCode GLError = ErrorCode.NoError; - - _IsCompressed = false; - _Width = 0; - _Height = 0; - _Depth = 0; - _MipMapCount = 0; - _BytesForMainSurface = 0; - _BytesPerBlock = 0; - _PixelInternalFormat = PixelInternalFormat.Rgba8; - byte[] _RawDataFromFile; - #endregion - - #region Try - try // Exceptions will be thrown if any Problem occurs while working on the file. - { - _RawDataFromFile = File.ReadAllBytes( @filename ); - - #region Translate Header to less cryptic representation - ConvertDX9Header( ref _RawDataFromFile ); // The first 128 Bytes of the file is non-image data - - // start by checking if all forced flags are present. Flags indicate valid fields, but aren't written by every tool ..... - if ( idString != "DDS " || // magic key - dwSize != 124 || // constant size of struct, never reused - pfSize != 32 || // constant size of struct, never reused - !CheckFlag( dwFlags, (uint) eDDSD.CAPS ) || // must know it's caps - !CheckFlag( dwFlags, (uint) eDDSD.PIXELFORMAT ) || // must know it's format - !CheckFlag( dwCaps1, (uint) eDDSCAPS.TEXTURE ) // must be a Texture - ) - throw new ArgumentException( "ERROR: File has invalid signature or missing Flags." ); - - #region Examine Flags - if ( CheckFlag( dwFlags, (uint) eDDSD.WIDTH ) ) - _Width = (int) dwWidth; - else - throw new ArgumentException( "ERROR: Flag for Width not set." ); - - if ( CheckFlag( dwFlags, (uint) eDDSD.HEIGHT ) ) - _Height = (int) dwHeight; - else - throw new ArgumentException( "ERROR: Flag for Height not set." ); - - if ( CheckFlag( dwFlags, (uint) eDDSD.DEPTH ) && CheckFlag( dwCaps2, (uint) eDDSCAPS2.VOLUME ) ) - { - dimension = TextureTarget.Texture3D; // image is 3D Volume - _Depth = (int) dwDepth; - throw Unfinished; - } else - {// image is 2D or Cube - if ( CheckFlag( dwCaps2, (uint) eDDSCAPS2.CUBEMAP ) ) - { - dimension = TextureTarget.TextureCubeMap; - _Depth = 6; - } else - { - dimension = TextureTarget.Texture2D; - _Depth = 1; - } - } - - // these flags must be set for mipmaps to be included - if ( CheckFlag( dwCaps1, (uint) eDDSCAPS.MIPMAP ) && CheckFlag( dwFlags, (uint) eDDSD.MIPMAPCOUNT ) ) - _MipMapCount = (int) dwMipMapCount; // image contains MipMaps - else - _MipMapCount = 1; // only 1 main image - - // Should never happen - if ( CheckFlag( dwFlags, (uint) eDDSD.PITCH ) && CheckFlag( dwFlags, (uint) eDDSD.LINEARSIZE ) ) - throw new ArgumentException( "INVALID: Pitch AND Linear Flags both set. Image cannot be uncompressed and DTXn compressed at the same time." ); - - // This flag is set if format is uncompressed RGB RGBA etc. - if ( CheckFlag( dwFlags, (uint) eDDSD.PITCH ) ) - { - // _BytesForMainSurface = (int) dwPitchOrLinearSize; // holds bytes-per-scanline for uncompressed - _IsCompressed = false; - throw Unfinished; - } - - // This flag is set if format is compressed DXTn. - if ( CheckFlag( dwFlags, (uint) eDDSD.LINEARSIZE ) ) - { - _BytesForMainSurface = (int) dwPitchOrLinearSize; - _IsCompressed = true; - } - #endregion Examine Flags - - #region Examine Pixel Format, anything but DXTn will fail atm. - if ( CheckFlag( pfFlags, (uint) eDDPF.FOURCC ) ) - switch ( (eFOURCC) pfFourCC ) - { - case eFOURCC.DXT1: - _PixelInternalFormat = (PixelInternalFormat) ExtTextureCompressionS3tc.CompressedRgbS3tcDxt1Ext; - _BytesPerBlock = 8; - _IsCompressed = true; - break; - //case eFOURCC.DXT2: - case eFOURCC.DXT3: - _PixelInternalFormat = (PixelInternalFormat) ExtTextureCompressionS3tc.CompressedRgbaS3tcDxt3Ext; - _BytesPerBlock = 16; - _IsCompressed = true; - break; - //case eFOURCC.DXT4: - case eFOURCC.DXT5: - _PixelInternalFormat = (PixelInternalFormat) ExtTextureCompressionS3tc.CompressedRgbaS3tcDxt5Ext; - _BytesPerBlock = 16; - _IsCompressed = true; - break; - default: - throw Unfinished; // handle uncompressed formats - } else - throw Unfinished; - // pf*Bitmasks should be examined here - #endregion - - // Works, but commented out because some texture authoring tools don't set this flag. - /* Safety Check, if file is only 1x 2D surface without mipmaps, eDDSCAPS.COMPLEX should not be set - if ( CheckFlag( dwCaps1, (uint) eDDSCAPS.COMPLEX ) ) - { - if ( result == eTextureDimension.Texture2D && _MipMapCount == 1 ) // catch potential problem - Trace.WriteLine( "Warning: Image is declared complex, but contains only 1 surface." ); - }*/ - - if ( TextureLoaderParameters.Verbose ) - Trace.WriteLine( "\n" + GetDescriptionFromMemory( filename, dimension ) ); - #endregion Translate Header to less cryptic representation - - #region send the Texture to GL - #region Generate and Bind Handle - GL.GenTextures( 1, out texturehandle ); - GL.BindTexture( dimension, texturehandle ); - #endregion Generate and Bind Handle - - int Cursor = HeaderSizeInBytes; - // foreach face in the cubemap, get all it's mipmaps levels. Only one iteration for Texture2D - for ( int Slices = 0 ; Slices < _Depth ; Slices++ ) - { - int trueMipMapCount = _MipMapCount - 1; // TODO: triplecheck correctness - int Width = _Width; - int Height = _Height; - for ( int Level = 0 ; Level < _MipMapCount ; Level++ ) // start at base image - { - #region determine Dimensions - int BlocksPerRow = ( Width + 3 ) >> 2; - int BlocksPerColumn = ( Height + 3 ) >> 2; - int SurfaceBlockCount = BlocksPerRow * BlocksPerColumn; // // DXTn stores Texels in 4x4 blocks, a Color block is 8 Bytes, an Alpha block is 8 Bytes for DXT3/5 - int SurfaceSizeInBytes = SurfaceBlockCount * _BytesPerBlock; - - // this check must evaluate to false for 2D and Cube maps, or it's impossible to determine MipMap sizes. - if ( TextureLoaderParameters.Verbose && Level == 0 && _IsCompressed && _BytesForMainSurface != SurfaceSizeInBytes ) - Trace.WriteLine( "Warning: Calculated byte-count of main image differs from what was read from file." ); - #endregion determine Dimensions - - // skip mipmaps smaller than a 4x4 Pixels block, which is the smallest DXTn unit. - if ( Width > 2 && Height > 2 ) - { // Note: there could be a potential problem with non-power-of-two cube maps - #region Prepare Array for TexImage - byte[] RawDataOfSurface = new byte[SurfaceSizeInBytes]; - if ( !TextureLoaderParameters.FlipImages ) - { // no changes to the image, copy as is - Array.Copy( _RawDataFromFile, Cursor, RawDataOfSurface, 0, SurfaceSizeInBytes ); - } else - { // Turn the blocks upside down and the rows aswell, done in a single pass through all blocks - for ( int sourceColumn = 0 ; sourceColumn < BlocksPerColumn ; sourceColumn++ ) - { - int targetColumn = BlocksPerColumn - sourceColumn - 1; - for ( int row = 0 ; row < BlocksPerRow ; row++ ) - { - int target = ( targetColumn * BlocksPerRow + row ) * _BytesPerBlock; - int source = ( sourceColumn * BlocksPerRow + row ) * _BytesPerBlock + Cursor; - #region Swap Bytes - switch ( _PixelInternalFormat ) - { - case (PixelInternalFormat) ExtTextureCompressionS3tc.CompressedRgbS3tcDxt1Ext: - // Color only - RawDataOfSurface[target + 0] = _RawDataFromFile[source + 0]; - RawDataOfSurface[target + 1] = _RawDataFromFile[source + 1]; - RawDataOfSurface[target + 2] = _RawDataFromFile[source + 2]; - RawDataOfSurface[target + 3] = _RawDataFromFile[source + 3]; - RawDataOfSurface[target + 4] = _RawDataFromFile[source + 7]; - RawDataOfSurface[target + 5] = _RawDataFromFile[source + 6]; - RawDataOfSurface[target + 6] = _RawDataFromFile[source + 5]; - RawDataOfSurface[target + 7] = _RawDataFromFile[source + 4]; - break; - case (PixelInternalFormat) ExtTextureCompressionS3tc.CompressedRgbaS3tcDxt3Ext: - // Alpha - RawDataOfSurface[target + 0] = _RawDataFromFile[source + 6]; - RawDataOfSurface[target + 1] = _RawDataFromFile[source + 7]; - RawDataOfSurface[target + 2] = _RawDataFromFile[source + 4]; - RawDataOfSurface[target + 3] = _RawDataFromFile[source + 5]; - RawDataOfSurface[target + 4] = _RawDataFromFile[source + 2]; - RawDataOfSurface[target + 5] = _RawDataFromFile[source + 3]; - RawDataOfSurface[target + 6] = _RawDataFromFile[source + 0]; - RawDataOfSurface[target + 7] = _RawDataFromFile[source + 1]; - - // Color - RawDataOfSurface[target + 8] = _RawDataFromFile[source + 8]; - RawDataOfSurface[target + 9] = _RawDataFromFile[source + 9]; - RawDataOfSurface[target + 10] = _RawDataFromFile[source + 10]; - RawDataOfSurface[target + 11] = _RawDataFromFile[source + 11]; - RawDataOfSurface[target + 12] = _RawDataFromFile[source + 15]; - RawDataOfSurface[target + 13] = _RawDataFromFile[source + 14]; - RawDataOfSurface[target + 14] = _RawDataFromFile[source + 13]; - RawDataOfSurface[target + 15] = _RawDataFromFile[source + 12]; - break; - case (PixelInternalFormat) ExtTextureCompressionS3tc.CompressedRgbaS3tcDxt5Ext: - // Alpha, the first 2 bytes remain - RawDataOfSurface[target + 0] = _RawDataFromFile[source + 0]; - RawDataOfSurface[target + 1] = _RawDataFromFile[source + 1]; - - // extract 3 bits each and flip them - GetBytesFromUInt24( ref RawDataOfSurface, (uint) target + 5, FlipUInt24( GetUInt24( ref _RawDataFromFile, (uint) source + 2 ) ) ); - GetBytesFromUInt24( ref RawDataOfSurface, (uint) target + 2, FlipUInt24( GetUInt24( ref _RawDataFromFile, (uint) source + 5 ) ) ); - - // Color - RawDataOfSurface[target + 8] = _RawDataFromFile[source + 8]; - RawDataOfSurface[target + 9] = _RawDataFromFile[source + 9]; - RawDataOfSurface[target + 10] = _RawDataFromFile[source + 10]; - RawDataOfSurface[target + 11] = _RawDataFromFile[source + 11]; - RawDataOfSurface[target + 12] = _RawDataFromFile[source + 15]; - RawDataOfSurface[target + 13] = _RawDataFromFile[source + 14]; - RawDataOfSurface[target + 14] = _RawDataFromFile[source + 13]; - RawDataOfSurface[target + 15] = _RawDataFromFile[source + 12]; - break; - default: - throw new ArgumentException( "ERROR: Should have never arrived here! Bad _PixelInternalFormat! Should have been dealt with much earlier." ); - } - #endregion Swap Bytes - } - } - } - #endregion Prepare Array for TexImage - - #region Create TexImage - switch ( dimension ) - { - case TextureTarget.Texture2D: - GL.CompressedTexImage2D( TextureTarget.Texture2D, - Level, - _PixelInternalFormat, - Width, - Height, - TextureLoaderParameters.Border, - SurfaceSizeInBytes, - RawDataOfSurface ); - break; - case TextureTarget.TextureCubeMap: - GL.CompressedTexImage2D( TextureTarget.TextureCubeMapPositiveX + Slices, - Level, - _PixelInternalFormat, - Width, - Height, - TextureLoaderParameters.Border, - SurfaceSizeInBytes, - RawDataOfSurface ); - break; - case TextureTarget.Texture1D: // Untested - case TextureTarget.Texture3D: // Untested - default: - throw new ArgumentException( "ERROR: Use DXT for 2D Images only. Cannot evaluate " + dimension ); - } - GL.Finish( ); - #endregion Create TexImage - - #region Query Success - int width, height, internalformat, compressed; - switch ( dimension ) - { - case TextureTarget.Texture1D: - case TextureTarget.Texture2D: - case TextureTarget.Texture3D: - GL.GetTexLevelParameter( dimension, Level, GetTextureParameter.TextureWidth, out width ); - GL.GetTexLevelParameter( dimension, Level, GetTextureParameter.TextureHeight, out height ); - GL.GetTexLevelParameter( dimension, Level, GetTextureParameter.TextureInternalFormat, out internalformat ); - GL.GetTexLevelParameter( dimension, Level, GetTextureParameter.TextureCompressed, out compressed ); - break; - case TextureTarget.TextureCubeMap: - GL.GetTexLevelParameter( TextureTarget.TextureCubeMapPositiveX + Slices, Level, GetTextureParameter.TextureWidth, out width ); - GL.GetTexLevelParameter( TextureTarget.TextureCubeMapPositiveX + Slices, Level, GetTextureParameter.TextureHeight, out height ); - GL.GetTexLevelParameter( TextureTarget.TextureCubeMapPositiveX + Slices, Level, GetTextureParameter.TextureInternalFormat, out internalformat ); - GL.GetTexLevelParameter( TextureTarget.TextureCubeMapPositiveX + Slices, Level, GetTextureParameter.TextureCompressed, out compressed ); - break; - default: - throw Unfinished; - } - GLError = GL.GetError( ); - if ( TextureLoaderParameters.Verbose ) - Trace.WriteLine( "GL: " + GLError.ToString( ) + " Level: " + Level + " DXTn: " + ( ( compressed == 1 ) ? "Yes" : "No" ) + " Frmt:" + (ExtTextureCompressionS3tc) internalformat + " " + width + "*" + height ); - if ( GLError != ErrorCode.NoError || compressed == 0 || width == 0 || height == 0 || internalformat == 0 ) - { - GL.DeleteTextures( 1, ref texturehandle ); - throw new ArgumentException( "ERROR: Something went wrong after GL.CompressedTexImage(); Last GL Error: " + GLError.ToString( ) ); - } - #endregion Query Success - } else - { - if ( trueMipMapCount > Level ) - trueMipMapCount = Level - 1; // The current Level is invalid - } - - #region Prepare the next MipMap level - Width /= 2; - if ( Width < 1 ) - Width = 1; - Height /= 2; - if ( Height < 1 ) - Height = 1; - Cursor += SurfaceSizeInBytes; - #endregion Prepare the next MipMap level - } - - #region Set States properly - GL.TexParameter( dimension, (TextureParameterName) All.TextureBaseLevel, 0 ); - GL.TexParameter( dimension, (TextureParameterName) All.TextureMaxLevel, trueMipMapCount ); - - int TexMaxLevel; - GL.GetTexParameter( dimension, GetTextureParameter.TextureMaxLevel, out TexMaxLevel ); - - if ( TextureLoaderParameters.Verbose ) - Trace.WriteLine( "Verification: GL: " + GL.GetError( ).ToString( ) + " TextureMaxLevel: " + TexMaxLevel + ( ( TexMaxLevel == trueMipMapCount ) ? " (Correct.)" : " (Wrong!)" ) ); - #endregion Set States properly - } - - #region Set Texture Parameters - GL.TexParameter( dimension, TextureParameterName.TextureMinFilter, (int) TextureLoaderParameters.MinificationFilter ); - GL.TexParameter( dimension, TextureParameterName.TextureMagFilter, (int) TextureLoaderParameters.MagnificationFilter ); - - GL.TexParameter( dimension, TextureParameterName.TextureWrapS, (int) TextureLoaderParameters.WrapModeS ); - GL.TexParameter( dimension, TextureParameterName.TextureWrapT, (int) TextureLoaderParameters.WrapModeT ); - - GL.TexEnv( TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvMode, (int) TextureLoaderParameters.EnvMode ); - - GLError = GL.GetError( ); - if ( GLError != ErrorCode.NoError ) - { - throw new ArgumentException( "Error setting Texture Parameters. GL Error: " + GLError ); - } - #endregion Set Texture Parameters - - // If it made it here without throwing any Exception the result is a valid Texture. - return; // success - #endregion send the Texture to GL - } catch ( Exception e ) - { - dimension = (TextureTarget) 0; - texturehandle = TextureLoaderParameters.OpenGLDefaultTexture; - throw new ArgumentException( "ERROR: Exception caught when attempting to load file " + filename + ".\n" + e + "\n" + GetDescriptionFromFile( filename ) ); - // return; // failure - } finally - { - _RawDataFromFile = null; // clarity, not really needed - } - #endregion Try - } - - #region Helpers - private static void ConvertDX9Header( ref byte[] input ) - { - UInt32 offset = 0; - idString = GetString( ref input, offset ); - offset += 4; - dwSize = GetUInt32( ref input, offset ); - offset += 4; - dwFlags = GetUInt32( ref input, offset ); - offset += 4; - dwHeight = GetUInt32( ref input, offset ); - offset += 4; - dwWidth = GetUInt32( ref input, offset ); - offset += 4; - dwPitchOrLinearSize = GetUInt32( ref input, offset ); - offset += 4; - dwDepth = GetUInt32( ref input, offset ); - offset += 4; - dwMipMapCount = GetUInt32( ref input, offset ); - offset += 4; -#if READALL - dwReserved1 = new UInt32[11]; // reserved -#endif - offset += 4 * 11; - pfSize = GetUInt32( ref input, offset ); - offset += 4; - pfFlags = GetUInt32( ref input, offset ); - offset += 4; - pfFourCC = GetUInt32( ref input, offset ); - offset += 4; -#if READALL - pfRGBBitCount = GetUInt32( ref input, offset ); - offset += 4; - pfRBitMask = GetUInt32( ref input, offset ); - offset += 4; - pfGBitMask = GetUInt32( ref input, offset ); - offset += 4; - pfBBitMask = GetUInt32( ref input, offset ); - offset += 4; - pfABitMask = GetUInt32( ref input, offset ); - offset += 4; -#else - offset += 20; -#endif - dwCaps1 = GetUInt32( ref input, offset ); - offset += 4; - dwCaps2 = GetUInt32( ref input, offset ); - offset += 4; -#if READALL - dwReserved2 = new UInt32[3]; // offset is 4+112 here, + 12 = 4+124 -#endif - offset += 4 * 3; - } - - /// Returns true if the flag is set, false otherwise - private static bool CheckFlag( uint variable, uint flag ) - { - return ( variable & flag ) > 0 ? true : false; - } - - private static string GetString( ref byte[] input, uint offset ) - { - return "" + (char) input[offset + 0] + (char) input[offset + 1] + (char) input[offset + 2] + (char) input[offset + 3]; - } - - private static uint GetUInt32( ref byte[] input, uint offset ) - { - return (uint) ( ( ( input[offset + 3] * 256 + input[offset + 2] ) * 256 + input[offset + 1] ) * 256 + input[offset + 0] ); - } - - private static uint GetUInt24( ref byte[] input, uint offset ) - { - return (uint) ( ( input[offset + 2] * 256 + input[offset + 1] ) * 256 + input[offset + 0] ); - } - - private static void GetBytesFromUInt24( ref byte[] input, uint offset, uint splitme ) - { - input[offset + 0] = (byte) ( splitme & 0x000000ff ); - input[offset + 1] = (byte) ( ( splitme & 0x0000ff00 ) >> 8 ); - input[offset + 2] = (byte) ( ( splitme & 0x00ff0000 ) >> 16 ); - return; - } - - /// DXT5 Alpha block flipping, inspired by code from Evan Hart (nVidia SDK) - private static uint FlipUInt24( uint inputUInt24 ) - { - byte[][] ThreeBits = new byte[2][]; - for ( int i = 0 ; i < 2 ; i++ ) - ThreeBits[i] = new byte[4]; - - // extract 3 bits each into the array - ThreeBits[0][0] = (byte) ( inputUInt24 & BitMask ); - inputUInt24 >>= 3; - ThreeBits[0][1] = (byte) ( inputUInt24 & BitMask ); - inputUInt24 >>= 3; - ThreeBits[0][2] = (byte) ( inputUInt24 & BitMask ); - inputUInt24 >>= 3; - ThreeBits[0][3] = (byte) ( inputUInt24 & BitMask ); - inputUInt24 >>= 3; - ThreeBits[1][0] = (byte) ( inputUInt24 & BitMask ); - inputUInt24 >>= 3; - ThreeBits[1][1] = (byte) ( inputUInt24 & BitMask ); - inputUInt24 >>= 3; - ThreeBits[1][2] = (byte) ( inputUInt24 & BitMask ); - inputUInt24 >>= 3; - ThreeBits[1][3] = (byte) ( inputUInt24 & BitMask ); - - // stuff 8x 3bits into 3 bytes - uint Result = 0; - Result = Result | (uint) ( ThreeBits[1][0] << 0 ); - Result = Result | (uint) ( ThreeBits[1][1] << 3 ); - Result = Result | (uint) ( ThreeBits[1][2] << 6 ); - Result = Result | (uint) ( ThreeBits[1][3] << 9 ); - Result = Result | (uint) ( ThreeBits[0][0] << 12 ); - Result = Result | (uint) ( ThreeBits[0][1] << 15 ); - Result = Result | (uint) ( ThreeBits[0][2] << 18 ); - Result = Result | (uint) ( ThreeBits[0][3] << 21 ); - return Result; - } - #endregion Helpers - - #region String Representations - private static string GetDescriptionFromFile( string filename ) - { - return "\n--> Header of " + filename + - "\nID: " + idString + - "\nSize: " + dwSize + - "\nFlags: " + dwFlags + " (" + (eDDSD) dwFlags + ")" + - "\nHeight: " + dwHeight + - "\nWidth: " + dwWidth + - "\nPitch: " + dwPitchOrLinearSize + - "\nDepth: " + dwDepth + - "\nMipMaps: " + dwMipMapCount + - "\n\n---PixelFormat---" + filename + - "\nSize: " + pfSize + - "\nFlags: " + pfFlags + " (" + (eDDPF) pfFlags + ")" + - "\nFourCC: " + pfFourCC + " (" + (eFOURCC) pfFourCC + ")" + -#if READALL - "\nBitcount: " + pfRGBBitCount + - "\nBitMask Red: " + pfRBitMask + - "\nBitMask Green: " + pfGBitMask + - "\nBitMask Blue: " + pfBBitMask + - "\nBitMask Alpha: " + pfABitMask + -#endif - "\n\n---Capabilities---" + filename + - "\nCaps1: " + dwCaps1 + " (" + (eDDSCAPS) dwCaps1 + ")" + - "\nCaps2: " + dwCaps2 + " (" + (eDDSCAPS2) dwCaps2 + ")"; - } - - private static string GetDescriptionFromMemory( string filename, TextureTarget Dimension ) - { - return "\nFile: " + filename + - "\nDimension: " + Dimension + - "\nSize: " + _Width + " * " + _Height + " * " + _Depth + - "\nCompressed: " + _IsCompressed + - "\nBytes for Main Image: " + _BytesForMainSurface + - "\nMipMaps: " + _MipMapCount; - } - #endregion String Representations - } -} diff --git a/Source/Examples/Utilities/LoaderGDI.cs b/Source/Examples/Utilities/LoaderGDI.cs deleted file mode 100644 index f966c5b4..00000000 --- a/Source/Examples/Utilities/LoaderGDI.cs +++ /dev/null @@ -1,152 +0,0 @@ -#region --- License --- -/* Licensed under the MIT/X11 license. - * Copyright (c) 2006-2008 the OpenTK Team. - * This notice may not be removed from any source distribution. - * See license.txt for licensing details. - */ -#endregion - -// TODO: Find paint program that can properly export 8/16-bit Textures and make sure they are loaded correctly. - -using System; -using System.Diagnostics; -using System.Drawing; -using System.Drawing.Imaging; - -using OpenTK; -using OpenTK.Graphics; -using OpenTK.Graphics.OpenGL; - -namespace Examples.TextureLoaders -{ - class ImageGDI - { - - public static void LoadFromDisk( string filename, out uint texturehandle, out TextureTarget dimension ) - { - dimension = (TextureTarget) 0; - texturehandle = TextureLoaderParameters.OpenGLDefaultTexture; - ErrorCode GLError = ErrorCode.NoError; - - Bitmap CurrentBitmap = null; - - try // Exceptions will be thrown if any Problem occurs while working on the file. - { - CurrentBitmap = new Bitmap( filename ); - if ( TextureLoaderParameters.FlipImages ) - CurrentBitmap.RotateFlip( RotateFlipType.RotateNoneFlipY ); - - if ( CurrentBitmap.Height > 1 ) - dimension = TextureTarget.Texture2D; - else - dimension = TextureTarget.Texture1D; - - GL.GenTextures( 1, out texturehandle ); - GL.BindTexture( dimension, texturehandle ); - - #region Load Texture - OpenTK.Graphics.OpenGL.PixelInternalFormat pif; - OpenTK.Graphics.OpenGL.PixelFormat pf; - OpenTK.Graphics.OpenGL.PixelType pt; - - if (TextureLoaderParameters.Verbose) - Trace.WriteLine( "File: " + filename + " Format: " + CurrentBitmap.PixelFormat ); - - switch ( CurrentBitmap.PixelFormat ) - { - case System.Drawing.Imaging.PixelFormat.Format8bppIndexed: // misses glColorTable setup - pif = OpenTK.Graphics.OpenGL.PixelInternalFormat.Rgb8; - pf = OpenTK.Graphics.OpenGL.PixelFormat.ColorIndex; - pt = OpenTK.Graphics.OpenGL.PixelType.Bitmap; - break; - case System.Drawing.Imaging.PixelFormat.Format16bppArgb1555: - case System.Drawing.Imaging.PixelFormat.Format16bppRgb555: // does not work - pif = OpenTK.Graphics.OpenGL.PixelInternalFormat.Rgb5A1; - pf = OpenTK.Graphics.OpenGL.PixelFormat.Bgr; - pt = OpenTK.Graphics.OpenGL.PixelType.UnsignedShort5551Ext; - break; - /* case System.Drawing.Imaging.PixelFormat.Format16bppRgb565: - pif = OpenTK.Graphics.OpenGL.PixelInternalFormat.R5G6B5IccSgix; - pf = OpenTK.Graphics.OpenGL.PixelFormat.R5G6B5IccSgix; - pt = OpenTK.Graphics.OpenGL.PixelType.UnsignedByte; - break; -*/ - case System.Drawing.Imaging.PixelFormat.Format24bppRgb: // works - pif = OpenTK.Graphics.OpenGL.PixelInternalFormat.Rgb8; - pf = OpenTK.Graphics.OpenGL.PixelFormat.Bgr; - pt = OpenTK.Graphics.OpenGL.PixelType.UnsignedByte; - break; - case System.Drawing.Imaging.PixelFormat.Format32bppRgb: // has alpha too? wtf? - case System.Drawing.Imaging.PixelFormat.Canonical: - case System.Drawing.Imaging.PixelFormat.Format32bppArgb: // works - pif = OpenTK.Graphics.OpenGL.PixelInternalFormat.Rgba; - pf = OpenTK.Graphics.OpenGL.PixelFormat.Bgra; - pt = OpenTK.Graphics.OpenGL.PixelType.UnsignedByte; - break; - default: - throw new ArgumentException( "ERROR: Unsupported Pixel Format " + CurrentBitmap.PixelFormat ); - } - - BitmapData Data = CurrentBitmap.LockBits( new System.Drawing.Rectangle( 0, 0, CurrentBitmap.Width, CurrentBitmap.Height ), ImageLockMode.ReadOnly, CurrentBitmap.PixelFormat ); - - if ( Data.Height > 1 ) - { // image is 2D - if (TextureLoaderParameters.BuildMipmapsForUncompressed) - { - throw new Exception("Cannot build mipmaps, Glu is deprecated."); - // Glu.Build2DMipmap(dimension, (int)pif, Data.Width, Data.Height, pf, pt, Data.Scan0); - } - else - GL.TexImage2D(dimension, 0, pif, Data.Width, Data.Height, TextureLoaderParameters.Border, pf, pt, Data.Scan0); - } else - { // image is 1D - if (TextureLoaderParameters.BuildMipmapsForUncompressed) - { - throw new Exception("Cannot build mipmaps, Glu is deprecated."); - // Glu.Build1DMipmap(dimension, (int)pif, Data.Width, pf, pt, Data.Scan0); - } - else - GL.TexImage1D(dimension, 0, pif, Data.Width, TextureLoaderParameters.Border, pf, pt, Data.Scan0); - } - - GL.Finish( ); - GLError = GL.GetError( ); - if ( GLError != ErrorCode.NoError ) - { - throw new ArgumentException( "Error building TexImage. GL Error: " + GLError ); - } - - CurrentBitmap.UnlockBits( Data ); - #endregion Load Texture - - #region Set Texture Parameters - GL.TexParameter( dimension, TextureParameterName.TextureMinFilter, (int) TextureLoaderParameters.MinificationFilter ); - GL.TexParameter( dimension, TextureParameterName.TextureMagFilter, (int) TextureLoaderParameters.MagnificationFilter ); - - GL.TexParameter( dimension, TextureParameterName.TextureWrapS, (int) TextureLoaderParameters.WrapModeS ); - GL.TexParameter( dimension, TextureParameterName.TextureWrapT, (int) TextureLoaderParameters.WrapModeT ); - - GL.TexEnv( TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvMode, (int) TextureLoaderParameters.EnvMode ); - - GLError = GL.GetError( ); - if ( GLError != ErrorCode.NoError ) - { - throw new ArgumentException( "Error setting Texture Parameters. GL Error: " + GLError ); - } - #endregion Set Texture Parameters - - return; // success - } catch ( Exception e ) - { - dimension = (TextureTarget) 0; - texturehandle = TextureLoaderParameters.OpenGLDefaultTexture; - throw new ArgumentException( "Texture Loading Error: Failed to read file " + filename + ".\n" + e ); - // return; // failure - } finally - { - CurrentBitmap = null; - } - } - - } -} \ No newline at end of file diff --git a/Source/Examples/Utilities/LoaderStatics.cs b/Source/Examples/Utilities/LoaderStatics.cs deleted file mode 100644 index 603bbc69..00000000 --- a/Source/Examples/Utilities/LoaderStatics.cs +++ /dev/null @@ -1,50 +0,0 @@ -#region --- License --- -/* Licensed under the MIT/X11 license. - * Copyright (c) 2006-2008 the OpenTK Team. - * This notice may not be removed from any source distribution. - * See license.txt for licensing details. - */ -#endregion - -using System; - -using OpenTK.Graphics.OpenGL; - -namespace Examples.TextureLoaders -{ - - /// The parameters in this class have only effect on the following Texture loads. - public static class TextureLoaderParameters - { - /// (Debug Aid, should be set to false) If set to false only Errors will be printed. If set to true, debug information (Warnings and Queries) will be printed in addition to Errors. - public static bool Verbose = false; - - /// Always-valid fallback parameter for GL.BindTexture (Default: 0). This number will be returned if loading the Texture failed. You can set this to a checkerboard texture or similar, which you have already loaded. - public static uint OpenGLDefaultTexture = 0; - - /// Compressed formats must have a border of 0, so this is constant. - public const int Border = 0; - - /// false==DirectX TexCoords, true==OpenGL TexCoords (Default: true) - public static bool FlipImages = true; - - /// When enabled, will use Glu to create MipMaps for images loaded with GDI+ (Default: false) - public static bool BuildMipmapsForUncompressed = false; - - /// Selects the Magnification filter for following Textures to be loaded. (Default: Nearest) - public static TextureMagFilter MagnificationFilter = TextureMagFilter.Nearest; - - /// Selects the Minification filter for following Textures to be loaded. (Default: Nearest) - public static TextureMinFilter MinificationFilter = TextureMinFilter.Nearest; - - /// Selects the S Wrapping for following Textures to be loaded. (Default: Repeat) - public static TextureWrapMode WrapModeS = TextureWrapMode.Repeat; - - /// Selects the T Wrapping for following Textures to be loaded. (Default: Repeat) - public static TextureWrapMode WrapModeT = TextureWrapMode.Repeat; - - /// Selects the Texture Environment Mode for the following Textures to be loaded. Default: Modulate) - public static TextureEnvMode EnvMode = TextureEnvMode.Modulate; - } - -} diff --git a/Source/Examples/app.manifest b/Source/Examples/app.manifest deleted file mode 100644 index da81b27d..00000000 --- a/Source/Examples/app.manifest +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - true - - - -