Skip to content

Instantly share code, notes, and snippets.

@nightcycle
Created September 1, 2023 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nightcycle/d5542c93b91f12a5cadb35bff5b1d013 to your computer and use it in GitHub Desktop.
Save nightcycle/d5542c93b91f12a5cadb35bff5b1d013 to your computer and use it in GitHub Desktop.
A type safe version of EgoMoose's ViewportModel class
--!strict
--[[
MIT License
Copyright (c) 2021 EgoMoose + 2023 Nightcycle
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.
--]]
-- Services
-- Packages
-- Modules
-- Types
export type ViewportData = {
Aspect: number,
YFov2: number,
TanYFov2: number,
XFov2: number,
TanXFov2: number,
CFov2: number,
SinCFov2: number,
}
export type ViewportModel = {
__index: ViewportModel,
ClassName: "ViewportModel",
Model: Model?,
ViewportFrame: ViewportFrame,
Camera: Camera,
_Points: {[number]: Vector3},
_ModelCFrame: CFrame,
_ModelSize: Vector3,
_ModelRadius: number,
_Viewport: ViewportData?,
new: (vpf: ViewportFrame, camera: Camera) -> ViewportModel,
SetModel: (self: ViewportModel, model: Model) -> (),
Calibrate: (self: ViewportModel) -> (),
GetFitDistance: (self: ViewportModel, focusPosition: Vector3) -> number,
GetMinimumFitCFrame: (self: ViewportModel, orientation: CFrame) -> CFrame,
}
-- Constants
local BLOCK = {0, 1, 2, 3, 4, 5, 6, 7}
local WEDGE = {0, 1, 3, 4, 5, 7}
local CORNER_WEDGE = {0, 1, 4, 5, 6}
-- Variables
-- References
-- Private Functions
-- Class
local ViewportModelClass = {} :: ViewportModel
ViewportModelClass.__index = ViewportModelClass
ViewportModelClass.ClassName = "ViewportModel"
-- Private
function getIndices(part: BasePart): {[number]: number}
if part:IsA("WedgePart") then
return WEDGE
elseif part:IsA("CornerWedgePart") then
return CORNER_WEDGE
end
return BLOCK
end
function getCorners(cf: CFrame, size2: Vector3, indices: {[number]: number}): {[number]: Vector3}
local corners = {}
for j, i in pairs(indices) do
corners[j] = cf * (size2 * Vector3.new(
2 * (math.floor(i / 4) % 2) - 1,
2 * (math.floor(i / 2) % 2) - 1,
2 * (i % 2) - 1
))
end
return corners
end
function getModelPointCloud(model: Model): {[number]: Vector3}
local points = {}
for _, part in pairs(model:GetDescendants()) do
if part:IsA("BasePart") then
local indices = getIndices(part)
local corners = getCorners(part.CFrame, part.Size / 2, indices)
for _, wp in pairs(corners) do
table.insert(points, wp)
end
end
end
return points
end
function viewProjectionEdgeHits(cloud: {[number]: Vector3}, axis: "X" | "Y" | "Z", depth: number, tanFov2: number): (number, number)
local max, min = -math.huge, math.huge
for _, lp in pairs(cloud) do
local distance = depth - lp.Z
local halfSpan = tanFov2 * distance
local a = (lp::any)[axis] + halfSpan
local b = (lp::any)[axis] - halfSpan
max = math.max(max, a, b)
min = math.min(min, a, b)
end
return max, min
end
-- Public Constructors
function ViewportModelClass.new(vpf: ViewportFrame, camera: Camera): ViewportModel
local self: ViewportModel = setmetatable({}, ViewportModelClass) :: any
self.Model = nil
self.ViewportFrame = vpf
self.Camera = camera
self._Points = {}
self._ModelCFrame = CFrame.new()
self._ModelSize = Vector3.new()
self._ModelRadius = 0
self._Viewport = nil
self:Calibrate()
return self
end
-- Public Methods
-- Used to set the model that is being focused on
-- should be used for new models and/or a change in the current model
-- e.g. parts added/removed from the model or the model cframe changed
function ViewportModelClass:SetModel(model: Model)
self.Model = model
local cf, size = model:GetBoundingBox()
self._Points = getModelPointCloud(model)
self._ModelCFrame = cf
self._ModelSize = size
self._ModelRadius = size.Magnitude / 2
end
-- Should be called when something about the viewport frame / camera changes
-- e.g. the frame size or the camera field of view
function ViewportModelClass:Calibrate()
local viewport = {}
local size = self.ViewportFrame.AbsoluteSize
viewport.Aspect = size.X / size.Y
viewport.YFov2 = math.rad(self.Camera.FieldOfView / 2)
viewport.TanYFov2 = math.tan(viewport.YFov2)
viewport.XFov2 = math.atan(viewport.TanYFov2 * viewport.Aspect)
viewport.TanXFov2 = math.tan(viewport.XFov2)
viewport.CFov2 = math.atan(viewport.TanYFov2 * math.min(1, viewport.Aspect))
viewport.SinCFov2 = math.sin(viewport.CFov2)
self._Viewport = viewport
end
-- returns a fixed distance that is guarnteed to encapsulate the full model
-- this is useful for when you want to rotate freely around an object w/o expensive calculations
-- focus position can be used to set the origin of where the camera's looking
-- otherwise the model's center is assumed
function ViewportModelClass:GetFitDistance(focusPosition: Vector3): number
local displacement: number = if focusPosition then (focusPosition - self._ModelCFrame.Position).Magnitude else 0
local radius = self._ModelRadius + displacement
local viewportData = self._Viewport
assert(viewportData, "calibration required")
return radius / viewportData.SinCFov2
end
-- returns the optimal camera cframe that would be needed to best fit
-- the model in the viewport frame at the given orientation.
-- keep in mind this functions best when the model's point-cloud is correct
-- as such models that rely heavily on meshesh, csg, etc will only return an accurate
-- result as their point cloud
function ViewportModelClass:GetMinimumFitCFrame(orientation: CFrame): CFrame
if not self.Model then
return CFrame.new()
end
local rotation = orientation - orientation.Position
local rInverse = rotation:Inverse()
local wcloud = self._Points
local cloud: {[number]: Vector3} = {rInverse * wcloud[1]}
local furthest = cloud[1].Z
local viewportData = self._Viewport
assert(viewportData, "calibration required")
for i = 2, #wcloud do
local lp: Vector3 = rInverse * wcloud[i]
furthest = math.min(furthest, lp.Z)
cloud[i] = lp
end
local hMax, hMin = viewProjectionEdgeHits(cloud, "X", furthest, viewportData.TanXFov2)
local vMax, vMin = viewProjectionEdgeHits(cloud, "Y", furthest, viewportData.TanYFov2)
local distance = math.max(
((hMax - hMin) / 2) / viewportData.TanXFov2,
((vMax - vMin) / 2) / viewportData.TanYFov2
)
return orientation * CFrame.new(
(hMax + hMin) / 2,
(vMax + vMin) / 2,
furthest + distance
)
end
--
return ViewportModelClass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment