OpenGL: Difference between revisions

46,717 bytes added ,  4 months ago
m
No edit summary
m (→‎{{header|Wren}}: Minor tidy)
 
(38 intermediate revisions by 15 users not shown)
Line 1:
{{task|3D}}
[[Category:GUI]]
[[Category:GUI]][[Category:Temporal media]]{{requires|Graphics}}In this task, the goal is to display a smooth shaded triangle with OpenGL.
[[Category:Temporal media]]
{{requires|Graphics}}
 
;Task:
[[image:Triangle.png|right|thumb|150px|Triangle created using C example compiled with [[GCC]] 4.1.2 and [[freeglut3]].]]
Display a smooth shaded triangle with OpenGL.
 
[[image:Triangle.png|right|thumb|300px|Triangle created using C example compiled with [[GCC]] 4.1.2 and [[freeglut3]].]]
<br><br>
 
=={{header|Ada}}==
Line 8 ⟶ 14:
 
opengl.adb:
<langsyntaxhighlight Adalang="ada">with Lumen.Window;
with Lumen.Events;
with Lumen.Events.Animate;
Line 128 ⟶ 134:
when Program_Exit =>
null; -- normal termination
end OpenGL;</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">hOpenGL32 := DllCall("LoadLibrary", "Str", "opengl32")
Gui, +LastFound +Resize
hDC := DllCall("GetDC", "uInt", WinExist())
Line 191 ⟶ 197:
DllCall("ReleaseDC", "uInt", hDC)
DllCall("FreeLibrary", "uInt", hOpenGL32)
ExitApp</langsyntaxhighlight>
 
 
=={{header|BaCon}}==
BaCon allows embedding C code. This is an example with GLUT.
<langsyntaxhighlight lang="qbasic">PRAGMA INCLUDE <GL/gl.h> <GL/freeglut.h>
PRAGMA LDFLAGS GL glut
 
Line 229 ⟶ 234:
 
glutDisplayFunc(Triangle)
glutMainLoop()</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> *FLOAT64
SYS "LoadLibrary", "OPENGL32.DLL" TO opengl%
Line 314 ⟶ 319:
ghRC% += 0 : IF ghRC% SYS `wglDeleteContext`, ghRC% : ghRC% = 0
ghDC% += 0 : IF ghDC% SYS "ReleaseDC", @hwnd%, ghDC% : ghDC% = 0
ENDPROC</langsyntaxhighlight>
 
=={{header|C}}==
Line 321 ⟶ 326:
In this example, we use [[:Category:GLUT|GLUT]] to create a window and handle the main loop in a portable way. Windowing systems like MS Windows and X11 have their own platform-specific ways of handling these things.
 
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <GL/gl.h>
#include <GL/glut.h>
Line 368 ⟶ 373:
 
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
C# example using the [http://www.opentk.com/ OpenTK] library, which is multiplatform and provides C# OpenGL bindings for .Net and Mono. This code creates its own window and draws the triangle into it.
 
<langsyntaxhighlight lang="csharp">using OpenTK;
using OpenTK.Graphics;
namespace OpenGLTest
Line 416 ⟶ 421:
}
}
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
Line 422 ⟶ 427:
 
In this example, we use [http://github.com/ztellman/penumbra Penumbra], which is an idiomatic wrapper for OpenGL.
<langsyntaxhighlight lang="lisp">(use 'penumbra.opengl)
(require '[penumbra.app :as app])
 
Line 443 ⟶ 448:
(color 0 0 1) (vertex 0 30)))
 
(app/start {:display display, :reshape reshape, :init init} {})</langsyntaxhighlight>
 
=={{header|D}}==
{{works with|GDC}}
 
{{works with|DMD}}
 
{{libheader|dglut}}
opengl_sample.d:
<lang d>module opengl_sample; // file name + directory
import dglut.core, dglut.window, dglut.opengl;
 
void main() {
with (new Canvas) {
setName("Triangle");
map;
 
onResize = (Canvas self) { // A delegate literal that takes a parameter.
with (self) glViewport(0, 0, width, height);
MatrixMode.Projection.Identity; // For functions without parameters, the () can be omitted.
glOrtho(-30, 30, -30, 30, -30, 30);
MatrixMode.Modelview;
};
 
onDisplay=(Canvas self) {
scope(exit) self.swap; // Scope guards ease exception-safe programming
glClearColor(0.3f, 0.3f, 0.3f, 0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity;
// A convenience wrapper around glTranslatef. Supports numbers, arrays and vectors.
Translate(-15, -15, 0);
// This is a delegate literal as well. Triangles is a wrapper around glBegin and glEnd.
Triangles = {
Color(1f, 0f, 0f); Vertex(0, 0);
Color(0f, 1f, 0f); Vertex(30, 0);
Color(0f, 0f, 1f); Vertex(0, 30);
};
};
}
loop;
}</lang>
 
=={{header|Common Lisp}}==
Line 492 ⟶ 457:
{{libheader|Lispbuilder-SDL}}
 
<langsyntaxhighlight lang="lisp">(defun draw-triangle (x y &key (z 0) (type 'right))
(case type
(right
Line 558 ⟶ 523:
(setup-gl w h)
(setf (sdl:frame-rate) 2)
(main-loop)))</langsyntaxhighlight>
 
=={{header|D}}==
{{works with|GDC}}
 
{{works with|DMD}}
 
{{libheader|dglut}}
opengl_sample.d:
<syntaxhighlight lang="d">module opengl_sample; // file name + directory
import dglut.core, dglut.window, dglut.opengl;
 
void main() {
with (new Canvas) {
setName("Triangle");
map;
 
onResize = (Canvas self) { // A delegate literal that takes a parameter.
with (self) glViewport(0, 0, width, height);
MatrixMode.Projection.Identity; // For functions without parameters, the () can be omitted.
glOrtho(-30, 30, -30, 30, -30, 30);
MatrixMode.Modelview;
};
 
onDisplay=(Canvas self) {
scope(exit) self.swap; // Scope guards ease exception-safe programming
glClearColor(0.3f, 0.3f, 0.3f, 0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity;
// A convenience wrapper around glTranslatef. Supports numbers, arrays and vectors.
Translate(-15, -15, 0);
// This is a delegate literal as well. Triangles is a wrapper around glBegin and glEnd.
Triangles = {
Color(1f, 0f, 0f); Vertex(0, 0);
Color(0f, 1f, 0f); Vertex(30, 0);
Color(0f, 0f, 1f); Vertex(0, 30);
};
};
}
loop;
}</syntaxhighlight>
=={{header|Delphi}}==
{{libheader| System.Classes}}
{{libheader| Sample.App}}
{{libheader| Winapi.OpenGL}}
{{libheader| System.UITypes}}
Thanks Neslib for libraries FastMath [https://github.com/neslib/FastMath], DelphiStb [https://github.com/neslib/DelphiStb] and Samples codes [https://github.com/neslib/DelphiLearnOpenGL] to abstract openGl functions and window creation.
<syntaxhighlight lang="delphi">
program OpenGLTriangle;
 
{$APPTYPE CONSOLE}
 
uses
System.Classes,
Sample.App,
Winapi.OpenGL,
System.UITypes;
 
type
TTriangleApp = class(TApplication)
public
procedure Initialize; override;
procedure Update(const ADeltaTimeSec, ATotalTimeSec: Double); override;
procedure Shutdown; override;
procedure KeyDown(const AKey: Integer; const AShift: TShiftState); override;
end;
 
{ TTriangleApp }
 
procedure TTriangleApp.Initialize;
begin
inherited;
glViewport(0, 0, width, height);
 
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0);
glMatrixMode(GL_MODELVIEW);
end;
 
procedure TTriangleApp.KeyDown(const AKey: Integer; const AShift: TShiftState);
begin
inherited;
if (AKey = vkEscape) then
Terminate;
end;
 
procedure TTriangleApp.Shutdown;
begin
inherited;
// Writeln('App is Shutdown');
end;
 
procedure TTriangleApp.Update(const ADeltaTimeSec, ATotalTimeSec: Double);
begin
inherited;
 
glClearColor(0.3, 0.3, 0.3, 0.0);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
 
glShadeModel(GL_SMOOTH);
 
glLoadIdentity();
glTranslatef(-15.0, -15.0, 0.0);
 
glBegin(GL_TRIANGLES);
glColor3f(1.0, 0.0, 0.0);
glVertex2f(0.0, 0.0);
glColor3f(0.0, 1.0, 0.0);
glVertex2f(30.0, 0.0);
glColor3f(0.0, 0.0, 1.0);
glVertex2f(0.0, 30.0);
glEnd();
 
glFlush();
end;
 
begin
RunApp(TTriangleApp, 640, 480, 'OpenGL Triangle');
end.</syntaxhighlight>
 
=={{header|eC}}==
{{libheader|Ecere}}
 
<langsyntaxhighlight Clang="c">#include <GL/gl.h>
import "ecere"
 
Line 597 ⟶ 681:
}
 
GLTriangle window {};</langsyntaxhighlight>
 
 
=={{header|Euphoria}}==
{{works with|OpenEuphoria < 4.0}}
Adapted from NeHe tutorial #3 nehe.gamedev.net
<langsyntaxhighlight lang="euphoria">
include get.e
include dll.e
Line 896 ⟶ 979:
 
WinMain()
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
Translated from C
<langsyntaxhighlight lang="factor">USING: kernel math math.rectangles opengl.gl sequences ui
ui.gadgets ui.render ;
IN: rosettacode.opengl
Line 933 ⟶ 1,016:
[ triangle-gadget new "Triangle" open-window ] with-ui ;
MAIN: triangle-window
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
Line 940 ⟶ 1,023:
{{libheader|Theseus}}
triangle.fs:
<langsyntaxhighlight lang="forth">import glconst import float
glconst also float also opengl also</langsyntaxhighlight>
 
triangle.m:
<langsyntaxhighlight lang="forth">#! xbigforth
\ automatic generated code
\ do not edit
Line 997 ⟶ 1,080:
$1 0 ?DO stop LOOP bye ;
script? [IF] main [THEN]
previous previous previous</langsyntaxhighlight>
 
=={{header|GoFreeBASIC}}==
This is adapted from example OpenGL code that's included with FreeBASIC distributions.
The win package used in this example is a simple wrapper around [http://www.glfw.org/ GLFW].
 
<syntaxhighlight lang="freebasic">#include "fbgfx.bi"
<lang go>// triangle displays a smooth shaded triangle with OpenGL.
#include once "GL/gl.bi"
package main
#include once "GL/glu.bi"
 
screen 18, 16, , 2
import (
"log"
"runtime"
"time"
 
glViewport 0, 0, 640, 480 'Set the viewport
gl "github.com/chsc/gogl/gl21"
glMatrixMode GL_PROJECTION ' Select projection
"github.com/mewmew/glfw/win"
glLoadIdentity ' Set this to default
gluPerspective 45.0, 640./480., 0.1, 100.0 ' Set perspective view options
glMatrixMode GL_MODELVIEW ' Set to modelview mode
glLoadIdentity ' ...and set it to default
glClearColor 0.5, 0.5, 0.5, 0.0 ' Set clearscreen color to middle grey
glShadeModel GL_SMOOTH ' set to smooth shading
glClearDepth 1.0 ' Allow the deletion of the depth buffer
glEnable GL_DEPTH_TEST ' turn on depth testing
glDepthFunc GL_LEQUAL ' The Type Of Depth Test To Do
glHint GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ' niceness tweaks
 
do
 
glClear GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT ' clear screen and depth
glLoadIdentity
 
glTranslatef 0.0f, 0.0f, -6.0f ' move camera back so we can see the triangle
 
glBegin GL_TRIANGLES ' Drawing Using Triangles
glColor3f 1.0f, 0.0f, 0.0f ' red
glVertex3f 0.0f, 1.0f, 0.0f ' Top
glColor3f 0.0f, 1.0f, 0.0f ' green
glVertex3f -1.0f,-1.0f, 0.0f ' Bottom Left
glColor3f 0.0f, 0.0f, 1.0f ' blue
glVertex3f 1.0f,-1.0f, 0.0f ' Bottom Right
glEnd ' Finished Drawing The Triangle
 
flip
 
loop while inkey = ""</syntaxhighlight>
 
=={{header|Go}}==
{{libheader|GoGL}}
{{libheader|GLFW 3.2 for Go}}
{{works with|Ubuntu 16.04}}
<br>
This program was also tested on Windows 10 but ''may'' only work if you comment out the marked line. This is because gl.Init() may produce an initialization error which is non-critical as far as this program is concerned. The reason for this error is unknown (see [[https://rosettacode.org/wiki/Talk:OpenGL Talk page]]).
<syntaxhighlight lang="go">package main
 
import (
gl "github.com/chsc/gogl/gl21"
"github.com/go-gl/glfw/v3.2/glfw"
"log"
"runtime"
)
 
// Window dimensions.
const (
Width = 640
Height = 480
)
 
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
 
func main() {
// OpenGL requires a dedicated OS thread.
runtime.LockOSThread()
defer runtime.UnlockOSThread()
 
err := glfw.Init()
// Open window with the specified dimensions.
check(err)
err := win.Open(Width, Height)
defer glfw.Terminate()
if err != nil {
log.Fatalln(err)
}
defer win.Close()
 
// Open window with the specified dimensions.
// Initiate viewport.
resize window, err := glfw.CreateWindow(Width, Height, "Triangle", nil, nil)
check(err)
 
window.MakeContextCurrent()
// Register that we are interested in receiving close and resize events.
win.EnableCloseChan()
win.EnableResizeChan()
 
err = gl.Init()
// 60 frames per second.
check(err) /* may need to comment out this line for this program to work on Windows 10 */
c := time.Tick(time.Second / 60)
 
// Initiate viewport.
// Event loop.
resize(Width, Height)
for {
 
select {
// Register that we are interested in receiving close and resize events.
case <-win.CloseChan:
window.SetCloseCallback(func(w *glfw.Window) {
return
return
case e := <-win.ResizeChan:
})
resize(e.Width, e.Height)
window.SetSizeCallback(func(w *glfw.Window, width, height int) {
case <-c:
resize(width, height)
draw()
})
}
 
}
for !window.ShouldClose() {
draw()
window.SwapBuffers()
glfw.PollEvents()
}
}
 
// resize resizes the window to the specified dimensions.
func resize(width, height int) {
gl.Viewport(0, 0, gl.Sizei(width), gl.Sizei(height))
gl.MatrixMode(gl.PROJECTION)
gl.LoadIdentity()
gl.Ortho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0)
gl.MatrixMode(gl.MODELVIEW)
}
 
// draw draws the triangle.
func draw() {
gl.ClearColor(0.3, 0.3, 0.3, 0.0)
gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
 
gl.ShadeModel(gl.SMOOTH)
 
gl.LoadIdentity()
gl.Translatef(-15.0, -15.0, 0.0)
 
gl.Begin(gl.TRIANGLES)
 
gl.Color3f(1.0, 0.0, 0.0)
gl.Vertex2f(0.0, 0.0)
 
gl.Color3f(0.0, 1.0, 0.0)
gl.Vertex2f(30.0, 0.0)
 
gl.Color3f(0.0, 0.0, 1.0)
gl.Vertex2f(0.0, 30.0)
 
gl.End()
 
gl.Flush()
win.SwapBuffers()
}</syntaxhighlight>
}
</lang>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Graphics.Rendering.OpenGL
import Graphics.UI.GLUT
 
Line 1,116 ⟶ 1,247:
corner r g b x y = do color (Color3 r g b :: Color3 GLfloat)
vertex (Vertex2 x y :: Vertex2 GLfloat)</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,124 ⟶ 1,255:
Additionally, if you are using 64 bit windows, to get opengl working on J602 you will need to copy jzopengl_win.ijs to jzopengl_win_64.ijs in system/classes/opengl/.
 
<langsyntaxhighlight Jlang="j">coclass 'example'
(coinsert[require) 'jzopengl'
 
Line 1,154 ⟶ 1,285:
)
 
conew~'example'</langsyntaxhighlight>
 
Note: OpenGL's initial state is well defined by the OpenGL standard.
Line 1,160 ⟶ 1,291:
=={{header|Java}}==
This example uses [http://lwjgl.org/ LWJGL], a game library which has an OpenGL binding for Java
<langsyntaxhighlight Javalang="java">import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
Line 1,218 ⟶ 1,349:
}
 
</syntaxhighlight>
</lang>
 
=={{header|JavaScript}}==
 
=={{header|JavaScript}} =(WebGL)===
 
Unfortunately for comparison with the other examples on this page, WebGL provides only OpenGL ES, which removes the classic “fixed-function pipeline” and glVertex() in favor of requiring you to write ''vertex shaders'' and ''fragment shaders'', and use vertex arrays. It is not hard to write shader programs to emulate as much of the fixed-function pipeline as you need, but it does mean more verbosity as you have to explicitly define all of the data you're going to communicate to your shader.
Line 1,227 ⟶ 1,359:
In the interest of brevity and not depending on an external matrix library, this example ''omits matrix operations entirely'', as OpenGL ES requires you to add those features yourself if you want them. Examples which show how to implement the classic OpenGL matrix stack are available at [http://learningwebgl.com/blog/?page_id=1217 Learning WebGL] (which this code was derived from).
 
<langsyntaxhighlight lang="html"><html style="margin: 0;">
<head>
<title>Minimal WebGL Example</title>
Line 1,342 ⟶ 1,474:
</script>
</body>
</html></langsyntaxhighlight>
 
=={{header|Julia}}==
Julia's Makie plotting package uses OpenGL as its backend. This example is from the Makie documentation.
<syntaxhighlight lang="julia">using Makie
 
mesh([(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)], color = [:red, :green, :blue], shading = false)
</syntaxhighlight>
 
=={{header|Kotlin}}==
Line 1,348 ⟶ 1,487:
{{libheader|GLUT}}
{{Works with|Ubuntu 14.04}}
<langsyntaxhighlight lang="scala">// Kotlin Native version 0.3
 
import kotlinx.cinterop.*
Line 1,395 ⟶ 1,534:
glutMainLoop()
}</langsyntaxhighlight>
 
{{output}}
Line 1,401 ⟶ 1,540:
Same as C entry
</pre>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">nomainwin
struct rect, x as long, y as long, x2 as long, y2 as long
struct PFD, Size as word, Version as word, Flags as long,_
PixelType as char[1], ColorBits as char[1], RedBits as char[1],_
RedShift as char[1], GreenBits as char[1], GreenShift as char[1],_
BlueBits as char[1], BlueShift as char[1], AlphaBits as char[1],_
AlphaShift as char[1],AccumBits as char[1], AccumRedBits as char[1],_
AccumGreenBits as char[1], AccumBlueBits as char[1], AccumAlphaBits as char[1],_
DepthBits as char[1], StencilBits as char[1], AuxBuffers as char[1],_
LayerType as char[1], Reserved as char[1], LayerMask as long,_
VisibleMask as long, DamageMask as long
PFD.Version.struct=1
PFD.ColorBits.struct=24
PFD.DepthBits.struct=16
PFD.Size.struct=len(PFD.struct)
PFD.Flags.struct=37
GlColorBufferBit=16384
open "opengl32.dll" for dll as #gl
open "glu32.dll" for dll as #glu
WindowWidth=500
WindowHeight=500
UpperLeftX=1
UpperLeftY=1
open "Triangle" for window_nf as #main
print #main,"trapclose [quit]"
MainH=hwnd(#main)
calldll #user32,"GetDC", MainH as ulong, MainDC as ulong
calldll #gdi32,"ChoosePixelFormat", MainDC as ulong, PFD as struct, ret as long
calldll #gdi32, "SetPixelFormat", MainDC as ulong, ret as long, PFD as struct, t as long
calldll #gl,"wglCreateContext", MainDC as ulong, GLContext as ulong
calldll #gl,"wglMakeCurrent", MainDC as ulong, GLContext as ulong, ret as long
calldll #gl,"glClear", GlColorBufferBit as long, ret as long
calldll #gl,"glRotated", 0 as double, 0 as double, 0 as double, 0 as double, ret as long
calldll #gl,"glBegin", 4 as long, ret as long
calldll #gl,"glColor3d", 0 as double, 0 as double, 255 as double, ret as long
calldll #gl,"glVertex3i", -1 as long, -1 as long, 0 as long, ret as long
calldll #gl,"glColor3d", 255 as double, 0 as double, 0 as double, ret as long
calldll #gl,"glVertex3i", 0 as long, 1 as long, 0 as long, ret as long
calldll #gl,"glColor3d", 0 as double, 255 as double, 0 as double, ret as long
calldll #gl,"glVertex3i", 1 as long, -1 as long, 0 as long, ret as long
calldll #gl,"glEnd", ret as void
calldll #gdi32,"SwapBuffers", MainDC as ulong, ret as long
wait
[quit]
calldll #gl,"wglMakeCurrent", 0 as ulong, 0 as ulong, ret as long
calldll #gl,"wglDeleteContext", GLContext as ulong, ret as long
calldll #user32, "ReleaseDC", MainH as ulong, MainDC as ulong,ret as long
close #main
close #glu
close #gl
end</syntaxhighlight>
 
=={{header|Lingo}}==
{{libheader|RavOpenGL xtra}}
<langsyntaxhighlight Lingolang="lingo">global gOpenGL -- RavOpenGL xtra instance
global GL -- OpenGL constants
 
Line 1,461 ⟶ 1,653:
-- Show the window
_movie.stage.visible = TRUE
end</langsyntaxhighlight>
 
=={{header|Lua}}==
Line 1,469 ⟶ 1,661:
Note that GL functions that take constants in LuaGL can take either the numbers representing those flags (ie. gl.XXX + gl.YYY) or a comma-separated string of those flags (ie. "XXX,YYY"). This example uses strings.
 
<langsyntaxhighlight lang="lua">local gl = require "luagl"
local iup = require "iuplua"
require "iupluagl"
Line 1,511 ⟶ 1,703:
 
iup.MainLoop()
</syntaxhighlight>
</lang>
 
=={{header|LibertyMathematica}} BASIC/ {{header|Wolfram Language}}==
Non-Windows only:
<lang lb>nomainwin
<syntaxhighlight lang="mathematica">Style[Graphics3D[{Polygon[{{-1, 0, 0}, {1, 0, 0}, {0, Sqrt[3], 0.5}},
struct rect, x as long, y as long, x2 as long, y2 as long
VertexColors -> {Red, Green, Blue}]}, Boxed -> False],
struct PFD, Size as word, Version as word, Flags as long,_
RenderingOptions -> {"3DRenderingEngine" -> "OpenGL"}]</syntaxhighlight>
PixelType as char[1], ColorBits as char[1], RedBits as char[1],_
RedShift as char[1], GreenBits as char[1], GreenShift as char[1],_
BlueBits as char[1], BlueShift as char[1], AlphaBits as char[1],_
AlphaShift as char[1],AccumBits as char[1], AccumRedBits as char[1],_
AccumGreenBits as char[1], AccumBlueBits as char[1], AccumAlphaBits as char[1],_
DepthBits as char[1], StencilBits as char[1], AuxBuffers as char[1],_
LayerType as char[1], Reserved as char[1], LayerMask as long,_
VisibleMask as long, DamageMask as long
PFD.Version.struct=1
PFD.ColorBits.struct=24
PFD.DepthBits.struct=16
PFD.Size.struct=len(PFD.struct)
PFD.Flags.struct=37
GlColorBufferBit=16384
open "opengl32.dll" for dll as #gl
open "glu32.dll" for dll as #glu
WindowWidth=500
WindowHeight=500
UpperLeftX=1
UpperLeftY=1
open "Triangle" for window_nf as #main
print #main,"trapclose [quit]"
MainH=hwnd(#main)
calldll #user32,"GetDC", MainH as ulong, MainDC as ulong
calldll #gdi32,"ChoosePixelFormat", MainDC as ulong, PFD as struct, ret as long
calldll #gdi32, "SetPixelFormat", MainDC as ulong, ret as long, PFD as struct, t as long
calldll #gl,"wglCreateContext", MainDC as ulong, GLContext as ulong
calldll #gl,"wglMakeCurrent", MainDC as ulong, GLContext as ulong, ret as long
calldll #gl,"glClear", GlColorBufferBit as long, ret as long
calldll #gl,"glRotated", 0 as double, 0 as double, 0 as double, 0 as double, ret as long
calldll #gl,"glBegin", 4 as long, ret as long
calldll #gl,"glColor3d", 0 as double, 0 as double, 255 as double, ret as long
calldll #gl,"glVertex3i", -1 as long, -1 as long, 0 as long, ret as long
calldll #gl,"glColor3d", 255 as double, 0 as double, 0 as double, ret as long
calldll #gl,"glVertex3i", 0 as long, 1 as long, 0 as long, ret as long
calldll #gl,"glColor3d", 0 as double, 255 as double, 0 as double, ret as long
calldll #gl,"glVertex3i", 1 as long, -1 as long, 0 as long, ret as long
calldll #gl,"glEnd", ret as void
calldll #gdi32,"SwapBuffers", MainDC as ulong, ret as long
wait
[quit]
calldll #gl,"wglMakeCurrent", 0 as ulong, 0 as ulong, ret as long
calldll #gl,"wglDeleteContext", GLContext as ulong, ret as long
calldll #user32, "ReleaseDC", MainH as ulong, MainDC as ulong,ret as long
close #main
close #glu
close #gl
end</lang>
 
=={{header|MAXScript}}==
The choice of OpenGL or D3D in MAX is a user configuration setting. All MAXScript code is platform independent.
<langsyntaxhighlight lang="maxscript">newMesh = mesh numVerts:3 numFaces:1
setMesh newMesh vertices:#([-100, -100, 0], [100, -100, 0], [-100, 100, 0]) faces:#([1, 2, 3])
defaultVCFaces newMesh
Line 1,578 ⟶ 1,723:
viewport.setType #view_top
max tool maximize
viewport.SetRenderLevel #smoothhighlights</langsyntaxhighlight>
 
=={{header|Mercury}}==
Line 1,584 ⟶ 1,729:
{{libheader|mercury_opengl}}
Translated from C.
<syntaxhighlight lang="text">:- module opengl.
:- interface.
 
Line 1,629 ⟶ 1,774:
mogl.load_identity(!IO),
mogl.ortho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0, !IO),
mogl.matrix_mode(modelview, !IO).</langsyntaxhighlight>
 
=={{header|Nim}}==
{{libheader|OpenGL}}
<lang nim>import opengl, glut
{{libheader|Nim bindings for OpenGL}}
<syntaxhighlight lang="nim">import opengl, opengl/glut
 
proc paint() {.cdecl.} =
Line 1,670 ⟶ 1,817:
glutReshapeFunc(reshape)
 
glutMainLoop()</langsyntaxhighlight>
 
=={{header|OCaml}}==
{{libheader|glMLite}}
<syntaxhighlight lang="ocaml">open GL
open Glut
 
let display() =
glClearColor 0.3 0.3 0.3 0.0;
glClear[GL_COLOR_BUFFER_BIT; GL_DEPTH_BUFFER_BIT];
 
glShadeModel GL_SMOOTH;
 
glLoadIdentity();
glTranslate (-15.0) (-15.0) (0.0);
 
glBegin GL_TRIANGLES;
glColor3 1.0 0.0 0.0;
glVertex2 0.0 0.0;
glColor3 0.0 1.0 0.0;
glVertex2 30.0 0.0;
glColor3 0.0 0.0 1.0;
glVertex2 0.0 30.0;
glEnd();
 
glFlush();
;;
 
let reshape ~width ~height =
glViewport 0 0 width height;
glMatrixMode GL_PROJECTION;
glLoadIdentity();
glOrtho(-30.0) 30.0 (-30.0) 30.0 (-30.0) 30.0;
glMatrixMode GL_MODELVIEW;
;;
 
let () =
ignore(glutInit Sys.argv);
glutInitWindowSize 640 480;
ignore(glutCreateWindow "Triangle");
 
glutDisplayFunc ~display;
glutReshapeFunc ~reshape;
 
glutMainLoop();
;;</syntaxhighlight>
 
=={{header|Ol}}==
All platform dependent actions are placed in (lib gl), which automatically creates OpenGL window with legacy (pre OpenGL 3.0) context. There are way to create modern context using "(gl:set-context-version 3 0)" with following "(import (OpenGL version-3-0))"; or any other valid version numbers.
OpenGL window works in background (as coroutine) and allow user to call any functions, including OpenGL, in REPL simultaneously with window rendering process.
 
<syntaxhighlight lang="scheme">
(import (lib gl))
(gl:set-window-title "Rosettacode OpenGL example")
 
(import (OpenGL version-1-0))
 
(glShadeModel GL_SMOOTH)
(glClearColor 0.3 0.3 0.3 1)
(glMatrixMode GL_PROJECTION)
(glLoadIdentity)
(glOrtho -30.0 30.0 -30.0 30.0 -30.0 30.0)
 
(gl:set-renderer (lambda (mouse)
(glClear GL_COLOR_BUFFER_BIT)
 
(glMatrixMode GL_MODELVIEW)
(glLoadIdentity)
(glTranslatef -15.0 -15.0 0.0)
(glBegin GL_TRIANGLES)
(glColor3f 1.0 0.0 0.0)
(glVertex2f 0.0 0.0)
(glColor3f 0.0 1.0 0.0)
(glVertex2f 30.0 0.0)
(glColor3f 0.0 0.0 1.0)
(glVertex2f 0.0 30.0)
(glEnd)
))
</syntaxhighlight>
 
=={{header|OxygenBasic}}==
<langsyntaxhighlight lang="oxygenbasic">
title="Rotating Triangle"
include "OpenglSceneFrame.inc"
Line 1,716 ⟶ 1,942:
end sub
 
</syntaxhighlight>
</lang>
=={{header|OCaml}}==
{{libheader|glMLite}}
<lang ocaml>open GL
open Glut
 
let display() =
glClearColor 0.3 0.3 0.3 0.0;
glClear[GL_COLOR_BUFFER_BIT; GL_DEPTH_BUFFER_BIT];
 
glShadeModel GL_SMOOTH;
 
glLoadIdentity();
glTranslate (-15.0) (-15.0) (0.0);
 
glBegin GL_TRIANGLES;
glColor3 1.0 0.0 0.0;
glVertex2 0.0 0.0;
glColor3 0.0 1.0 0.0;
glVertex2 30.0 0.0;
glColor3 0.0 0.0 1.0;
glVertex2 0.0 30.0;
glEnd();
 
glFlush();
;;
 
let reshape ~width ~height =
glViewport 0 0 width height;
glMatrixMode GL_PROJECTION;
glLoadIdentity();
glOrtho(-30.0) 30.0 (-30.0) 30.0 (-30.0) 30.0;
glMatrixMode GL_MODELVIEW;
;;
 
let () =
ignore(glutInit Sys.argv);
glutInitWindowSize 640 480;
ignore(glutCreateWindow "Triangle");
 
glutDisplayFunc ~display;
glutReshapeFunc ~reshape;
 
glutMainLoop();
;;</lang>
 
=={{header|Pascal}}==
Line 1,768 ⟶ 1,950:
{{libheader|GLUT}}
Ported from the C example.
<langsyntaxhighlight lang="pascal">Program OpenGLDemo;
 
uses
Line 1,818 ⟶ 2,000:
end.
 
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use OpenGL;
 
sub triangle {
Line 1,844 ⟶ 2,026:
glpFlush;
 
glpMainLoop;</langsyntaxhighlight>
 
==={{libheader|Perl/SDL}}===
<langsyntaxhighlight lang="perl">use SDL::App;
use SDL::Event;
use SDL::OpenGL;
Line 1,875 ⟶ 2,057:
$app->loop ({
SDL_QUIT() => sub { exit; },
});</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/pGUI}}
Adapted from the included demo\Arwen32dibdemo\shadepol.exw, draws the same thing as the image at the top of this page, but (as per the talk page) does not use openGL, just windows api (BitBlt etc) and some low-level fully open source routines (all included).
{{libheader|Phix/online}}
<lang Phix>include demo\Arwen32dibdemo\a32dpoly.ew
{{trans|JavaScript}}
 
This can be run online [http://phix.x10.mx/p2js/OpenGL.htm here], also works on desktop/Phix.<br>
a32Dib0 screen_dib = 0
You can find older windows 32bit only and OpenGL 1.0 verions [[OpenGL/Phix|here]].
integer dx = 0, dy = 0, dw = 0, dh = 0
<!--<syntaxhighlight lang="phix">(phixonline)-->
 
<span style="color: #000080;font-style:italic;">--
constant win = create(Window, "Arwen32Dib bitmap shaded triangle demo", 0, 0, Default, Default, 480, 300, 0)
-- demo\rosetta\OpenGL.exw
 
-- =======================
function winHandler(integer id, integer msg, atom wParam, object lParam)
--</span>
sequence rect
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
if id or object(lParam) then end if -- suppress warnings
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.1"</span><span style="color: #0000FF;">)</span>
if msg=WM_PAINT then
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
if sequence(screen_dib) then
<span style="color: #008080;">include</span> <span style="color: #000000;">opengl</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
clearDib(screen_dib, {0, 0, 0})
drawShadedPolygonToDib(screen_dib, {{dx, dy}, {dx, dh-dy}, {dw-dx, dh-dy}}, {{255, 0, 0}, {0, 0, 255}, {0, 255, 0}})
drawDib(win, screen_dib, 0, 0, 0, 0, screen_dib[DibWidth]-1, screen_dib[DibHeight]-1)
end if
elsif msg=WM_SIZE then
rect = getClientRect(win)
dw = rect[3]
dh = rect[4]
dx = floor(dw/4)+1
dy = floor(dh/4)+1
if sequence(screen_dib) then killDib(screen_dib) end if
screen_dib = newDib(dw, dh)
elsif msg=WM_CHAR
and wParam=VK_ESCAPE then
closeWindow(win)
end if
return 0
end function
setHandler(win, routine_id("winHandler"))
 
WinMain(win, SW_NORMAL)
 
if sequence(screen_dib) then killDib(screen_dib) end if</lang>
And here is a proper openGL version, translated from Lua, and included in the distro as demo\pGUI\triangle.exw:
{{libheader|pGUI}}
<lang Phix>include pGUI.e
include opengl.e
 
function resize_cb(Ihandle /*ih*/, integer width, integer height)
glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0)
glMatrixMode(GL_MODELVIEW)
return IUP_DEFAULT
end function
 
function action(Ihandle /*ih*/)
 
glClearColor(0.3,0.3,0.3,0.0)
glClear(GL_COLOR_BUFFER_BIT+GL_DEPTH_BUFFER_BIT)
<span style="color: #004080;">Ihandln</span> <span style="color: #000000;">dlg</span>
glShadeModel(GL_SMOOTH)
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">canvas</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">fragment_shader</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
glLoadIdentity()
precision highp float;
glTranslate(-15.0, -15.0, 0.0)
varying vec4 v_color;
void main(void) {
// "Varying" variables are implicitly interpolated across triangles.
gl_FragColor = v_color;
}"""</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">vertex_shader</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
attribute vec3 a_position;
attribute vec4 a_color;
varying vec4 v_color;
void main(void) {
gl_Position = vec4(a_position, 1.0);
v_color = a_color;
}"""</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">get_shader</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">src</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">stype</span><span style="color: #0000FF;">)</span>
glBegin(GL_TRIANGLES)
<span style="color: #004080;">integer</span> <span style="color: #000000;">shader</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">glCreateShader</span><span style="color: #0000FF;">(</span><span style="color: #000000;">stype</span><span style="color: #0000FF;">)</span>
glColor(1.0, 0.0, 0.0)
<span style="color: #7060A8;">glShaderSource</span><span style="color: #0000FF;">(</span><span style="color: #000000;">shader</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">src</span><span style="color: #0000FF;">)</span>
glVertex(0.0, 0.0)
<span style="color: #7060A8;">glCompileShader</span><span style="color: #0000FF;">(</span><span style="color: #000000;">shader</span><span style="color: #0000FF;">)</span>
glColor(0.0, 1.0, 0.0)
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">glGetShaderParameter</span><span style="color: #0000FF;">(</span><span style="color: #000000;">shader</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">GL_COMPILE_STATUS</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
glVertex(30.0, 0.0)
<span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">glGetShaderInfoLog</span><span style="color: #0000FF;">(</span><span style="color: #000000;">shader</span><span style="color: #0000FF;">))</span>
glColor(0.0, 0.0, 1.0)
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
glVertex(0.0, 30.0)
<span style="color: #008080;">return</span> <span style="color: #000000;">shader</span>
glEnd()
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">vertices</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- (bl)</span>
glFlush()
<span style="color: #0000FF;">+</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- (br)</span>
 
<span style="color: #0000FF;">-</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">+</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span> <span style="color: #0000FF;">},</span> <span style="color: #000080;font-style:italic;">-- (tl)
return IUP_DEFAULT
-- +0.5, +0.5, 0 }, -- (tr)</span>
end function
<span style="color: #000000;">colours</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- red (bl)</span>
 
<span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- green (br)</span>
Ihandle dialog, canvas
<span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span> <span style="color: #0000FF;">}</span> <span style="color: #000080;font-style:italic;">-- blue (tl)</span>
 
function map_cb(Ihandle /*ih*/)
<span style="color: #008080;">procedure</span> <span style="color: #000000;">set_shader</span><span style="color: #0000FF;">()</span>
IupGLMakeCurrent(canvas)
<span style="color: #7060A8;">IupGLMakeCurrent</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">)</span>
integer {width, height} = IupGetIntInt(dialog, "RASTERSIZE")
<span style="color: #004080;">integer</span> <span style="color: #000000;">shaderProgram</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">glCreateProgram</span><span style="color: #0000FF;">()</span>
{} = resize_cb(dialog, width, height)
<span style="color: #7060A8;">glAttachShader</span><span style="color: #0000FF;">(</span><span style="color: #000000;">shaderProgram</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">get_shader</span><span style="color: #0000FF;">(</span><span style="color: #000000;">vertex_shader</span><span style="color: #0000FF;">,</span><span style="color: #004600;">GL_VERTEX_SHADER</span><span style="color: #0000FF;">))</span>
return IUP_DEFAULT
<span style="color: #7060A8;">glAttachShader</span><span style="color: #0000FF;">(</span><span style="color: #000000;">shaderProgram</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">get_shader</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fragment_shader</span><span style="color: #0000FF;">,</span><span style="color: #004600;">GL_FRAGMENT_SHADER</span><span style="color: #0000FF;">))</span>
end function
<span style="color: #7060A8;">glLinkProgram</span><span style="color: #0000FF;">(</span><span style="color: #000000;">shaderProgram</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">glGetProgramParameter</span><span style="color: #0000FF;">(</span><span style="color: #000000;">shaderProgram</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">GL_LINK_STATUS</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
IupOpen()
<span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">glGetProgramInfoLog</span><span style="color: #0000FF;">(</span><span style="color: #000000;">shaderProgram</span><span style="color: #0000FF;">))</span>
IupGLCanvasOpen()
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
 
<span style="color: #7060A8;">glUseProgram</span><span style="color: #0000FF;">(</span><span style="color: #000000;">shaderProgram</span><span style="color: #0000FF;">)</span>
canvas = IupGLCanvas(Icallback("action"), "RASTERSIZE=640x480")
<span style="color: #000080;font-style:italic;">// Get the indexes to communicate vertex attributes to the program.</span>
IupSetCallback(canvas, "RESIZE_CB", Icallback("resize_cb"))
<span style="color: #004080;">integer</span> <span style="color: #000000;">positionAttr</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">glGetAttribLocation</span><span style="color: #0000FF;">(</span><span style="color: #000000;">shaderProgram</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"a_position"</span><span style="color: #0000FF;">),</span>
 
<span style="color: #000000;">colorAttr</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">glGetAttribLocation</span><span style="color: #0000FF;">(</span><span style="color: #000000;">shaderProgram</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"a_color"</span><span style="color: #0000FF;">)</span>
dialog = IupDialog(canvas, "MAP_CB", Icallback("map_cb"), "TITLE=Triangle, SHRINK=YES")
 
<span style="color: #000080;font-style:italic;">// And specify that we will be actually delivering data to those attributes.</span>
IupShow(dialog)
<span style="color: #7060A8;">glEnableVertexAttribArray</span><span style="color: #0000FF;">(</span><span style="color: #000000;">positionAttr</span><span style="color: #0000FF;">)</span>
IupMainLoop()
<span style="color: #7060A8;">glEnableVertexAttribArray</span><span style="color: #0000FF;">(</span><span style="color: #000000;">colorAttr</span><span style="color: #0000FF;">)</span>
IupDestroy(dialog)
IupClose()</lang>
<span style="color: #000080;font-style:italic;">// Store vertex positions and colors in array buffer objects.</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">positionBuffer</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">glCreateBuffer</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">glBindBuffer</span><span style="color: #0000FF;">(</span><span style="color: #004600;">GL_ARRAY_BUFFER</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">positionBuffer</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{</span><span style="color: #004080;">integer</span> <span style="color: #000000;">size</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">pData</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">glFloat32Array</span><span style="color: #0000FF;">(</span><span style="color: #000000;">vertices</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">glBufferData</span><span style="color: #0000FF;">(</span><span style="color: #004600;">GL_ARRAY_BUFFER</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">size</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">pData</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">GL_STATIC_DRAW</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">glEnableVertexAttribArray</span><span style="color: #0000FF;">(</span><span style="color: #000000;">positionBuffer</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">colorBuffer</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">glCreateBuffer</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">glBindBuffer</span><span style="color: #0000FF;">(</span><span style="color: #004600;">GL_ARRAY_BUFFER</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">colorBuffer</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">size</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">pData</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">glFloat32Array</span><span style="color: #0000FF;">(</span><span style="color: #000000;">colours</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">glBufferData</span><span style="color: #0000FF;">(</span><span style="color: #004600;">GL_ARRAY_BUFFER</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">size</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">pData</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">GL_STATIC_DRAW</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">glEnableVertexAttribArray</span><span style="color: #0000FF;">(</span><span style="color: #000000;">colorBuffer</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">glEnable</span><span style="color: #0000FF;">(</span><span style="color: #004600;">GL_DEPTH_TEST</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">// Specify the array data to render.
// 3 and 4 are the lengths of the vectors (3 for XYZ, 4 for RGBA).</span>
<span style="color: #7060A8;">glBindBuffer</span><span style="color: #0000FF;">(</span><span style="color: #004600;">GL_ARRAY_BUFFER</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">positionBuffer</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">glVertexAttribPointer</span><span style="color: #0000FF;">(</span><span style="color: #000000;">positionAttr</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">GL_FLOAT</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">false</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">glEnableVertexAttribArray</span><span style="color: #0000FF;">(</span><span style="color: #000000;">positionAttr</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">glBindBuffer</span><span style="color: #0000FF;">(</span><span style="color: #004600;">GL_ARRAY_BUFFER</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">colorBuffer</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">glVertexAttribPointer</span><span style="color: #0000FF;">(</span><span style="color: #000000;">colorAttr</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">GL_FLOAT</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">false</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">glEnableVertexAttribArray</span><span style="color: #0000FF;">(</span><span style="color: #000000;">colorAttr</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #004080;">bool</span> <span style="color: #000000;">drawn</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">action</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">drawn</span> <span style="color: #008080;">or</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">glClearColor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0.3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0.3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0.3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1.0</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">w</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetIntInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"DRAWSIZE"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">glViewport</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">w</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">glClear</span><span style="color: #0000FF;">(</span><span style="color: #004600;">GL_COLOR_BUFFER_BIT</span> <span style="color: #0000FF;">||</span> <span style="color: #004600;">GL_DEPTH_BUFFER_BIT</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">// Draw triangles using the specified arrays.</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">numVertices</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">vertices</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">3</span> <span style="color: #000080;font-style:italic;">// 3 coordinates per vertex</span>
<span style="color: #7060A8;">glDrawArrays</span><span style="color: #0000FF;">(</span><span style="color: #004600;">GL_TRIANGLES</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">numVertices</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">// Check for errors.</span>
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">glGetError</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">e</span><span style="color: #0000FF;">=</span><span style="color: #004600;">GL_NO_ERROR</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"GL error %d\n"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">e</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">glFlush</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">drawn</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">true</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">canvas</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGLCanvas</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"action"</span><span style="color: #0000FF;">),</span> <span style="color: #008000;">"RASTERSIZE=640x480"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"TITLE=OpenGLShader, SHRINK=YES"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupMap</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">set_shader</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDestroy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
 
=={{header|PicoLisp}}==
This is for the 64-bit version.
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/openGl.l")
 
(glutInit)
Line 2,009 ⟶ 2,229:
(mouseFunc '((Btn State X Y) (bye)))
 
(glutMainLoop)</langsyntaxhighlight>
 
=={{header|Pike}}==
Uses GLUE to create the window. Rendering code is based on the C example.
<langsyntaxhighlight lang="pike">int main() {
GLUE.init(([
"fullscreen": 0,
Line 2,049 ⟶ 2,269:
sleep(0.01);
}
}</langsyntaxhighlight>
 
=={{header|PureBasic}}==
Line 2,055 ⟶ 2,275:
 
 
<syntaxhighlight lang="purebasic">
<lang Purebasic>
XIncludeFile "OpenGL.pbi"
pfd.PIXELFORMATDESCRIPTOR
Line 2,098 ⟶ 2,318:
Wend
 
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">#!/usr/bin/env python
#-*- coding: utf-8 -*-
 
Line 2,142 ⟶ 2,362:
glutReshapeFunc(reshape)
 
glutMainLoop()</langsyntaxhighlight>
=={{header|QB64}}==
 
<syntaxhighlight lang="qb64">
'Task
'Display a smooth shaded triangle with OpenGL.
Screen _NewImage(600, 600, 32)
Dim Shared glInit As Integer
glInput = 0
Do While InKey$ = "": Loop
End
Sub _GL ()
If glInit = 0 Then
_glViewport 1, 1, 600, 600
_glClearColor 0, 0, 0, 1
glInit = -1
End If
_glClear _GL_COLOR_BUFFER_BIT
_glBegin _GL_TRIANGLES
_glColor4f 1, 0, 0, 1
_glVertex2f -1, -1
_glColor4f 0, 1, 0, 1
_glVertex2f 0, 0
_glColor4f 0, 0, 1, 1
_glVertex2f 1, -1
_glEnd
End Sub
</syntaxhighlight>
=={{header|R}}==
{{libheader|rgl}}
<langsyntaxhighlight Rlang="r">library(rgl)
x <- c(-1, -1, 1)
y <- c(0, -1, -1)
Line 2,152 ⟶ 2,399:
M <- cbind(x,y,z)
rgl.bg(color="gray15")
triangles3d(M, col=rainbow(8))</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 2,160 ⟶ 2,407:
If OpenGL context creation fails please consult Racket [http://docs.racket-lang.org/gui/libs.html documentation]
 
<langsyntaxhighlight lang="racket">
#lang racket/gui
(require sgl/gl)
Line 2,203 ⟶ 2,450:
 
(send win show #t)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2019.11}}
At this time there is not a publicly available OpenGL <-> Raku library, but it isn't too difficult to just call into the underlying C libraries. Here's a minimal example.
 
It's a little verbose since it is doing all of the setup and loading manually.
 
<syntaxhighlight lang="raku" line>use NativeCall;
 
class Window is repr('CPointer') {}
class Monitor is repr('CPointer') {}
 
# GLFW
 
constant $lib = ('glfw', v3);
 
sub glfwInit(--> int32) is native($lib) {*}
sub glfwCreateWindow(int32, int32, Str, Monitor, Window --> Window) is native($lib) {*}
sub glfwTerminate() is native($lib) {*}
sub glfwMakeContextCurrent(Window) is native($lib) {*}
sub glfwSetWindowShouldClose(Window, int32) is native($lib) {*}
sub glfwWindowShouldClose(Window --> int32) is native($lib) {*}
sub glfwSwapBuffers(Window) is native($lib) {*}
sub glfwSwapInterval(int32) is native($lib) {*}
sub glfwPollEvents() is native($lib) {*}
sub glfwGetFramebufferSize(Window, int32 is rw, int32 is rw) is native($lib) {*}
 
# OpenGL
 
enum PrimitiveMode(
GL_TRIANGLES => 0x0004,
);
 
enum MatrixMode(
GL_MATRIX_MODE => 0x0BA0,
GL_MODELVIEW => 0x1700,
GL_PROJECTION => 0x1701,
);
 
constant $gllib = 'GL';
 
sub glViewport(int32, int32, int32, int32) is native($gllib) {*}
sub glClear(int32) is native($gllib) {*}
sub glMatrixMode(int32) is native($gllib) {*}
sub glLoadIdentity() is native($gllib) {*}
sub glOrtho(num64, num64, num64, num64, num64, num64) is native($gllib) {*}
sub glRotatef(num32, num32, num32, num32) is native($gllib) {*}
sub glBegin(int32) is native($gllib) {*}
sub glColor3f(num32, num32, num32) is native($gllib) {*}
sub glVertex3f(num32, num32, num32) is native($gllib) {*}
sub glEnd() is native($gllib) {*}
 
constant GL_COLOR_BUFFER_BIT = 0x00004000;
 
die 'Failed to initialize GLFW' unless glfwInit().so;
 
my $w = glfwCreateWindow(640, 480, "OpenGL Triangle", Nil, Nil);
without $w { glfwTerminate(); die 'Failed to create window' }
 
glfwMakeContextCurrent($w);
glfwSwapInterval(1);
 
while not glfwWindowShouldClose($w) {
my num32 $ratio;
my int32 $width;
my int32 $height;
 
glfwGetFramebufferSize($w, $width, $height);
$ratio = ($width / $height).Num;
 
glViewport(0, 0, $width, $height);
glClear(GL_COLOR_BUFFER_BIT);
 
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-$ratio, $ratio, -1e0, 1e0, 1e0, -1e0);
glMatrixMode(GL_MODELVIEW);
 
glLoadIdentity();
glRotatef((now % 360 * 100e0) , 0e0, 0e0, 1e0);
 
glBegin(GL_TRIANGLES);
glColor3f(1e0, 0e0, 0e0);
glVertex3f(5e-1, -2.88e-1, 0e0);
glColor3f(0e0, 1e0, 0e0);
glVertex3f(-5e-1, -2.88e-1, 0e0);
glColor3f(0e0, 0e0, 1e0);
glVertex3f( 0e0, 5.73e-1, 0e0);
glEnd();
 
glfwSwapBuffers($w);
glfwPollEvents();
}
 
glfwTerminate();
</syntaxhighlight>
 
See screen cap: [https://github.com/thundergnat/rc/blob/master/img/OpenGL-Triangle-perl6.png OpenGL-Triangle-perl6.png] (Offsite PNG image.)
 
Additional Output: [https://drive.google.com/file/d/1J_QqfWZeg39Qmkek1mrjhqLD1ekwaMCk/view (Offsite Media file) ]
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project: OpenGL
 
load "freeglut.ring"
load "opengl21lib.ring"
 
func main
glutInit()
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA)
glutInitWindowSize(320,320)
glutInitWindowPosition(100, 10)
glutCreateWindow("OpenGL")
glutDisplayFunc(:renderScene)
glutMainLoop()
 
func renderScene
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glBegin(GL_TRIANGLES)
glVertex3f(-0.5,-0.5,0.0)
glVertex3f(0.5,0.0,0.0)
glVertex3f(0.0,0.5,0.0)
glEnd()
glutSwapBuffers()
</syntaxhighlight>
Outputimage:
 
[https://1drv.ms/u/s!AqDUIunCqVnIg1BFt-zV2LphRyjQ OPenGL]
 
=={{header|Ruby}}==
{{libheader|ruby-opengl}}
 
<langsyntaxhighlight lang="ruby">require 'rubygems'
require 'gl'
require 'glut'
Line 2,251 ⟶ 2,628:
glutReshapeFunc(reshape)
 
glutMainLoop</langsyntaxhighlight>
=={{header|Rust}}==
using glutin for window creation and glow for opengl/opengles functions. as such, the fixed function pipeline is not supported
<syntaxhighlight lang="rust">use glow::*;
use glutin::event::*;
use glutin::event_loop::{ControlFlow, EventLoop};
use std::os::raw::c_uint;
 
const VERTEX: &str = "#version 410
const vec2 verts[3] = vec2[3](
vec2(0.5f, 1.0f),
vec2(0.0f, 0.0f),
vec2(1.0f, 0.0f)
);
out vec2 vert;
void main() {
vert = verts[gl_VertexID];
gl_Position = vec4(vert - 0.5, 0.0, 1.0);
}";
 
const FRAGMENT: &str = "#version 410
precision mediump float;
in vec2 vert;
out vec4 color;
void main() {
color = vec4(vert, 0.5, 1.0);
}";
 
unsafe fn create_program(gl: &Context, vert: &str, frag: &str) -> c_uint {
let program = gl.create_program().expect("Cannot create program");
let shader_sources = [(glow::VERTEX_SHADER, vert), (glow::FRAGMENT_SHADER, frag)];
 
let mut shaders = Vec::new();
for (shader_type, shader_source) in shader_sources.iter() {
let shader = gl
.create_shader(*shader_type)
.expect("Cannot create shader");
gl.shader_source(shader, shader_source);
gl.compile_shader(shader);
if !gl.get_shader_compile_status(shader) {
panic!(gl.get_shader_info_log(shader));
}
gl.attach_shader(program, shader);
shaders.push(shader);
}
 
gl.link_program(program);
if !gl.get_program_link_status(program) {
panic!(gl.get_program_info_log(program));
}
 
for shader in shaders {
gl.detach_shader(program, shader);
gl.delete_shader(shader);
}
program
}
 
fn main() {
let (gl, event_loop, window) = unsafe {
let el = EventLoop::new();
let wb = glutin::window::WindowBuilder::new()
.with_title("Hello triangle!")
.with_inner_size(glutin::dpi::LogicalSize::new(1024.0, 768.0));
let windowed_context = glutin::ContextBuilder::new()
.with_vsync(true)
.build_windowed(wb, &el)
.unwrap();
let windowed_context = windowed_context.make_current().unwrap();
let context = glow::Context::from_loader_function(|s| {
windowed_context.get_proc_address(s) as *const _
});
(context, el, windowed_context)
};
 
let (program, vab) = unsafe {
let vertex_array = gl
.create_vertex_array()
.expect("Cannot create vertex array");
gl.bind_vertex_array(Some(vertex_array));
 
let program = create_program(&gl, VERTEX, FRAGMENT);
gl.use_program(Some(program));
 
(program, vertex_array)
};
 
event_loop.run(move |ev, _, flow| match ev {
Event::WindowEvent {
event: WindowEvent::CloseRequested, ..
} => {
unsafe {
gl.delete_program(program);
gl.delete_vertex_array(vab);
}
*flow = ControlFlow::Exit;
}
Event::WindowEvent {
event: WindowEvent::Resized(size), ..
} => {
unsafe {
gl.viewport(0, 0, size.width as i32, size.height as i32);
}
window.resize(size);
}
Event::RedrawRequested(_) => unsafe {
gl.clear_color(0.1, 0.2, 0.3, 1.0);
gl.clear(glow::COLOR_BUFFER_BIT);
gl.draw_arrays(glow::TRIANGLES, 0, 3);
window.swap_buffers().unwrap();
},
_ => {}
});
}</syntaxhighlight>
=={{header|Scala}}==
{{libheader|Light Weight Java Game Library}}
<langsyntaxhighlight Scalalang="scala">import org.lwjgl.opengl.{ Display, DisplayMode }
import org.lwjgl.opengl.GL11._
 
Line 2,293 ⟶ 2,782:
Thread.sleep(1000)
}
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{libheader|Tk}}
{{libheader|tcl3d}}
<langsyntaxhighlight Tcllang="tcl">package require Tk
package require tcl3d
 
Line 2,327 ⟶ 2,816:
togl .surface -width 640 -height 480 -double true -depth true \
-displayproc paintShape -reshapeproc resizedWin
pack .surface -fill both -expand 1</langsyntaxhighlight>Most of this code should be very familiar to anyone looking at the C version above, or with normal [[Tk]] applications.
 
=={{header|Wren}}==
{{trans|C}}
{{libheader|FreeGLUT}}
It is not currently possible for Wren-cli to access OpenGL directly, so we need to use an embedded application to complete this task. The following embeds a Wren script in a C application, the language which Wren itself is written in.
 
We wrap as many OpenGL/FreeGLUT calls as possible from the Wren side though glutInit (requires command line parameters) and glutMainLoop (requires a re-entrant VM) must be called by the host.
 
Notice that we can't pass Wren methods directly to the glutDisplayFunc and glutReshapeFunc functions for callback registration purposes because of re-entrancy problems so, instead, we pass sufficient information from Wren to enable the callbacks to be constructed from the C side.
<syntaxhighlight lang="wren">/* OpenGL.wren */
 
var GL_COLOR_BUFFER_BIT = 0x4000
var GL_DEPTH_BUFFER_BIT = 0x0100
 
var GL_SMOOTH = 0x1d01
var GL_MODELVIEW = 0x1700
var GL_PROJECTION = 0x1701
 
var GL_TRIANGLES = 0x0004
 
var GLUT_ACTION_ON_WINDOW_CLOSE = 0x01f9
var GLUT_ACTION_GLUTMAINLOOP_RETURNS = 0x0001
 
class GL {
foreign static clearColor(red, green, blue, alpha)
 
foreign static clear(mask)
 
foreign static shadeModel(mode)
 
foreign static loadIdentity()
 
foreign static translatef(x, y, z)
 
foreign static begin(mode)
 
foreign static color3f(red, green, blue)
 
foreign static vertex2f(x, y)
 
foreign static end()
 
foreign static flush()
 
foreign static viewport(x, y, width, height)
 
foreign static matrixMode(mode)
 
foreign static ortho(left, right, bottom, top, nearVal, farVal)
}
 
class Glut {
foreign static initWindowSize(width, height)
 
foreign static createWindow(name)
 
foreign static displayFunc(clazz, signature)
 
foreign static reshapeFunc(clazz, signature)
 
foreign static setOption(eWhat, value)
}
 
class GLCallbacks {
static paint() {
GL.clearColor(0.3, 0.3, 0.3, 0)
GL.clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
GL.shadeModel(GL_SMOOTH)
GL.loadIdentity()
GL.translatef(-15, -15, 0)
GL.begin(GL_TRIANGLES)
GL.color3f(1, 0, 0)
GL.vertex2f(0, 0)
GL.color3f(0, 1, 0)
GL.vertex2f(30, 0)
GL.color3f(0, 0, 1)
GL.vertex2f(0, 30)
GL.end()
GL.flush()
}
 
static reshape(width, height) {
GL.viewport(0, 0, width, height)
GL.matrixMode(GL_PROJECTION)
GL.loadIdentity()
GL.ortho(-30, 30, -30, 30, -30, 30)
GL.matrixMode(GL_MODELVIEW)
}
}
 
Glut.initWindowSize(640, 480)
Glut.createWindow("Triangle")
Glut.displayFunc("GLCallbacks", "paint()")
Glut.reshapeFunc("GLCallbacks", "reshape(_,_)")
Glut.setOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS)</syntaxhighlight>
<br>
We now embed this Wren script in the following C program, compile and run it.
<syntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <GL/gl.h>
#include <GL/freeglut.h>
#include "wren.h"
 
/* C <=> Wren interface functions */
 
WrenVM *vm;
 
const char *displayClass, *displayMethod, *reshapeClass, *reshapeMethod;
 
void display() {
wrenEnsureSlots(vm, 1);
wrenGetVariable(vm, "main", displayClass, 0);
WrenHandle *method = wrenMakeCallHandle(vm, displayMethod);
wrenCall(vm, method);
wrenReleaseHandle(vm, method);
}
 
void reshape(int width, int height) {
wrenEnsureSlots(vm, 3);
wrenGetVariable(vm, "main", reshapeClass, 0);
WrenHandle *method = wrenMakeCallHandle(vm, reshapeMethod);
wrenSetSlotDouble(vm, 1, (double)width);
wrenSetSlotDouble(vm, 2, (double)height);
wrenCall(vm, method);
wrenReleaseHandle(vm, method);
}
 
void C_clearColor(WrenVM* vm) {
GLclampf red = (GLclampf)wrenGetSlotDouble(vm, 1);
GLclampf green = (GLclampf)wrenGetSlotDouble(vm, 2);
GLclampf blue = (GLclampf)wrenGetSlotDouble(vm, 3);
GLclampf alpha = (GLclampf)wrenGetSlotDouble(vm, 4);
glClearColor(red, green, blue, alpha);
}
 
void C_clear(WrenVM* vm) {
GLbitfield mask = (GLbitfield)wrenGetSlotDouble(vm, 1);
glClear(mask);
}
 
void C_shadeModel(WrenVM* vm) {
GLenum mode = (GLenum)wrenGetSlotDouble(vm, 1);
glShadeModel(mode);
}
 
void C_loadIdentity(WrenVM* vm) {
glLoadIdentity();
}
 
void C_translatef(WrenVM* vm) {
GLfloat x = (GLfloat)wrenGetSlotDouble(vm, 1);
GLfloat y = (GLfloat)wrenGetSlotDouble(vm, 2);
GLfloat z = (GLfloat)wrenGetSlotDouble(vm, 3);
glTranslatef(x, y, z);
}
 
void C_begin(WrenVM* vm) {
GLenum mode = (GLenum)wrenGetSlotDouble(vm, 1);
glBegin(mode);
}
 
void C_color3f(WrenVM* vm) {
GLfloat red = (GLfloat)wrenGetSlotDouble(vm, 1);
GLfloat green = (GLfloat)wrenGetSlotDouble(vm, 2);
GLfloat blue = (GLfloat)wrenGetSlotDouble(vm, 3);
glColor3f(red, green, blue);
}
 
void C_vertex2f(WrenVM* vm) {
GLfloat x = (GLfloat)wrenGetSlotDouble(vm, 1);
GLfloat y = (GLfloat)wrenGetSlotDouble(vm, 2);
glVertex2f(x, y);
}
 
void C_end(WrenVM* vm) {
glEnd();
}
 
void C_flush(WrenVM* vm) {
glFlush();
}
 
void C_viewport(WrenVM* vm) {
GLint x = (GLint) wrenGetSlotDouble(vm, 1);
GLint y = (GLint) wrenGetSlotDouble(vm, 2);
GLsizei width = (GLsizei)wrenGetSlotDouble(vm, 3);
GLsizei height = (GLsizei)wrenGetSlotDouble(vm, 4);
glViewport(x, y, width, height);
}
 
void C_matrixMode(WrenVM* vm) {
GLenum mode = (GLenum)wrenGetSlotDouble(vm, 1);
glMatrixMode(mode);
}
 
void C_ortho(WrenVM* vm) {
GLdouble left = (GLdouble)wrenGetSlotDouble(vm, 1);
GLdouble right = (GLdouble)wrenGetSlotDouble(vm, 2);
GLdouble bottom = (GLdouble)wrenGetSlotDouble(vm, 3);
GLdouble top = (GLdouble)wrenGetSlotDouble(vm, 4);
GLdouble nearVal = (GLdouble)wrenGetSlotDouble(vm, 5);
GLdouble farVal = (GLdouble)wrenGetSlotDouble(vm, 6);
glOrtho(left, right, bottom, top, nearVal, farVal);
}
 
void C_initWindowSize(WrenVM* vm) {
int width = (int)wrenGetSlotDouble(vm, 1);
int height = (int)wrenGetSlotDouble(vm, 2);
glutInitWindowSize(width, height);
}
 
void C_createWindow(WrenVM* vm) {
const char *name = wrenGetSlotString(vm, 1);
glutCreateWindow(name);
}
 
void C_displayFunc(WrenVM* vm) {
displayClass = wrenGetSlotString(vm, 1);
displayMethod = wrenGetSlotString(vm, 2);
glutDisplayFunc(&display);
}
 
void C_reshapeFunc(WrenVM* vm) {
reshapeClass = wrenGetSlotString(vm, 1);
reshapeMethod = wrenGetSlotString(vm, 2);
glutReshapeFunc(&reshape);
}
 
void C_setOption(WrenVM* vm) {
GLenum eWhat = (GLenum)wrenGetSlotDouble(vm, 1);
int value = (int)wrenGetSlotDouble(vm, 2);
glutSetOption(eWhat, value);
}
 
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "GL") == 0) {
if (isStatic && strcmp(signature, "clearColor(_,_,_,_)") == 0) return C_clearColor;
if (isStatic && strcmp(signature, "clear(_)") == 0) return C_clear;
if (isStatic && strcmp(signature, "shadeModel(_)") == 0) return C_shadeModel;
if (isStatic && strcmp(signature, "loadIdentity()") == 0) return C_loadIdentity;
if (isStatic && strcmp(signature, "translatef(_,_,_)") == 0) return C_translatef;
if (isStatic && strcmp(signature, "begin(_)") == 0) return C_begin;
if (isStatic && strcmp(signature, "color3f(_,_,_)") == 0) return C_color3f;
if (isStatic && strcmp(signature, "vertex2f(_,_)") == 0) return C_vertex2f;
if (isStatic && strcmp(signature, "end()") == 0) return C_end;
if (isStatic && strcmp(signature, "flush()") == 0) return C_flush;
if (isStatic && strcmp(signature, "viewport(_,_,_,_)") == 0) return C_viewport;
if (isStatic && strcmp(signature, "matrixMode(_)") == 0) return C_matrixMode;
if (isStatic && strcmp(signature, "ortho(_,_,_,_,_,_)") == 0) return C_ortho;
} else if (strcmp(className, "Glut") == 0) {
if (isStatic && strcmp(signature, "initWindowSize(_,_)") == 0) return C_initWindowSize;
if (isStatic && strcmp(signature, "createWindow(_)") == 0) return C_createWindow;
if (isStatic && strcmp(signature, "displayFunc(_,_)") == 0) return C_displayFunc;
if (isStatic && strcmp(signature, "reshapeFunc(_,_)") == 0) return C_reshapeFunc;
if (isStatic && strcmp(signature, "setOption(_,_)") == 0) return C_setOption;
}
}
return NULL;
}
 
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
 
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
 
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
 
int main(int argc, char **argv) {
glutInit(&argc, argv);
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignMethodFn = &bindForeignMethod;
vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "OpenGL.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
glutMainLoop();
wrenFreeVM(vm);
free(script);
return 0;
}</syntaxhighlight>
 
{{out}}
<pre>
Same as C example.
</pre>
 
{{omit from|ACL2}}
9,476

edits