Skip to content

Instantly share code, notes, and snippets.

@drewolbrich
Last active August 11, 2024 03:43
Show Gist options
  • Select an option

  • Save drewolbrich/284d92eb3df5580cb635a50cbe49dab5 to your computer and use it in GitHub Desktop.

Select an option

Save drewolbrich/284d92eb3df5580cb635a50cbe49dab5 to your computer and use it in GitHub Desktop.
SIMD look-at functions
//
// SIMD+LookAt.swift
//
// Created by Drew Olbrich on 11/10/23.
// Copyright © 2023 Lunar Skydiving LLC. All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import simd
/// Creates a 4x4 matrix that orients the +Z axis in the direction of `at`, and the
/// +Y axis toward `up`.
func simd_look(at: SIMD3<Float>, up: SIMD3<Float> = SIMD3<Float>(0, 1, 0)) -> simd_float4x4 {
let zAxis = normalize(at)
let xAxis = normalize(cross(up, zAxis))
let yAxis = normalize(cross(zAxis, xAxis))
return simd_float4x4(
SIMD4(xAxis, w: 0),
SIMD4(yAxis, w: 0),
SIMD4(zAxis, w: 0),
SIMD4(0, 0, 0, 1)
)
}
/// Creates a 4x4 matrix that positions the origin at `from`, orienting the +Z axis
/// so it points at `at`, and the +Y axis in the direction of `up`.
func simd_look(at: SIMD3<Float>, from: SIMD3<Float>, up: SIMD3<Float> = SIMD3<Float>(0, 1, 0)) -> simd_float4x4 {
let zAxis = normalize(at - from)
let xAxis = normalize(cross(up, zAxis))
let yAxis = normalize(cross(zAxis, xAxis))
return simd_float4x4(
SIMD4(xAxis, w: 0),
SIMD4(yAxis, w: 0),
SIMD4(zAxis, w: 0),
SIMD4(from, 1)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment