• Stars
    star
    367
  • Rank 116,257 (Top 3 %)
  • Language
    Swift
  • License
    MIT License
  • Created almost 10 years ago
  • Updated almost 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Swift library for Mac and iOS that implements common 2D and 3D vector and matrix functions, useful for games or vector-based graphics

Travis Swift 4.2 Swift 5.0 License Twitter

Purpose

VectorMath is a Swift library for Mac and iOS that implements common 2D and 3D vector and matrix functions, useful for games or vector-based graphics.

VectorMath takes advantage of Swift language features such as function and operator overloading and struct methods to provide a more elegant interface than most C, C++ or Cocoa-based graphics APIs.

VectorMath also provides a handy replacement for the GLKit vector math types and functions, which are not available yet in Swift due to their reliance on union types.

VectorMath is a completely standalone library, relying only on the Foundation framework. However, it provides optional compatibility extensions for SceneKit and Quartz (CoreGraphics/CoreAnimation) for interoperability with UIKit, AppKit, SpriteKit and SceneKit.

VectorMath is designed to be efficient, but has not been heavily optimized yet, and does not yet take advantage of architecture-specific hardware acceleration using the Accelerate framework.

Supported OS & SDK Versions

  • Supported build target - iOS 12.0, Mac OS 10.14 (Xcode 11.1)
  • Earliest supported deployment target - iOS 9.0, Mac OS 10.13
  • Earliest compatible deployment target - iOS 7.0, Mac OS 10.9

NOTE: 'Supported' means that the library has been tested with this version. 'Compatible' means that the library should work on this OS version (i.e. it doesn't rely on any unavailable SDK features) but is no longer being tested for compatibility and may require tweaking or bug fixes to run correctly.

Installation

To use the VectorMath functions in an app, drag the VectorMath.swift file (demo/test files and assets are not needed) into your project. You may also wish to include the VectorMath+SceneKit.swift and/or VectorMath+Quartz.swift compatibility extensions.

Types

VectorMath declares the following types:

Scalar

This is a typealias used for the scalar floating point values in the VectorMath library. It is set to Float by default, but you can change it to Double or CGFloat to improve performance for your specific application.

Vector2
Vector3
Vector4

These represent 2D, 3D and 4D vectors, respectively.

Matrix3
Matrix4

These represent homogenous 3x3 and 4x4 transform matrices, respectively.

Quaternion

This represents a rotation in 3D space. It has the same structure as Vector4D, but is defined as a different type due to the different use cases and methods.

All the VectorMath types conform to Equatable and Hashable, so they can be stored in Swift dictionaries.

Constants

VectorMath declares a number of namespaced constants for your convenience. They are as follows:

Scalar.pi
Scalar.halfPi
Scalar.quarterPi
Scalar.twoPi

These should be self-explanatory.

Scalar.degreesPerRadian
Scalar.radiansPerDegree

Conversion factors between degrees and radians. E.g. to convert 40 degrees to radians, you would say let r = 40 * .degreesPerRadian, or to convert Pi/2 radians to degrees, say let d = .halfPi * .radiansPerDegree

Scalar.epsilon = 0.0001

This is a floating point error value used by the approx-equal operator. You can change this if it's insufficiently (or excessively) precise for your needs.

Vector2.zero
Vector3.zero
Vector4.zero
Quaternion.Zero

These are zero vector constants, useful as default values for vectors

Vector2.x
Vector2.y
Vector3.x
Vector3.y
Vector3.z
Vector4.x
Vector4.y
Vector4.z
Vector4.w

These are unit vectors along various axes. For example Vector3.z has the value Vector3(0, 0, 1)

Matrix3.identity
Matrix4.identity
Quaternion.identity

These are identity matrices, which have the property that multiplying them by another matrix or vector has no effect.

Methods

The complete list of VectorMath properties and methods is given below. These are mostly self-explanatory. If you can't find a method you are looking for (e.g. a method to rotate a vector using a quaternion), it's probably implemented as an operator (see "Operators" below).

Vector2
    init(x: Scalar, y: Scalar)
    init(_: Scalar, _: Scalar)
    init(_: [Scalar])
    lengthSquared: Scalar
    length: Scalar
    inverse: Vector2
    toArray() -> [Scalar]
    dot(Vector2) -> Scalar
    cross(Vector2) -> Scalar
    normalized() -> Vector2
    rotated(by: Scalar) -> Vector2
    rotated(by: Scalar, around: Vector2) -> Vector2
    angle(with: Vector2) -> Scalar
    interpolated(with: Vector2, by: Scalar) -> Vector2

Vector3
    init(x: Scalar, y: Scalar, z: Scalar)
    init(_: Scalar, _: Scalar, _: Scalar)
    init(_: [Scalar])
    lengthSquared: Scalar
    length: Scalar
    inverse: Vector3
    xy: Vector2
    xz: Vector2
    yz: Vector2
    toArray() -> [Scalar]
    dot(Vector3) -> Scalar
    cross(Vector3) -> Vector3
    normalized() -> Vector3
    interpolated(with: Vector3, by: Scalar) -> Vector3

Vector4
    init(x: Scalar, y: Scalar, z: Scalar, w: Scalar)
    init(_: Scalar, _: Scalar, _: Scalar, _: Scalar)
    init(_: Vector3, w: Scalar)
    init(_: [Scalar])
    lengthSquared: Scalar
    length: Scalar
    inverse: Vector4
    xyz: Vector3
    xy: Vector2
    xz: Vector2
    yz: Vector2
    toArray() -> [Scalar]
    toVector3() -> Vector3
    dot(Vector4) -> Scalar
    normalized() -> Vector4
    interpolated(with: Vector4, by: Scalar) -> Vector4

Matrix3
    init(m11: Scalar, m12: Scalar, ... m33: Scalar)
    init(_: Scalar, _: Scalar, ... _: Scalar)
    init(scale: Vector2)
    init(translation: Vector2)
    init(rotation: Scalar)
    init(_: [Scalar])
    adjugate: Matrix3
    determinant: Scalar
    transpose: Matrix3
    inverse: Matrix3
    toArray() -> [Scalar]
    interpolated(with: Matrix3, by: Scalar) -> Matrix3

Matrix4
    init(m11: Scalar, m12: Scalar, ... m33: Scalar)
    init(_: Scalar, _: Scalar, ... _: Scalar)
    init(scale: Vector3)
    init(translation: Vector3)
    init(rotation: Vector4)
    init(quaternion: Quaternion)
    init(fovx: Scalar, fovy: Scalar, near: Scalar, far: Scalar)
    init(fovx: Scalar, aspect: Scalar, near: Scalar, far: Scalar)
    init(fovy: Scalar, aspect: Scalar, near: Scalar, far: Scalar)
    init(top: Scalar, right: Scalar, bottom: Scalar, left: Scalar, near: Scalar, far: Scalar)
    init(_: [Scalar])
    adjugate: Matrix4
    determinant: Scalar
    transpose: Matrix4
    inverse: Matrix4
    toArray() -> [Scalar]
    interpolated(with: Matrix3, by: Scalar) -> Matrix3

Quaternion
    init(x: Scalar, y: Scalar, z: Scalar, w: Scalar)
    init(_: Scalar, _: Scalar, _: Scalar, _: Scalar)
    init(axisAngle: Vector4)
    init(pitch: Scalar, yaw: Scalar, roll: Scalar)
    init(rotationMatrix m: Matrix4)
    init(_: [Scalar])
    lengthSquared: Scalar
    length: Scalar
    inverse: Quaternion
    xyz: Vector3
    pitch: Scalar
    yaw: Scalar
    roll: Scalar
    toAxisAngle() -> Vector4
    toPitchYawRoll() -> (pitch: Scalar, yaw: Scalar, roll: Scalar)
    toArray() -> [Scalar]
    dot(Quaternion) -> Scalar
    normalized() -> Quaternion
    interpolated(with: Quaternion, by: Scalar) -> Quaternion

Operators

VectorMath makes extensive use of operator overloading, but I've tried not to go overboard with custom operators. The only nonstandard operator defined is ~=, meaning "approximately equal", which is extremely useful for comparing Scalar, Vector or Matrix values for equality, as, due to floating point imprecision, they are rarely identical.

The *, /, +, - and == operators are implemented for most of the included types. * in particular is useful for matrix and vector transforms. For example, to apply a matrix transform "m" to a vector "v" you can write m * v. * can also be used in conjunction with a Scalar value to scale a vector.

Unary minus is supported for inversion/negation on vectors and matrices.

Dot product, cross product and normalization are not available in operator form, but are supplied as methods on the various types.

Acknowledgements

Many of the algorithms used in VectorMath were ported or adapted from the Kazmath vector math library for C (https://github.com/Kazade/kazmath), or derived from the awesome Matrix and Quaternion FAQ (http://www.j3d.org/matrix_faq/matrfaq_latest.html).

In addition, the following people have contributed directly to the project:

  • @harlanhaskins - SPM and Linux support
  • @milpitas - CocoaPods support
  • @billhsu / @ismailbozk - Bug fixes and test coverage
  • @jiropole - MapKit integration
  • @nicklockwood - Everything else

(Full list of contributors)

More Repositories

1

iCarousel

A simple, highly customisable, data-driven 3D carousel for iOS and Mac OS
Objective-C
11,999
star
2

SwiftFormat

A command-line tool and Xcode Extension for formatting Swift code
Swift
7,781
star
3

FXBlurView

[DEPRECATED]
Objective-C
4,942
star
4

iRate

[DEPRECATED]
Objective-C
4,100
star
5

FXForms

[DEPRECATED]
Objective-C
2,926
star
6

SwipeView

SwipeView is a class designed to simplify the implementation of horizontal, paged scrolling views on iOS. It is based on a UIScrollView, but adds convenient functionality such as a UITableView-style dataSource/delegate interface for loading views dynamically, and efficient view loading, unloading and recycling.
Objective-C
2,646
star
7

layout

A declarative UI framework for iOS
Swift
2,231
star
8

iVersion

[DEPRECATED]
Objective-C
1,947
star
9

NullSafe

NullSafe is a simple category on NSNull that returns nil for unrecognised messages instead of throwing an exception
Objective-C
1,943
star
10

RetroRampage

Tutorial series demonstrating how to build a retro first-person shooter from scratch in Swift
Swift
1,486
star
11

XMLDictionary

[DEPRECATED]
Objective-C
1,139
star
12

AutoCoding

AutoCoding is a category on NSObject that provides automatic support for NSCoding and NSCopying to every object.
Objective-C
1,068
star
13

GZIP

A simple NSData category for gzipping/unzipping data in iOS and Mac OS
Objective-C
983
star
14

FastCoding

A faster and more flexible binary file format replacement for NSCoding, Property Lists and JSON
C
976
star
15

AsyncImageView

[DEPRECATED]
Objective-C
906
star
16

iConsole

[DEPRECATED]
Objective-C
859
star
17

Expression

A cross-platform Swift library for evaluating mathematical expressions at runtime
Swift
822
star
18

FXLabel

[DEPRECATED]
Objective-C
816
star
19

CountryPicker

CountryPicker is a custom UIPickerView subclass that provides an iOS control allowing a user to select a country from a list. It can optionally display a flag next to each country name, and the library includes a set of 249 high-quality, public domain flag images from FAMFAMFAM (http://www.famfamfam.com/lab/icons/flags/) that have been painstakingly re-named by country code to work with the library.
Objective-C
740
star
20

Euclid

A Swift library for creating and manipulating 3D geometry
Swift
637
star
21

SoundManager

Simple sound and music player class for playing audio on Mac and iPhone
Objective-C
630
star
22

FXImageView

FXImageView is a class designed to simplify the application of common visual effects such as reflections and drop-shadows to images, and also to help the performance of image loading by handling it on a background thread.
Objective-C
628
star
23

Base64

[DEPRECATED]
Objective-C
578
star
24

FXKeychain

[DEPRECATED]
Objective-C
554
star
25

MustOverride

Provides a macro that you can use to ensure that a method of an abstract base class *must* be overriden by its subclasses.
Objective-C
523
star
26

LayerSprites

LayerSprites is a library designed to simplify the use of sprite sheets (image maps containing multiple sub-images) in UIKit applications without using OpenGL or 3rd-party game libraries. Can load sprite sheets in the Coco2D format.
Objective-C
504
star
27

GLView

[DEPRECATED]
Objective-C
477
star
28

FXNotifications

An alternative API for NSNotificationCenter that doesn't suck
Objective-C
392
star
29

ShapeScript

The ShapeScript 3D modeling app for macOS and iOS
Swift
391
star
30

LRUCache

LRUCache is an open-source replacement for NSCache that behaves in a predictable, debuggable way
Swift
378
star
31

ReflectionView

[DEPRECATED]
Objective-C
359
star
32

Swiftenstein

Simple Wolfenstein 3D clone written in Swift
Swift
359
star
33

JPNG

JPNG is a bespoke image file format that combines the compression benefits of JPEG with the alpha channel support of a PNG file. The JPNG library provides an Objective-C implementation of this format along with transparent JPNG loading support for iOS and Mac OS.
Objective-C
340
star
34

StandardPaths

StandardPaths is a category on NSFileManager for simplifying access to standard application directories on iOS and Mac OS and abstracting the iCloud backup flags on iOS. It also provides support for working with device-specific file suffixes, such as the @2x suffix for Retina displays, or the -568h suffix for iPhone 5 and can optionally swizzle certain UIKit methods to support these suffixes more consistently.
Objective-C
336
star
35

ViewUtils

ViewUtils is a collection of category methods designed that extend UIView with all the handy little properties and functionality that you always wished were built-in to begin with.
Objective-C
324
star
36

FXPageControl

Simple, drop-in replacement for the iPhone UIPageControl that allows customisation of the dot colour, size and spacing.
Objective-C
298
star
37

BaseModel

BaseModel provides a base class for building model objects for your iOS or Mac OS projects. It saves you the hassle of writing boilerplate code, and encourages good practices by reducing the incentive to cut corners in your model implementation.
Objective-C
288
star
38

OrderedDictionary

This library provides OrderedDictionary and MutableOrderedDictionary subclasses.
Objective-C
278
star
39

ColorUtils

[DEPRECATED]
Objective-C
256
star
40

Tribute

A command-line tool for tracking Swift project licenses
Swift
246
star
41

OSNavigationController

[DEPRECATED]
Objective-C
233
star
42

Consumer

Mac and iOS library for parsing structured text
Swift
226
star
43

iNotify

[DEPRECATED]
Objective-C
225
star
44

FPSControls

An experimental implementation of touch-friendly first-person shooter controls using SceneKit and Swift
Swift
215
star
45

OSCache

OSCache is an open-source re-implementation of NSCache that behaves in a predictable, debuggable way.
Objective-C
200
star
46

Chess

A simple Chess game for iOS, written in Swift
Swift
177
star
47

RequestQueue

[DEPRECATED]
Objective-C
174
star
48

FXReachability

Lightweight reachability class for Mac and iOS
Objective-C
173
star
49

Sprinter

A library for formatting strings on iOS and macOS
Swift
166
star
50

CryptoCoding

CryptoCoding is a superset of the NSCoding protocol that allows for simple, seamless AES encryption of any NSCoding-compatible object.
Objective-C
148
star
51

RequestUtils

A collection of category methods designed to simplify the process of HTTP request construction and manipulation in Cocoa.
Objective-C
142
star
52

CubeController

CubeController is a UIViewController subclass that can be used to create a rotating 3D cube navigation.
Objective-C
142
star
53

HTMLLabel

[DEPRECATED]
Objective-C
139
star
54

NSOperationStack

[DEPRECATED]
Objective-C
118
star
55

SVGPath

Cross-platform Swift library for parsing SVGPath strings
Swift
111
star
56

HRCoder

HRCoder is a replacement for the NSKeyedArchiver and NSKeyedUnarchiver classes that uses a human-readable/editable format that can easily be stored in a regular Plist or JSON file.
Objective-C
104
star
57

iPrompt

[DEPRECATED]
Objective-C
99
star
58

Presentations

Code samples and projects for presentations that I have given
Objective-C
98
star
59

FXPhotoEditView

[DEPRECATED]
Objective-C
92
star
60

StackView

StackView is a class designed to simplify the implementation of vertical stacks of views on iOS. You can think of it as a bit like a simplified version of UITableView.
Objective-C
73
star
61

WebContentView

[DEPRECATED]
Objective-C
69
star
62

StringCoding

StringCoding is a simple Mac/iOS library for setting object properties of any type using string values. It can automatically detect the property type and attempt to interpret the string as the right kind of value. It's particularly oriented towards iOS app theming (see README for details).
Objective-C
57
star
63

ArrayUtils

[DEPRECATED]
Objective-C
49
star
64

Swune

Swift/UIKit reimplementation of the Dune II RTS game
Swift
46
star
65

Parsing

Supporting code for my talk entitled "Parsing Formal Languages with Swift"
Swift
42
star
66

MACAddress

[DEPRECATED]
Objective-C
39
star
67

FXParser

[DEPRECATED]
Objective-C
34
star
68

RotateView

Objective-C
34
star
69

RandomSequence

A class for creating independent, repeatable pseudorandom number sequences on Mac and iOS
Objective-C
28
star
70

FloatyBalloon

This is the source code for a simple game called Floaty Balloon, based on the gameplay of Flappy Bird. It was created as a tutorial for http://iosdevelopertips.com
Objective-C
25
star
71

Concurrency

Full source code for a simple currency calculator app
Objective-C
15
star
72

FXJSON

[DEPRECATED]
Objective-C
15
star
73

PNGvsJPEG

This is a simple benchmark app to compare JPEG vs PNG loading performance on iOS. Spoiler: JPEG wins.
Objective-C
6
star