gls.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gls
  5. // #include <stdlib.h>
  6. // #include "glcorearb.h"
  7. // #include "glapi.h"
  8. import "C"
  9. import (
  10. "fmt"
  11. "math"
  12. "reflect"
  13. "unsafe"
  14. )
  15. // GLS encapsulates the state of an OpenGL context and contains
  16. // methods to call OpenGL functions.
  17. type GLS struct {
  18. stats Stats // statistics
  19. prog *Program // current active shader program
  20. programs map[*Program]bool // shader programs cache
  21. checkErrors bool // check openGL API errors flag
  22. activeTexture uint32 // cached last set active texture unit
  23. viewportX int32 // cached last set viewport x
  24. viewportY int32 // cached last set viewport y
  25. viewportWidth int32 // cached last set viewport width
  26. viewportHeight int32 // cached last set viewport height
  27. lineWidth float32 // cached last set line width
  28. sideView int // cached last set triangle side view mode
  29. frontFace uint32 // cached last set glFrontFace value
  30. depthFunc uint32 // cached last set depth function
  31. depthMask int // cached last set depth mask
  32. capabilities map[int]int // cached capabilities (Enable/Disable)
  33. blendEquation uint32 // cached last set blend equation value
  34. blendSrc uint32 // cached last set blend src value
  35. blendDst uint32 // cached last set blend equation destination value
  36. blendEquationRGB uint32 // cached last set blend equation rgb value
  37. blendEquationAlpha uint32 // cached last set blend equation alpha value
  38. blendSrcRGB uint32 // cached last set blend src rgb
  39. blendSrcAlpha uint32 // cached last set blend src alpha value
  40. blendDstRGB uint32 // cached last set blend destination rgb value
  41. blendDstAlpha uint32 // cached last set blend destination alpha value
  42. polygonModeFace uint32 // cached last set polygon mode face
  43. polygonModeMode uint32 // cached last set polygon mode mode
  44. polygonOffsetFactor float32 // cached last set polygon offset factor
  45. polygonOffsetUnits float32 // cached last set polygon offset units
  46. gobuf []byte // conversion buffer with GO memory
  47. cbuf []byte // conversion buffer with C memory
  48. }
  49. // Stats contains counters of OpenGL resources being used as well
  50. // the cummulative numbers of some OpenGL calls for performance evaluation.
  51. type Stats struct {
  52. Shaders int // Current number of shader programs
  53. Vaos int // Number of Vertex Array Objects
  54. Buffers int // Number of Buffer Objects
  55. Textures int // Number of Textures
  56. Caphits uint64 // Cummulative number of hits for Enable/Disable
  57. UnilocHits uint64 // Cummulative number of uniform location cache hits
  58. UnilocMiss uint64 // Cummulative number of uniform location cache misses
  59. Unisets uint64 // Cummulative number of uniform sets
  60. Drawcalls uint64 // Cummulative number of draw calls
  61. }
  62. // Polygon side view.
  63. const (
  64. FrontSide = iota + 1
  65. BackSide
  66. DoubleSide
  67. )
  68. const (
  69. capUndef = 0
  70. capDisabled = 1
  71. capEnabled = 2
  72. uintUndef = math.MaxUint32
  73. intFalse = 0
  74. intTrue = 1
  75. )
  76. const (
  77. FloatSize = int32(unsafe.Sizeof(float32(0)))
  78. )
  79. // New creates and returns a new instance of an GLS object
  80. // which encapsulates the state of an OpenGL context
  81. // This should be called only after an active OpenGL context
  82. // was established, such as by creating a new window.
  83. func New() (*GLS, error) {
  84. gs := new(GLS)
  85. gs.reset()
  86. // Load OpenGL functions
  87. err := C.glapiLoad()
  88. if err != 0 {
  89. return nil, fmt.Errorf("Error loading OpenGL")
  90. }
  91. gs.setDefaultState()
  92. gs.checkErrors = true
  93. // Preallocates conversion buffers
  94. size := 1 * 1024
  95. gs.gobuf = make([]byte, size)
  96. p := C.malloc(C.size_t(size))
  97. gs.cbuf = (*[1 << 30]byte)(unsafe.Pointer(p))[:size:size]
  98. return gs, nil
  99. }
  100. // SetCheckErrors enables/disables checking for errors after the
  101. // call of any OpenGL function. It is enabled by default but
  102. // could be disabled after an application is stable to improve the performance.
  103. func (gs *GLS) SetCheckErrors(enable bool) {
  104. if enable {
  105. C.glapiCheckError(1)
  106. } else {
  107. C.glapiCheckError(0)
  108. }
  109. gs.checkErrors = enable
  110. }
  111. // ChecksErrors returns if error checking is enabled or not.
  112. func (gs *GLS) CheckErrors() bool {
  113. return gs.checkErrors
  114. }
  115. // reset resets the internal state kept of the OpenGL
  116. func (gs *GLS) reset() {
  117. gs.lineWidth = 0.0
  118. gs.sideView = uintUndef
  119. gs.frontFace = 0
  120. gs.depthFunc = 0
  121. gs.depthMask = uintUndef
  122. gs.capabilities = make(map[int]int)
  123. gs.programs = make(map[*Program]bool)
  124. gs.prog = nil
  125. gs.activeTexture = uintUndef
  126. gs.blendEquation = uintUndef
  127. gs.blendSrc = uintUndef
  128. gs.blendDst = uintUndef
  129. gs.blendEquationRGB = 0
  130. gs.blendEquationAlpha = 0
  131. gs.blendSrcRGB = uintUndef
  132. gs.blendSrcAlpha = uintUndef
  133. gs.blendDstRGB = uintUndef
  134. gs.blendDstAlpha = uintUndef
  135. gs.polygonModeFace = 0
  136. gs.polygonModeMode = 0
  137. gs.polygonOffsetFactor = -1
  138. gs.polygonOffsetUnits = -1
  139. }
  140. // setDefaultState is used internally to set the initial state of OpenGL
  141. // for this context.
  142. func (gs *GLS) setDefaultState() {
  143. C.glClearColor(0, 0, 0, 1)
  144. C.glClearDepth(1)
  145. C.glClearStencil(0)
  146. gs.Enable(DEPTH_TEST)
  147. gs.DepthFunc(LEQUAL)
  148. gs.FrontFace(CCW)
  149. gs.CullFace(BACK)
  150. gs.Enable(CULL_FACE)
  151. gs.Enable(BLEND)
  152. gs.BlendEquation(FUNC_ADD)
  153. gs.BlendFunc(SRC_ALPHA, ONE_MINUS_SRC_ALPHA)
  154. gs.Enable(VERTEX_PROGRAM_POINT_SIZE)
  155. gs.Enable(PROGRAM_POINT_SIZE)
  156. gs.Enable(MULTISAMPLE)
  157. gs.Enable(POLYGON_OFFSET_FILL)
  158. gs.Enable(POLYGON_OFFSET_LINE)
  159. gs.Enable(POLYGON_OFFSET_POINT)
  160. }
  161. // Stats copy the current values of the internal statistics structure
  162. // to the specified pointer.
  163. func (gs *GLS) Stats(s *Stats) {
  164. *s = gs.stats
  165. s.Shaders = len(gs.programs)
  166. }
  167. func (gs *GLS) ActiveTexture(texture uint32) {
  168. if gs.activeTexture == texture {
  169. return
  170. }
  171. C.glActiveTexture(C.GLenum(texture))
  172. gs.activeTexture = texture
  173. }
  174. func (gs *GLS) AttachShader(program, shader uint32) {
  175. C.glAttachShader(C.GLuint(program), C.GLuint(shader))
  176. }
  177. func (gs *GLS) BindBuffer(target int, vbo uint32) {
  178. C.glBindBuffer(C.GLenum(target), C.GLuint(vbo))
  179. }
  180. func (gs *GLS) BindTexture(target int, tex uint32) {
  181. C.glBindTexture(C.GLenum(target), C.GLuint(tex))
  182. }
  183. func (gs *GLS) BindVertexArray(vao uint32) {
  184. C.glBindVertexArray(C.GLuint(vao))
  185. }
  186. func (gs *GLS) BlendEquation(mode uint32) {
  187. if gs.blendEquation == mode {
  188. return
  189. }
  190. C.glBlendEquation(C.GLenum(mode))
  191. gs.blendEquation = mode
  192. }
  193. func (gs *GLS) BlendEquationSeparate(modeRGB uint32, modeAlpha uint32) {
  194. if gs.blendEquationRGB == modeRGB && gs.blendEquationAlpha == modeAlpha {
  195. return
  196. }
  197. C.glBlendEquationSeparate(C.GLenum(modeRGB), C.GLenum(modeAlpha))
  198. gs.blendEquationRGB = modeRGB
  199. gs.blendEquationAlpha = modeAlpha
  200. }
  201. func (gs *GLS) BlendFunc(sfactor, dfactor uint32) {
  202. if gs.blendSrc == sfactor && gs.blendDst == dfactor {
  203. return
  204. }
  205. C.glBlendFunc(C.GLenum(sfactor), C.GLenum(dfactor))
  206. gs.blendSrc = sfactor
  207. gs.blendDst = dfactor
  208. }
  209. func (gs *GLS) BlendFuncSeparate(srcRGB uint32, dstRGB uint32, srcAlpha uint32, dstAlpha uint32) {
  210. if gs.blendSrcRGB == srcRGB && gs.blendDstRGB == dstRGB &&
  211. gs.blendSrcAlpha == srcAlpha && gs.blendDstAlpha == dstAlpha {
  212. return
  213. }
  214. C.glBlendFuncSeparate(C.GLenum(srcRGB), C.GLenum(dstRGB), C.GLenum(srcAlpha), C.GLenum(dstAlpha))
  215. gs.blendSrcRGB = srcRGB
  216. gs.blendDstRGB = dstRGB
  217. gs.blendSrcAlpha = srcAlpha
  218. gs.blendDstAlpha = dstAlpha
  219. }
  220. func (gs *GLS) BufferData(target uint32, size int, data interface{}, usage uint32) {
  221. C.glBufferData(C.GLenum(target), C.GLsizeiptr(size), ptr(data), C.GLenum(usage))
  222. }
  223. func (gs *GLS) ClearColor(r, g, b, a float32) {
  224. C.glClearColor(C.GLfloat(r), C.GLfloat(g), C.GLfloat(b), C.GLfloat(a))
  225. }
  226. func (gs *GLS) Clear(mask uint) {
  227. C.glClear(C.GLbitfield(mask))
  228. }
  229. func (gs *GLS) CompileShader(shader uint32) {
  230. C.glCompileShader(C.GLuint(shader))
  231. }
  232. func (gs *GLS) CreateProgram() uint32 {
  233. p := C.glCreateProgram()
  234. return uint32(p)
  235. }
  236. func (gs *GLS) CreateShader(stype uint32) uint32 {
  237. h := C.glCreateShader(C.GLenum(stype))
  238. return uint32(h)
  239. }
  240. func (gs *GLS) DeleteBuffers(bufs ...uint32) {
  241. C.glDeleteBuffers(C.GLsizei(len(bufs)), (*C.GLuint)(&bufs[0]))
  242. gs.stats.Buffers -= len(bufs)
  243. }
  244. func (gs *GLS) DeleteShader(shader uint32) {
  245. C.glDeleteShader(C.GLuint(shader))
  246. }
  247. func (gs *GLS) DeleteProgram(program uint32) {
  248. C.glDeleteProgram(C.GLuint(program))
  249. }
  250. func (gs *GLS) DeleteTextures(tex ...uint32) {
  251. C.glDeleteTextures(C.GLsizei(len(tex)), (*C.GLuint)(&tex[0]))
  252. gs.stats.Textures -= len(tex)
  253. }
  254. func (gs *GLS) DeleteVertexArrays(vaos ...uint32) {
  255. C.glDeleteVertexArrays(C.GLsizei(len(vaos)), (*C.GLuint)(&vaos[0]))
  256. gs.stats.Vaos -= len(vaos)
  257. }
  258. func (gs *GLS) DepthFunc(mode uint32) {
  259. if gs.depthFunc == mode {
  260. return
  261. }
  262. C.glDepthFunc(C.GLenum(mode))
  263. gs.depthFunc = mode
  264. }
  265. func (gs *GLS) DepthMask(flag bool) {
  266. if gs.depthMask == intTrue && flag {
  267. return
  268. }
  269. if gs.depthMask == intFalse && !flag {
  270. return
  271. }
  272. C.glDepthMask(bool2c(flag))
  273. if flag {
  274. gs.depthMask = intTrue
  275. } else {
  276. gs.depthMask = intFalse
  277. }
  278. }
  279. func (gs *GLS) DrawArrays(mode uint32, first int32, count int32) {
  280. C.glDrawArrays(C.GLenum(mode), C.GLint(first), C.GLsizei(count))
  281. gs.stats.Drawcalls++
  282. }
  283. func (gs *GLS) DrawElements(mode uint32, count int32, itype uint32, start uint32) {
  284. C.glDrawElements(C.GLenum(mode), C.GLsizei(count), C.GLenum(itype), unsafe.Pointer(uintptr(start)))
  285. gs.stats.Drawcalls++
  286. }
  287. func (gs *GLS) Enable(cap int) {
  288. if gs.capabilities[cap] == capEnabled {
  289. gs.stats.Caphits++
  290. return
  291. }
  292. C.glEnable(C.GLenum(cap))
  293. gs.capabilities[cap] = capEnabled
  294. }
  295. func (gs *GLS) EnableVertexAttribArray(index uint32) {
  296. C.glEnableVertexAttribArray(C.GLuint(index))
  297. }
  298. func (gs *GLS) Disable(cap int) {
  299. if gs.capabilities[cap] == capDisabled {
  300. gs.stats.Caphits++
  301. return
  302. }
  303. C.glDisable(C.GLenum(cap))
  304. gs.capabilities[cap] = capDisabled
  305. }
  306. func (gs *GLS) CullFace(mode uint32) {
  307. C.glCullFace(C.GLenum(mode))
  308. }
  309. func (gs *GLS) FrontFace(mode uint32) {
  310. if gs.frontFace == mode {
  311. return
  312. }
  313. C.glFrontFace(C.GLenum(mode))
  314. gs.frontFace = mode
  315. }
  316. func (gs *GLS) GenBuffer() uint32 {
  317. var buf uint32
  318. C.glGenBuffers(1, (*C.GLuint)(&buf))
  319. gs.stats.Buffers++
  320. return buf
  321. }
  322. func (gs *GLS) GenerateMipmap(target uint32) {
  323. C.glGenerateMipmap(C.GLenum(target))
  324. }
  325. func (gs *GLS) GenTexture() uint32 {
  326. var tex uint32
  327. C.glGenTextures(1, (*C.GLuint)(&tex))
  328. gs.stats.Textures++
  329. return tex
  330. }
  331. func (gs *GLS) GenVertexArray() uint32 {
  332. var vao uint32
  333. C.glGenVertexArrays(1, (*C.GLuint)(&vao))
  334. gs.stats.Vaos++
  335. return vao
  336. }
  337. func (gs *GLS) GetAttribLocation(program uint32, name string) int32 {
  338. loc := C.glGetAttribLocation(C.GLuint(program), gs.gobufStr(name))
  339. return int32(loc)
  340. }
  341. func (gs *GLS) GetProgramiv(program, pname uint32, params *int32) {
  342. C.glGetProgramiv(C.GLuint(program), C.GLenum(pname), (*C.GLint)(params))
  343. }
  344. // GetProgramInfoLog returns the information log for the specified program object.
  345. func (gs *GLS) GetProgramInfoLog(program uint32) string {
  346. var length int32
  347. gs.GetProgramiv(program, INFO_LOG_LENGTH, &length)
  348. if length == 0 {
  349. return ""
  350. }
  351. C.glGetProgramInfoLog(C.GLuint(program), C.GLsizei(length), nil, gs.gobufSize(uint32(length)))
  352. return string(gs.gobuf[:length])
  353. }
  354. // GetShaderInfoLog returns the information log for the specified shader object.
  355. func (gs *GLS) GetShaderInfoLog(shader uint32) string {
  356. var length int32
  357. gs.GetShaderiv(shader, INFO_LOG_LENGTH, &length)
  358. if length == 0 {
  359. return ""
  360. }
  361. C.glGetShaderInfoLog(C.GLuint(shader), C.GLsizei(length), nil, gs.gobufSize(uint32(length)))
  362. return string(gs.gobuf[:length])
  363. }
  364. func (gs *GLS) GetString(name uint32) string {
  365. cs := C.glGetString(C.GLenum(name))
  366. return C.GoString((*C.char)(unsafe.Pointer(cs)))
  367. }
  368. // GetUniformLocation returns the location of a uniform variable for the specified program.
  369. func (gs *GLS) GetUniformLocation(program uint32, name string) int32 {
  370. loc := C.glGetUniformLocation(C.GLuint(program), gs.gobufStr(name))
  371. return int32(loc)
  372. }
  373. func (gs *GLS) GetViewport() (x, y, width, height int32) {
  374. return gs.viewportX, gs.viewportY, gs.viewportWidth, gs.viewportHeight
  375. }
  376. func (gs *GLS) LineWidth(width float32) {
  377. if gs.lineWidth == width {
  378. return
  379. }
  380. C.glLineWidth(C.GLfloat(width))
  381. gs.lineWidth = width
  382. }
  383. func (gs *GLS) LinkProgram(program uint32) {
  384. C.glLinkProgram(C.GLuint(program))
  385. }
  386. func (gs *GLS) GetShaderiv(shader, pname uint32, params *int32) {
  387. C.glGetShaderiv(C.GLuint(shader), C.GLenum(pname), (*C.GLint)(params))
  388. }
  389. func (gs *GLS) ShaderSource(shader uint32, src string) {
  390. csource := gs.cbufStr(src)
  391. C.glShaderSource(C.GLuint(shader), 1, (**C.GLchar)(unsafe.Pointer(&csource)), nil)
  392. }
  393. func (gs *GLS) TexImage2D(target uint32, level int32, iformat int32, width int32, height int32, border int32, format uint32, itype uint32, data interface{}) {
  394. C.glTexImage2D(C.GLenum(target),
  395. C.GLint(level),
  396. C.GLint(iformat),
  397. C.GLsizei(width),
  398. C.GLsizei(height),
  399. C.GLint(border),
  400. C.GLenum(format),
  401. C.GLenum(itype),
  402. ptr(data))
  403. }
  404. func (gs *GLS) TexParameteri(target uint32, pname uint32, param int32) {
  405. C.glTexParameteri(C.GLenum(target), C.GLenum(pname), C.GLint(param))
  406. }
  407. func (gs *GLS) PolygonMode(face, mode uint32) {
  408. if gs.polygonModeFace == face && gs.polygonModeMode == mode {
  409. return
  410. }
  411. C.glPolygonMode(C.GLenum(face), C.GLenum(mode))
  412. gs.polygonModeFace = face
  413. gs.polygonModeMode = mode
  414. }
  415. func (gs *GLS) PolygonOffset(factor float32, units float32) {
  416. if gs.polygonOffsetFactor == factor && gs.polygonOffsetUnits == units {
  417. return
  418. }
  419. C.glPolygonOffset(C.GLfloat(factor), C.GLfloat(units))
  420. gs.polygonOffsetFactor = factor
  421. gs.polygonOffsetUnits = units
  422. }
  423. func (gs *GLS) Uniform1i(location int32, v0 int32) {
  424. C.glUniform1i(C.GLint(location), C.GLint(v0))
  425. gs.stats.Unisets++
  426. }
  427. func (gs *GLS) Uniform1f(location int32, v0 float32) {
  428. C.glUniform1f(C.GLint(location), C.GLfloat(v0))
  429. gs.stats.Unisets++
  430. }
  431. func (gs *GLS) Uniform2f(location int32, v0, v1 float32) {
  432. C.glUniform2f(C.GLint(location), C.GLfloat(v0), C.GLfloat(v1))
  433. gs.stats.Unisets++
  434. }
  435. func (gs *GLS) Uniform3f(location int32, v0, v1, v2 float32) {
  436. C.glUniform3f(C.GLint(location), C.GLfloat(v0), C.GLfloat(v1), C.GLfloat(v2))
  437. gs.stats.Unisets++
  438. }
  439. func (gs *GLS) Uniform4f(location int32, v0, v1, v2, v3 float32) {
  440. C.glUniform4f(C.GLint(location), C.GLfloat(v0), C.GLfloat(v1), C.GLfloat(v2), C.GLfloat(v3))
  441. gs.stats.Unisets++
  442. }
  443. func (gs *GLS) UniformMatrix3fv(location int32, count int32, transpose bool, pm *float32) {
  444. C.glUniformMatrix3fv(C.GLint(location), C.GLsizei(count), bool2c(transpose), (*C.GLfloat)(pm))
  445. gs.stats.Unisets++
  446. }
  447. func (gs *GLS) UniformMatrix4fv(location int32, count int32, transpose bool, pm *float32) {
  448. C.glUniformMatrix4fv(C.GLint(location), C.GLsizei(count), bool2c(transpose), (*C.GLfloat)(pm))
  449. gs.stats.Unisets++
  450. }
  451. func (gs *GLS) Uniform1fv(location int32, count int32, v []float32) {
  452. C.glUniform1fv(C.GLint(location), C.GLsizei(count), (*C.GLfloat)(&v[0]))
  453. gs.stats.Unisets++
  454. }
  455. func (gs *GLS) Uniform2fv(location int32, count int32, v []float32) {
  456. C.glUniform2fv(C.GLint(location), C.GLsizei(count), (*C.GLfloat)(&v[0]))
  457. gs.stats.Unisets++
  458. }
  459. func (gs *GLS) Uniform3fv(location int32, count int32, v []float32) {
  460. C.glUniform3fv(C.GLint(location), C.GLsizei(count), (*C.GLfloat)(&v[0]))
  461. gs.stats.Unisets++
  462. }
  463. func (gs *GLS) Uniform4fv(location int32, count int32, v []float32) {
  464. C.glUniform4fv(C.GLint(location), C.GLsizei(count), (*C.GLfloat)(&v[0]))
  465. gs.stats.Unisets++
  466. }
  467. func (gs *GLS) VertexAttribPointer(index uint32, size int32, xtype uint32, normalized bool, stride int32, offset uint32) {
  468. C.glVertexAttribPointer(C.GLuint(index), C.GLint(size), C.GLenum(xtype), bool2c(normalized), C.GLsizei(stride), unsafe.Pointer(uintptr(offset)))
  469. }
  470. func (gs *GLS) Viewport(x, y, width, height int32) {
  471. C.glViewport(C.GLint(x), C.GLint(y), C.GLsizei(width), C.GLsizei(height))
  472. gs.viewportX = x
  473. gs.viewportY = y
  474. gs.viewportWidth = width
  475. gs.viewportHeight = height
  476. }
  477. // Use set this program as the current program.
  478. func (gs *GLS) UseProgram(prog *Program) {
  479. if prog.handle == 0 {
  480. panic("Invalid program")
  481. }
  482. C.glUseProgram(C.GLuint(prog.handle))
  483. gs.prog = prog
  484. // Inserts program in cache if not already there.
  485. if !gs.programs[prog] {
  486. gs.programs[prog] = true
  487. log.Debug("New Program activated. Total: %d", len(gs.programs))
  488. }
  489. }
  490. // Ptr takes a slice or pointer (to a singular scalar value or the first
  491. // element of an array or slice) and returns its GL-compatible address.
  492. //
  493. // For example:
  494. //
  495. // var data []uint8
  496. // ...
  497. // gl.TexImage2D(gl.TEXTURE_2D, ..., gl.UNSIGNED_BYTE, gl.Ptr(&data[0]))
  498. func ptr(data interface{}) unsafe.Pointer {
  499. if data == nil {
  500. return unsafe.Pointer(nil)
  501. }
  502. var addr unsafe.Pointer
  503. v := reflect.ValueOf(data)
  504. switch v.Type().Kind() {
  505. case reflect.Ptr:
  506. e := v.Elem()
  507. switch e.Kind() {
  508. case
  509. reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
  510. reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
  511. reflect.Float32, reflect.Float64:
  512. addr = unsafe.Pointer(e.UnsafeAddr())
  513. default:
  514. panic(fmt.Errorf("unsupported pointer to type %s; must be a slice or pointer to a singular scalar value or the first element of an array or slice", e.Kind()))
  515. }
  516. case reflect.Uintptr:
  517. addr = unsafe.Pointer(v.Pointer())
  518. case reflect.Slice:
  519. addr = unsafe.Pointer(v.Index(0).UnsafeAddr())
  520. default:
  521. panic(fmt.Errorf("unsupported type %s; must be a slice or pointer to a singular scalar value or the first element of an array or slice", v.Type()))
  522. }
  523. return addr
  524. }
  525. // bool2c convert a Go bool to C.GLboolean
  526. func bool2c(b bool) C.GLboolean {
  527. if b {
  528. return C.GLboolean(1)
  529. }
  530. return C.GLboolean(0)
  531. }
  532. // gobufSize returns a pointer to static buffer with the specified size not including the terminator.
  533. // If there is available space, there is no memory allocation.
  534. func (gs *GLS) gobufSize(size uint32) *C.GLchar {
  535. if size+1 > uint32(len(gs.gobuf)) {
  536. gs.gobuf = make([]byte, size+1)
  537. }
  538. return (*C.GLchar)(unsafe.Pointer(&gs.gobuf[0]))
  539. }
  540. // gobufStr converts a Go String to a C string by copying it to a static buffer
  541. // and returning a pointer to the start of the buffer.
  542. // If there is available space, there is no memory allocation.
  543. func (gs *GLS) gobufStr(s string) *C.GLchar {
  544. p := gs.gobufSize(uint32(len(s) + 1))
  545. copy(gs.gobuf, s)
  546. gs.gobuf[len(s)] = 0
  547. return p
  548. }
  549. // cbufSize returns a pointer to static buffer with C memory
  550. // If there is available space, there is no memory allocation.
  551. func (gs *GLS) cbufSize(size uint32) *C.GLchar {
  552. if size > uint32(len(gs.cbuf)) {
  553. if len(gs.cbuf) > 0 {
  554. C.free(unsafe.Pointer(&gs.cbuf[0]))
  555. }
  556. p := C.malloc(C.size_t(size))
  557. gs.cbuf = (*[1 << 30]byte)(unsafe.Pointer(p))[:size:size]
  558. }
  559. return (*C.GLchar)(unsafe.Pointer(&gs.cbuf[0]))
  560. }
  561. // cbufStr converts a Go String to a C string by copying it to a single pre-allocated buffer
  562. // using C memory and returning a pointer to the start of the buffer.
  563. // If there is available space, there is no memory allocation.
  564. func (gs *GLS) cbufStr(s string) *C.GLchar {
  565. p := gs.cbufSize(uint32(len(s) + 1))
  566. copy(gs.cbuf, s)
  567. gs.cbuf[len(s)] = 0
  568. return p
  569. }