Swift 3 and OpenGL on Linux and macOS with GLFW
Posted on November 19, 2016 by Paul
This is a short article about how to get started with Swift 3 and OpenGL on Linux and macOS. In order to keep the code portable on both operating systems, we’ll use GLFW to create a window with an OpenGL context. Keep in mind that, at time of this writing, Swift can call directly any C library. However, if you need to use a C++ library you will need to write a C wrapper around it, because Swift 3 is not interoperable with C++.
As a practical example, we’ll use OpenGL to draw a yellow rectangle on a red background. In order to keep the code short and as simple as possible, we’ll use the fixed OpenGL functionality. If you want to use modern OpenGL, please check my other OpenGL articles. Replacing the fixed OpenGL functionality from the article example is left as an exercise for the reader. Basically, once you know how to call OpenGL functions from Swift and compile the code, it is just a question of writing supporting code for dealing with shaders, buffers and so on.
macOS prerequisites:
On macOS, first you need to install Xcode from the App Store. Start Xcode and agree with the license.
Next, install Apple’s Command Line Tools with:
Once the above is installed, install the Homebrew package manager:
Next, we’ll use Homebrew to install GLFW:
Ubuntu Linux prerequisites:
If you don’t have latest versions of Swift and Clang installed on your system, check my Getting started with Swift 3 on Linux article.
Next step is to install GLFW:
Swift OpenGL example
At this point, I assume that you can build and run a Swift code from your Terminal. Assuming that you have a simple Swift program saved as test.swift, this is how you can compile and run the code:
In order to use a C function from Swift, we need to let the compiler know the function definition. This can be done using an Objective-C header file. For example, if we want to use GLFW from Swift, we will add the next line in a file ending in .h:
I’ll assume the above line was saved in a file named opengl_includes.h.
Next, we can write our Swift code that uses GLFW and OpenGL functions:
Save the above code as main.swift.
macOS compilation:
At this point, you should have two files opengl_includes.h and main.swift in your current directory. Use the next command to create an executable:
This is what you should see:
Ubuntu Linux compilation
At this point, you should have two files opengl_includes.h and main.swift in your current directory. Use the next command to create an executable:
This is what you should see:
If you are interested to learn more about the latest Swift syntax, I would recommend reading Swift Programming: The Big Nerd Ranch Guide (2nd Edition) by M Mathias, J Gallagher:
If you are interested to learn more about OpenGL, I would recommend reading OpenGL SuperBible by Graham Sellers, Richard S. Wright Jr., Nicholas Haemel: