PageRenderTime 48ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/ThirdParty/OpenTK.1.0/Source/Compatibility/Tao/OpenGl/GlHelper.cs

http://github.com/virtualglobebook/OpenGlobe
C# | 555 lines | 309 code | 71 blank | 175 comment | 47 complexity | 3872b284361a31ccd86f1241154d016f MD5 | raw file
  1. #region License
  2. /*
  3. MIT License
  4. Copyright ©2003-2007 Tao Framework Team
  5. http://www.taoframework.com
  6. All rights reserved.
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in all
  14. copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. SOFTWARE.
  22. */
  23. #endregion License
  24. #region --- Using Directives ---
  25. using System;
  26. using System.Collections.Generic;
  27. using System.Text;
  28. using System.Runtime.InteropServices;
  29. using System.Reflection;
  30. using System.Diagnostics;
  31. using System.Reflection.Emit;
  32. using System.IO;
  33. #endregion
  34. namespace Tao.OpenGl
  35. {
  36. /// <summary>
  37. /// OpenGL binding for .NET, implementing OpenGL 2.1, plus extensions.
  38. /// </summary>
  39. /// <remarks>
  40. /// <para>
  41. /// This class contains all OpenGL enums and functions defined in the 2.1 specification.
  42. /// The official .spec files can be found at: http://opengl.org/registry/.
  43. /// </para>
  44. /// <para>
  45. /// We rely on static initialization to obtain the entry points for OpenGL functions.
  46. /// Please ensure that a valid OpenGL context has been made current in the pertinent thread <b>before</b>
  47. /// any OpenGL functions are called (toolkits like GLUT, SDL or GLFW will automatically take care of
  48. /// the context initialization process). Without a valid OpenGL context, we will only be able
  49. /// to retrieve statically exported entry points (typically corresponding to OpenGL version 1.1 under Windows,
  50. /// 1.3 under Linux and 1.4 under Windows Vista), and extension methods will need to be loaded manually.
  51. /// </para>
  52. /// <para>
  53. /// If you prefer to have more control on extension loading, you can use the
  54. /// ReloadFunctions or ReloadFunction methods to manually force the initialisation of OpenGL entry points.
  55. /// The ReloadFunctions method should be called whenever you change an existing visual or pixelformat. This
  56. /// generally happens when you change the color/stencil/depth buffer associated with a window (but probably
  57. /// not the resolution). This may or may not be necessary under Linux/MacOS, but is generally required for
  58. /// Windows.
  59. /// </para>
  60. /// <para>
  61. /// You can use the Gl.IsExtensionSupported method to check whether any given category of extension functions
  62. /// exists in the current OpenGL context. The results can be cached to speed up future searches.
  63. /// Keep in mind that different OpenGL contexts may support different extensions, and under different entry
  64. /// points. Always check if all required extensions are still supported when changing visuals or pixel
  65. /// formats.
  66. /// </para>
  67. /// <para>
  68. /// You may retrieve the entry point for an OpenGL function using the Gl.GetDelegate method.
  69. /// </para>
  70. /// <para>
  71. /// <see href="http://opengl.org/registry/"/>
  72. /// <seealso cref="Gl.IsExtensionSupported"/>
  73. /// <seealso cref="Gl.GetDelegate"/>
  74. /// <seealso cref="Gl.ReloadFunctions"/>
  75. /// </para>
  76. /// </remarks>
  77. [Obsolete("Use OpenTK.Graphics.OpenGL instead.")]
  78. public static partial class Gl
  79. {
  80. #region --- Fields ---
  81. static StringBuilder sb = new StringBuilder();
  82. static object gl_lock = new object();
  83. internal const string Library = "opengl32.dll";
  84. //private static Dictionary<string, bool> AvailableExtensions = new Dictionary<string, bool>();
  85. private static SortedList<string, bool> AvailableExtensions = new SortedList<string, bool>();
  86. private static bool rebuildExtensionList;
  87. private static Type glClass;
  88. private static Type delegatesClass;
  89. private static Type importsClass;
  90. private static FieldInfo[] delegates;
  91. #endregion
  92. #region --- Static Constructor ---
  93. static Gl()
  94. {
  95. glClass = typeof(Gl);
  96. delegatesClass = glClass.GetNestedType("Delegates", BindingFlags.Static | BindingFlags.NonPublic);
  97. importsClass = glClass.GetNestedType("Imports", BindingFlags.Static | BindingFlags.NonPublic);
  98. // 'Touch' Imports class to force initialization. We don't want anything yet, just to have
  99. // this class ready.
  100. if (Imports.FunctionMap != null) { }
  101. ReloadFunctions();
  102. }
  103. #endregion
  104. #region --- Methods ---
  105. #region internal static partial class Imports
  106. /// <summary>
  107. /// Contains DllImports for the core OpenGL functions.
  108. /// </summary>
  109. internal static partial class Imports
  110. {
  111. /// <summary>
  112. /// Build a string->MethodInfo map to speed up extension loading.
  113. /// </summary>
  114. internal static SortedList<string, MethodInfo> FunctionMap; // This is faster than either Dictionary or SortedDictionary
  115. static Imports()
  116. {
  117. MethodInfo[] methods = importsClass.GetMethods(BindingFlags.Static | BindingFlags.NonPublic);
  118. FunctionMap = new SortedList<string, MethodInfo>(methods.Length);
  119. foreach (MethodInfo m in methods)
  120. FunctionMap.Add(m.Name, m);
  121. }
  122. }
  123. #endregion
  124. #region public static bool IsExtensionSupported(string name)
  125. /// <summary>
  126. /// Determines whether the specified OpenGL extension category is available in
  127. /// the current OpenGL context. Equivalent to IsExtensionSupported(name, true)
  128. /// </summary>
  129. /// <param name="name">The string for the OpenGL extension category (eg. "GL_ARB_multitexture")</param>
  130. /// <returns>True if the specified extension is available, false otherwise.</returns>
  131. public static bool IsExtensionSupported(string name)
  132. {
  133. if (rebuildExtensionList)
  134. BuildExtensionList();
  135. lock (gl_lock)
  136. {
  137. sb.Remove(0, sb.Length);
  138. if (!name.StartsWith("GL_"))
  139. sb.Append("gl_");
  140. sb.Append(name.ToLower());
  141. // Search the cache for the string.
  142. return AvailableExtensions.ContainsKey(sb.ToString());
  143. }
  144. }
  145. #endregion
  146. #region public static Delegate GetDelegate(string name, Type signature)
  147. /// <summary>
  148. /// Creates a System.Delegate that can be used to call an OpenGL function, core or extension.
  149. /// </summary>
  150. /// <param name="name">The name of the OpenGL function (eg. "glNewList")</param>
  151. /// <param name="signature">The signature of the OpenGL function.</param>
  152. /// <returns>
  153. /// A System.Delegate that can be used to call this OpenGL function, or null if the specified
  154. /// function name did not correspond to an OpenGL function.
  155. /// </returns>
  156. public static Delegate GetDelegate(string name, Type signature)
  157. {
  158. MethodInfo m;
  159. return GetExtensionDelegate(name, signature) ??
  160. (Imports.FunctionMap.TryGetValue((name.Substring(2)), out m) ?
  161. Delegate.CreateDelegate(signature, m) : null);
  162. }
  163. #endregion
  164. #region public static void ReloadFunctions()
  165. /// <summary>
  166. /// Loads all OpenGL functions (core and extensions).
  167. /// </summary>
  168. /// <remarks>
  169. /// <para>
  170. /// This function will be automatically called the first time you use any opengl function. There is
  171. /// </para>
  172. /// <para>
  173. /// Call this function manually whenever you need to update OpenGL entry points.
  174. /// This need may arise if you change the pixelformat/visual, or in case you cannot
  175. /// (or do not want) to use the automatic initialization of the GL class.
  176. /// </para>
  177. /// </remarks>
  178. public static void ReloadFunctions()
  179. {
  180. // Using reflection is more than 3 times faster than directly loading delegates on the first
  181. // run, probably due to code generation overhead. Subsequent runs are faster with direct loading
  182. // than with reflection, but the first time is more significant.
  183. if (delegates == null)
  184. delegates = delegatesClass.GetFields(BindingFlags.Static | BindingFlags.NonPublic);
  185. foreach (FieldInfo f in delegates)
  186. f.SetValue(null, GetDelegate(f.Name, f.FieldType));
  187. rebuildExtensionList = true;
  188. }
  189. static void set(object d, Delegate value)
  190. {
  191. d = value;
  192. }
  193. #endregion
  194. #region public static bool ReloadFunction(string function)
  195. /// <summary>
  196. /// Tries to reload the given OpenGL function (core or extension).
  197. /// </summary>
  198. /// <param name="function">The name of the OpenGL function (i.e. glShaderSource)</param>
  199. /// <returns>True if the function was found and reloaded, false otherwise.</returns>
  200. /// <remarks>
  201. /// <para>
  202. /// Use this function if you require greater granularity when loading OpenGL entry points.
  203. /// </para>
  204. /// <para>
  205. /// While the automatic initialisation will load all OpenGL entry points, in some cases
  206. /// the initialisation can take place before an OpenGL Context has been established.
  207. /// In this case, use this function to load the entry points for the OpenGL functions
  208. /// you will need, or use ReloadFunctions() to load all available entry points.
  209. /// </para>
  210. /// <para>
  211. /// This function returns true if the given OpenGL function is supported, false otherwise.
  212. /// </para>
  213. /// <para>
  214. /// To query for supported extensions use the IsExtensionSupported() function instead.
  215. /// </para>
  216. /// </remarks>
  217. public static bool Load(string function)
  218. {
  219. FieldInfo f = delegatesClass.GetField(function, BindingFlags.Static | BindingFlags.NonPublic);
  220. if (f == null)
  221. return false;
  222. Delegate old = f.GetValue(null) as Delegate;
  223. Delegate @new = GetDelegate(f.Name, f.FieldType);
  224. if (old.Target != @new.Target)
  225. {
  226. f.SetValue(null, @new);
  227. rebuildExtensionList = true;
  228. }
  229. return @new != null;
  230. }
  231. #endregion
  232. #region private static void BuildExtensionList()
  233. /// <summary>
  234. /// Builds a cache of all supported extensions.
  235. /// </summary>
  236. private static void BuildExtensionList()
  237. {
  238. // Assumes there is an opengl context current.
  239. AvailableExtensions.Clear();
  240. string version_string = Gl.glGetString(Gl.GL_VERSION);
  241. if (String.IsNullOrEmpty(version_string))
  242. throw new ApplicationException("Failed to retrieve OpenGL version. Is there an opengl context current?");
  243. string version;
  244. // Most drivers return the version in the 3 first characters of the version string,
  245. // (e.g. on Ati X1950 with Catalyst 7.10 -> "2.0.6956 Release"). However, Mesa seems
  246. // to do something strange: "1.4 (2.1 Mesa 7.0.1).".
  247. // We'll do some trickery to get the second version number (2.1), but this may break on
  248. // some implementations...
  249. // This works on Ati, Mesa, Nvidia, but I'd like someone to test on Intel, too.
  250. if (version_string.ToLower().Contains("mesa"))
  251. {
  252. int index = version_string.IndexOf('(');
  253. if (index != -1)
  254. version = version_string.Substring(index + 1, 3);
  255. else
  256. version = version_string.TrimStart(' ');
  257. }
  258. else
  259. version = version_string.TrimStart(' ');
  260. // Ugh, this look ugly.
  261. if (version.StartsWith("1.2"))
  262. {
  263. AvailableExtensions.Add("gl_version_1_1", true);
  264. AvailableExtensions.Add("gl_version_1_2", true);
  265. }
  266. else if (version.StartsWith("1.3"))
  267. {
  268. AvailableExtensions.Add("gl_version_1_1", true);
  269. AvailableExtensions.Add("gl_version_1_2", true);
  270. AvailableExtensions.Add("gl_version_1_3", true);
  271. }
  272. else if (version.StartsWith("1.4"))
  273. {
  274. AvailableExtensions.Add("gl_version_1_1", true);
  275. AvailableExtensions.Add("gl_version_1_2", true);
  276. AvailableExtensions.Add("gl_version_1_3", true);
  277. AvailableExtensions.Add("gl_version_1_4", true);
  278. }
  279. else if (version.StartsWith("1.5"))
  280. {
  281. AvailableExtensions.Add("gl_version_1_1", true);
  282. AvailableExtensions.Add("gl_version_1_2", true);
  283. AvailableExtensions.Add("gl_version_1_3", true);
  284. AvailableExtensions.Add("gl_version_1_4", true);
  285. AvailableExtensions.Add("gl_version_1_5", true);
  286. }
  287. else if (version.StartsWith("2.0"))
  288. {
  289. AvailableExtensions.Add("gl_version_1_1", true);
  290. AvailableExtensions.Add("gl_version_1_2", true);
  291. AvailableExtensions.Add("gl_version_1_3", true);
  292. AvailableExtensions.Add("gl_version_1_4", true);
  293. AvailableExtensions.Add("gl_version_1_5", true);
  294. AvailableExtensions.Add("gl_version_2_0", true);
  295. }
  296. else if (version.StartsWith("2.1"))
  297. {
  298. AvailableExtensions.Add("gl_version_1_1", true);
  299. AvailableExtensions.Add("gl_version_1_2", true);
  300. AvailableExtensions.Add("gl_version_1_3", true);
  301. AvailableExtensions.Add("gl_version_1_4", true);
  302. AvailableExtensions.Add("gl_version_1_5", true);
  303. AvailableExtensions.Add("gl_version_2_0", true);
  304. AvailableExtensions.Add("gl_version_2_1", true);
  305. }
  306. string extension_string = Gl.glGetString(Gl.GL_EXTENSIONS);
  307. if (String.IsNullOrEmpty(extension_string))
  308. return; // no extensions are available
  309. string[] extensions = extension_string.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  310. foreach (string ext in extensions)
  311. AvailableExtensions.Add(ext.ToLower(), true);
  312. rebuildExtensionList = false;
  313. }
  314. #endregion
  315. #endregion
  316. #region --- GetProcAddress ---
  317. private static IGetProcAddress getProcAddress;
  318. internal interface IGetProcAddress
  319. {
  320. IntPtr GetProcAddress(string function);
  321. }
  322. internal class GetProcAddressWindows : IGetProcAddress
  323. {
  324. [System.Runtime.InteropServices.DllImport(Library, EntryPoint = "wglGetProcAddress", ExactSpelling = true)]
  325. private static extern IntPtr wglGetProcAddress(String lpszProc);
  326. public IntPtr GetProcAddress(string function)
  327. {
  328. return wglGetProcAddress(function);
  329. }
  330. }
  331. internal class GetProcAddressX11 : IGetProcAddress
  332. {
  333. [DllImport(Library, EntryPoint = "glXGetProcAddress")]
  334. private static extern IntPtr glxGetProcAddress([MarshalAs(UnmanagedType.LPTStr)] string procName);
  335. public IntPtr GetProcAddress(string function)
  336. {
  337. return glxGetProcAddress(function);
  338. }
  339. }
  340. internal class GetProcAddressOSX : IGetProcAddress
  341. {
  342. private const string Library = "libdl.dylib";
  343. [DllImport(Library, EntryPoint = "NSIsSymbolNameDefined")]
  344. private static extern bool NSIsSymbolNameDefined(string s);
  345. [DllImport(Library, EntryPoint = "NSLookupAndBindSymbol")]
  346. private static extern IntPtr NSLookupAndBindSymbol(string s);
  347. [DllImport(Library, EntryPoint = "NSAddressOfSymbol")]
  348. private static extern IntPtr NSAddressOfSymbol(IntPtr symbol);
  349. public IntPtr GetProcAddress(string function)
  350. {
  351. string fname = "_" + function;
  352. if (!NSIsSymbolNameDefined(fname))
  353. return IntPtr.Zero;
  354. IntPtr symbol = NSLookupAndBindSymbol(fname);
  355. if (symbol != IntPtr.Zero)
  356. symbol = NSAddressOfSymbol(symbol);
  357. return symbol;
  358. }
  359. }
  360. #region private static IntPtr GetAddress(string function)
  361. /// <summary>
  362. /// Retrieves the entry point for a dynamically exported OpenGL function.
  363. /// </summary>
  364. /// <param name="function">The function string for the OpenGL function (eg. "glNewList")</param>
  365. /// <returns>
  366. /// An IntPtr contaning the address for the entry point, or IntPtr.Zero if the specified
  367. /// OpenGL function is not dynamically exported.
  368. /// </returns>
  369. /// <remarks>
  370. /// <para>
  371. /// The Marshal.GetDelegateForFunctionPointer method can be used to turn the return value
  372. /// into a call-able delegate.
  373. /// </para>
  374. /// <para>
  375. /// This function is cross-platform. It determines the underlying platform and uses the
  376. /// correct wgl, glx or agl GetAddress function to retrieve the function pointer.
  377. /// </para>
  378. /// <see cref="Marshal.GetDelegateForFunctionPointer"/>
  379. /// </remarks>
  380. private static IntPtr GetAddress(string function)
  381. {
  382. if (getProcAddress == null)
  383. {
  384. if (System.Environment.OSVersion.Platform == PlatformID.Win32NT ||
  385. System.Environment.OSVersion.Platform == PlatformID.Win32S ||
  386. System.Environment.OSVersion.Platform == PlatformID.Win32Windows ||
  387. System.Environment.OSVersion.Platform == PlatformID.WinCE)
  388. {
  389. getProcAddress = new GetProcAddressWindows();
  390. }
  391. else if (System.Environment.OSVersion.Platform == PlatformID.Unix ||
  392. System.Environment.OSVersion.Platform == (PlatformID)4)
  393. {
  394. // Distinguish between Unix and Mac OS X kernels.
  395. switch (DetectUnixKernel())
  396. {
  397. case "Unix":
  398. case "Linux":
  399. getProcAddress = new GetProcAddressX11();
  400. break;
  401. case "Darwin":
  402. getProcAddress = new GetProcAddressOSX();
  403. break;
  404. default:
  405. throw new PlatformNotSupportedException(
  406. DetectUnixKernel() + ": Unknown Unix platform - cannot load extensions. Please report a bug at http://taoframework.com");
  407. }
  408. }
  409. else
  410. {
  411. throw new PlatformNotSupportedException(
  412. "Extension loading is only supported under Mac OS X, Unix/X11 and Windows. We are sorry for the inconvience.");
  413. }
  414. }
  415. return getProcAddress.GetProcAddress(function);
  416. }
  417. #endregion
  418. #region private static string DetectUnixKernel()
  419. /// <summary>
  420. /// Executes "uname" which returns a string representing the name of the
  421. /// underlying Unix kernel.
  422. /// </summary>
  423. /// <returns>"Unix", "Linux", "Darwin" or null.</returns>
  424. /// <remarks>Source code from "Mono: A Developer's Notebook"</remarks>
  425. private static string DetectUnixKernel()
  426. {
  427. ProcessStartInfo startInfo = new ProcessStartInfo();
  428. startInfo.Arguments = "-s";
  429. startInfo.RedirectStandardOutput = true;
  430. startInfo.RedirectStandardError = true;
  431. startInfo.UseShellExecute = false;
  432. foreach (string unameprog in new string[] { "/usr/bin/uname", "/bin/uname", "uname" })
  433. {
  434. try
  435. {
  436. startInfo.FileName = unameprog;
  437. Process uname = Process.Start(startInfo);
  438. StreamReader stdout = uname.StandardOutput;
  439. return stdout.ReadLine().Trim();
  440. }
  441. catch (System.IO.FileNotFoundException)
  442. {
  443. // The requested executable doesn't exist, try next one.
  444. continue;
  445. }
  446. catch (System.ComponentModel.Win32Exception)
  447. {
  448. continue;
  449. }
  450. }
  451. return null;
  452. }
  453. #endregion
  454. #region internal static Delegate GetExtensionDelegate(string name, Type signature)
  455. /// <summary>
  456. /// Creates a System.Delegate that can be used to call a dynamically exported OpenGL function.
  457. /// </summary>
  458. /// <param name="name">The name of the OpenGL function (eg. "glNewList")</param>
  459. /// <param name="signature">The signature of the OpenGL function.</param>
  460. /// <returns>
  461. /// A System.Delegate that can be used to call this OpenGL function or null
  462. /// if the function is not available in the current OpenGL context.
  463. /// </returns>
  464. internal static Delegate GetExtensionDelegate(string name, Type signature)
  465. {
  466. IntPtr address = GetAddress(name);
  467. if (address == IntPtr.Zero ||
  468. address == new IntPtr(1) || // Workaround for buggy nvidia drivers which return
  469. address == new IntPtr(2)) // 1 or 2 instead of IntPtr.Zero for some extensions.
  470. {
  471. return null;
  472. }
  473. else
  474. {
  475. return Marshal.GetDelegateForFunctionPointer(address, signature);
  476. }
  477. }
  478. #endregion
  479. #endregion
  480. }
  481. }