repo stringclasses 254
values | file_path stringlengths 29 241 | code stringlengths 100 233k | tokens int64 14 69.4k |
|---|---|---|---|
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/Button.luau | --[=[
@class Button
A basic button that supports text, an icon, or both. This should be used as a standalone button
or as a secondary button alongside a [MainButton] for the primary action in a group of options.
| Dark | Light |
| - | - |
|  |  |
The `OnActivated` prop should be a callback which is run when the button is clicked.
For example:
```lua
local function MyComponent()
return React.createElement(StudioComponents.Button, {
Text = "Click Me",
OnActivated = function()
print("Button clicked!")
end
})
end
```
The default size of buttons can be found in [Constants.DefaultButtonHeight]. To override this,
there are two main options, which may be combined:
1. Pass a `Size` prop.
2. Pass an `AutomaticSize` prop.
AutomaticSize is a simpler version of Roblox's built-in AutomaticSize system. Passing a value of
`Enum.AutomaticSize.X` will override the button's width to fit the text and/or icon. Passing a
value of `Enum.AutomaticSize.Y` will do the same but with the button's height. Passing
`Enum.AutomaticSize.XY` will override both axes.
]=]
local React = require("@pkg/@jsdotlua/react")
local BaseButton = require("./Foundation/BaseButton")
--[=[
@within Button
@interface IconProps
@field Image string
@field Size Vector2
@field Transparency number?
@field Color Color3?
@field UseThemeColor boolean?
@field Alignment HorizontalAlignment?
@field ResampleMode Enum.ResamplerMode?
@field RectOffset Vector2?
@field RectSize Vector2?
The `Alignment` prop is used to configure which side of any text the icon
appears on. Left-alignment is the default and center-alignment is not supported.
When specifying icon color, at most one of `Color` and `UseThemeColor` should be specified.
]=]
--[=[
@within Button
@interface Props
@tag Component Props
@field ... CommonProps
@field AutomaticSize AutomaticSize?
@field OnActivated (() -> ())?
@field Text string?
@field Icon IconProps?
]=]
local function Button(props: BaseButton.BaseButtonConsumerProps)
local merged = table.clone(props) :: BaseButton.BaseButtonProps
merged.BackgroundColorStyle = Enum.StudioStyleGuideColor.Button
merged.BorderColorStyle = Enum.StudioStyleGuideColor.ButtonBorder
merged.TextColorStyle = Enum.StudioStyleGuideColor.ButtonText
return React.createElement(BaseButton, merged)
end
return Button
| 602 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/ColorPicker.luau | --[=[
@class ColorPicker
An interface for selecting a color with a Hue / Saturation box and a Value slider.
Individual RGB and HSV values can also be modified manually.
| Dark | Light |
| - | - |
|  |  |
This is a controlled component, which means the current color should be passed in to the
`Color` prop and a callback value to the `OnChanged` prop which gets run when the user attempts
to change the color. For example:
```lua
local function MyComponent()
local color, setColor = React.useState(Color3.fromHex("#008080"))
return React.createElement(StudioComponents.ColorPicker, {
Value = color,
OnChanged = setColor,
})
end
```
The default size of this component is exposed in [Constants.DefaultColorPickerSize].
To keep all inputs accessible, it is recommended not to use a smaller size than this.
This component is not a modal or dialog box (this should be implemented separately).
]=]
local React = require("@pkg/@jsdotlua/react")
local CommonProps = require("../CommonProps")
local Constants = require("../Constants")
local Label = require("./Label")
local NumericInput = require("./NumericInput")
local useMouseDrag = require("../Hooks/useMouseDrag")
local useTheme = require("../Hooks/useTheme")
local function clampVector2(v: Vector2, vmin: Vector2, vmax: Vector2)
return Vector2.new(math.clamp(v.X, vmin.X, vmax.X), math.clamp(v.Y, vmin.Y, vmax.Y))
end
--[=[
@within ColorPicker
@interface Props
@tag Component Props
@field ... CommonProps
@field Color Color3
@field OnChanged ((newColor: Color3) -> ())?
]=]
type ColorPickerProps = CommonProps.T & {
Color: Color3,
OnChanged: ((newColor: Color3) -> ())?,
}
local SPLIT_Y = 76
local SPLIT_X = 50
local PADDING = 8
local function generateHueKeypoints(value: number)
local keypoints = {}
local regions = 6
for hue = 0, regions do
local offset = hue / regions
local color = Color3.fromHSV((regions - hue) / regions, 1, value)
table.insert(keypoints, ColorSequenceKeypoint.new(offset, color))
end
return ColorSequence.new(keypoints)
end
local noop = function() end
local function ValPicker(props: {
HSV: { number },
OnChanged: (hue: number, sat: number, val: number) -> (),
Disabled: boolean?,
})
local theme = useTheme()
local hue, sat, val = unpack(props.HSV)
local drag = useMouseDrag(function(rbx: GuiObject, input: InputObject)
local mousePos = input.Position.Y
local alpha = (mousePos - rbx.AbsolutePosition.Y) / rbx.AbsoluteSize.Y
alpha = math.clamp(alpha, 0, 1)
props.OnChanged(hue, sat, 1 - alpha)
end, { hue, sat, val, props.OnChanged } :: { unknown })
React.useEffect(function()
if props.Disabled and drag.isActive() then
drag.cancel()
end
end, { props.Disabled, drag.isActive() })
local gradientTarget = Color3.fromHSV(hue, sat, 1)
return React.createElement("TextButton", {
Active = false,
AutoButtonColor = false,
Text = "",
Size = UDim2.new(0, 14, 1, 0),
AnchorPoint = Vector2.new(1, 0),
Position = UDim2.new(1, -6, 0, 0),
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Border),
BackgroundColor3 = Color3.fromRGB(255, 255, 255),
BackgroundTransparency = if props.Disabled then 0.75 else 0,
[React.Event.InputBegan] = if not props.Disabled then drag.onInputBegan else nil,
[React.Event.InputChanged] = if not props.Disabled then drag.onInputChanged else nil,
[React.Event.InputEnded] = if not props.Disabled then drag.onInputEnded else nil,
}, {
Gradient = React.createElement("UIGradient", {
Color = ColorSequence.new(Color3.fromRGB(0, 0, 0), gradientTarget),
Rotation = 270,
}),
Arrow = React.createElement("ImageLabel", {
AnchorPoint = Vector2.new(0, 0.5),
Size = UDim2.fromOffset(5, 9),
Position = UDim2.new(1, 1, 1 - val, 0),
BackgroundTransparency = 1,
Image = "rbxassetid://7507468017",
ImageColor3 = theme:GetColor(Enum.StudioStyleGuideColor.TitlebarText),
Visible = not props.Disabled,
}),
Cover = props.Disabled and React.createElement("Frame", {
Size = UDim2.fromScale(1, 1),
BorderSizePixel = 0,
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainBackground),
BackgroundTransparency = 0.5,
ZIndex = 2,
}),
})
end
local function HueSatPicker(props: {
HSV: { number },
OnChanged: (hue: number, sat: number, val: number) -> (),
Disabled: boolean?,
})
local theme = useTheme()
local hue, sat, val = unpack(props.HSV)
local bgVal = 220 / 255 -- used to just use val but was weird when val was low
local indicatorBackground = if bgVal > 0.4 then Color3.new(0, 0, 0) else Color3.fromRGB(200, 200, 200)
local drag = useMouseDrag(function(rbx: GuiObject, input: InputObject)
local mousePos = Vector2.new(input.Position.X, input.Position.Y)
local alpha = (mousePos - rbx.AbsolutePosition) / rbx.AbsoluteSize
alpha = clampVector2(alpha, Vector2.zero, Vector2.one)
props.OnChanged(1 - alpha.X, 1 - alpha.Y, val)
end, { hue, sat, val, props.OnChanged } :: { unknown })
React.useEffect(function()
if props.Disabled and drag.isActive() then
drag.cancel()
end
end, { props.Disabled, drag.isActive() })
return React.createElement("TextButton", {
Size = UDim2.new(1, -30, 1, 0),
ClipsDescendants = true,
AutoButtonColor = false,
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Border),
BackgroundTransparency = if props.Disabled then 0.75 else 0,
Active = false,
Text = "",
[React.Event.InputBegan] = if not props.Disabled then drag.onInputBegan else nil,
[React.Event.InputChanged] = if not props.Disabled then drag.onInputChanged else nil,
[React.Event.InputEnded] = if not props.Disabled then drag.onInputEnded else nil,
}, {
Hue = React.createElement("Frame", {
BackgroundColor3 = Color3.fromRGB(255, 255, 255),
Size = UDim2.fromScale(1, 1),
ZIndex = 0,
}, {
Gradient = React.createElement("UIGradient", {
Color = generateHueKeypoints(bgVal),
}),
}),
Sat = React.createElement("Frame", {
BackgroundColor3 = Color3.fromRGB(255, 255, 255),
Size = UDim2.fromScale(1, 1),
ZIndex = 1,
}, {
Gradient = React.createElement("UIGradient", {
Color = ColorSequence.new(Color3.fromHSV(1, 0, bgVal)),
Transparency = NumberSequence.new(1, 0),
Rotation = 90,
}),
}),
Indicator = React.createElement("Frame", {
AnchorPoint = Vector2.new(0.5, 0.5),
Position = UDim2.new(1 - hue, 0, 1 - sat, 0),
Size = UDim2.fromOffset(20, 20),
BackgroundTransparency = 1,
ZIndex = 2,
Visible = not props.Disabled,
}, {
Vertical = React.createElement("Frame", {
Position = UDim2.fromOffset(9, 0),
Size = UDim2.new(0, 2, 1, 0),
BorderSizePixel = 0,
BackgroundColor3 = indicatorBackground,
}),
Horizontal = React.createElement("Frame", {
Position = UDim2.fromOffset(0, 9),
Size = UDim2.new(1, 0, 0, 2),
BorderSizePixel = 0,
BackgroundColor3 = indicatorBackground,
}),
}),
Cover = props.Disabled and React.createElement("Frame", {
Size = UDim2.fromScale(1, 1),
BorderSizePixel = 0,
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainBackground),
BackgroundTransparency = 0.5,
ZIndex = 3,
}),
})
end
local function ColorControl(props: {
AnchorPoint: Vector2?,
Position: UDim2?,
Label: string,
Value: number,
Max: number,
Callback: (n: number) -> (),
Disabled: boolean?,
})
local div = 28
return React.createElement("Frame", {
AnchorPoint = props.AnchorPoint,
Position = props.Position,
Size = UDim2.new(0.5, -PADDING, 0, Constants.DefaultInputHeight),
BackgroundTransparency = 1,
}, {
Label = React.createElement(Label, {
Text = `{props.Label}:`,
TextXAlignment = Enum.TextXAlignment.Right,
Size = UDim2.new(0, div, 1, 0),
Disabled = props.Disabled,
}),
Input = React.createElement(NumericInput, {
AnchorPoint = Vector2.new(1, 0),
Position = UDim2.fromScale(1, 0),
Size = UDim2.new(1, -div - 5, 1, 0),
Value = props.Value,
Min = 0,
Max = props.Max,
OnValidChanged = props.Callback,
Arrows = true,
Disabled = props.Disabled,
}),
})
end
local function ColorControls(props: {
HSV: { number },
RGB: { number },
OnChangedHSV: (hue: number, sat: number, val: number) -> (),
OnChangedRGB: (red: number, green: number, blue: number) -> (),
Disabled: boolean?,
})
local hue, sat, val = unpack(props.HSV)
local red, green, blue = unpack(props.RGB)
return React.createElement("Frame", {
Size = UDim2.new(1, -SPLIT_X - PADDING, 1, 0),
AnchorPoint = Vector2.new(1, 0),
Position = UDim2.fromScale(1, 0),
BackgroundTransparency = 1,
}, {
Hue = React.createElement(ColorControl, {
AnchorPoint = Vector2.new(0, 0),
Label = "Hue",
Value = math.round(hue * 360),
Max = 360,
Callback = function(newHue)
props.OnChangedHSV(newHue / 360, sat, val)
end,
Disabled = props.Disabled,
}),
Sat = React.createElement(ColorControl, {
AnchorPoint = Vector2.new(0, 0.5),
Position = UDim2.fromScale(0, 0.5),
Label = "Sat",
Value = math.round(sat * 255),
Max = 255,
Callback = function(newSat)
props.OnChangedHSV(hue, newSat / 255, val)
end,
Disabled = props.Disabled,
}),
Val = React.createElement(ColorControl, {
AnchorPoint = Vector2.new(0, 1),
Position = UDim2.fromScale(0, 1),
Label = "Val",
Value = math.round(val * 255),
Max = 255,
Callback = function(newVal)
props.OnChangedHSV(hue, sat, newVal / 255)
end,
Disabled = props.Disabled,
}),
Red = React.createElement(ColorControl, {
AnchorPoint = Vector2.new(1, 0),
Position = UDim2.fromScale(1, 0),
Label = "Red",
Value = math.round(red * 255),
Max = 255,
Callback = function(newRed)
props.OnChangedRGB(newRed / 255, green, blue)
end,
Disabled = props.Disabled,
}),
Green = React.createElement(ColorControl, {
AnchorPoint = Vector2.new(1, 0.5),
Position = UDim2.fromScale(1, 0.5),
Label = "Green",
Value = math.round(green * 255),
Max = 255,
Callback = function(newGreen)
props.OnChangedRGB(red, newGreen / 255, blue)
end,
Disabled = props.Disabled,
}),
Blue = React.createElement(ColorControl, {
AnchorPoint = Vector2.new(1, 1),
Position = UDim2.fromScale(1, 1),
Label = "Blue",
Value = math.round(blue * 255),
Max = 255,
Callback = function(newBlue)
props.OnChangedRGB(red, green, newBlue / 255)
end,
Disabled = props.Disabled,
}),
})
end
local function ColorPicker(props: ColorPickerProps)
local theme = useTheme()
local onChanged: (color: Color3) -> () = props.OnChanged or noop
-- avoids information loss when converting hsv -> rgb -> hsv between renders
local hsv, setHSV = React.useState({ props.Color:ToHSV() })
React.useEffect(function()
setHSV(function(oldHSV)
if Color3.fromHSV(unpack(oldHSV)) ~= props.Color then
return { props.Color:ToHSV() }
end
return oldHSV
end)
end, { props.Color })
local pickerProps = {
HSV = hsv,
OnChanged = function(hue, sat, val)
setHSV({ hue, sat, val })
onChanged(Color3.fromHSV(hue, sat, val))
end,
Disabled = props.Disabled,
}
local modifier = Enum.StudioStyleGuideModifier.Default
if props.Disabled then
modifier = Enum.StudioStyleGuideModifier.Disabled
end
return React.createElement("Frame", {
AnchorPoint = props.AnchorPoint,
Position = props.Position,
Size = props.Size or Constants.DefaultColorPickerSize,
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainBackground, modifier),
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Border, modifier),
BorderMode = Enum.BorderMode.Inset,
LayoutOrder = props.LayoutOrder,
ZIndex = props.ZIndex,
}, {
Padding = React.createElement("UIPadding", {
PaddingLeft = UDim.new(0, PADDING),
PaddingRight = UDim.new(0, PADDING),
PaddingTop = UDim.new(0, PADDING),
PaddingBottom = UDim.new(0, PADDING),
}),
TopArea = React.createElement("Frame", {
Size = UDim2.new(1, 0, 1, -SPLIT_Y - PADDING),
BackgroundTransparency = 1,
}, {
ValPicker = React.createElement(ValPicker, pickerProps),
HueSatPicker = React.createElement(HueSatPicker, pickerProps),
}),
BtmArea = React.createElement("Frame", {
AnchorPoint = Vector2.new(0, 1),
Size = UDim2.new(1, 0, 0, SPLIT_Y),
Position = UDim2.fromScale(0, 1),
BackgroundTransparency = 1,
}, {
Preview = React.createElement("Frame", {
Size = UDim2.new(0, SPLIT_X, 1, 0),
BackgroundTransparency = if props.Disabled then 0.75 else 0,
BackgroundColor3 = props.Color,
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Border),
}),
Controls = React.createElement(ColorControls, {
HSV = hsv,
RGB = { props.Color.R, props.Color.G, props.Color.B },
OnChangedHSV = pickerProps.OnChanged,
OnChangedRGB = function(red, green, blue)
onChanged(Color3.new(red, green, blue))
end,
Disabled = props.Disabled,
}),
}),
})
end
return ColorPicker
| 3,822 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/DatePicker.luau | --[=[
@class DatePicker
An interface for selecting a date from a calendar.
| Dark | Light |
| - | - |
|  |  |
This is a controlled component, which means you should pass in an initial date to the `Date`
prop and a callback value to the `OnChanged` prop which gets called with the new date when
the user selects one. For example:
```lua
local function MyComponent()
local date, setDate = React.useState(DateTime.now())
return React.createElement(StudioComponents.DatePicker, {
Date = date,
OnChanged = setDate,
})
end
```
In most cases the desired behavior would be to close the interface once a selection is made,
in which case you can use the `OnChanged` prop as a trigger for this.
The default size of this component is exposed in [Constants.DefaultDatePickerSize].
To keep all inputs accessible, it is recommended not to use a smaller size than this.
This component is not a modal or dialog box (this should be implemented separately).
]=]
local React = require("@pkg/@jsdotlua/react")
local BaseButton = require("./Foundation/BaseButton")
local CommonProps = require("../CommonProps")
local Constants = require("../Constants")
local useTheme = require("../Hooks/useTheme")
type TimeData = {
Year: number,
Month: number,
Day: number,
}
local TITLE_HEIGHT = 28
local OUTER_PAD = 3
local LOCALE = "en-us"
local ARROWS_ASSET = "rbxassetid://11156696202"
--[[
ideas:
- props for minimum and maximum date
- selecting a date range
- localization
]]
local dayShortName = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" }
local function getDayNumberText(day: number): string
if day > 9 then
return tostring(day)
end
return `{string.rep(" ", 2)}{day}`
end
local function getDaysInMonth(year: number, month: number)
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12 then
return 31
elseif month == 4 or month == 6 or month == 9 or month == 11 then
return 30
elseif year % 4 == 0 and (year % 100 ~= 0 or year % 400 == 0) then
return 29
end
return 28
end
-- 1 = monday, 7 = sunday
local function getDayOfWeek(year: number, month: number, day: number): number
local time = DateTime.fromUniversalTime(year, month, day)
local dayWeek = tonumber(time:FormatUniversalTime("d", LOCALE)) :: number
return 1 + (dayWeek - 1) % 7
end
local function DayButton(props: {
LayoutOrder: number,
Fade: boolean?,
Text: string,
Selected: boolean,
Disabled: boolean?,
OnActivated: () -> (),
})
return React.createElement(BaseButton, {
LayoutOrder = props.LayoutOrder,
Selected = props.Selected,
BackgroundColorStyle = Enum.StudioStyleGuideColor.RibbonButton,
BorderColorStyle = Enum.StudioStyleGuideColor.RibbonButton,
TextTransparency = props.Fade and 0.5 or 0,
Text = props.Text,
Disabled = props.Disabled,
OnActivated = props.OnActivated,
})
end
local function MonthButton(props: {
Position: UDim2,
AnchorPoint: Vector2?,
ImageRectOffset: Vector2,
Disabled: boolean?,
OnActivated: () -> (),
})
local theme = useTheme()
local hovered, setHovered = React.useState(false)
local pressed, setPressed = React.useState(false)
local color = Enum.StudioStyleGuideColor.Titlebar
local modifier = Enum.StudioStyleGuideModifier.Default
if props.Disabled then
modifier = Enum.StudioStyleGuideModifier.Disabled
elseif pressed then
color = Enum.StudioStyleGuideColor.Button
modifier = Enum.StudioStyleGuideModifier.Pressed
elseif hovered then
color = Enum.StudioStyleGuideColor.Button
modifier = Enum.StudioStyleGuideModifier.Hover
end
return React.createElement("TextButton", {
Text = "",
AutoButtonColor = false,
Position = props.Position,
AnchorPoint = props.AnchorPoint,
Size = UDim2.fromOffset(15, 17),
BorderSizePixel = 0,
BackgroundColor3 = theme:GetColor(color, modifier),
[React.Event.Activated] = function()
if not props.Disabled then
props.OnActivated()
end
end,
[React.Event.InputBegan] = function(_, input)
if props.Disabled then
return
elseif input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(true)
elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
setPressed(true)
end
end :: any,
[React.Event.InputEnded] = function(_, input)
if input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(false)
elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
setPressed(false)
end
end :: any,
}, {
Icon = React.createElement("ImageLabel", {
Size = UDim2.fromOffset(5, 9),
Position = UDim2.fromOffset(5, 4),
BackgroundTransparency = 1,
Image = ARROWS_ASSET,
ImageColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainText),
ImageRectSize = Vector2.new(5, 9),
ImageRectOffset = props.ImageRectOffset,
ImageTransparency = if props.Disabled then 0.7 else 0,
}),
})
end
--[=[
@within DatePicker
@interface Props
@tag Component Props
@field ... CommonProps
@field Date DateTime
@field OnChanged (newDate: DateTime) -> ()
]=]
type DatePickerProps = CommonProps.T & {
Date: DateTime,
OnChanged: ((newDate: DateTime) -> ())?,
}
type PageState = {
year: number?,
month: number?,
}
local function DatePicker(props: DatePickerProps)
local theme = useTheme()
local chosenPage, setChosenPage = React.useState({
year = nil,
month = nil,
} :: PageState)
local selectedTime = props.Date
local selectedData = selectedTime:ToUniversalTime() :: TimeData
local displayTime = props.Date
if chosenPage.year ~= nil then
displayTime = DateTime.fromUniversalTime(chosenPage.year, chosenPage.month)
end
-- reconcile state when selected date changes
-- so that we show the correct page
React.useEffect(function()
local data = props.Date:ToUniversalTime() :: TimeData
setChosenPage({
year = data.Year,
month = data.Month,
})
return function() end
end, { props.Date })
local displayData = displayTime:ToUniversalTime() :: TimeData
local displayYear = displayData.Year
local displayMonth = displayData.Month
local daysInMonth = getDaysInMonth(displayYear, displayMonth)
local lastMonthYear = if displayMonth == 1 then displayYear - 1 else displayYear
local lastMonth = if displayMonth == 1 then 12 else displayMonth - 1
local daysInLastMonth = getDaysInMonth(lastMonthYear, lastMonth)
local daysPrior = getDayOfWeek(displayYear, displayMonth, 1) - 1
local daysAfter = 7 * 6 - daysInMonth - daysPrior
-- common-year february starting on a monday (e.g. february 2027)
-- we display 7 days before, 1-28, then 7 days after
if daysPrior == 0 and daysAfter == 14 then
daysPrior = 7
daysAfter = 7
end
local colorModifier = Enum.StudioStyleGuideModifier.Default
if props.Disabled then
colorModifier = Enum.StudioStyleGuideModifier.Disabled
end
local items: { React.ReactNode } = {}
local index = 1
for i = 1, 7 do
items[index] = React.createElement("TextLabel", {
Text = dayShortName[i],
LayoutOrder = i,
Font = Constants.DefaultFont,
TextSize = Constants.DefaultTextSize,
TextColor3 = theme:GetColor(Enum.StudioStyleGuideColor.TitlebarText, colorModifier),
BackgroundTransparency = 1,
})
index += 1
end
local function makeOnActivated(day: number, month: number, year: number)
return function()
local newDate = DateTime.fromUniversalTime(year, month, day)
if props.OnChanged then
props.OnChanged(newDate)
end
end
end
for i = 1, daysPrior do
local day = daysInLastMonth - daysPrior + i
local month = (displayMonth - 2) % 12 + 1
local year = if displayMonth == 1 then displayYear - 1 else displayYear
items[index] = React.createElement(DayButton, {
Selected = day == selectedData.Day and month == selectedData.Month and year == selectedData.Year,
Text = getDayNumberText(day),
LayoutOrder = index,
Fade = true,
OnActivated = makeOnActivated(day, month, year),
Disabled = props.Disabled,
})
index += 1
end
for i = 1, daysInMonth do
local day = i
local month = displayMonth
local year = displayYear
items[index] = React.createElement(DayButton, {
Selected = day == selectedData.Day and month == selectedData.Month and year == selectedData.Year,
Text = getDayNumberText(day),
LayoutOrder = index,
OnActivated = makeOnActivated(day, month, year),
Disabled = props.Disabled,
})
index += 1
end
for i = 1, daysAfter do
local day = i
local month = displayMonth % 12 + 1
local year = if displayMonth == 12 then displayYear + 1 else displayYear
items[index] = React.createElement(DayButton, {
Selected = day == selectedData.Day and month == selectedData.Month and year == selectedData.Year,
Text = getDayNumberText(i),
LayoutOrder = index,
Fade = true,
OnActivated = makeOnActivated(day, month, year),
Disabled = props.Disabled,
})
index += 1
end
return React.createElement("Frame", {
Size = props.Size or Constants.DefaultDatePickerSize,
AnchorPoint = props.AnchorPoint,
Position = props.Position,
ZIndex = props.ZIndex,
LayoutOrder = props.LayoutOrder,
}, {
Main = React.createElement("Frame", {
Size = UDim2.fromScale(1, 1),
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainBackground),
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Border),
}, {
Header = React.createElement("TextLabel", {
Size = UDim2.new(1, 0, 0, TITLE_HEIGHT),
Text = displayTime:FormatUniversalTime("MMMM YYYY", LOCALE),
Font = Constants.DefaultFont,
TextSize = Constants.DefaultTextSize,
TextColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainText, colorModifier),
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Titlebar),
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Border),
}, {
PrevMonth = React.createElement(MonthButton, {
Disabled = props.Disabled,
Position = UDim2.fromOffset(4, 6),
ImageRectOffset = Vector2.new(0, 0),
OnActivated = function()
setChosenPage({
year = displayMonth == 1 and displayYear - 1 or displayYear,
month = displayMonth == 1 and 12 or displayMonth - 1,
})
end,
}),
NextMonth = React.createElement(MonthButton, {
Disabled = props.Disabled,
Position = UDim2.new(1, -4, 0, 6),
AnchorPoint = Vector2.new(1, 0),
ImageRectOffset = Vector2.new(5, 0),
OnActivated = function()
setChosenPage({
year = displayMonth == 12 and displayYear + 1 or displayYear,
month = displayMonth == 12 and 1 or displayMonth + 1,
})
end,
}),
}),
Grid = React.createElement("Frame", {
AnchorPoint = Vector2.new(0, 1),
Position = UDim2.new(0, 3, 1, -OUTER_PAD),
Size = UDim2.new(1, -6, 1, -TITLE_HEIGHT - OUTER_PAD * 2),
BackgroundTransparency = 1,
}, {
Layout = React.createElement("UIGridLayout", {
SortOrder = Enum.SortOrder.LayoutOrder,
CellSize = UDim2.new(1 / 7, 0, 1 / 7, 0),
CellPadding = UDim2.fromOffset(0, 0),
FillDirectionMaxCells = 7,
HorizontalAlignment = Enum.HorizontalAlignment.Center,
VerticalAlignment = Enum.VerticalAlignment.Center,
}),
}, items),
}),
})
end
return DatePicker
| 3,041 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/DropShadowFrame.luau | --[=[
@class DropShadowFrame
A container frame equivalent in appearance to a [Background] with a
drop shadow in the lower right sides and corner.
This matches the appearance of some built-in Roblox Studio elements such as tooltips.
It is useful for providing contrast against a background.
| Dark | Light |
| - | - |
|  |  |
Any children passed will be parented to the container frame. For example:
```lua
local function MyComponent()
return React.createElement(StudioComponents.DropShadowFrame, {}, {
MyLabel = React.createElement(StudioComponents.Label, ...),
MyCheckbox = React.createElement(StudioComponents.Checkbox, ...),
})
end
```
]=]
local React = require("@pkg/@jsdotlua/react")
local CommonProps = require("../CommonProps")
local useTheme = require("../Hooks/useTheme")
local shadowData = {
{
Position = UDim2.fromOffset(4, 4),
Size = UDim2.new(1, 1, 1, 1),
Radius = 5,
Transparency = 0.96,
},
{
Position = UDim2.fromOffset(1, 1),
Size = UDim2.new(1, -2, 1, -2),
Radius = 4,
Transparency = 0.88,
},
{
Position = UDim2.fromOffset(1, 1),
Size = UDim2.new(1, -2, 1, -2),
Radius = 3,
Transparency = 0.80,
},
{
Position = UDim2.fromOffset(1, 1),
Size = UDim2.new(1, -2, 1, -2),
Radius = 2,
Transparency = 0.77,
},
}
--[=[
@within DropShadowFrame
@interface Props
@tag Component Props
@field ... CommonProps
@field children React.ReactNode
]=]
type DropShadowFrameProps = CommonProps.T & {
children: React.ReactNode,
}
local function DropShadowFrame(props: DropShadowFrameProps)
local theme = useTheme()
local shadow
for i = #shadowData, 1, -1 do
local data = shadowData[i]
shadow = React.createElement("Frame", {
Position = data.Position,
Size = data.Size,
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.DropShadow),
BackgroundTransparency = data.Transparency,
BorderSizePixel = 0,
ZIndex = 0,
}, {
Corner = React.createElement("UICorner", {
CornerRadius = UDim.new(0, data.Radius),
}),
}, shadow)
end
return React.createElement("Frame", {
AnchorPoint = props.AnchorPoint,
Position = props.Position,
Size = props.Size or UDim2.fromScale(1, 1),
LayoutOrder = props.LayoutOrder,
ZIndex = props.ZIndex,
BackgroundTransparency = 1,
}, {
Shadow = not props.Disabled and shadow,
Content = React.createElement("Frame", {
Size = UDim2.fromScale(1, 1),
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainBackground),
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Border),
ZIndex = 1,
}, props.children),
})
end
return DropShadowFrame
| 798 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/Dropdown/ClearButton.luau | local React = require("@pkg/@jsdotlua/react")
local useTheme = require("../../Hooks/useTheme")
type ClearButtonProps = {
Size: UDim2,
Position: UDim2,
AnchorPoint: Vector2,
OnActivated: () -> (),
}
local function ClearButton(props: ClearButtonProps)
local theme = useTheme()
local hovered, setHovered = React.useState(false)
return React.createElement("TextButton", {
AnchorPoint = props.AnchorPoint,
Position = props.Position,
Size = props.Size,
BackgroundTransparency = 1,
ZIndex = 2,
Text = "",
[React.Event.InputBegan] = function(_, input: InputObject)
if input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(true)
end
end,
[React.Event.InputEnded] = function(_, input: InputObject)
if input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(false)
end
end,
[React.Event.Activated] = function()
props.OnActivated()
end,
}, {
Icon = React.createElement("ImageLabel", {
AnchorPoint = Vector2.new(0.5, 0.5),
Position = UDim2.fromScale(0.5, 0.5),
Size = UDim2.fromOffset(10, 10),
Image = "rbxassetid://16969027907",
ImageColor3 = theme:GetColor(Enum.StudioStyleGuideColor.SubText),
ImageTransparency = if hovered then 0 else 0.6,
BackgroundTransparency = 1,
}),
})
end
return ClearButton
| 369 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/Dropdown/DropdownItem.luau | local React = require("@pkg/@jsdotlua/react")
local Constants = require("../../Constants")
local useTheme = require("../../Hooks/useTheme")
local BaseIcon = require("../Foundation/BaseIcon")
local DropdownTypes = require("./Types")
type DropdownItemProps = {
Id: string,
Text: string,
Icon: DropdownTypes.DropdownItemIcon?,
LayoutOrder: number,
Height: number,
TextInset: number,
Selected: boolean,
OnSelected: (item: string) -> (),
}
local function DropdownItem(props: DropdownItemProps)
local theme = useTheme()
local hovered, setHovered = React.useState(false)
local modifier = Enum.StudioStyleGuideModifier.Default
if props.Selected then
modifier = Enum.StudioStyleGuideModifier.Selected
elseif hovered then
modifier = Enum.StudioStyleGuideModifier.Hover
end
local iconNode: React.Node?
if props.Icon then
local iconColor = Color3.fromRGB(255, 255, 255)
if props.Icon.UseThemeColor then
iconColor = theme:GetColor(Enum.StudioStyleGuideColor.MainText)
elseif props.Icon.Color then
iconColor = props.Icon.Color
end
local iconProps = (table.clone(props.Icon) :: any) :: BaseIcon.BaseIconProps
iconProps.Color = iconColor
iconProps.AnchorPoint = Vector2.new(0, 0.5)
iconProps.Position = UDim2.fromScale(0, 0.5)
iconProps.Size = UDim2.fromOffset(props.Icon.Size.X, props.Icon.Size.Y)
iconProps.Disabled = nil
iconProps.LayoutOrder = nil
iconNode = React.createElement(BaseIcon, iconProps)
end
return React.createElement("Frame", {
LayoutOrder = props.LayoutOrder,
Size = UDim2.new(1, 0, 0, props.Height),
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Item, modifier),
BorderSizePixel = 0,
}, {
Button = React.createElement("TextButton", {
Position = UDim2.fromOffset(0, 1),
Size = UDim2.new(1, 0, 1, -1),
BackgroundTransparency = 1,
AutoButtonColor = false,
Text = "",
[React.Event.InputBegan] = function(_, input)
if input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(true)
end
end,
[React.Event.InputEnded] = function(_, input)
if input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(false)
end
end,
[React.Event.Activated] = function()
props.OnSelected(props.Id)
end,
}, {
Padding = React.createElement("UIPadding", {
PaddingLeft = UDim.new(0, props.TextInset),
PaddingBottom = UDim.new(0, 2),
}),
Icon = iconNode,
Label = React.createElement("TextLabel", {
BackgroundTransparency = 1,
AnchorPoint = Vector2.new(1, 0),
Position = UDim2.fromScale(1, 0),
Size = UDim2.new(1, if props.Icon then -props.Icon.Size.X - 4 else 0, 1, 0),
Font = Constants.DefaultFont,
TextSize = Constants.DefaultTextSize,
TextColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainText, modifier),
TextXAlignment = Enum.TextXAlignment.Left,
TextTruncate = Enum.TextTruncate.AtEnd,
Text = props.Text,
}),
}),
})
end
return DropdownItem
| 806 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/Dropdown/Types.luau | --[=[
@within Dropdown
@type DropdownItem string | DropdownItemDetail
]=]
export type DropdownItem = string | DropdownItemDetail
--[=[
@within Dropdown
@interface DropdownItemDetail
@field Id string
@field Text string
@field Icon DropdownItemIcon?
]=]
export type DropdownItemDetail = {
Id: string,
Text: string,
Icon: DropdownItemIcon?,
}
--[=[
@within Dropdown
@interface DropdownItemIcon
@field Image string
@field Size Vector2
@field Transparency number?
@field Color Color3?
@field UseThemeColor boolean?
@field ResampleMode Enum.ResamplerMode?
@field RectOffset Vector2?
@field RectSize Vector2?
]=]
export type DropdownItemIcon = {
Image: string,
Size: Vector2,
Transparency: number?,
Color: Color3?,
ResampleMode: Enum.ResamplerMode?,
RectOffset: Vector2?,
RectSize: Vector2?,
UseThemeColor: boolean?,
}
return {}
| 223 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/Foundation/BaseButton.luau | local React = require("@pkg/@jsdotlua/react")
local CommonProps = require("../../CommonProps")
local Constants = require("../../Constants")
local getTextSize = require("../../getTextSize")
local useTheme = require("../../Hooks/useTheme")
local BaseIcon = require("./BaseIcon")
local PADDING_X = 8
local PADDING_Y = 4
local DEFAULT_HEIGHT = Constants.DefaultButtonHeight
export type BaseButtonIconProps = {
Image: string,
Size: Vector2,
Transparency: number?,
Color: Color3?,
ResampleMode: Enum.ResamplerMode?,
RectOffset: Vector2?,
RectSize: Vector2?,
UseThemeColor: boolean?,
Alignment: Enum.HorizontalAlignment?,
}
export type BaseButtonConsumerProps = CommonProps.T & {
AutomaticSize: Enum.AutomaticSize?,
OnActivated: (() -> ())?,
Selected: boolean?,
Text: string?,
TextTransparency: number?,
Icon: BaseButtonIconProps?,
}
export type BaseButtonProps = BaseButtonConsumerProps & {
BackgroundColorStyle: Enum.StudioStyleGuideColor?,
BorderColorStyle: Enum.StudioStyleGuideColor?,
TextColorStyle: Enum.StudioStyleGuideColor?,
}
local function BaseButton(props: BaseButtonProps)
local theme = useTheme()
local textSize = if props.Text then getTextSize(props.Text) else Vector2.zero
local iconSize = if props.Icon then props.Icon.Size else Vector2.zero
local contentWidth = textSize.X + iconSize.X
if props.Text and props.Icon then
contentWidth += PADDING_X
end
local contentHeight = textSize.Y
if props.Icon then
contentHeight = math.max(contentHeight, iconSize.Y)
end
local hovered, setHovered = React.useState(false)
local pressed, setPressed = React.useState(false)
local modifier = Enum.StudioStyleGuideModifier.Default
if props.Disabled then
modifier = Enum.StudioStyleGuideModifier.Disabled
elseif props.Selected then
modifier = Enum.StudioStyleGuideModifier.Selected
elseif pressed and hovered then
modifier = Enum.StudioStyleGuideModifier.Pressed
elseif hovered then
modifier = Enum.StudioStyleGuideModifier.Hover
end
local backColorStyle = props.BackgroundColorStyle or Enum.StudioStyleGuideColor.Button
local borderColorStyle = props.BorderColorStyle or Enum.StudioStyleGuideColor.ButtonBorder
local textColorStyle = props.TextColorStyle or Enum.StudioStyleGuideColor.ButtonText
local backColor = theme:GetColor(backColorStyle, modifier)
local borderColor3 = theme:GetColor(borderColorStyle, modifier)
local textColor = theme:GetColor(textColorStyle, modifier)
local size = props.Size or UDim2.new(1, 0, 0, DEFAULT_HEIGHT)
local autoSize = props.AutomaticSize
if autoSize == Enum.AutomaticSize.X or autoSize == Enum.AutomaticSize.XY then
size = UDim2.new(UDim.new(0, contentWidth + PADDING_X * 2), size.Height)
end
if autoSize == Enum.AutomaticSize.Y or autoSize == Enum.AutomaticSize.XY then
size = UDim2.new(size.Width, UDim.new(0, math.max(DEFAULT_HEIGHT, contentHeight + PADDING_Y * 2)))
end
local iconNode: React.Node?
if props.Icon then
local iconProps = (table.clone(props.Icon) :: any) :: BaseIcon.BaseIconProps
iconProps.Disabled = props.Disabled
iconProps.Color = iconProps.Color or if props.Icon.UseThemeColor then textColor else nil
iconProps.LayoutOrder = if props.Icon.Alignment == Enum.HorizontalAlignment.Right then 3 else 1
iconProps.Size = UDim2.fromOffset(props.Icon.Size.X, props.Icon.Size.Y)
iconNode = React.createElement(BaseIcon, iconProps)
end
return React.createElement("TextButton", {
AutoButtonColor = false,
AnchorPoint = props.AnchorPoint,
Position = props.Position,
Size = size,
LayoutOrder = props.LayoutOrder,
ZIndex = props.ZIndex,
Text = "",
BackgroundColor3 = backColor,
BorderColor3 = borderColor3,
[React.Event.InputBegan] = function(_, input)
if input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(true)
elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
setPressed(true)
end
end,
[React.Event.InputEnded] = function(_, input)
if input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(false)
elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
setPressed(false)
end
end,
[React.Event.Activated] = function()
if not props.Disabled and props.OnActivated then
props.OnActivated()
end
end,
}, {
Layout = React.createElement("UIListLayout", {
Padding = UDim.new(0, PADDING_X),
SortOrder = Enum.SortOrder.LayoutOrder,
FillDirection = Enum.FillDirection.Horizontal,
HorizontalAlignment = Enum.HorizontalAlignment.Center,
VerticalAlignment = Enum.VerticalAlignment.Center,
}),
Icon = iconNode,
Label = props.Text and React.createElement("TextLabel", {
TextColor3 = textColor,
Font = Constants.DefaultFont,
TextSize = Constants.DefaultTextSize,
Text = props.Text,
TextTransparency = props.TextTransparency or 0,
Size = UDim2.new(0, textSize.X, 1, 0),
BackgroundTransparency = 1,
LayoutOrder = 2,
}),
})
end
return BaseButton
| 1,208 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/Foundation/BaseIcon.luau | local React = require("@pkg/@jsdotlua/react")
local CommonProps = require("../../CommonProps")
export type BaseIconConsumerProps = CommonProps.T & {
Image: string,
Transparency: number?,
Color: Color3?,
ResampleMode: Enum.ResamplerMode?,
RectOffset: Vector2?,
RectSize: Vector2?,
}
export type BaseIconProps = BaseIconConsumerProps
local function BaseIcon(props: BaseIconProps)
return React.createElement("ImageLabel", {
Size = props.Size,
Position = props.Position,
AnchorPoint = props.AnchorPoint,
LayoutOrder = props.LayoutOrder,
ZIndex = props.ZIndex,
BackgroundTransparency = 1,
Image = props.Image,
ImageColor3 = props.Color,
ImageTransparency = 1 - (1 - (props.Transparency or 0)) * (1 - if props.Disabled then 0.2 else 0),
ImageRectOffset = props.RectOffset,
ImageRectSize = props.RectSize,
ResampleMode = props.ResampleMode,
})
end
return BaseIcon
| 234 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/Foundation/BaseLabelledToggle.luau | local React = require("@pkg/@jsdotlua/react")
local CommonProps = require("../../CommonProps")
local Constants = require("../../Constants")
local getTextSize = require("../../getTextSize")
local useTheme = require("../../Hooks/useTheme")
local DEFAULT_HEIGHT = Constants.DefaultToggleHeight
local BOX_SIZE = 16
local INNER_PADDING = 6
export type BaseLabelledToggleConsumerProps = CommonProps.T & {
ContentAlignment: Enum.HorizontalAlignment?,
ButtonAlignment: Enum.HorizontalAlignment?,
OnChanged: (() -> ())?,
Label: string?,
}
export type BaseLabelledToggleProps = BaseLabelledToggleConsumerProps & {
RenderButton: React.FC<{ Hovered: boolean }>?,
}
local function BaseLabelledToggle(props: BaseLabelledToggleProps)
local theme = useTheme()
local hovered, setHovered = React.useState(false)
local mainModifier = Enum.StudioStyleGuideModifier.Default
if props.Disabled then
mainModifier = Enum.StudioStyleGuideModifier.Disabled
elseif hovered then
mainModifier = Enum.StudioStyleGuideModifier.Hover
end
local contentAlignment = props.ContentAlignment or Enum.HorizontalAlignment.Left
local buttonAlignment = props.ButtonAlignment or Enum.HorizontalAlignment.Left
local textWidth = if props.Label then getTextSize(props.Label).X else 0
local textAlignment = Enum.TextXAlignment.Left
local buttonOrder = 1
local labelOrder = 2
if buttonAlignment == Enum.HorizontalAlignment.Right then
buttonOrder = 2
labelOrder = 1
textAlignment = Enum.TextXAlignment.Right
end
local content = nil
if props.RenderButton then
content = React.createElement(props.RenderButton, {
Hovered = hovered,
})
end
return React.createElement("TextButton", {
Size = props.Size or UDim2.new(1, 0, 0, DEFAULT_HEIGHT),
Position = props.Position,
AnchorPoint = props.AnchorPoint,
LayoutOrder = props.LayoutOrder,
ZIndex = props.ZIndex,
BackgroundTransparency = 1,
Text = "",
[React.Event.InputBegan] = function(_, input)
if input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(true)
end
end,
[React.Event.InputEnded] = function(_, input)
if input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(false)
end
end,
[React.Event.Activated] = function()
if not props.Disabled and props.OnChanged then
props.OnChanged()
end
end,
}, {
Layout = React.createElement("UIListLayout", {
HorizontalAlignment = contentAlignment,
VerticalAlignment = Enum.VerticalAlignment.Center,
FillDirection = Enum.FillDirection.Horizontal,
SortOrder = Enum.SortOrder.LayoutOrder,
Padding = UDim.new(0, INNER_PADDING),
}),
Button = React.createElement("Frame", {
BackgroundTransparency = 1,
Size = UDim2.fromOffset(BOX_SIZE, BOX_SIZE),
LayoutOrder = buttonOrder,
}, {
Content = content,
}),
Label = props.Label and React.createElement("TextLabel", {
BackgroundTransparency = 1,
Size = UDim2.new(1, -BOX_SIZE - INNER_PADDING, 1, 0),
TextXAlignment = textAlignment,
TextTruncate = Enum.TextTruncate.AtEnd,
Text = props.Label,
Font = Constants.DefaultFont,
TextSize = Constants.DefaultTextSize,
TextColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainText, mainModifier),
LayoutOrder = labelOrder,
}, {
Constraint = React.createElement("UISizeConstraint", {
MaxSize = Vector2.new(textWidth, math.huge),
}),
Pad = React.createElement("UIPadding", {
PaddingBottom = UDim.new(0, 1),
}),
}),
})
end
return BaseLabelledToggle
| 852 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/Foundation/BaseTextInput.luau | local React = require("@pkg/@jsdotlua/react")
local CommonProps = require("../../CommonProps")
local Constants = require("../../Constants")
local getTextSize = require("../../getTextSize")
local useTheme = require("../../Hooks/useTheme")
local PLACEHOLDER_TEXT_COLOR = Color3.fromRGB(102, 102, 102)
local EDGE_PADDING_PX = 5
local DEFAULT_HEIGHT = Constants.DefaultInputHeight
local TEXT_SIZE = Constants.DefaultTextSize
local FONT = Constants.DefaultFont
local function joinDictionaries(dict0, dict1)
local joined = table.clone(dict0)
for k, v in dict1 do
joined[k] = v
end
return joined
end
export type BaseTextInputConsumerProps = CommonProps.T & {
PlaceholderText: string?,
ClearTextOnFocus: boolean?,
OnFocused: (() -> ())?,
OnFocusLost: ((text: string, enterPressed: boolean, input: InputObject) -> ())?,
children: React.ReactNode,
}
export type BaseTextInputProps = BaseTextInputConsumerProps & {
Text: string,
OnChanged: (newText: string) -> (),
RightPaddingExtra: number?,
}
local function BaseTextInput(props: BaseTextInputProps)
local theme = useTheme()
local hovered, setHovered = React.useState(false)
local focused, setFocused = React.useState(false)
local disabled = props.Disabled == true
local predictNextCursor = React.useRef(-1) :: { current: number }
local lastCursor = React.useRef(-1) :: { current: number }
local mainModifier = Enum.StudioStyleGuideModifier.Default
local borderModifier = Enum.StudioStyleGuideModifier.Default
if disabled then
mainModifier = Enum.StudioStyleGuideModifier.Disabled
borderModifier = Enum.StudioStyleGuideModifier.Disabled
elseif focused then
borderModifier = Enum.StudioStyleGuideModifier.Selected
elseif hovered then
borderModifier = Enum.StudioStyleGuideModifier.Hover
end
local cursor, setCursor = React.useState(-1)
local containerSize, setContainerSize = React.useState(Vector2.zero)
local innerOffset = React.useRef(0) :: { current: number }
local fullTextWidth = getTextSize(props.Text).X
local textFieldSize = UDim2.fromScale(1, 1)
if not disabled then
local min = EDGE_PADDING_PX
local max = containerSize.X - EDGE_PADDING_PX
local textUpToCursor = string.sub(props.Text, 1, cursor - 1)
local offset = getTextSize(textUpToCursor).X + EDGE_PADDING_PX
local innerArea = max - min
local fullOffset = offset + innerOffset.current
if fullTextWidth <= innerArea or not focused then
innerOffset.current = 0
else
if fullOffset < min then
innerOffset.current += min - fullOffset
elseif fullOffset > max then
innerOffset.current -= fullOffset - max
end
innerOffset.current = math.max(innerOffset.current, innerArea - fullTextWidth)
end
else
innerOffset.current = 0
end
if focused then
local textFieldWidth = math.max(containerSize.X, fullTextWidth + EDGE_PADDING_PX * 2)
textFieldSize = UDim2.new(0, textFieldWidth, 1, 0)
end
local textFieldProps = {
Size = textFieldSize,
Position = UDim2.fromOffset(innerOffset.current, 0),
BackgroundTransparency = 1,
Font = FONT,
Text = props.Text,
TextSize = TEXT_SIZE,
TextColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainText, mainModifier),
TextXAlignment = Enum.TextXAlignment.Left,
TextTruncate = if focused then Enum.TextTruncate.None else Enum.TextTruncate.AtEnd,
[React.Event.InputBegan] = function(_, input: InputObject)
if input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(true)
end
end,
[React.Event.InputEnded] = function(_, input: InputObject)
if input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(false)
end
end,
children = {
Padding = React.createElement("UIPadding", {
PaddingLeft = UDim.new(0, EDGE_PADDING_PX),
PaddingRight = UDim.new(0, EDGE_PADDING_PX),
}),
},
}
local textField
if disabled then
textField = React.createElement("TextLabel", textFieldProps)
else
textField = React.createElement(
"TextBox",
joinDictionaries(textFieldProps, {
PlaceholderText = props.PlaceholderText,
PlaceholderColor3 = PLACEHOLDER_TEXT_COLOR,
ClearTextOnFocus = props.ClearTextOnFocus,
MultiLine = false,
[React.Change.CursorPosition] = function(rbx: TextBox)
-- cursor position changed fires before text changed, so we defer it until after;
-- this enables us to use the pre-text-changed cursor position to revert to
task.defer(function()
lastCursor.current = rbx.CursorPosition
end)
setCursor(rbx.CursorPosition)
end,
[React.Change.Text] = function(rbx: TextBox)
local newText = rbx.Text
if newText ~= props.Text then
predictNextCursor.current = rbx.CursorPosition
rbx.Text = props.Text
rbx.CursorPosition = math.max(1, lastCursor.current)
props.OnChanged((string.gsub(newText, "[\n\r]", "")))
elseif focused then
rbx.CursorPosition = math.max(1, predictNextCursor.current)
end
end,
[React.Event.Focused] = function()
setFocused(true)
if props.OnFocused then
props.OnFocused()
end
end,
[React.Event.FocusLost] = function(rbx: TextBox, enterPressed: boolean, input: InputObject)
setFocused(false)
if props.OnFocusLost then
props.OnFocusLost(rbx.Text, enterPressed, input)
end
end :: () -> (),
})
)
end
local rightPaddingExtra = props.RightPaddingExtra or 0
return React.createElement("Frame", {
AnchorPoint = props.AnchorPoint,
Position = props.Position,
Size = props.Size or UDim2.new(1, 0, 0, DEFAULT_HEIGHT),
LayoutOrder = props.LayoutOrder,
ZIndex = props.ZIndex,
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.InputFieldBackground, mainModifier),
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.InputFieldBorder, borderModifier),
BorderMode = Enum.BorderMode.Inset,
[React.Change.AbsoluteSize] = function(rbx: Frame)
setContainerSize(rbx.AbsoluteSize - Vector2.new(rightPaddingExtra, 0))
end,
}, {
Clipping = React.createElement("Frame", {
Size = UDim2.new(1, -rightPaddingExtra, 1, 0),
BackgroundTransparency = 1,
ClipsDescendants = true,
ZIndex = 0,
}, {
TextField = textField,
}),
}, props.children)
end
return BaseTextInput
| 1,581 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/Label.luau | --[=[
@class Label
A basic text label with default styling to match built-in labels as closely as possible.
| Dark | Light |
| - | - |
|  |  |
By default, text color matches the current theme's MainText color, which is the color
used in the Explorer and Properties widgets as well as most other places. It can be overriden
in two ways:
1. Passing a [StudioStyleGuideColor](https://create.roblox.com/docs/reference/engine/enums/StudioStyleGuideColor)
to the `TextColorStyle` prop. This is the preferred way to recolor text
because it will use the correct version of the color for the user's current selected theme.
2. Passing a [Color3] value to the `TextColor3` prop. This is useful when a color is not represented
by any StudioStyleGuideColor or should remain constant regardless of theme.
Example of creating an error message label:
```lua
local function MyComponent()
return React.createElement(StudioComponents.Label, {
Text = "Please enter at least 5 characters!",
TextColorStyle = Enum.StudioStyleGuideColor.ErrorText,
})
end
```
Plugins like [Theme Color Shower](https://create.roblox.com/store/asset/3115567199/Theme-Color-Shower)
are useful for finding a StudioStyleGuideColor to use.
This component will parent any children passed to it to the underlying TextLabel instance.
This is useful for things like adding extra padding around the text using a nested UIPadding,
or adding a UIStroke / UIGradient.
Labels use [Constants.DefaultFont] for Font and [Constants.DefaultTextSize] for TextSize. This
cannot currently be overriden via props.
]=]
local React = require("@pkg/@jsdotlua/react")
local CommonProps = require("../CommonProps")
local Constants = require("../Constants")
local useTheme = require("../Hooks/useTheme")
--[=[
@within Label
@interface Props
@tag Component Props
@field ... CommonProps
@field Text string
@field TextWrapped boolean?
@field TextXAlignment Enum.TextXAlignment?
@field TextYAlignment Enum.TextYAlignment?
@field TextTruncate Enum.TextTruncate?
@field TextTransparency number?
@field TextColor3 Color3?
@field RichText boolean?
@field MaxVisibleGraphemes number?
@field TextColorStyle Enum.StudioStyleGuideColor?
@field children React.ReactNode
]=]
type LabelProps = CommonProps.T & {
Text: string,
TextWrapped: boolean?,
TextXAlignment: Enum.TextXAlignment?,
TextYAlignment: Enum.TextYAlignment?,
TextTruncate: Enum.TextTruncate?,
TextTransparency: number?,
TextColor3: Color3?,
RichText: boolean?,
MaxVisibleGraphemes: number?,
TextColorStyle: Enum.StudioStyleGuideColor?,
children: React.ReactNode,
}
local function Label(props: LabelProps)
local theme = useTheme()
local modifier = Enum.StudioStyleGuideModifier.Default
if props.Disabled then
modifier = Enum.StudioStyleGuideModifier.Disabled
end
local style = props.TextColorStyle or Enum.StudioStyleGuideColor.MainText
local color = theme:GetColor(style, modifier)
if props.TextColor3 ~= nil then
color = props.TextColor3
end
return React.createElement("TextLabel", {
AnchorPoint = props.AnchorPoint,
Position = props.Position,
Size = props.Size or UDim2.fromScale(1, 1),
LayoutOrder = props.LayoutOrder,
ZIndex = props.ZIndex,
Text = props.Text,
BackgroundTransparency = 1,
Font = Constants.DefaultFont,
TextSize = Constants.DefaultTextSize,
TextColor3 = color,
TextTransparency = props.TextTransparency,
TextXAlignment = props.TextXAlignment,
TextYAlignment = props.TextYAlignment,
TextTruncate = props.TextTruncate,
TextWrapped = props.TextWrapped,
RichText = props.RichText,
MaxVisibleGraphemes = props.MaxVisibleGraphemes,
}, props.children)
end
return Label
| 921 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/LoadingDots.luau | --[=[
@class LoadingDots
A basic animated loading indicator. This matches similar indicators used in various places
around Studio. This should be used for short processes where the user does not need to see
information about how complete the loading is. For longer or more detailed loading processes,
consider using a [ProgressBar].
| Dark | Light |
| - | - |
|  |  |
Example of usage:
```lua
local function MyComponent()
return React.createElement(StudioComponents.LoadingDots, {})
end
```
]=]
local RunService = game:GetService("RunService")
local React = require("@pkg/@jsdotlua/react")
local CommonProps = require("../CommonProps")
local useTheme = require("../Hooks/useTheme")
--[=[
@within LoadingDots
@interface Props
@tag Component Props
@field ... CommonProps
]=]
type LoadingDotsProps = CommonProps.T
local function Dot(props: {
LayoutOrder: number,
Transparency: React.Binding<number>,
Disabled: boolean?,
})
local theme = useTheme()
return React.createElement("Frame", {
LayoutOrder = props.LayoutOrder,
Size = UDim2.fromOffset(10, 10),
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.ButtonText),
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.ButtonBorder),
BackgroundTransparency = if props.Disabled then 0.75 else props.Transparency,
})
end
local function LoadingDots(props: LoadingDotsProps)
local clockBinding, setClockBinding = React.useBinding(os.clock())
React.useEffect(function()
local connection = RunService.Heartbeat:Connect(function()
setClockBinding(os.clock())
end)
return function()
return connection:Disconnect()
end
end, {})
local alphaBinding = clockBinding:map(function(clock: number)
return clock % 1
end)
return React.createElement("Frame", {
AnchorPoint = props.AnchorPoint,
Position = props.Position,
Size = props.Size or UDim2.fromScale(1, 1),
LayoutOrder = props.LayoutOrder,
ZIndex = props.ZIndex,
BackgroundTransparency = 1,
}, {
Layout = React.createElement("UIListLayout", {
SortOrder = Enum.SortOrder.LayoutOrder,
FillDirection = Enum.FillDirection.Horizontal,
HorizontalAlignment = Enum.HorizontalAlignment.Center,
VerticalAlignment = Enum.VerticalAlignment.Center,
Padding = UDim.new(0, 8),
}),
Dot0 = React.createElement(Dot, {
LayoutOrder = 0,
Transparency = alphaBinding,
Disabled = props.Disabled,
}),
Dot1 = React.createElement(Dot, {
LayoutOrder = 1,
Transparency = alphaBinding:map(function(alpha: number)
return (alpha - 0.2) % 1
end),
Disabled = props.Disabled,
}),
Dot2 = React.createElement(Dot, {
LayoutOrder = 2,
Transparency = alphaBinding:map(function(alpha: number)
return (alpha - 0.4) % 1
end),
Disabled = props.Disabled,
}),
})
end
return LoadingDots
| 740 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/MainButton.luau | --[=[
@class MainButton
A variant of a [Button] used to indicate a primary action, for example an 'OK/Accept' button
in a modal.
| Dark | Light |
| - | - |
|  |  |
See the docs for [Button] for information about customization and usage.
]=]
local React = require("@pkg/@jsdotlua/react")
local BaseButton = require("./Foundation/BaseButton")
--[=[
@within MainButton
@interface IconProps
@field Image string
@field Size Vector2
@field Transparency number?
@field Color Color3?
@field UseThemeColor boolean?
@field Alignment HorizontalAlignment?
@field ResampleMode Enum.ResamplerMode?
@field RectOffset Vector2?
@field RectSize Vector2?
]=]
--[=[
@within MainButton
@interface Props
@tag Component Props
@field ... CommonProps
@field AutomaticSize AutomaticSize?
@field OnActivated (() -> ())?
@field Text string?
@field Icon IconProps?
]=]
local function MainButton(props: BaseButton.BaseButtonConsumerProps)
local merged = table.clone(props) :: BaseButton.BaseButtonProps
merged.BackgroundColorStyle = Enum.StudioStyleGuideColor.DialogMainButton
merged.BorderColorStyle = Enum.StudioStyleGuideColor.DialogButtonBorder
merged.TextColorStyle = Enum.StudioStyleGuideColor.DialogMainButtonText
return React.createElement(BaseButton, merged)
end
return MainButton
| 344 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/NumberSequencePicker/AxisLabel.luau | local React = require("@pkg/@jsdotlua/react")
local Constants = require("../../Constants")
local useTheme = require("../../Hooks/useTheme")
local function AxisLabel(props: {
AnchorPoint: Vector2?,
Position: UDim2?,
TextXAlignment: Enum.TextXAlignment?,
Value: number,
Disabled: boolean?,
})
local theme = useTheme()
return React.createElement("TextLabel", {
AnchorPoint = props.AnchorPoint,
Position = props.Position,
Size = UDim2.fromOffset(14, 14),
BackgroundTransparency = 1,
Text = tostring(props.Value),
Font = Constants.DefaultFont,
TextSize = Constants.DefaultTextSize,
TextColor3 = theme:GetColor(Enum.StudioStyleGuideColor.DimmedText),
TextTransparency = if props.Disabled then 0.5 else 0,
TextXAlignment = props.TextXAlignment,
ZIndex = -1,
})
end
return AxisLabel
| 206 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/NumberSequencePicker/Constants.luau | return {
EnvelopeTransparency = 0.65,
EnvelopeColorStyle = Enum.StudioStyleGuideColor.DialogMainButton,
EnvelopeHandleHeight = 16,
}
| 36 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/NumberSequencePicker/DashedLine.luau | local React = require("@pkg/@jsdotlua/react")
local useTheme = require("../../Hooks/useTheme")
local TEX_HORIZONTAL = "rbxassetid://15431624045"
local TEX_VERTICAL = "rbxassetid://15431692101"
local function DashedLine(props: {
AnchorPoint: Vector2?,
Position: UDim2?,
Size: UDim2,
Direction: Enum.FillDirection,
Transparency: number?,
Disabled: boolean?,
})
local theme = useTheme()
local horizontal = props.Direction == Enum.FillDirection.Horizontal
local transparency = props.Transparency or 0
if props.Disabled then
transparency = 1 - 0.5 * (1 - transparency)
end
return React.createElement("ImageLabel", {
Image = if horizontal then TEX_HORIZONTAL else TEX_VERTICAL,
AnchorPoint = props.AnchorPoint,
Position = props.Position,
Size = props.Size,
BorderSizePixel = 0,
ScaleType = Enum.ScaleType.Tile,
TileSize = if horizontal then UDim2.fromOffset(4, 1) else UDim2.fromOffset(1, 4),
BackgroundTransparency = 1,
ImageColor3 = theme:GetColor(Enum.StudioStyleGuideColor.DimmedText),
ImageTransparency = transparency,
ZIndex = 0,
})
end
return DashedLine
| 293 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/NumberSequencePicker/FreeLine.luau | local React = require("@pkg/@jsdotlua/react")
local TEX = "rbxassetid://15434098501"
local function FreeLine(props: {
Pos0: Vector2,
Pos1: Vector2,
Color: Color3,
Transparency: number?,
ZIndex: number?,
Disabled: boolean?,
})
local mid = (props.Pos0 + props.Pos1) / 2
local vector = props.Pos1 - props.Pos0
local rotation = math.atan2(-vector.X, vector.Y) + math.pi / 2
local length = vector.Magnitude
local transparency = props.Transparency or 0
if props.Disabled then
transparency = 1 - 0.5 * (1 - transparency)
end
return React.createElement("ImageLabel", {
AnchorPoint = Vector2.one / 2,
Position = UDim2.fromOffset(math.round(mid.X), math.round(mid.Y)),
Size = UDim2.fromOffset(vector.Magnitude, 3),
Rotation = math.deg(rotation),
BackgroundTransparency = 1,
ImageColor3 = props.Color,
ImageTransparency = transparency,
Image = TEX,
ScaleType = if length < 128 then Enum.ScaleType.Crop else Enum.ScaleType.Stretch,
ZIndex = props.ZIndex,
})
end
return FreeLine
| 286 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/NumberSequencePicker/LabelledNumericInput.luau | local React = require("@pkg/@jsdotlua/react")
local Label = require("../Label")
local NumericInput = require("../NumericInput")
local TextInput = require("../TextInput")
local getTextSize = require("../../getTextSize")
local PADDING = 5
local INPUT_WIDTH = 40
local function format(n: number)
return string.format(`%.3f`, n)
end
local noop = function() end
local function LabelledNumericInput(props: {
Label: string,
Value: number?,
Disabled: boolean?,
OnChanged: (value: number) -> (),
OnSubmitted: (value: number) -> (),
LayoutOrder: number,
Min: number?,
Max: number?,
})
local textWidth = getTextSize(props.Label).X
local input: React.ReactNode
if props.Value and not props.Disabled then
local value = props.Value :: number
input = React.createElement(NumericInput, {
Value = value,
Min = props.Min,
Max = props.Max,
Step = 0,
FormatValue = format,
OnValidChanged = props.OnChanged,
OnSubmitted = props.OnSubmitted,
})
else
input = React.createElement(TextInput, {
Text = if props.Value then format(props.Value) else "",
OnChanged = noop,
Disabled = true,
})
end
return React.createElement("Frame", {
Size = UDim2.new(0, textWidth + INPUT_WIDTH + PADDING, 1, 0),
BackgroundTransparency = 1,
LayoutOrder = props.LayoutOrder,
}, {
Label = React.createElement(Label, {
Size = UDim2.new(0, textWidth, 1, 0),
Text = props.Label,
Disabled = props.Value == nil,
}),
Input = React.createElement("Frame", {
AnchorPoint = Vector2.new(1, 0),
Position = UDim2.fromScale(1, 0),
Size = UDim2.new(0, INPUT_WIDTH, 1, 0),
BackgroundTransparency = 1,
}, input),
})
end
return LabelledNumericInput
| 461 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/NumberSequencePicker/SequenceNode.luau | local React = require("@pkg/@jsdotlua/react")
local useMouseDrag = require("../../Hooks/useMouseDrag")
local useMouseIcon = require("../../Hooks/useMouseIcon")
local useTheme = require("../../Hooks/useTheme")
local PickerConstants = require("./Constants")
local CATCHER_SIZE = 15
local ENVELOPE_GRAB_HEIGHT = PickerConstants.EnvelopeHandleHeight
local ENVELOPE_TRANSPARENCY = PickerConstants.EnvelopeTransparency
local ENVELOPE_COLOR_STYLE = PickerConstants.EnvelopeColorStyle
local function EnvelopeHandle(props: {
Top: boolean,
Size: UDim2,
OnDragBegan: () -> (),
OnDragEnded: () -> (),
OnEnvelopeDragged: (y: number, top: boolean) -> (),
Disabled: boolean?,
})
local theme = useTheme()
local dragStart = React.useRef(0 :: number?)
local dragOffset = React.useRef(0)
local function onDragBegin(rbx: GuiObject, input: InputObject)
local pos = input.Position.Y
local reference
if props.Top then
reference = rbx.AbsolutePosition.Y
else
reference = rbx.AbsolutePosition.Y + rbx.AbsoluteSize.Y
end
dragStart.current = pos
dragOffset.current = reference - pos
props.OnDragBegan()
end
local drag = useMouseDrag(function(_, input: InputObject)
local position = input.Position.Y
if not dragStart.current or math.abs(position - dragStart.current) > 0 then
local outPosition
if props.Top then
outPosition = position + dragOffset.current :: number + ENVELOPE_GRAB_HEIGHT
else
outPosition = position + dragOffset.current :: number - ENVELOPE_GRAB_HEIGHT
end
props.OnEnvelopeDragged(outPosition, props.Top)
dragStart.current = nil
end
end, { props.OnEnvelopeDragged }, onDragBegin, props.OnDragEnded)
local hovered, setHovered = React.useState(false)
local mouseIcon = useMouseIcon()
React.useEffect(function()
if (hovered or drag.isActive()) and not props.Disabled then
mouseIcon.setIcon("rbxasset://SystemCursors/SplitNS")
else
mouseIcon.clearIcon()
end
end, { hovered, drag.isActive(), props.Disabled } :: { unknown })
React.useEffect(function()
return function()
mouseIcon.clearIcon()
end
end, {})
return React.createElement("TextButton", {
Text = "",
AutoButtonColor = false,
Size = props.Size,
AnchorPoint = Vector2.new(0, if props.Top then 0 else 1),
Position = UDim2.fromScale(0, if props.Top then 0 else 1),
BackgroundTransparency = 1,
BorderSizePixel = 0,
[React.Event.InputBegan] = function(rbx, input)
if input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(true)
end
drag.onInputBegan(rbx, input)
end,
[React.Event.InputChanged] = drag.onInputChanged,
[React.Event.InputEnded] = function(rbx, input)
if input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(false)
end
drag.onInputEnded(rbx, input)
end,
ZIndex = 2,
}, {
Visual = React.createElement("Frame", {
AnchorPoint = Vector2.new(0.5, if props.Top then 0 else 1),
Position = UDim2.fromScale(0.5, if props.Top then 0 else 1),
Size = UDim2.fromOffset(if drag.isActive() or hovered then 3 else 1, ENVELOPE_GRAB_HEIGHT + 2),
BorderSizePixel = 0,
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainText),
}, {
Bar = React.createElement("Frame", {
AnchorPoint = Vector2.new(0.5, if props.Top then 1 else 0),
Position = UDim2.fromScale(0.5, if props.Top then 1 else 0),
Size = UDim2.fromOffset(9, if drag.isActive() or hovered then 3 else 1),
BorderSizePixel = 0,
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainText),
}),
}),
})
end
local function SequenceNode(props: {
ContentSize: Vector2,
Keypoint: NumberSequenceKeypoint,
OnNodeDragged: (position: Vector2) -> (),
OnEnvelopeDragged: (y: number, top: boolean) -> (),
Active: boolean,
OnHovered: () -> (),
OnDragBegan: () -> (),
OnDragEnded: () -> (),
Disabled: boolean?,
})
local theme = useTheme()
local mouseIcon = useMouseIcon()
local nodeDragStart = React.useRef(Vector2.zero :: Vector2?)
local nodeDragOffset = React.useRef(Vector2.zero)
local function onNodeDragBegin(rbx: GuiObject, input: InputObject)
local pos = Vector2.new(input.Position.X, input.Position.Y)
local corner = rbx.AbsolutePosition
local center = corner + rbx.AbsoluteSize / 2
nodeDragStart.current = pos
nodeDragOffset.current = center - pos
props.OnDragBegan()
end
local nodeDrag = useMouseDrag(function(_, input: InputObject)
local position = Vector2.new(input.Position.X, input.Position.Y)
if not nodeDragStart.current or (position - nodeDragStart.current).Magnitude > 0 then
props.OnNodeDragged(position + nodeDragOffset.current :: Vector2)
nodeDragStart.current = nil
end
end, { props.OnNodeDragged }, onNodeDragBegin, props.OnDragEnded)
local px = math.round(props.Keypoint.Time * props.ContentSize.X)
local py = math.round((1 - props.Keypoint.Value) * props.ContentSize.Y)
local envelopeHeight = math.round(props.Keypoint.Envelope * props.ContentSize.Y) * 2 + 1
local fullHeight = envelopeHeight + (ENVELOPE_GRAB_HEIGHT + 1) * 2
local handleClearance = (fullHeight - CATCHER_SIZE) / 2 - 1
local innerSize = if props.Active then 11 else 7
local nodeHovered, setNodeHovered = React.useState(false)
React.useEffect(function()
if props.Active and nodeDrag.isActive() then
mouseIcon.setIcon("rbxasset://SystemCursors/ClosedHand")
elseif props.Active and nodeHovered then
mouseIcon.setIcon("rbxasset://SystemCursors/OpenHand")
else
mouseIcon.clearIcon()
end
end, { props.Active, nodeHovered, nodeDrag.isActive() })
React.useEffect(function()
if props.Disabled then
mouseIcon.clearIcon()
end
if nodeDrag.isActive() then
nodeDrag.cancel()
end
end, { props.Disabled })
local envelopeTransparency = ENVELOPE_TRANSPARENCY
local mainModifier = Enum.StudioStyleGuideModifier.Default
if props.Disabled then
envelopeTransparency = 1 - 0.5 * (1 - envelopeTransparency)
mainModifier = Enum.StudioStyleGuideModifier.Disabled
end
return React.createElement("Frame", {
Position = UDim2.fromOffset(px - (CATCHER_SIZE - 1) / 2, py - (fullHeight - 1) / 2),
Size = UDim2.fromOffset(CATCHER_SIZE, fullHeight),
BackgroundTransparency = 1,
ZIndex = 2,
}, {
Line = React.createElement("Frame", {
AnchorPoint = Vector2.one / 2,
Position = UDim2.fromScale(0.5, 0.5),
Size = UDim2.fromOffset(1, envelopeHeight),
BorderSizePixel = 0,
BackgroundColor3 = theme:GetColor(ENVELOPE_COLOR_STYLE),
BackgroundTransparency = envelopeTransparency,
ZIndex = 0,
}),
Node = React.createElement("TextButton", {
Text = "",
AutoButtonColor = false,
AnchorPoint = Vector2.one / 2,
Position = UDim2.fromScale(0.5, 0.5),
Size = UDim2.new(1, 0, 0, CATCHER_SIZE),
BackgroundTransparency = 1,
[React.Event.InputBegan] = function(rbx, input)
if props.Disabled then
return
elseif input.UserInputType == Enum.UserInputType.MouseMovement then
setNodeHovered(true)
props.OnHovered()
end
nodeDrag.onInputBegan(rbx, input)
end,
[React.Event.InputChanged] = function(rbx, input)
if props.Disabled then
return
end
nodeDrag.onInputChanged(rbx, input)
end,
[React.Event.InputEnded] = function(rbx, input)
if props.Disabled then
return
elseif input.UserInputType == Enum.UserInputType.MouseMovement then
setNodeHovered(false)
end
nodeDrag.onInputEnded(rbx, input)
end,
ZIndex = 1,
}, {
Inner = React.createElement("Frame", {
AnchorPoint = Vector2.one / 2,
Position = UDim2.fromScale(0.5, 0.5),
Size = UDim2.fromOffset(innerSize, innerSize),
BackgroundColor3 = if props.Active
then theme:GetColor(Enum.StudioStyleGuideColor.MainBackground, mainModifier)
else theme:GetColor(Enum.StudioStyleGuideColor.InputFieldBackground, mainModifier),
ZIndex = 2,
}, {
Stroke = React.createElement("UIStroke", {
Color = if props.Active
then theme:GetColor(Enum.StudioStyleGuideColor.MainText, mainModifier)
else theme:GetColor(Enum.StudioStyleGuideColor.DimmedText, mainModifier),
Thickness = if nodeDrag.isActive() then 2 else 1,
}),
}),
}),
Top = props.Active and React.createElement(EnvelopeHandle, {
Top = true,
Size = UDim2.new(1, 0, 0, math.min(ENVELOPE_GRAB_HEIGHT, handleClearance)),
OnDragBegan = props.OnDragBegan,
OnDragEnded = props.OnDragEnded,
OnEnvelopeDragged = props.OnEnvelopeDragged,
}),
Bottom = props.Active and React.createElement(EnvelopeHandle, {
Top = false,
Size = UDim2.new(1, 0, 0, math.min(ENVELOPE_GRAB_HEIGHT, handleClearance)),
OnDragBegan = props.OnDragBegan,
OnDragEnded = props.OnDragEnded,
OnEnvelopeDragged = props.OnEnvelopeDragged,
}),
})
end
return SequenceNode
| 2,425 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/NumberSequencePicker/init.luau | --[=[
@class NumberSequencePicker
An interface for modifying [NumberSequence](https://create.roblox.com/docs/reference/engine/datatypes/NumberSequence) values.
This closely resembles the built-in NumberSequence picker for editing properties, with minor adjustments
for improved readability.
| Dark | Light |
| - | - |
|  |  |
As this is a controlled component, you should pass a NumberSequence to the `Value` prop
representing the current value, and a callback to the `OnChanged` prop which gets run when the
user attempts to change the sequence using the interface. For example:
```lua
local function MyComponent()
local sequence, setSequence = React.useState(NumberSequence.new(...))
return React.createElement(StudioComponents.NumberSequencePicker, {
Value = sequence,
OnChanged = setSequence,
})
end
```
The default size of this component is exposed in [Constants.DefaultNumberSequencePickerSize].
To keep all inputs accessible, it is recommended not to use a smaller size than this.
]=]
local React = require("@pkg/@jsdotlua/react")
local CommonProps = require("../../CommonProps")
local Constants = require("../../Constants")
local PickerConstants = require("./Constants")
local Button = require("../Button")
local useTheme = require("../../Hooks/useTheme")
local AxisLabel = require("./AxisLabel")
local DashedLine = require("./DashedLine")
local FreeLine = require("./FreeLine")
local LabelledNumericInput = require("./LabelledNumericInput")
local SequenceNode = require("./SequenceNode")
local function clampVector2(v: Vector2, vmin: Vector2, vmax: Vector2)
return Vector2.new(math.clamp(v.X, vmin.X, vmax.X), math.clamp(v.Y, vmin.Y, vmax.Y))
end
--[=[
@within NumberSequencePicker
@interface Props
@tag Component Props
@field ... CommonProps
@field Value NumberSequence
@field OnChanged ((newValue: NumberSequence) -> ())?
]=]
type NumberSequencePickerProps = CommonProps.T & {
Value: NumberSequence,
OnChanged: ((newValue: NumberSequence) -> ())?,
}
local GRID_ROWS = 4
local GRID_COLS = 10
local ENVELOPE_TRANSPARENCY = PickerConstants.EnvelopeTransparency
local ENVELOPE_COLOR_STYLE = PickerConstants.EnvelopeColorStyle
local function identity(v)
return v
end
local function NumberSequencePicker(props: NumberSequencePickerProps)
local theme = useTheme()
local sequence = props.Value
local onChanged: (NumberSequence) -> () = props.OnChanged or function() end
local hoveringIndex: number?, setHoveringIndex = React.useState(nil :: number?)
local draggingIndex: number?, setDraggingIndex = React.useState(nil :: number?)
React.useEffect(function()
if props.Disabled then
setHoveringIndex(nil)
setDraggingIndex(nil)
end
end, { props.Disabled })
local contentPos, setContentPos = React.useState(Vector2.zero)
local contentSize, setContentSize = React.useState(Vector2.zero)
local borders: { [string]: React.ReactNode } = {}
for col = 0, GRID_COLS, 0.5 do
local border = React.createElement(DashedLine, {
Position = UDim2.fromOffset(math.round(col / GRID_COLS * contentSize.X), 0),
Size = UDim2.new(0, 1, 1, 0),
Direction = Enum.FillDirection.Vertical,
Transparency = if col % 1 == 0 then 0 else 0.75,
Disabled = props.Disabled,
})
borders[`BorderCol{col}`] = border
end
for row = 0, GRID_ROWS, 0.5 do
local border = React.createElement(DashedLine, {
Position = UDim2.fromOffset(0, math.round(row / GRID_ROWS * contentSize.Y)),
Size = UDim2.new(1, 0, 0, 1),
Direction = Enum.FillDirection.Horizontal,
Transparency = if row % 1 == 0 then 0 else 0.75,
Disabled = props.Disabled,
})
borders[`BorderRow{row}`] = border
end
local function onNodeDragged(index: number, position: Vector2)
local offset = position - contentPos
offset = clampVector2(offset / contentSize, Vector2.zero, Vector2.one)
offset = Vector2.new(offset.X, 1 - offset.Y)
local origin = sequence.Keypoints[index]
local before = sequence.Keypoints[index - 1]
local after = sequence.Keypoints[index + 1]
local minTime = if index == #sequence.Keypoints then 1 elseif index == 1 then 0 else before.Time
local maxTime = if index == 1 then 0 elseif index == #sequence.Keypoints then 1 else after.Time
local newEnvelope = origin.Envelope
if offset.Y + newEnvelope > 1 then
newEnvelope = 1 - offset.Y
end
if offset.Y - newEnvelope < 0 then
newEnvelope = offset.Y
end
local newKeypoint = NumberSequenceKeypoint.new(math.clamp(offset.X, minTime, maxTime), offset.Y, newEnvelope)
local newKeypoints = table.clone(sequence.Keypoints)
newKeypoints[index] = newKeypoint
onChanged(NumberSequence.new(newKeypoints))
end
local function onEnvelopeDragged(index: number, y: number, top: boolean)
local keypoint = sequence.Keypoints[index]
local offset = (y - contentPos.Y) / contentSize.Y
local value = 1 - keypoint.Value
local newEnvelope
local maxValue = math.min(value, 1 - value)
if top then
newEnvelope = math.clamp(value - offset, 0, maxValue)
else
newEnvelope = math.clamp(offset - value, 0, maxValue)
end
local newKeypoints = table.clone(sequence.Keypoints)
newKeypoints[index] = NumberSequenceKeypoint.new(keypoint.Time, keypoint.Value, newEnvelope)
onChanged(NumberSequence.new(newKeypoints))
end
local points: { [string]: React.ReactNode } = {}
for i, keypoint in sequence.Keypoints do
points[`Point{i}`] = React.createElement(SequenceNode, {
ContentSize = contentSize,
Keypoint = keypoint,
Active = hoveringIndex == i or draggingIndex == i,
Disabled = props.Disabled,
OnHovered = function()
if draggingIndex == nil and hoveringIndex ~= i then
setHoveringIndex(i)
end
end,
OnNodeDragged = function(position)
onNodeDragged(i, position)
end,
OnEnvelopeDragged = function(y, top)
onEnvelopeDragged(i, y, top)
end,
OnDragBegan = function()
setDraggingIndex(i)
end,
OnDragEnded = function()
setDraggingIndex(nil)
end,
})
end
local lines: { [string]: React.ReactNode } = {}
for i = 1, #sequence.Keypoints - 1 do
local kp0 = sequence.Keypoints[i]
local kp1 = sequence.Keypoints[i + 1]
local p0 = Vector2.new(kp0.Time, 1 - kp0.Value)
local p1 = Vector2.new(kp1.Time, 1 - kp1.Value)
lines[`Line{i}`] = React.createElement(FreeLine, {
Pos0 = p0 * contentSize,
Pos1 = p1 * contentSize,
Color = theme:GetColor(Enum.StudioStyleGuideColor.DialogMainButton),
ZIndex = 1,
Disabled = props.Disabled,
})
end
local envelopes: { [string]: React.ReactNode } = {}
for i = 1, #sequence.Keypoints - 1 do
local kp0 = sequence.Keypoints[i]
local kp1 = sequence.Keypoints[i + 1]
if kp0.Envelope == 0 and kp1.Envelope == 0 then
continue
end
local p0 = Vector2.new(kp0.Time, 1 - kp0.Value)
local p1 = Vector2.new(kp1.Time, 1 - kp1.Value)
envelopes[`EnvelopeOver{i}`] = React.createElement(FreeLine, {
Pos0 = contentSize * Vector2.new(p0.X, p0.Y - kp0.Envelope), -- NB: roblox enforces bound
Pos1 = contentSize * Vector2.new(p1.X, p1.Y - kp1.Envelope),
Color = theme:GetColor(ENVELOPE_COLOR_STYLE),
Transparency = ENVELOPE_TRANSPARENCY,
ZIndex = 1,
Disabled = props.Disabled,
})
envelopes[`EnvelopeUnder{i}`] = React.createElement(FreeLine, {
Pos0 = contentSize * Vector2.new(p0.X, p0.Y + kp0.Envelope),
Pos1 = contentSize * Vector2.new(p1.X, p1.Y + kp1.Envelope),
Color = theme:GetColor(ENVELOPE_COLOR_STYLE),
Transparency = ENVELOPE_TRANSPARENCY,
ZIndex = 1,
Disabled = props.Disabled,
})
end
local axisLabels: { [string]: React.ReactNode } = {}
for row = 1, GRID_ROWS do
axisLabels[`AxisLabelRow{row}`] = React.createElement(AxisLabel, {
AnchorPoint = Vector2.new(1, 0.5),
Position = UDim2.new(0, -5, 1 - row / GRID_ROWS, 0),
TextXAlignment = Enum.TextXAlignment.Right,
Value = row / GRID_ROWS,
Disabled = props.Disabled,
})
end
for col = 1, GRID_COLS do
axisLabels[`AxisLabelCol{col}`] = React.createElement(AxisLabel, {
AnchorPoint = Vector2.new(0.5, 0),
Position = UDim2.new(col / GRID_COLS, 0, 1, 5),
Value = col / GRID_COLS,
Disabled = props.Disabled,
})
end
axisLabels["AxisLabelZero"] = React.createElement(AxisLabel, {
AnchorPoint = Vector2.new(1, 0),
Position = UDim2.new(0, -5, 1, 5),
TextXAlignment = Enum.TextXAlignment.Right,
Value = 0,
Disabled = props.Disabled,
})
local function tryAddKeypoint(keypoint: NumberSequenceKeypoint)
if #sequence.Keypoints == 20 then
return
end
local newKeypoints = table.clone(sequence.Keypoints)
for i = 1, #sequence.Keypoints do
local kp0 = sequence.Keypoints[i]
local kp1 = sequence.Keypoints[i + 1]
if keypoint.Time >= kp0.Time and keypoint.Time <= kp1.Time then
table.insert(newKeypoints, i + 1, keypoint)
onChanged(NumberSequence.new(newKeypoints))
setHoveringIndex(i + 1)
break
end
end
end
local activeIndex = draggingIndex or hoveringIndex
local activeKeypoint = if activeIndex then sequence.Keypoints[activeIndex] else nil
local minTime, maxTime
if activeKeypoint then
local i = activeIndex :: number
local before = sequence.Keypoints[i - 1]
local after = sequence.Keypoints[i + 1]
minTime = if not after then 1 elseif not before then 0 else before.Time
maxTime = if not before then 0 elseif not after then 1 else after.Time
end
local minValue = 0
local maxValue = 1
local minEnvelope = 0
local maxEnvelope
if activeKeypoint then
local current = activeKeypoint :: NumberSequenceKeypoint
maxEnvelope = math.min(current.Value, 1 - current.Value)
end
local function updateKeypoint(keypointProps: {
Time: number?,
Value: number?,
Envelope: number?,
})
local current = activeKeypoint :: NumberSequenceKeypoint
local newKeypoints = table.clone(sequence.Keypoints)
newKeypoints[activeIndex :: number] = NumberSequenceKeypoint.new(
keypointProps.Time or current.Time,
keypointProps.Value or current.Value,
keypointProps.Envelope or current.Envelope
)
onChanged(NumberSequence.new(newKeypoints))
end
return React.createElement("Frame", {
AnchorPoint = props.AnchorPoint,
Position = props.Position,
Size = props.Size or Constants.DefaultNumberSequencePickerSize,
LayoutOrder = props.LayoutOrder,
ZIndex = props.ZIndex,
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainBackground),
BorderSizePixel = 0,
}, {
Padding = React.createElement("UIPadding", {
PaddingLeft = UDim.new(0, PickerConstants.EnvelopeHandleHeight + 1),
PaddingRight = UDim.new(0, PickerConstants.EnvelopeHandleHeight + 1),
PaddingTop = UDim.new(0, PickerConstants.EnvelopeHandleHeight + 1),
PaddingBottom = UDim.new(0, 10),
}),
ContentArea = React.createElement("Frame", {
Position = UDim2.fromOffset(22, 0), -- axis labels
Size = UDim2.fromScale(1, 1)
- UDim2.fromOffset(0, PickerConstants.EnvelopeHandleHeight + 4 + Constants.DefaultInputHeight)
- UDim2.fromOffset(22, 10) -- axis labels
- UDim2.fromOffset(1, 1), -- outer/lower border
BackgroundTransparency = 1,
[React.Change.AbsolutePosition] = function(rbx: Frame)
setContentPos(rbx.AbsolutePosition)
end,
[React.Change.AbsoluteSize] = function(rbx: Frame)
setContentSize(rbx.AbsoluteSize)
end,
[React.Event.InputBegan] = function(rbx: Frame, input: InputObject)
if not draggingIndex and input.UserInputType == Enum.UserInputType.MouseButton1 then
local offset = Vector2.new(input.Position.X, input.Position.Y) - rbx.AbsolutePosition
offset = offset / rbx.AbsoluteSize
offset = clampVector2(offset, Vector2.zero, Vector2.one)
local newKeypoint = NumberSequenceKeypoint.new(offset.X, 1 - offset.Y)
tryAddKeypoint(newKeypoint)
end
end :: () -> (),
}, borders, points, lines, envelopes, axisLabels),
ControlsArea = React.createElement("Frame", {
AnchorPoint = Vector2.new(0, 1),
Position = UDim2.fromScale(0, 1),
Size = UDim2.new(1, 0, 0, Constants.DefaultInputHeight),
BackgroundTransparency = 1,
BorderSizePixel = 0,
}, {
Layout = React.createElement("UIListLayout", {
FillDirection = Enum.FillDirection.Horizontal,
SortOrder = Enum.SortOrder.LayoutOrder,
Padding = UDim.new(0, 15),
}),
Time = React.createElement(LabelledNumericInput, {
LayoutOrder = 1,
Label = "Time",
Min = minTime,
Max = maxTime,
Value = if activeKeypoint then activeKeypoint.Time else nil,
Disabled = not activeIndex or activeIndex <= 1 or activeIndex >= #sequence.Keypoints,
OnChanged = identity,
OnSubmitted = function(newTime)
updateKeypoint({ Time = math.clamp(newTime, minTime, maxTime) })
end,
}),
Value = React.createElement(LabelledNumericInput, {
LayoutOrder = 2,
Label = "Value",
Min = minValue,
Max = maxValue,
Value = if activeKeypoint then activeKeypoint.Value else nil,
OnChanged = identity,
OnSubmitted = function(newValue)
updateKeypoint({ Value = math.clamp(newValue, minValue, maxValue) })
end,
}),
Envelope = React.createElement(LabelledNumericInput, {
LayoutOrder = 3,
Label = "Envelope",
Min = minEnvelope,
Max = maxEnvelope,
Value = if activeKeypoint then activeKeypoint.Envelope else nil,
OnChanged = identity,
OnSubmitted = function(newEnvelope)
updateKeypoint({ Envelope = math.clamp(newEnvelope, minEnvelope, maxEnvelope) })
end,
}),
Delete = React.createElement("Frame", {
LayoutOrder = 4,
Size = UDim2.new(0, 105, 1, 0),
BackgroundTransparency = 1,
}, {
Button = React.createElement(Button, {
Position = UDim2.fromOffset(0, 1),
Size = UDim2.new(1, 0, 1, -2),
Text = "Delete Keypoint",
Disabled = activeKeypoint == nil or activeIndex <= 1 or activeIndex >= #sequence.Keypoints,
OnActivated = function()
if activeIndex then
local newKeypoints = table.clone(sequence.Keypoints)
table.remove(newKeypoints, activeIndex)
onChanged(NumberSequence.new(newKeypoints))
end
end,
}),
}),
}),
})
end
return NumberSequencePicker
| 3,976 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/NumericInput.luau | --[=[
@class NumericInput
An input field matching the appearance of a [TextInput] but which filters inputted text to only
allow numeric values, optionally with arrow and slider controls.
| Dark | Light |
| - | - |
|  |  |
This is a controlled component with similar behavior to [TextInput]. The current numeric value
to display should be passed to the `Value` prop, and a callback should be passed to the
`OnValidChanged` prop which is run when the user types a (valid) numeric input.
Optionally, a minimum value can be passed to the `Min` prop, as well as a maximum value to the
`Max` prop. A step (increment) value may also be passed to the the `Step` prop, which defaults
to 1 (allowing only whole number values). Passing a non-integer step value will also allow a
decimal point to be typed in the input box.
Use the `Arrows` and `Slider` props to specify whether up/down arrows and a slider should be
included. If arrows or a slider are displayed, they will increment the value by the amount of the step.
Completing a slide with a slider will call the `OnSubmitted` prop (if provided) with the latest value.
Only decimal inputs are allowed (so, for example, hex characters a-f will not be permitted).
]=]
local RunService = game:GetService("RunService")
local React = require("@pkg/@jsdotlua/react")
local BaseTextInput = require("./Foundation/BaseTextInput")
local Slider = require("./Slider")
local Constants = require("../Constants")
local useFreshCallback = require("../Hooks/useFreshCallback")
local useTheme = require("../Hooks/useTheme")
--[=[
@within NumericInput
@interface Props
@tag Component Props
@field ... CommonProps
@field Value number
@field OnValidChanged ((n: number) -> ())?
@field Min number?
@field Max number?
@field Step number?
@field OnSubmitted ((n: number) -> ())?
@field FormatValue ((n: number) -> string)?
@field Arrows boolean?
@field Slider boolean?
@field PlaceholderText string?
@field ClearTextOnFocus boolean?
@field OnFocused (() -> ())?
@field OnFocusLost ((text: string, enterPressed: boolean, input: InputObject) -> ())?
]=]
type NumericInputProps = BaseTextInput.BaseTextInputConsumerProps & {
OnValidChanged: ((n: number) -> ())?,
Value: number,
Min: number?,
Max: number?,
Step: number?,
OnSubmitted: ((n: number) -> ())?,
FormatValue: ((n: number) -> string)?,
Arrows: boolean?,
Slider: boolean?,
}
local MAX = 2 ^ 53
local ARROW_WIDTH = 19
local SLIDER_SPLIT = 0.45
local function roundToStep(n: number, step: number): number
if step == 0 then
return n
end
return math.round(n / step) * step
end
local function tonumberPositiveZero(s: string): number?
local n = tonumber(s)
if n == -0 then
return 0
end
return n
end
local function applyFormat(n: number, formatter: ((n: number) -> string)?)
if n == -0 then
n = 0
end
if formatter ~= nil then
return formatter(n)
end
return tostring(n)
end
local function NumericInputArrow(props: {
HeightBinding: React.Binding<number>,
Side: number,
Callback: (side: number) -> (),
Disabled: boolean?,
})
local theme = useTheme()
local connection = React.useRef(nil) :: { current: RBXScriptConnection? }
local hovered, setHovered = React.useState(false)
local pressed, setPressed = React.useState(false)
local modifier = Enum.StudioStyleGuideModifier.Default
if props.Disabled then
modifier = Enum.StudioStyleGuideModifier.Disabled
elseif pressed then
modifier = Enum.StudioStyleGuideModifier.Pressed
elseif hovered then
modifier = Enum.StudioStyleGuideModifier.Hover
end
local maybeActivate = useFreshCallback(function()
if hovered then
props.Callback(props.Side)
end
end, { hovered, props.Callback, props.Side } :: { unknown })
local function startHolding()
if connection.current then
connection.current:Disconnect()
end
local nextScroll = os.clock() + 0.35
connection.current = RunService.PostSimulation:Connect(function()
if os.clock() >= nextScroll then
maybeActivate()
nextScroll += 0.05
end
end)
props.Callback(props.Side)
end
local function stopHolding()
if connection.current then
connection.current:Disconnect()
connection.current = nil
end
end
React.useEffect(stopHolding, {})
React.useEffect(function()
if props.Disabled and pressed then
stopHolding()
setPressed(false)
end
if props.Disabled then
setHovered(false)
end
end, { props.Disabled, pressed })
return React.createElement("TextButton", {
AutoButtonColor = false,
BorderSizePixel = 0,
Text = "",
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Button, modifier),
Size = props.HeightBinding:map(function(height: number)
if props.Side == 0 then
return UDim2.new(1, 0, 0, math.floor(height / 2))
else
return UDim2.new(1, 0, 0, math.ceil(height / 2) - 1)
end
end),
Position = props.HeightBinding:map(function(height: number)
if props.Side == 0 then
return UDim2.fromOffset(0, 0)
else
return UDim2.fromOffset(0, math.floor(height / 2) + 1)
end
end),
[React.Event.InputBegan] = function(_, input)
if props.Disabled then
return
elseif input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(true)
elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
setPressed(true)
startHolding()
end
end,
[React.Event.InputEnded] = function(_, input)
if props.Disabled then
return
elseif input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(false)
elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
setPressed(false)
stopHolding()
end
end,
}, {
Image = React.createElement("ImageLabel", {
Image = "rbxassetid://14699332993",
Size = UDim2.fromOffset(7, 4),
ImageColor3 = theme:GetColor(Enum.StudioStyleGuideColor.ButtonText, modifier),
BackgroundTransparency = 1,
AnchorPoint = Vector2.new(0.5, 0.5),
Position = UDim2.fromScale(0.5, 0.5),
ImageRectSize = Vector2.new(7, 4),
ImageRectOffset = Vector2.new(0, if props.Side == 0 then 0 else 4),
ImageTransparency = if props.Disabled then 0.2 else 0,
}),
})
end
local function NumericInput(props: NumericInputProps)
local theme = useTheme()
local min = math.max(props.Min or -MAX, -MAX)
local max = math.min(props.Max or MAX, MAX)
local step = props.Step or 1
assert(max >= min, `max ({max}) was less than min ({min})`)
assert(step >= 0, `step ({step}) was less than 0`)
local pattern = if step % 1 == 0 and step ~= 0 then "[^%-%d]" else "[^%-%.%d]"
local lastCleanText, setLastCleanText = React.useState(applyFormat(props.Value, props.FormatValue))
local onValidChanged: (number) -> () = props.OnValidChanged or function() end
React.useEffect(function()
setLastCleanText(function(freshLastCleanText)
if tonumberPositiveZero(freshLastCleanText) ~= props.Value then
return applyFormat(props.Value, props.FormatValue)
end
return freshLastCleanText
end)
end, { props.Value, props.FormatValue } :: { unknown })
local heightBinding, setHeightBinding = React.useBinding(0)
local function buttonCallback(side: number)
local usingStep = (if step == 0 then 1 else step) * (if side == 0 then 1 else -1)
local newValue = math.clamp(props.Value + usingStep, min, max)
if newValue ~= props.Value then
onValidChanged(newValue)
end
end
local modifier = Enum.StudioStyleGuideModifier.Default
if props.Disabled then
modifier = Enum.StudioStyleGuideModifier.Disabled
end
return React.createElement("Frame", {
AnchorPoint = props.AnchorPoint,
Position = props.Position,
Size = props.Size or UDim2.new(1, 0, 0, Constants.DefaultInputHeight),
LayoutOrder = props.LayoutOrder,
ZIndex = props.ZIndex,
BorderSizePixel = 0,
BackgroundTransparency = 1,
}, {
InputHolder = React.createElement("Frame", {
Size = UDim2.fromScale(if props.Slider then SLIDER_SPLIT else 1, 1),
BackgroundTransparency = 1,
}, {
Input = React.createElement(BaseTextInput, {
Disabled = props.Disabled,
Size = UDim2.fromScale(1, 1),
ClearTextOnFocus = props.ClearTextOnFocus,
PlaceholderText = props.PlaceholderText,
Text = lastCleanText,
RightPaddingExtra = if props.Arrows then ARROW_WIDTH + 1 else 0,
OnChanged = function(newText: string)
local cleanText = string.gsub(newText, pattern, "")
local number = tonumberPositiveZero(cleanText)
if number ~= nil then
if number >= min and number <= max and roundToStep(number, step) == number then
onValidChanged(number)
end
end
setLastCleanText(cleanText)
end,
OnFocusLost = function(_, enterPressed: boolean, inputObject: InputObject)
local number = tonumberPositiveZero(lastCleanText)
local outValue = props.Value
if number ~= nil then
outValue = math.clamp(roundToStep(number, step), min, max)
end
onValidChanged(outValue)
if props.OnSubmitted then
props.OnSubmitted(outValue)
end
setLastCleanText(applyFormat(outValue, props.FormatValue))
if props.OnFocusLost then
props.OnFocusLost(lastCleanText, enterPressed, inputObject)
end
end,
OnFocused = props.OnFocused,
}),
Arrows = props.Arrows and React.createElement("Frame", {
BorderSizePixel = 0,
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Button, modifier),
AnchorPoint = Vector2.new(1, 0),
Position = UDim2.new(1, -1, 0, 1),
Size = UDim2.new(0, ARROW_WIDTH, 1, -2),
[React.Change.AbsoluteSize] = function(rbx)
setHeightBinding(rbx.AbsoluteSize.Y)
end,
}, {
Up = React.createElement(NumericInputArrow, {
Disabled = props.Disabled or props.Value >= max,
Callback = buttonCallback,
HeightBinding = heightBinding,
Side = 0,
}),
Down = React.createElement(NumericInputArrow, {
Disabled = props.Disabled or props.Value <= min,
Callback = buttonCallback,
HeightBinding = heightBinding,
Side = 1,
}),
}),
}),
Slider = props.Slider and React.createElement(Slider, {
AnchorPoint = Vector2.new(1, 0),
Position = UDim2.fromScale(1, 0),
Size = UDim2.new(1 - SLIDER_SPLIT, -5, 1, 0),
Value = props.Value,
Min = min,
Max = max,
Step = step,
OnChanged = props.OnValidChanged,
OnCompleted = props.OnSubmitted,
Disabled = props.Disabled,
}),
})
end
return NumericInput
| 2,800 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/PluginProvider.luau | --[=[
@class PluginProvider
This component provides an interface to plugin apis for other components in the tree. It should
be provided with a single `Plugin` prop that must point to `plugin` (your plugin's root instance).
You do not have to use this component unless you want custom mouse icons via the [useMouseIcon]
hook. Right now, the only built-in component that relies on this is [Splitter]. Theming and all
other functionality will work regardless of whether this component is used.
You should only render one PluginProvider in your tree. Commonly, this is done at the top of
the tree with the rest of your plugin as children/descendants.
Example of usage:
```lua
local function MyComponent()
return React.createElement(StudioComponents.PluginProvider, {
Plugin = plugin,
}, {
MyExample = React.createElement(MyExample, ...)
})
end
```
]=]
local HttpService = game:GetService("HttpService")
local React = require("@pkg/@jsdotlua/react")
local PluginContext = require("../Contexts/PluginContext")
type IconStackEntry = {
id: string,
icon: string,
}
--[=[
@within PluginProvider
@interface Props
@tag Component Props
@field Plugin Plugin
@field children React.ReactNode
]=]
type PluginProviderProps = {
Plugin: Plugin,
children: React.ReactNode,
}
local function PluginProvider(props: PluginProviderProps)
local plugin = props.Plugin
local iconStack = React.useRef({}) :: { current: { IconStackEntry } }
local function updateMouseIcon()
local top = iconStack.current[#iconStack.current]
plugin:GetMouse().Icon = if top then top.icon else ""
end
local function pushMouseIcon(icon)
local id = HttpService:GenerateGUID(false)
table.insert(iconStack.current, { id = id, icon = icon })
updateMouseIcon()
return id
end
local function popMouseIcon(id)
for i = #iconStack.current, 1, -1 do
local item = iconStack.current[i]
if item.id == id then
table.remove(iconStack.current, i)
end
end
updateMouseIcon()
end
React.useEffect(function()
return function()
table.clear(iconStack.current)
plugin:GetMouse().Icon = ""
end
end, {})
return React.createElement(PluginContext.Provider, {
value = {
plugin = plugin,
pushMouseIcon = pushMouseIcon,
popMouseIcon = popMouseIcon,
},
}, props.children)
end
return PluginProvider
| 563 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/ProgressBar.luau | --[=[
@class ProgressBar
A basic progress indicator. This should be used for longer or more detailed loading processes.
For shorter loading processes, consider using a [LoadingDots] component.
| Dark | Light |
| - | - |
|  |  |
Pass a number representing the current progress into the `Value` prop. You can optionally pass a
number representing the maximum value into the `Max` prop, which defaults to 1 if not provided.
The `Value` prop should be between 0 and `Max`. For example:
```lua
local function MyComponent()
return React.createElement(StudioComponents.ProgressBar, {
Value = 5, -- loaded 5 items
Max = 10, -- out of a total of 10 items
})
end
```
By default, the progress bar will display text indicating the progress as a percentage,
rounded to the nearest whole number. This can be customized by providing a prop to `Formatter`,
which should be a function that takes two numbers representing the current value and the maximum value
and returns a string to be displayed. For example:
```lua
local function MyComponent()
return React.createElement(StudioComponents.ProgressBar, {
Value = 3,
Max = 20,
Formatter = function(current, max)
return `Loaded {current} / {max} assets...`
end,
})
end
```
By default, the height of a progress bar is equal to the value in [Constants.DefaultProgressBarHeight].
This can be configured via props.
]=]
local React = require("@pkg/@jsdotlua/react")
local CommonProps = require("../CommonProps")
local Constants = require("../Constants")
local useTheme = require("../Hooks/useTheme")
--[=[
@within ProgressBar
@interface Props
@tag Component Props
@field ... CommonProps
@field Value number
@field Max number?
@field Formatter ((value: number, max: number) -> string)?
]=]
type ProgressBarProps = CommonProps.T & {
Value: number,
Max: number?,
Formatter: ((value: number, max: number) -> string)?,
}
local function defaultFormatter(value: number, max: number)
return string.format("%i%%", 100 * value / max)
end
local function ProgressBar(props: ProgressBarProps)
local theme = useTheme()
local formatter: (number, number) -> string = defaultFormatter
if props.Formatter then
formatter = props.Formatter
end
local max = props.Max or 1
local value = math.clamp(props.Value, 0, max)
local alpha = value / max
local text = formatter(value, max)
local modifier = Enum.StudioStyleGuideModifier.Default
if props.Disabled then
modifier = Enum.StudioStyleGuideModifier.Disabled
end
return React.createElement("Frame", {
AnchorPoint = props.AnchorPoint,
Position = props.Position,
Size = props.Size or UDim2.new(1, 0, 0, Constants.DefaultProgressBarHeight),
LayoutOrder = props.LayoutOrder,
ZIndex = props.ZIndex,
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.InputFieldBackground, modifier),
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.InputFieldBorder, modifier),
}, {
Bar = React.createElement("Frame", {
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.DialogMainButton, modifier),
BorderSizePixel = 0,
Size = UDim2.fromScale(alpha, 1),
ClipsDescendants = true,
ZIndex = 1,
}, {
Left = React.createElement("TextLabel", {
BackgroundTransparency = 1,
Size = UDim2.fromScale(1 / alpha, 1) - UDim2.fromOffset(0, 1),
Font = Constants.DefaultFont,
TextSize = Constants.DefaultTextSize,
TextColor3 = Color3.fromRGB(12, 12, 12),
TextTransparency = if props.Disabled then 0.5 else 0,
Text = text,
}),
}),
Under = React.createElement("TextLabel", {
BackgroundTransparency = 1,
Size = UDim2.fromScale(1, 1) - UDim2.fromOffset(0, 1),
Font = Constants.DefaultFont,
TextSize = Constants.DefaultTextSize,
TextColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainText, modifier),
Text = text,
ZIndex = 0,
}),
})
end
return ProgressBar
| 1,018 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/RadioButton.luau | --[=[
@class RadioButton
An input element similar to a [Checkbox] which can either be selected or not selected.
This should be used for an option in a mutually exclusive group of options (the user can
only select one out of the group). This grouping behavior is not included and must be
implemented separately.
| Dark | Light |
| - | - |
|  |  |
The props and behavior for this component are the same as [Checkbox]. Importantly, this is
also a controlled component, which means it does not manage its own selected state. A value
must be passed to the `Value` prop and a callback should be passed to the `OnChanged` prop.
For example:
```lua
local function MyComponent()
local selected, setSelected = React.useState(false)
return React.createElement(StudioComponents.RadioButton, {
Value = selected,
OnChanged = setSelected,
})
end
```
For more information about customizing this component via props, refer to the documentation
for [Checkbox]. The default height for this component is found in [Constants.DefaultToggleHeight].
]=]
local React = require("@pkg/@jsdotlua/react")
local BaseLabelledToggle = require("./Foundation/BaseLabelledToggle")
local useTheme = require("../Hooks/useTheme")
local PADDING = 1
local INNER_PADDING = 3
--[=[
@within RadioButton
@interface Props
@tag Component Props
@field ... CommonProps
@field Value boolean?
@field OnChanged (() -> ())?
@field Label string?
@field ContentAlignment HorizontalAlignment?
@field ButtonAlignment HorizontalAlignment?
]=]
type RadioButtonProps = BaseLabelledToggle.BaseLabelledToggleConsumerProps & {
Value: boolean,
}
local function RadioButton(props: RadioButtonProps)
local theme = useTheme()
local mergedProps = table.clone(props) :: BaseLabelledToggle.BaseLabelledToggleProps
function mergedProps.RenderButton(subProps: { Hovered: boolean })
local mainModifier = Enum.StudioStyleGuideModifier.Default
if props.Disabled then
mainModifier = Enum.StudioStyleGuideModifier.Disabled
elseif subProps.Hovered then
mainModifier = Enum.StudioStyleGuideModifier.Hover
end
return React.createElement("Frame", {
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.CheckedFieldBackground, mainModifier),
BackgroundTransparency = 0,
Size = UDim2.new(1, -PADDING * 2, 1, -PADDING * 2),
Position = UDim2.fromOffset(1, PADDING),
}, {
Corner = React.createElement("UICorner", {
CornerRadius = UDim.new(0.5, 0),
}),
Stroke = React.createElement("UIStroke", {
Color = theme:GetColor(Enum.StudioStyleGuideColor.CheckedFieldBorder, mainModifier),
Transparency = 0,
}),
Inner = if props.Value == true
then React.createElement("Frame", {
Size = UDim2.new(1, -INNER_PADDING * 2, 1, -INNER_PADDING * 2),
Position = UDim2.fromOffset(INNER_PADDING, INNER_PADDING),
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.DialogMainButton, mainModifier),
BackgroundTransparency = 0.25,
}, {
Corner = React.createElement("UICorner", {
CornerRadius = UDim.new(0.5, 0),
}),
})
else nil,
})
end
return React.createElement(BaseLabelledToggle, mergedProps)
end
return RadioButton
| 817 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/ScrollFrame/ScrollBar.luau | local React = require("@pkg/@jsdotlua/react")
local useMouseDrag = require("../../Hooks/useMouseDrag")
local useTheme = require("../../Hooks/useTheme")
local Constants = require("./Constants")
local ScrollBarArrow = require("./ScrollBarArrow")
local Types = require("./Types")
local SCROLLBAR_THICKNESS = Constants.ScrollBarThickness
local INPUT_MOVE = Enum.UserInputType.MouseMovement
local function flipVector2(vector: Vector2, shouldFlip: boolean)
return if shouldFlip then Vector2.new(vector.Y, vector.X) else vector
end
local function flipUDim2(udim: UDim2, shouldFlip: boolean)
return if shouldFlip then UDim2.new(udim.Height, udim.Width) else udim
end
type ScrollData = Types.ScrollData
type ScrollBarProps = {
BumpScroll: (scrollVector: Vector2) -> (),
Orientation: Types.BarOrientation,
ScrollData: React.Binding<ScrollData>,
ScrollOffset: React.Binding<Vector2>,
SetScrollOffset: (offset: Vector2) -> (),
Disabled: boolean?,
}
local function ScrollBar(props: ScrollBarProps)
local vertical = props.Orientation == "Vertical"
local scrollDataBinding = props.ScrollData
local theme = useTheme()
local hovered, setHovered = React.useState(false)
local dragStartMouse = React.useRef(nil) :: { current: Vector2? }
local dragStartCanvas = React.useRef(nil) :: { current: Vector2? }
local function onDragStarted(_, input: InputObject)
dragStartMouse.current = Vector2.new(input.Position.X, input.Position.Y)
dragStartCanvas.current = props.ScrollOffset:getValue()
end
local function onDragEnded()
dragStartMouse.current = nil
dragStartCanvas.current = nil
end
local function onDragged(_, input: InputObject)
local scrollData = scrollDataBinding:getValue()
local contentSize = scrollData.ContentSize
local windowSize = scrollData.WindowSize
local innerBarSize = scrollData.InnerBarSize
local offsetFrom = dragStartCanvas.current :: Vector2
local mouseFrom = dragStartMouse.current :: Vector2
local mouseDelta = Vector2.new(input.Position.X, input.Position.Y) - mouseFrom
local shiftAlpha = mouseDelta / (innerBarSize - scrollData.BarSize)
local overflow = contentSize - windowSize
local newOffset = offsetFrom + overflow * shiftAlpha
newOffset = newOffset:Min(overflow)
newOffset = newOffset:Max(Vector2.zero)
local freshScrollOffset = props.ScrollOffset:getValue()
if vertical then
props.SetScrollOffset(Vector2.new(freshScrollOffset.X, newOffset.Y))
else
props.SetScrollOffset(Vector2.new(newOffset.X, freshScrollOffset.Y))
end
end
local dragDeps = { props.ScrollOffset, props.SetScrollOffset } :: { unknown }
local drag = useMouseDrag(onDragged, dragDeps, onDragStarted, onDragEnded)
React.useEffect(function()
if props.Disabled and drag.isActive() then
drag.cancel()
onDragEnded()
end
-- if props.Disabled then
-- setHovered(false)
-- end
end, { props.Disabled, drag.isActive() })
local modifier = Enum.StudioStyleGuideModifier.Default
if props.Disabled then
modifier = Enum.StudioStyleGuideModifier.Disabled
elseif hovered or drag.isActive() then
modifier = Enum.StudioStyleGuideModifier.Pressed
end
return React.createElement("Frame", {
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.ScrollBarBackground),
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Border),
Visible = scrollDataBinding:map(function(data: ScrollData)
return if vertical then data.BarVisible.Y else data.BarVisible.X
end),
AnchorPoint = flipVector2(Vector2.new(1, 0), not vertical),
Position = flipUDim2(UDim2.fromScale(1, 0), not vertical),
Size = scrollDataBinding:map(function(data)
local extra = if (vertical and data.BarVisible.X) or (not vertical and data.BarVisible.Y)
then -SCROLLBAR_THICKNESS - 1
else 0
return flipUDim2(UDim2.new(0, SCROLLBAR_THICKNESS, 1, extra), not vertical)
end),
}, {
Arrow0 = React.createElement(ScrollBarArrow, {
Side = 0,
Orientation = props.Orientation,
BumpScroll = props.BumpScroll,
Disabled = props.Disabled,
}),
Arrow1 = React.createElement(ScrollBarArrow, {
Side = 1,
Orientation = props.Orientation,
BumpScroll = props.BumpScroll,
Position = flipUDim2(UDim2.fromScale(0, 1), not vertical),
AnchorPoint = flipVector2(Vector2.new(0, 1), not vertical),
Disabled = props.Disabled,
}),
Region = React.createElement("Frame", {
BackgroundTransparency = 1,
Position = flipUDim2(UDim2.fromOffset(0, SCROLLBAR_THICKNESS + 1), not vertical),
Size = flipUDim2(UDim2.new(1, 0, 1, -(SCROLLBAR_THICKNESS + 1) * 2), not vertical),
}, {
Handle = React.createElement("Frame", {
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.ScrollBar, modifier),
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Border, modifier),
Size = scrollDataBinding:map(function(data: ScrollData)
local size = if vertical then data.BarSize.Y else data.BarSize.X
return flipUDim2(UDim2.new(1, 0, 0, size), not vertical)
end),
Position = scrollDataBinding:map(function(data: ScrollData)
local position = if vertical then data.BarPosition.Y else data.BarPosition.X
return flipUDim2(UDim2.fromScale(0, position), not vertical)
end),
AnchorPoint = scrollDataBinding:map(function(data: ScrollData)
local position = if vertical then data.BarPosition.Y else data.BarPosition.X
return flipVector2(Vector2.new(0, position), not vertical)
end),
[React.Event.InputBegan] = function(rbx: Frame, input: InputObject)
if input.UserInputType == INPUT_MOVE then
setHovered(true)
end
if not props.Disabled then
drag.onInputBegan(rbx, input)
end
end,
[React.Event.InputChanged] = function(rbx: Frame, input: InputObject)
if not props.Disabled then
drag.onInputChanged(rbx, input)
end
end,
[React.Event.InputEnded] = function(rbx: Frame, input: InputObject)
if input.UserInputType == INPUT_MOVE then
setHovered(false)
end
if not props.Disabled then
drag.onInputEnded(rbx, input)
end
end,
}),
}),
})
end
return ScrollBar
| 1,588 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/ScrollFrame/ScrollBarArrow.luau | local RunService = game:GetService("RunService")
local React = require("@pkg/@jsdotlua/react")
local useFreshCallback = require("../../Hooks/useFreshCallback")
local useTheme = require("../../Hooks/useTheme")
local Constants = require("./Constants")
local Types = require("./Types")
local ARROW_IMAGE = "rbxassetid://6677623152"
local SCROLLBAR_THICKNESS = Constants.ScrollBarThickness
local ARROW_SCROLL_AMOUNT = Constants.ArrowScrollAmount
local function getArrowImageOffset(orientation: Types.BarOrientation, side: number)
if orientation == "Vertical" then
return Vector2.new(0, side * SCROLLBAR_THICKNESS)
end
return Vector2.new(SCROLLBAR_THICKNESS, side * SCROLLBAR_THICKNESS)
end
local function getScrollVector(orientation: Types.BarOrientation, side: number)
local scrollAmount = ARROW_SCROLL_AMOUNT * (if side == 0 then -1 else 1)
local scrollVector = Vector2.new(0, scrollAmount)
if orientation == "Horizontal" then
scrollVector = Vector2.new(scrollAmount, 0)
end
return scrollVector
end
type ScrollBarArrowProps = {
BumpScroll: (scrollVector: Vector2) -> (),
Orientation: Types.BarOrientation,
Side: number,
Position: UDim2?,
AnchorPoint: Vector2?,
Disabled: boolean?,
}
local function ScrollBarArrow(props: ScrollBarArrowProps)
local theme = useTheme()
local connection = React.useRef(nil) :: { current: RBXScriptConnection? }
local pressed, setPressed = React.useState(false)
local hovered, setHovered = React.useState(false)
local modifier = Enum.StudioStyleGuideModifier.Default
if props.Disabled then
modifier = Enum.StudioStyleGuideModifier.Disabled
elseif pressed then
modifier = Enum.StudioStyleGuideModifier.Pressed
end
local maybeScroll = useFreshCallback(function()
if hovered then
props.BumpScroll(getScrollVector(props.Orientation, props.Side))
end
end, { hovered, props.BumpScroll, props.Orientation, props.Side } :: { unknown })
local function startHolding()
if connection.current then
connection.current:Disconnect()
end
local nextScroll = os.clock() + 0.35
connection.current = RunService.PostSimulation:Connect(function()
if os.clock() >= nextScroll then
maybeScroll()
nextScroll += 0.05
end
end)
props.BumpScroll(getScrollVector(props.Orientation, props.Side))
end
local function stopHolding()
if connection.current then
connection.current:Disconnect()
connection.current = nil
end
end
React.useEffect(stopHolding, {})
React.useEffect(function()
if props.Disabled and pressed then
stopHolding()
setPressed(false)
end
if props.Disabled then
setHovered(false)
end
end, { props.Disabled, pressed })
local hostClass = "ImageLabel"
local hostProps = {
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.ScrollBar, modifier),
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Border, modifier),
Size = UDim2.fromOffset(SCROLLBAR_THICKNESS, SCROLLBAR_THICKNESS),
Image = ARROW_IMAGE,
ImageRectSize = Vector2.new(SCROLLBAR_THICKNESS, SCROLLBAR_THICKNESS),
ImageRectOffset = getArrowImageOffset(props.Orientation, props.Side),
ImageColor3 = theme:GetColor(Enum.StudioStyleGuideColor.TitlebarText, modifier),
Position = props.Position,
AnchorPoint = props.AnchorPoint,
}
if props.Disabled ~= true then
hostClass = "ImageButton"
hostProps.AutoButtonColor = false
hostProps[React.Event.InputBegan] = function(_, input: InputObject)
if input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(true)
elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
setPressed(true)
startHolding()
end
end
hostProps[React.Event.InputEnded] = function(_, input: InputObject)
if input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(false)
elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
setPressed(false)
stopHolding()
end
end
end
return React.createElement(hostClass, hostProps)
end
return ScrollBarArrow
| 970 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/ScrollFrame/Types.luau | export type ScrollData = {
ContentSize: Vector2,
WindowSize: Vector2,
InnerBarSize: Vector2,
BarVisible: { X: boolean, Y: boolean },
BarSize: Vector2,
BarPosition: Vector2,
}
export type BarOrientation = "Horizontal" | "Vertical"
return {}
| 68 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/ScrollFrame/init.luau | --[=[
@class ScrollFrame
A container with scrollable contents. This works the same way as a built-in [ScrollingFrame] but
has visual changes to match the appearance of built-in scrollers in Studio.
| Dark | Light |
| - | - |
|  |  |
ScrollFrames automatically size their canvas to fit their contents, which are passed via the
`children` parameters in createElement. By default, children are laid out with a [UIListLayout];
this can be overriden via the `Layout` prop. Either "UIListLayout" or "UIGridLayout" may be
passed to `Layout.ClassName`. Any other properties to be applied to the layout should also be
passed in the `Layout` prop. For example:
```lua
local function MyComponent()
return React.createElement(StudioComponents.ScrollFrame, {
Layout = {
ClassName = "UIListLayout",
Padding = UDim.new(0, 10),
FillDirection = Enum.FillDirection.Horizontal,
}
}, {
SomeChild = React.createElement(...),
AnotherChild = React.createElement(...),
})
end
```
By default, scrolling on both the X and Y axes is enabled. To configure this, pass an
[Enum.ScrollingDirection] value to the `ScrollingDirection` prop. Padding around the outside of
contents can also be configured via the `PaddingLeft`, `PaddingRight`, `PaddingTop`, and
`PaddingBottom` props.
:::info
The built-in Studio scrollers were changed during this project's lifetime to be significantly
narrower. This component retains the old, wider, size because it is more accessible.
:::
]=]
local React = require("@pkg/@jsdotlua/react")
local CommonProps = require("../../CommonProps")
local useTheme = require("../../Hooks/useTheme")
local Constants = require("./Constants")
local ScrollBar = require("./ScrollBar")
local Types = require("./Types")
local SCROLL_WHEEL_SPEED = Constants.WheelScrollAmount
local SCROLLBAR_THICKNESS = Constants.ScrollBarThickness
local SCROLLBAR_MIN_LENGTH = SCROLLBAR_THICKNESS
local function clampVector2(v: Vector2, vmin: Vector2, vmax: Vector2)
return Vector2.new(math.clamp(v.X, vmin.X, vmax.X), math.clamp(v.Y, vmin.Y, vmax.Y))
end
type ScrollData = Types.ScrollData
local defaultLayout = {
ClassName = "UIListLayout",
SortOrder = Enum.SortOrder.LayoutOrder,
}
--[=[
@within ScrollFrame
@interface Props
@tag Component Props
@field ... CommonProps
@field Layout { ClassName: string, [string]: any }?
@field ScrollingDirection Enum.ScrollingDirection?
@field PaddingLeft UDim?
@field PaddingRight UDim?
@field PaddingTop UDim?
@field PaddingBottom UDim?
@field OnScrolled ((scrollOffset: Vector2) -> ())?
@field children React.ReactNode
]=]
type ScrollFrameProps = CommonProps.T & {
ScrollingDirection: Enum.ScrollingDirection?,
PaddingLeft: UDim?,
PaddingRight: UDim?,
PaddingTop: UDim?,
PaddingBottom: UDim?,
OnScrolled: ((scrollOffset: Vector2) -> ())?,
Layout: {
ClassName: string, -- Luau: should be "UIListLayout | "UIGridLayout" but causes problems
[string]: any, -- native props
}?,
children: React.ReactNode,
}
local function computePaddingSize(data: {
PaddingLeft: UDim?,
PaddingRight: UDim?,
PaddingTop: UDim?,
PaddingBottom: UDim?,
WindowSize: Vector2,
})
local paddingX = (data.PaddingLeft or UDim.new(0, 0)) + (data.PaddingRight or UDim.new(0, 0))
local paddingY = (data.PaddingTop or UDim.new(0, 0)) + (data.PaddingBottom or UDim.new(0, 0))
return Vector2.new(
paddingX.Scale * data.WindowSize.X + paddingX.Offset,
paddingY.Scale * data.WindowSize.Y + paddingY.Offset
)
end
local function getRegionData(props: ScrollFrameProps, contentSize: Vector2, windowSize: Vector2)
local scrollingEnabled = {
X = props.ScrollingDirection ~= Enum.ScrollingDirection.Y,
Y = props.ScrollingDirection ~= Enum.ScrollingDirection.X,
}
local paddingSize = computePaddingSize({
PaddingLeft = props.PaddingLeft,
PaddingRight = props.PaddingRight,
PaddingTop = props.PaddingTop,
PaddingBottom = props.PaddingBottom,
WindowSize = windowSize,
})
contentSize += paddingSize
local overflow = contentSize - windowSize
local visible = { X = false, Y = false }
for _ = 1, 2 do -- in case Y relayout affects X, we do it twice
if overflow.X > 0 and not visible.X and scrollingEnabled.X then
windowSize -= Vector2.new(0, SCROLLBAR_THICKNESS + 1)
visible.X = true
end
if overflow.Y > 0 and not visible.Y and scrollingEnabled.Y then
windowSize -= Vector2.new(SCROLLBAR_THICKNESS + 1, 0)
visible.Y = true
end
overflow = contentSize - windowSize
end
return {
ContentSize = contentSize,
WindowSize = windowSize,
Overflow = overflow,
Visible = visible,
}
end
local function ScrollFrame(props: ScrollFrameProps)
local theme = useTheme()
local scrollOffsetBinding, setScrollOffsetBinding = React.useBinding(Vector2.zero)
local contentSizeBinding, setContentSizeBinding = React.useBinding(Vector2.zero)
local windowSizeBinding, setWindowSizeBinding = React.useBinding(Vector2.zero)
local function setScrollOffset(offset: Vector2)
if offset ~= scrollOffsetBinding:getValue() then
setScrollOffsetBinding(offset)
if props.OnScrolled then
props.OnScrolled(offset)
end
end
end
local function getScrollData(): ScrollData
local regionData = getRegionData(props, contentSizeBinding:getValue(), windowSizeBinding:getValue())
local contentSize = regionData.ContentSize
local windowSize = regionData.WindowSize
local overflow = regionData.Overflow
local visible = regionData.Visible
local alpha = clampVector2(windowSize / contentSize, Vector2.zero, Vector2.one)
local innerBarSize = windowSize - Vector2.one * (SCROLLBAR_THICKNESS + 1) * 2
local scrollOffset = scrollOffsetBinding:getValue()
local offset = alpha * innerBarSize
offset = offset:Max(Vector2.one * SCROLLBAR_MIN_LENGTH)
offset = offset:Min(innerBarSize + Vector2.one * 2)
offset = offset:Max(Vector2.zero)
local sizeX = if visible.X then offset.X else 0
local sizeY = if visible.Y then offset.Y else 0
local size = Vector2.new(sizeX, sizeY)
local position = clampVector2(scrollOffset / overflow, Vector2.zero, Vector2.one)
return {
ContentSize = contentSize,
WindowSize = windowSize,
InnerBarSize = innerBarSize,
BarVisible = visible,
BarSize = size,
BarPosition = position,
}
end
local function revalidateScrollOffset()
local regionData = getRegionData(props, contentSizeBinding:getValue(), windowSizeBinding:getValue())
local currentOffset = scrollOffsetBinding:getValue()
local maxOffset = regionData.Overflow:Max(Vector2.zero)
maxOffset = maxOffset:Min(
Vector2.new(
if regionData.Visible.X then maxOffset.X else 0,
if regionData.Visible.Y then maxOffset.Y else 0
)
)
local newOffset = currentOffset:Min(maxOffset)
if newOffset ~= currentOffset then
setScrollOffset(newOffset)
end
end
React.useEffect(
revalidateScrollOffset,
{
props.ScrollingDirection,
props.Layout,
props.PaddingLeft,
props.PaddingRight,
props.PaddingBottom,
props.PaddingTop,
} :: { unknown }
)
local function bumpScroll(scrollVector: Vector2)
local scrollData = getScrollData()
local windowSize = scrollData.WindowSize
local contentSize = scrollData.ContentSize
local scrollOffset = scrollOffsetBinding:getValue()
local scrollTarget = scrollOffset + scrollVector
local scrollBounds = contentSize - windowSize
scrollBounds = scrollBounds:Max(Vector2.zero)
setScrollOffset(clampVector2(scrollTarget, Vector2.zero, scrollBounds))
end
local function handleMainInput(_, input: InputObject)
if props.Disabled then
return
elseif input.UserInputType == Enum.UserInputType.MouseWheel then
local amount = SCROLL_WHEEL_SPEED * -input.Position.Z
local scrollData = getScrollData()
local shiftHeld = input:IsModifierKeyDown(Enum.ModifierKey.Shift)
local scrollVector
if shiftHeld then
if scrollData.BarVisible.X then
scrollVector = Vector2.new(amount, 0)
end
elseif scrollData.BarVisible.Y then
scrollVector = Vector2.new(0, amount)
elseif scrollData.BarVisible.X then
scrollVector = Vector2.new(amount, 0)
end
if scrollVector then
bumpScroll(scrollVector)
end
end
end
local scrollDataBinding = React.joinBindings({
contentSizeBinding,
windowSizeBinding,
scrollOffsetBinding,
}):map(getScrollData)
local modifier = Enum.StudioStyleGuideModifier.Default
if props.Disabled then
modifier = Enum.StudioStyleGuideModifier.Disabled
end
local layoutBase = table.clone(props.Layout or defaultLayout)
local layoutProps: { [any]: any } = {}
for key, val in layoutBase :: { [string]: any } do
if key ~= "ClassName" then
layoutProps[key] = val
end
end
layoutProps[React.Change.AbsoluteContentSize] = function(rbx: UIListLayout | UIGridLayout)
setContentSizeBinding(rbx.AbsoluteContentSize)
revalidateScrollOffset()
end
--[[
Children need to be able to use actual window size for their sizes.
To facilitate this, the parent Window frame's size equals the clipping area.
However, this causes the layout in e.g. layout mode Center to lay elements out
... from the center of the Window, rather than the Canvas.
We fix this by simply overriding the alignments when the bars are visible
... since those properties make no difference in those cases.
]]
layoutProps.HorizontalAlignment = scrollDataBinding:map(function(data: ScrollData)
return if data.BarVisible.X then Enum.HorizontalAlignment.Left else layoutBase.HorizontalAlignment
end)
layoutProps.VerticalAlignment = scrollDataBinding:map(function(data: ScrollData)
return if data.BarVisible.Y then Enum.VerticalAlignment.Top else layoutBase.VerticalAlignment
end)
local mainSize = scrollDataBinding:map(function(data: ScrollData)
local windowSize = data.WindowSize:Max(Vector2.zero)
return UDim2.fromOffset(windowSize.X, windowSize.Y)
end)
return React.createElement("Frame", {
-- sinks scroll input that would otherwise zoom the studio camera
-- also prevents the drag-box appearing on lmb-drag
Active = true,
LayoutOrder = props.LayoutOrder,
ZIndex = props.ZIndex,
AnchorPoint = props.AnchorPoint,
Position = props.Position,
Size = props.Size or UDim2.fromScale(1, 1),
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainBackground, modifier),
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Border, modifier),
[React.Event.InputBegan] = handleMainInput,
[React.Event.InputChanged] = handleMainInput,
[React.Change.AbsoluteSize] = function(rbx: Frame)
setWindowSizeBinding(rbx.AbsoluteSize)
revalidateScrollOffset()
end :: any,
}, {
Cover = if props.Disabled
then React.createElement("Frame", {
ZIndex = 2,
Size = mainSize,
BorderSizePixel = 0,
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainBackground),
BackgroundTransparency = 0.25,
})
else nil,
Clipping = React.createElement("Frame", {
Size = mainSize,
BackgroundTransparency = 1,
ClipsDescendants = true,
}, {
Window = React.createElement("Frame", {
Size = UDim2.fromScale(1, 1),
BackgroundTransparency = 1,
Position = scrollOffsetBinding:map(function(offset: Vector2)
return UDim2.fromOffset(-offset.X, -offset.Y)
end),
}, {
Padding = React.createElement("UIPadding", {
PaddingLeft = props.PaddingLeft,
PaddingRight = props.PaddingRight,
PaddingTop = props.PaddingTop,
PaddingBottom = props.PaddingBottom,
}),
Layout = React.createElement(layoutBase.ClassName, layoutProps),
}, props.children),
}),
VerticalScrollBar = React.createElement(ScrollBar, {
Orientation = "Vertical" :: "Vertical", -- Luau
ScrollData = scrollDataBinding,
ScrollOffset = scrollOffsetBinding,
SetScrollOffset = setScrollOffset,
BumpScroll = bumpScroll,
Disabled = props.Disabled,
}),
HorizontalScrollBar = React.createElement(ScrollBar, {
Orientation = "Horizontal" :: "Horizontal", -- Luau
ScrollData = scrollDataBinding,
ScrollOffset = scrollOffsetBinding,
SetScrollOffset = setScrollOffset,
BumpScroll = bumpScroll,
Disabled = props.Disabled,
}),
})
end
return ScrollFrame
| 3,096 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/Slider.luau | --[=[
@class Slider
A component for selecting a numeric value from a range of values with an optional increment.
These are seen in some number-valued properties in the built-in Properties widget, as well as in
various built-in plugins such as the Terrain Editor.
| Dark | Light |
| - | - |
|  |  |
As with other components in this library, this is a controlled component. You should pass a
value to the `Value` prop representing the current value, as well as a callback to the `OnChanged`
prop which will be run when the user changes the value via dragging or clicking on the slider.
In addition to these, you must also provide a `Min` and a `Max` prop, which together define the
range of the slider. Optionally, a `Step` prop can be provided, which defines the increment of
the slider. This defaults to 0, which allows any value in the range. For a complete example:
```lua
local function MyComponent()
local value, setValue = React.useState(1)
return React.createElement(StudioComponents.Slider, {
Value = value,
OnChanged = setValue,
Min = 0,
Max = 10,
Step = 1,
})
end
```
Optionally, an `OnCompleted` callback prop can be provided. This will be called with the latest
value of the Slider when sliding is finished. It is also called if, while sliding is in progress,
the component becomes Disabled via props or is unmounted.
Two further props can optionally be provided:
1. `Border` determines whether a border is drawn around the component.
This is useful for giving visual feedback when the slider is hovered or selected.
2. `Background` determines whether the component has a visible background.
If this is value is missing or set to `false`, any border will also be hidden.
Both of these props default to `true`.
By default, the height of sliders is equal to the value found in [Constants.DefaultSliderHeight].
While this can be overriden by props, in order to keep inputs accessible it is not recommended
to make the component any smaller than this.
]=]
local React = require("@pkg/@jsdotlua/react")
local CommonProps = require("../CommonProps")
local Constants = require("../Constants")
local useFreshCallback = require("../Hooks/useFreshCallback")
local useMouseDrag = require("../Hooks/useMouseDrag")
local useTheme = require("../Hooks/useTheme")
--[=[
@within Slider
@interface Props
@tag Component Props
@field ... CommonProps
@field Value number
@field OnChanged ((newValue: number) -> ())?
@field OnCompleted ((newValue: number) -> ())?
@field Min number
@field Max number
@field Step number?
@field Border boolean?
@field Background boolean?
]=]
type SliderProps = CommonProps.T & {
Value: number,
OnChanged: ((newValue: number) -> ())?,
OnCompleted: ((newValue: number) -> ())?,
Min: number,
Max: number,
Step: number?,
Border: boolean?,
Background: boolean?,
}
local PADDING_BAR_SIDE = 3
local PADDING_REGION_TOP = 1
local PADDING_REGION_SIDE = 6
local INPUT_MOVE = Enum.UserInputType.MouseMovement
local function Slider(props: SliderProps)
local theme = useTheme()
local onChanged: (number) -> () = props.OnChanged or function() end
local dragCallback = function(rbx: GuiObject, input: InputObject)
local regionPos = rbx.AbsolutePosition.X + PADDING_REGION_SIDE
local regionSize = rbx.AbsoluteSize.X - PADDING_REGION_SIDE * 2
local inputPos = input.Position.X
local alpha = (inputPos - regionPos) / regionSize
local step = props.Step or 0
local value = props.Min * (1 - alpha) + props.Max * alpha
if step > 0 then
value = math.round(value / step) * step
end
value = math.clamp(value, props.Min, props.Max)
if value ~= props.Value then
onChanged(value)
end
end
local dragEndedCallback = useFreshCallback(function()
if props.OnCompleted then
props.OnCompleted(props.Value)
end
end, { props.Value, props.OnCompleted } :: { unknown })
local dragDeps = { props.Value, props.Min, props.Max, props.Step, props.OnCompleted, onChanged } :: { unknown }
local drag = useMouseDrag(dragCallback, dragDeps, nil, dragEndedCallback)
local hovered, setHovered = React.useState(false)
local mainModifier = Enum.StudioStyleGuideModifier.Default
if props.Disabled then
mainModifier = Enum.StudioStyleGuideModifier.Disabled
end
local handleModifier = Enum.StudioStyleGuideModifier.Default
if props.Disabled then
handleModifier = Enum.StudioStyleGuideModifier.Disabled
elseif hovered or drag.isActive() then
handleModifier = Enum.StudioStyleGuideModifier.Hover
end
local handleFill = theme:GetColor(Enum.StudioStyleGuideColor.Button, handleModifier)
local handleBorder = theme:GetColor(Enum.StudioStyleGuideColor.Border, handleModifier)
React.useEffect(function()
if props.Disabled and drag.isActive() then
drag.cancel()
end
end, { props.Disabled, drag.isActive() })
local function inputBegan(rbx: Frame, input: InputObject)
if input.UserInputType == INPUT_MOVE then
setHovered(true)
end
if not props.Disabled then
drag.onInputBegan(rbx, input)
end
end
local function inputChanged(rbx: Frame, input: InputObject)
if not props.Disabled then
drag.onInputChanged(rbx, input)
end
end
local function inputEnded(rbx: Frame, input: InputObject)
if input.UserInputType == INPUT_MOVE then
setHovered(false)
end
if not props.Disabled then
drag.onInputEnded(rbx, input)
end
end
-- if we use a Frame here, the 2d studio selection rectangle will appear when dragging
-- we could prevent that using Active = true, but that displays the Click cursor
-- ... the best workaround is a TextButton with Active = false
return React.createElement("TextButton", {
Text = "",
Active = false,
AutoButtonColor = false,
Size = props.Size or UDim2.new(1, 0, 0, Constants.DefaultSliderHeight),
Position = props.Position,
AnchorPoint = props.AnchorPoint,
LayoutOrder = props.LayoutOrder,
ZIndex = props.ZIndex,
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.InputFieldBackground, mainModifier),
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.InputFieldBorder, handleModifier),
BorderMode = Enum.BorderMode.Inset,
BorderSizePixel = if props.Border == false then 0 else 1,
BackgroundTransparency = if props.Background == false then 1 else 0,
[React.Event.InputBegan] = inputBegan,
[React.Event.InputChanged] = inputChanged,
[React.Event.InputEnded] = inputEnded,
}, {
Bar = React.createElement("Frame", {
ZIndex = 1,
AnchorPoint = Vector2.new(0, 0.5),
Position = UDim2.new(0, PADDING_BAR_SIDE, 0.5, 0),
Size = UDim2.new(1, -PADDING_BAR_SIDE * 2, 0, 2),
BorderSizePixel = 0,
BackgroundTransparency = props.Disabled and 0.4 or 0,
BackgroundColor3 = theme:GetColor(
-- surprising values, but provides correct colors
Enum.StudioStyleGuideColor.TitlebarText,
Enum.StudioStyleGuideModifier.Disabled
),
}),
HandleRegion = React.createElement("Frame", {
ZIndex = 2,
Position = UDim2.fromOffset(PADDING_REGION_SIDE, PADDING_REGION_TOP),
Size = UDim2.new(1, -PADDING_REGION_SIDE * 2, 1, -PADDING_REGION_TOP * 2),
BackgroundTransparency = 1,
}, {
Handle = React.createElement("Frame", {
AnchorPoint = Vector2.new(0.5, 0),
Position = UDim2.fromScale((props.Value - props.Min) / (props.Max - props.Min), 0),
Size = UDim2.new(0, 10, 1, 0),
BorderMode = Enum.BorderMode.Inset,
BorderSizePixel = 1,
BorderColor3 = handleBorder:Lerp(handleFill, props.Disabled and 0.5 or 0),
BackgroundColor3 = handleFill,
}),
}),
})
end
return Slider
| 1,972 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/Splitter.luau | --[=[
@class Splitter
A container frame similar to a [Background] but split into two panels, with a draggable control
for resizing the panels within the container. Resizing one section to be larger will reduce the
size of the other section, and vice versa. This is useful for letting users resize content.
| Dark | Light |
| - | - |
|  |  |
This is a controlled component. The current split location should be passed as a number between
0 and 1 to the `Alpha` prop, and a callback should be passed to the `OnChanged` prop, which
is run with the new alpha value when the user uses the splitter.
You can also optionally provide `MinAlpha` and `MaxAlpha` props (numbers between 0 and 1) which
limit the resizing. These values default to 0.1 and 0.9.
To render children in each side, use the `children` parameters in createElement and provide the
keys `Side0` and `Side1`. For a complete example:
```lua
local function MyComponent()
local division, setDivision = React.useState(0.5)
return React.createElement(StudioComponents.Splitter, {
Alpha = division,
OnChanged = setDivision,
}, {
Side0 = React.createElement(...),
Side1 = React.createElement(...),
})
end
```
By default, the split is horizontal, which means that the frame is split into a left and right
side. This can be changed, for example to a vertical split (top and bottom), by providing an
[Enum.FillDirection] value to the `FillDirection` prop.
This component can use your system's splitter mouse icons when interacting with the splitter bar.
To enable this behavior, ensure you have rendered a [PluginProvider] somewhere higher up in
the tree.
]=]
local React = require("@pkg/@jsdotlua/react")
local CommonProps = require("../CommonProps")
local useMouseDrag = require("../Hooks/useMouseDrag")
local useMouseIcon = require("../Hooks/useMouseIcon")
local useTheme = require("../Hooks/useTheme")
local function flipVector2(vector: Vector2, shouldFlip: boolean)
return if shouldFlip then Vector2.new(vector.Y, vector.X) else vector
end
local function flipUDim2(udim: UDim2, shouldFlip: boolean)
return if shouldFlip then UDim2.new(udim.Height, udim.Width) else udim
end
local HANDLE_THICKNESS = 6
local DEFAULT_MIN_ALPHA = 0.1
local DEFAULT_MAX_ALPHA = 0.9
--[=[
@within Splitter
@interface Props
@tag Component Props
@field ... CommonProps
@field Alpha number
@field OnChanged ((newAlpha: number) -> ())?
@field FillDirection Enum.FillDirection?
@field MinAlpha number?
@field MaxAlpha number?
@field children { Side0: React.ReactNode?, Side1: React.ReactNode? }?
]=]
export type SplitterProps = CommonProps.T & {
Alpha: number,
OnChanged: ((newAlpha: number) -> ())?,
FillDirection: Enum.FillDirection?,
MinAlpha: number?,
MaxAlpha: number?,
children: {
Side0: React.ReactNode,
Side1: React.ReactNode,
}?,
}
local icons = {
[Enum.FillDirection.Horizontal] = "rbxasset://SystemCursors/SplitEW",
[Enum.FillDirection.Vertical] = "rbxasset://SystemCursors/SplitNS",
}
local function Splitter(props: SplitterProps)
local theme = useTheme()
local mouseIcon = useMouseIcon()
local fillDirection = props.FillDirection or Enum.FillDirection.Horizontal
local children = props.children or {
Side0 = nil,
Side1 = nil,
}
local drag = useMouseDrag(function(bar: GuiObject, input: InputObject)
local region = bar.Parent :: Frame
local position = Vector2.new(input.Position.X, input.Position.Y)
local alpha = (position - region.AbsolutePosition) / region.AbsoluteSize
alpha = alpha:Max(Vector2.one * (props.MinAlpha or DEFAULT_MIN_ALPHA))
alpha = alpha:Min(Vector2.one * (props.MaxAlpha or DEFAULT_MAX_ALPHA))
if props.OnChanged then
if fillDirection == Enum.FillDirection.Horizontal and alpha.X ~= props.Alpha then
props.OnChanged(alpha.X)
elseif fillDirection == Enum.FillDirection.Vertical and alpha.Y ~= props.Alpha then
props.OnChanged(alpha.Y)
end
end
end, { props.Alpha, props.OnChanged, props.MinAlpha, props.MaxAlpha, fillDirection } :: { unknown })
React.useEffect(function()
if props.Disabled and drag.isActive() then
drag.cancel()
end
end, { props.Disabled, drag.isActive() })
local hovered, setHovered = React.useState(false)
React.useEffect(function()
if (hovered or drag.isActive()) and not props.Disabled then
local icon = icons[fillDirection]
mouseIcon.setIcon(icon)
else
mouseIcon.clearIcon()
end
end, { mouseIcon, hovered, drag.isActive(), props.Disabled, fillDirection } :: { unknown })
local function onInputBegan(rbx: Frame, input: InputObject)
if input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(true)
end
if not props.Disabled then
drag.onInputBegan(rbx, input)
end
end
local function onInputChanged(rbx: Frame, input: InputObject)
if not props.Disabled then
drag.onInputChanged(rbx, input)
end
end
local function onInputEnded(rbx: Frame, input: InputObject)
if input.UserInputType == Enum.UserInputType.MouseMovement then
setHovered(false)
end
if not props.Disabled then
drag.onInputEnded(rbx, input)
end
end
local shouldFlip = fillDirection == Enum.FillDirection.Vertical
local alpha = props.Alpha
alpha = math.max(alpha, props.MinAlpha or DEFAULT_MIN_ALPHA)
alpha = math.min(alpha, props.MaxAlpha or DEFAULT_MAX_ALPHA)
local handleTransparency = if props.Disabled then 0.75 else 0
local handleColorStyle = Enum.StudioStyleGuideColor.DialogButton
if props.Disabled then
handleColorStyle = Enum.StudioStyleGuideColor.Border
end
return React.createElement("Frame", {
AnchorPoint = props.AnchorPoint,
Position = props.Position,
Size = props.Size or UDim2.fromScale(1, 1),
LayoutOrder = props.LayoutOrder,
ZIndex = props.ZIndex,
BackgroundTransparency = 1,
}, {
Handle = React.createElement("Frame", {
Active = true, -- prevents the drag-box when in coregui mode
AnchorPoint = flipVector2(Vector2.new(0.5, 0), shouldFlip),
Position = flipUDim2(UDim2.fromScale(alpha, 0), shouldFlip),
Size = flipUDim2(UDim2.new(0, HANDLE_THICKNESS, 1, 0), shouldFlip),
BackgroundTransparency = handleTransparency,
BackgroundColor3 = theme:GetColor(handleColorStyle),
BorderSizePixel = 0,
[React.Event.InputBegan] = onInputBegan,
[React.Event.InputChanged] = onInputChanged,
[React.Event.InputEnded] = onInputEnded,
ZIndex = 1,
}, {
LeftBorder = not props.Disabled and React.createElement("Frame", {
Size = flipUDim2(UDim2.new(0, 1, 1, 0), shouldFlip),
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Border),
BorderSizePixel = 0,
}),
RightBorder = not props.Disabled and React.createElement("Frame", {
Position = flipUDim2(UDim2.new(1, -1, 0, 0), shouldFlip),
Size = flipUDim2(UDim2.new(0, 1, 1, 0), shouldFlip),
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Border),
BorderSizePixel = 0,
}),
}),
Side0 = React.createElement("Frame", {
Size = flipUDim2(UDim2.new(alpha, -math.floor(HANDLE_THICKNESS / 2), 1, 0), shouldFlip),
BackgroundTransparency = 1,
ClipsDescendants = true,
ZIndex = 0,
}, {
Child = children.Side0,
}),
Side1 = React.createElement("Frame", {
AnchorPoint = flipVector2(Vector2.new(1, 0), shouldFlip),
Position = flipUDim2(UDim2.fromScale(1, 0), shouldFlip),
Size = flipUDim2(UDim2.new(1 - alpha, -math.ceil(HANDLE_THICKNESS / 2), 1, 0), shouldFlip),
BackgroundTransparency = 1,
ClipsDescendants = true,
ZIndex = 0,
}, {
Child = children.Side1,
}),
})
end
return Splitter
| 2,057 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Components/TextInput.luau | --[=[
@class TextInput
A basic input field for entering any kind of text. This matches the appearance of the search
boxes in the Explorer and Properties widgets, among other inputs in Studio.
| Dark | Light |
| - | - |
|  |  |
This is a controlled component, which means the current text should be passed in to the
`Text` prop and a callback value to the `OnChanged` prop which gets run when the user attempts
types in the input field. For example:
```lua
local function MyComponent()
local text, setText = React.useState("")
return React.createElement(StudioComponents.TextInput, {
Text = text,
OnChanged = setText,
})
end
```
This allows complete control over the text displayed and keeps the source of truth in your own
code. This is helpful for consistency and controlling the state from elsewhere in the tree. It
also allows you to easily filter what can be typed into the text input. For example, to only
permit entering lowercase letters:
```lua
local function MyComponent()
local text, setText = React.useState("")
return React.createElement(StudioComponents.TextInput, {
Text = text,
OnChanged = function(newText),
local filteredText = string.gsub(newText, "[^a-z]", "")
setText(filteredText)
end,
})
end
```
By default, the height of this component is equal to the value in [Constants.DefaultInputHeight].
While this can be overriden by props, in order to keep inputs accessible it is not recommended
to make the component any smaller than this.
]=]
local React = require("@pkg/@jsdotlua/react")
local BaseTextInput = require("./Foundation/BaseTextInput")
local Constants = require("../Constants")
--[=[
@within TextInput
@interface Props
@tag Component Props
@field ... CommonProps
@field Text string
@field OnChanged ((newText: string) -> ())?
@field PlaceholderText string?
@field ClearTextOnFocus boolean?
@field OnFocused (() -> ())?
@field OnFocusLost ((text: string, enterPressed: boolean, input: InputObject) -> ())?
]=]
type TextInputProps = BaseTextInput.BaseTextInputConsumerProps & {
Text: string,
OnChanged: ((newText: string) -> ())?,
}
local function TextInput(props: TextInputProps)
return React.createElement(BaseTextInput, {
AnchorPoint = props.AnchorPoint,
Position = props.Position,
Size = props.Size or UDim2.new(1, 0, 0, Constants.DefaultInputHeight),
LayoutOrder = props.LayoutOrder,
ZIndex = props.ZIndex,
Disabled = props.Disabled,
Text = props.Text,
PlaceholderText = props.PlaceholderText,
ClearTextOnFocus = props.ClearTextOnFocus,
OnFocused = props.OnFocused,
OnFocusLost = props.OnFocusLost,
OnChanged = props.OnChanged or function() end,
}, props.children)
end
return TextInput
| 673 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Constants.luau | --[=[
@class Constants
This module exposes values that are read from in various components.
These can be used to, for example, match the appearance of custom components with components
from this library.
:::warning
The table returned by this module is read-only. It is not a config.
:::
]=]
local Constants = {}
--- @within Constants
--- @prop DefaultFont Font
--- The default font for text.
Constants.DefaultFont = Enum.Font.SourceSans
--- @within Constants
--- @prop DefaultTextSize number
--- The default size for text.
Constants.DefaultTextSize = 14
--- @within Constants
--- @prop DefaultButtonHeight number
--- The default height of buttons.
Constants.DefaultButtonHeight = 24
--- @within Constants
--- @prop DefaultToggleHeight number
--- The default height of toggles (Checkbox and RadioButton).
Constants.DefaultToggleHeight = 20
--- @within Constants
--- @prop DefaultInputHeight number
--- The default height of text and numeric inputs.
Constants.DefaultInputHeight = 22
--- @within Constants
--- @prop DefaultSliderHeight number
--- The default height of sliders.
Constants.DefaultSliderHeight = 22
--- @within Constants
--- @prop DefaultDropdownHeight number
--- The default height of the permanent section of dropdowns.
Constants.DefaultDropdownHeight = 20
--- @within Constants
--- @prop DefaultDropdownRowHeight number
--- The default height of rows in dropdown lists.
Constants.DefaultDropdownRowHeight = 16
--- @within Constants
--- @prop DefaultProgressBarHeight number
--- The default height of progress bars.
Constants.DefaultProgressBarHeight = 14
--- @within Constants
--- @prop DefaultColorPickerSize UDim2
--- The default window size of color pickers.
Constants.DefaultColorPickerSize = UDim2.fromOffset(260, 285)
--- @within Constants
--- @prop DefaultNumberSequencePickerSize UDim2
--- The default window size of number sequence pickers.
Constants.DefaultNumberSequencePickerSize = UDim2.fromOffset(425, 285)
--- @within Constants
--- @prop DefaultDatePickerSize UDim2
--- The default window size of date pickers.
Constants.DefaultDatePickerSize = UDim2.fromOffset(202, 160)
return table.freeze(Constants)
| 477 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Contexts/PluginContext.luau | local React = require("@pkg/@jsdotlua/react")
export type PluginContext = {
plugin: Plugin,
pushMouseIcon: (icon: string) -> string,
popMouseIcon: (id: string) -> (),
}
return React.createContext(nil :: PluginContext?)
| 56 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Hooks/useFreshCallback.luau | local React = require("@pkg/@jsdotlua/react")
type Callback<Args..., Rets...> = (Args...) -> Rets...
local function useFreshCallback<Args..., Rets...>(
-- stylua: ignore
callback: Callback<Args..., Rets...>,
deps: { any }?
): Callback<Args..., Rets...>
local ref = React.useRef(callback) :: { current: Callback<Args..., Rets...> }
React.useEffect(function()
ref.current = callback
end, deps)
return function(...)
return ref.current(...)
end
end
return useFreshCallback
| 128 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Hooks/useMouseDrag.luau | local React = require("@pkg/@jsdotlua/react")
local useFreshCallback = require("../Hooks/useFreshCallback")
local function useMouseDrag(
callback: (rbx: GuiObject, input: InputObject) -> (),
deps: { any }?,
onBeganCallback: ((rbx: GuiObject, input: InputObject) -> ())?, -- NB: consumer needs to guard against stale state
onEndedCallback: (() -> ())?
)
local freshCallback = useFreshCallback(callback, deps)
-- we use a state so consumers can re-render
-- ... as well as a ref so we have an immediately-updated/available value
local holdingState, setHoldingState = React.useState(false)
local holding = React.useRef(false)
local lastRbx = React.useRef(nil :: GuiObject?)
local moveInput = React.useRef(nil :: InputObject?)
local moveConnection = React.useRef(nil :: RBXScriptConnection?)
local function runCallback(input: InputObject)
freshCallback(lastRbx.current :: GuiObject, input)
end
local function connect()
if moveConnection.current then
moveConnection.current:Disconnect()
end
local input = moveInput.current :: InputObject
local signal = input:GetPropertyChangedSignal("Position")
moveConnection.current = signal:Connect(function()
runCallback(input)
end)
runCallback(input)
end
local function disconnect()
if moveConnection.current then
moveConnection.current:Disconnect()
moveConnection.current = nil
end
if onEndedCallback and holding.current == true then
onEndedCallback()
end
end
-- React.useEffect(function()
-- if moveInput.current then
-- runCallback(moveInput.current)
-- end
-- end, deps)
React.useEffect(function()
return disconnect
end, {})
local function onInputBegan(rbx: GuiObject, input: InputObject)
lastRbx.current = rbx
if input.UserInputType == Enum.UserInputType.MouseMovement then
moveInput.current = input
elseif input.UserInputType == Enum.UserInputType.MouseButton1 then
holding.current = true
setHoldingState(true)
if onBeganCallback then
onBeganCallback(rbx, input)
end
if moveInput.current then
connect()
else
-- case: clicked without move input first
-- this can happen if the instance moves to be under the mouse
runCallback(input)
end
end
end
local function onInputChanged(rbx: GuiObject, input: InputObject)
lastRbx.current = rbx
if input.UserInputType == Enum.UserInputType.MouseMovement then
moveInput.current = input
if holding.current and not moveConnection.current then
-- handles the case above and connects listener on first move
connect()
end
end
end
local function onInputEnded(rbx: GuiObject, input: InputObject)
lastRbx.current = rbx
if input.UserInputType == Enum.UserInputType.MouseButton1 then
disconnect()
holding.current = false
setHoldingState(false)
end
end
local function isActive()
return holdingState == true
end
local function cancel()
disconnect()
holding.current = false
moveInput.current = nil
setHoldingState(false)
end
return {
isActive = isActive,
cancel = cancel,
onInputBegan = onInputBegan,
onInputChanged = onInputChanged,
onInputEnded = onInputEnded,
}
end
return useMouseDrag
| 776 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Hooks/useMouseIcon.luau | --[=[
@class useMouseIcon
A hook used internally by components for setting and clearing custom mouse icons. To use this
hook, you need to also render a single [PluginProvider] somewhere higher up in the tree.
To set the mouse icon, use the `setIcon` function and pass an asset url. All components under
the PluginProvider that use this hook share an icon stack; the most recent component to call
`setIcon` will have its icon set as the final mouse icon. Calling `setIcon` twice without
clearing it in between will override the previous icon set by this component.
Calling `clearIcon` removes the icon set by this component from the stack, which may mean the
mouse icon falls back to the next icon on the stack set by another component. Ensure you call
`clearIcon` on unmount otherwise your icon may never get unset. For example:
```lua
local function MyComponent()
local mouseIconApi = useMouseIcon()
React.useEffect(function() -- clear icon on unmount
return function()
mouseIconApi.clearIcon()
end
end, {})
return React.createElement(SomeComponent, {
OnHoverStart = function()
mouseIconApi.setIcon(...) -- some icon for hover
end,
OnHoverEnd = function()
mouseIconApi.clearIcon()
end
})
end
```
]=]
--[=[
@within useMouseIcon
@interface mouseIconApi
@field setIcon (icon: string) -> ()
@field getIcon () -> string?
@field clearIcon () -> ()
]=]
local React = require("@pkg/@jsdotlua/react")
local PluginContext = require("../Contexts/PluginContext")
local useFreshCallback = require("../Hooks/useFreshCallback")
local function useMouseIcon()
local plugin = React.useContext(PluginContext)
local lastIconId: string?, setLastIconId = React.useState(nil :: string?)
local lastIconAssetUrl: string?, setLastIconAssetUrl = React.useState(nil :: string?)
local function getIcon(): string?
return lastIconAssetUrl
end
local function setIcon(assetUrl: string)
if plugin ~= nil and assetUrl ~= lastIconAssetUrl then
if lastIconId ~= nil then
plugin.popMouseIcon(lastIconId)
end
local newId = plugin.pushMouseIcon(assetUrl)
setLastIconId(newId)
setLastIconAssetUrl(assetUrl)
end
end
local clearIcon = useFreshCallback(function()
if plugin ~= nil and lastIconId ~= nil then
plugin.popMouseIcon(lastIconId)
setLastIconId(nil)
setLastIconAssetUrl(nil)
end
end, { lastIconId })
React.useEffect(function()
return clearIcon
end, {})
return {
getIcon = getIcon,
setIcon = setIcon,
clearIcon = clearIcon,
}
end
return useMouseIcon
| 634 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Hooks/usePlugin.luau | --[=[
@class usePlugin
A hook used to obtain a reference to the root [plugin](https://create.roblox.com/docs/reference/engine/classes/Plugin)
instance associated with the current plugin. It requires a single [PluginProvider] to be present
higher up in the tree.
```lua
local function MyComponent()
local plugin = usePlugin()
...
end
```
]=]
local React = require("@pkg/@jsdotlua/react")
local PluginContext = require("../Contexts/PluginContext")
local function usePlugin()
local pluginContext = React.useContext(PluginContext)
return pluginContext and pluginContext.plugin
end
return usePlugin
| 141 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Hooks/useTheme.luau | --[=[
@class useTheme
A hook used internally by components for reading the selected Studio Theme and thereby visually
theming components appropriately. It is exposed here so that custom components can use this
API to achieve the same effect. Calling the hook returns a [StudioTheme] instance. For example:
```lua
local function MyThemedComponent()
local theme = useTheme()
local color = theme:GetColor(
Enum.StudioStyleGuideColor.ScriptBackground,
Enum.StudioStyleGuideModifier.Default
)
return React.createElement("Frame", {
BackgroundColor3 = color,
...
})
end
```
]=]
local Studio = settings().Studio
local React = require("@pkg/@jsdotlua/react")
local ThemeContext = require("../Contexts/ThemeContext")
local function useTheme()
local theme = React.useContext(ThemeContext)
local studioTheme, setStudioTheme = React.useState(Studio.Theme)
React.useEffect(function()
if theme then
return
end
local connection = Studio.ThemeChanged:Connect(function()
setStudioTheme(Studio.Theme)
end)
return function()
connection:Disconnect()
end
end, { theme })
return theme or studioTheme
end
return useTheme
| 269 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/Background.story.luau | local React = require("@pkg/@jsdotlua/react")
local Background = require("../Components/Background")
local createStory = require("./Helpers/createStory")
local function Story()
return React.createElement(Background)
end
return createStory(Story)
| 49 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/Button.story.luau | local React = require("@pkg/@jsdotlua/react")
local Button = require("../Components/Button")
local createStory = require("./Helpers/createStory")
local function StoryButton(props: {
Text: string?,
HasIcon: boolean?,
Disabled: boolean?,
})
return React.createElement(Button, {
LayoutOrder = if props.Disabled then 2 else 1,
Icon = props.HasIcon and {
Image = "rbxassetid://18786011824",
UseThemeColor = true,
Size = Vector2.new(16, 16),
Alignment = Enum.HorizontalAlignment.Left,
RectOffset = Vector2.new(1000, 0),
RectSize = Vector2.new(16, 16),
} :: any,
Text = props.Text,
OnActivated = if not props.Disabled then function() end else nil,
Disabled = props.Disabled,
AutomaticSize = Enum.AutomaticSize.XY,
})
end
local function StoryItem(props: {
LayoutOrder: number,
Text: string?,
HasIcon: boolean?,
Disabled: boolean?,
})
local height, setHeight = React.useBinding(0)
return React.createElement("Frame", {
Size = height:map(function(value)
return UDim2.new(1, 0, 0, value)
end),
LayoutOrder = props.LayoutOrder,
BackgroundTransparency = 1,
}, {
Layout = React.createElement("UIListLayout", {
Padding = UDim.new(0, 10),
SortOrder = Enum.SortOrder.LayoutOrder,
FillDirection = Enum.FillDirection.Horizontal,
HorizontalAlignment = Enum.HorizontalAlignment.Center,
[React.Change.AbsoluteContentSize] = function(rbx)
setHeight(rbx.AbsoluteContentSize.Y)
end,
}),
Enabled = React.createElement(StoryButton, {
Text = props.Text,
HasIcon = props.HasIcon,
}),
Disabled = React.createElement(StoryButton, {
Text = props.Text,
HasIcon = props.HasIcon,
Disabled = true,
}),
})
end
local function Story()
return React.createElement(React.Fragment, {}, {
Icon = React.createElement(StoryItem, {
LayoutOrder = 1,
HasIcon = true,
}),
Text = React.createElement(StoryItem, {
LayoutOrder = 2,
Text = "Example Text",
}),
TextLonger = React.createElement(StoryItem, {
LayoutOrder = 3,
Text = "Example Longer Text",
}),
TextMulti = React.createElement(StoryItem, {
LayoutOrder = 4,
Text = "Example Text\nover two lines",
}),
IconTextIcon = React.createElement(StoryItem, {
LayoutOrder = 5,
HasIcon = true,
Text = "Example Text with Icon",
}),
})
end
return createStory(Story)
| 635 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/Checkbox.story.luau | local React = require("@pkg/@jsdotlua/react")
local Checkbox = require("../Components/Checkbox")
local createStory = require("./Helpers/createStory")
local function StoryItem(props: {
LayoutOrder: number,
Value: boolean?,
Label: string,
})
return React.createElement("Frame", {
Size = UDim2.new(0, 200, 0, 50),
BackgroundTransparency = 1,
LayoutOrder = props.LayoutOrder,
}, {
Layout = React.createElement("UIListLayout", {
SortOrder = Enum.SortOrder.LayoutOrder,
Padding = UDim.new(0, 2),
VerticalAlignment = Enum.VerticalAlignment.Center,
}),
Enabled = React.createElement(Checkbox, {
Label = props.Label,
Value = props.Value,
OnChanged = function() end,
LayoutOrder = 1,
}),
Disabled = React.createElement(Checkbox, {
Label = `{props.Label} (Disabled)`,
Value = props.Value,
OnChanged = function() end,
Disabled = true,
LayoutOrder = 2,
}),
})
end
local function Story()
local value, setValue = React.useState(true)
return React.createElement(React.Fragment, {}, {
Interactive = React.createElement(Checkbox, {
Size = UDim2.fromOffset(200, 20),
Label = "Interactive (try me)",
Value = value,
OnChanged = function()
setValue(not value)
end,
LayoutOrder = 1,
}),
True = React.createElement(StoryItem, {
Label = "True",
Value = true,
LayoutOrder = 2,
}),
False = React.createElement(StoryItem, {
Label = "False",
Value = false,
LayoutOrder = 3,
}),
Indeterminate = React.createElement(StoryItem, {
Label = "Indeterminate",
Value = nil,
LayoutOrder = 4,
}),
})
end
return createStory(Story)
| 449 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/ColorPicker.story.luau | local React = require("@pkg/@jsdotlua/react")
local ColorPicker = require("../Components/ColorPicker")
local createStory = require("./Helpers/createStory")
local function StoryItem(props: { Disabled: boolean? })
local color, setColor = React.useState(Color3.fromRGB(255, 255, 0))
return React.createElement(ColorPicker, {
Color = color,
OnChanged = setColor,
Disabled = props.Disabled,
})
end
local function Story()
return React.createElement(React.Fragment, {}, {
Enabled = React.createElement(StoryItem),
Disabled = React.createElement(StoryItem, { Disabled = true }),
})
end
return createStory(Story)
| 142 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/DatePicker.story.luau | local React = require("@pkg/@jsdotlua/react")
local DatePicker = require("../Components/DatePicker")
local Label = require("../Components/Label")
local createStory = require("./Helpers/createStory")
local function Story()
local date, setDate = React.useState(DateTime.now())
return React.createElement(React.Fragment, {}, {
Picker = React.createElement(DatePicker, {
Date = date,
OnChanged = setDate,
LayoutOrder = 1,
}),
Display = React.createElement(Label, {
LayoutOrder = 2,
Size = UDim2.new(1, 0, 0, 20),
Text = `Selected: {date:FormatUniversalTime("LL", "en-us")}`,
}),
})
end
return createStory(Story)
| 164 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/DropShadowFrame.story.luau | local React = require("@pkg/@jsdotlua/react")
local Checkbox = require("../Components/Checkbox")
local DropShadowFrame = require("../Components/DropShadowFrame")
local Label = require("../Components/Label")
local createStory = require("./Helpers/createStory")
local function Story()
local boxValue, setBoxValue = React.useState(false)
return React.createElement(DropShadowFrame, {
Size = UDim2.fromOffset(175, 75),
}, {
Layout = React.createElement("UIListLayout", {
SortOrder = Enum.SortOrder.LayoutOrder,
Padding = UDim.new(0, 10),
}),
Padding = React.createElement("UIPadding", {
PaddingLeft = UDim.new(0, 10),
PaddingRight = UDim.new(0, 10),
PaddingTop = UDim.new(0, 10),
PaddingBottom = UDim.new(0, 10),
}),
Label = React.createElement(Label, {
LayoutOrder = 1,
Text = "Example label",
Size = UDim2.new(1, 0, 0, 16),
TextXAlignment = Enum.TextXAlignment.Left,
}),
Checkbox = React.createElement(Checkbox, {
LayoutOrder = 2,
Value = boxValue,
OnChanged = function()
setBoxValue(not boxValue)
end,
Label = "Example checkbox",
}),
})
end
return createStory(Story)
| 322 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/Dropdown.story.luau | local React = require("@pkg/@jsdotlua/react")
local Constants = require("../Constants")
local Dropdown = require("../Components/Dropdown")
local createStory = require("./Helpers/createStory")
local useTheme = require("../Hooks/useTheme")
local classNames = {
"Part",
"Script",
"Player",
"Folder",
"Tool",
"SpawnLocation",
"MeshPart",
"Model",
"ClickDetector",
"Decal",
"ProximityPrompt",
"SurfaceAppearance",
"Texture",
"Animation",
"Accessory",
"Humanoid",
}
-- hack to get themed class images
local function getClassImage(className: string, theme: StudioTheme)
return `rbxasset://studio_svg_textures/Shared/InsertableObjects/{theme}/Standard/{className}.png`
end
local function StoryItem(props: {
LayoutOrder: number,
Disabled: boolean?,
})
local theme = useTheme()
local selectedClassName: string?, setSelectedClassName = React.useState(nil :: string?)
local classes = {}
for i, className in classNames do
classes[i] = {
Id = className,
Text = className,
Icon = {
Image = getClassImage(className, theme),
Size = Vector2.one * 16,
},
}
end
return React.createElement(Dropdown, {
Size = UDim2.fromOffset(200, Constants.DefaultDropdownHeight),
BackgroundTransparency = 1,
LayoutOrder = props.LayoutOrder,
Items = classes,
SelectedItem = selectedClassName,
OnItemSelected = function(newName: string?)
setSelectedClassName(newName)
end,
DefaultText = "Select a Class...",
MaxVisibleRows = 8,
RowHeight = 24,
ClearButton = true,
Disabled = props.Disabled,
})
end
local function Story()
return React.createElement(React.Fragment, {}, {
Enabled = React.createElement(StoryItem, {
LayoutOrder = 1,
}),
Disabled = React.createElement(StoryItem, {
LayoutOrder = 2,
Disabled = true,
}),
})
end
return createStory(Story)
| 465 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/Helpers/createStory.luau | local React = require("@pkg/@jsdotlua/react")
local ReactRoblox = require("@pkg/@jsdotlua/react-roblox")
local PluginProvider = require("../../Components/PluginProvider")
local ScrollFrame = require("../../Components/ScrollFrame")
local ThemeContext = require("../../Contexts/ThemeContext")
local getStoryPlugin = require("./getStoryPlugin")
local themes = settings().Studio:GetAvailableThemes()
themes[1], themes[2] = themes[2], themes[1]
local function StoryTheme(props: {
Theme: StudioTheme,
Size: UDim2,
LayoutOrder: number,
} & {
children: React.ReactNode,
})
return React.createElement("Frame", {
Size = props.Size,
LayoutOrder = props.LayoutOrder,
BackgroundColor3 = props.Theme:GetColor(Enum.StudioStyleGuideColor.MainBackground),
BorderSizePixel = 0,
}, {
Provider = React.createElement(ThemeContext.Provider, {
value = props.Theme,
}, {
Inner = React.createElement(ScrollFrame, {
Layout = {
ClassName = "UIListLayout",
SortOrder = Enum.SortOrder.LayoutOrder,
HorizontalAlignment = Enum.HorizontalAlignment.Center,
VerticalAlignment = Enum.VerticalAlignment.Center,
Padding = UDim.new(0, 10),
},
PaddingLeft = UDim.new(0, 10),
PaddingRight = UDim.new(0, 10),
PaddingTop = UDim.new(0, 10),
PaddingBottom = UDim.new(0, 10),
}, props.children),
}),
})
end
local function createStory(component: React.FC<any>)
return function(target: Frame)
local items: { React.ReactNode } = {}
local order = 0
local function getOrder()
order += 1
return order
end
for i, theme in themes do
local widthOffset = if #themes > 2 and i == #themes then -1 else 0
if i == 1 and #themes > 1 then
widthOffset -= 1
end
table.insert(
items,
React.createElement(StoryTheme, {
Theme = theme,
Size = UDim2.new(1 / #themes, widthOffset, 1, 0),
LayoutOrder = getOrder(),
}, React.createElement(component))
)
-- invisible divider to prevent scrollframe edges overlapping as
-- they have default borders (outside, not inset)
if i < #themes then
table.insert(
items,
React.createElement("Frame", {
Size = UDim2.new(0, 2, 1, 0),
BackgroundTransparency = 1,
LayoutOrder = getOrder(),
})
)
end
end
local element = React.createElement(PluginProvider, {
Plugin = getStoryPlugin(),
}, {
Layout = React.createElement("UIListLayout", {
SortOrder = Enum.SortOrder.LayoutOrder,
FillDirection = Enum.FillDirection.Horizontal,
}),
Padding = React.createElement("UIPadding", {
PaddingBottom = UDim.new(0, 45), -- tray buttons
}),
}, items)
local root = ReactRoblox.createRoot(Instance.new("Folder"))
local portal = ReactRoblox.createPortal(element, target)
root:render(portal)
return function()
root:unmount()
end
end
end
return createStory
| 765 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/Helpers/getStoryPlugin.luau | --!nocheck
--!nolint UnknownGlobal
-- selene: allow(undefined_variable)
local plugin = PluginManager():CreatePlugin()
return function()
return plugin
end
| 38 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/Helpers/studiocomponents.storybook.luau | --!nocheck
local React = require("@pkg/@jsdotlua/react")
local ReactRoblox = require("@pkg/@jsdotlua/react-roblox")
return {
name = "StudioComponents",
storyRoots = {
script.Parent.Parent,
},
packages = {
React = React,
ReactRoblox = ReactRoblox,
},
}
| 78 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/Label.story.luau | local React = require("@pkg/@jsdotlua/react")
local Label = require("../Components/Label")
local createStory = require("./Helpers/createStory")
local styles = {
Enum.StudioStyleGuideColor.MainText,
Enum.StudioStyleGuideColor.SubText,
Enum.StudioStyleGuideColor.TitlebarText,
Enum.StudioStyleGuideColor.BrightText,
Enum.StudioStyleGuideColor.DimmedText,
Enum.StudioStyleGuideColor.ButtonText,
Enum.StudioStyleGuideColor.LinkText,
Enum.StudioStyleGuideColor.WarningText,
Enum.StudioStyleGuideColor.ErrorText,
Enum.StudioStyleGuideColor.InfoText,
}
local function StoryItem(props: {
TextColorStyle: Enum.StudioStyleGuideColor,
LayoutOrder: number,
})
return React.createElement("Frame", {
Size = UDim2.new(0, 170, 0, 40),
LayoutOrder = props.LayoutOrder,
BackgroundTransparency = 1,
}, {
Enabled = React.createElement(Label, {
Text = props.TextColorStyle.Name,
TextColorStyle = props.TextColorStyle,
TextXAlignment = Enum.TextXAlignment.Center,
Size = UDim2.new(1, 0, 0, 20),
}),
Disabled = React.createElement(Label, {
Text = `{props.TextColorStyle.Name} (Disabled)`,
Size = UDim2.new(1, 0, 0, 20),
Position = UDim2.fromOffset(0, 20),
TextColorStyle = props.TextColorStyle,
TextXAlignment = Enum.TextXAlignment.Center,
Disabled = true,
}),
})
end
local function Story()
local items = {}
for i, style in styles do
items[i] = React.createElement(StoryItem, {
TextColorStyle = style,
LayoutOrder = i,
})
end
return React.createElement(React.Fragment, {}, items)
end
return createStory(Story)
| 429 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/LoadingDots.story.luau | local React = require("@pkg/@jsdotlua/react")
local LoadingDots = require("../Components/LoadingDots")
local createStory = require("./Helpers/createStory")
local function Story()
return React.createElement(LoadingDots, {})
end
return createStory(Story)
| 56 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/MainButton.story.luau | local React = require("@pkg/@jsdotlua/react")
local MainButton = require("../Components/MainButton")
local createStory = require("./Helpers/createStory")
local function StoryButton(props: {
Text: string?,
HasIcon: boolean?,
Disabled: boolean?,
})
return React.createElement(MainButton, {
LayoutOrder = if props.Disabled then 2 else 1,
Icon = if props.HasIcon
then {
Image = "rbxasset://studio_svg_textures/Shared/InsertableObjects/Dark/Standard/Part.png",
Size = Vector2.one * 16,
UseThemeColor = true,
Alignment = Enum.HorizontalAlignment.Left,
}
else nil,
Text = props.Text,
OnActivated = if not props.Disabled then function() end else nil,
Disabled = props.Disabled,
AutomaticSize = Enum.AutomaticSize.XY,
})
end
local function StoryItem(props: {
LayoutOrder: number,
Text: string?,
HasIcon: boolean?,
Disabled: boolean?,
})
local height, setHeight = React.useBinding(0)
return React.createElement("Frame", {
Size = height:map(function(value)
return UDim2.new(1, 0, 0, value)
end),
LayoutOrder = props.LayoutOrder,
BackgroundTransparency = 1,
}, {
Layout = React.createElement("UIListLayout", {
Padding = UDim.new(0, 10),
SortOrder = Enum.SortOrder.LayoutOrder,
FillDirection = Enum.FillDirection.Horizontal,
HorizontalAlignment = Enum.HorizontalAlignment.Center,
[React.Change.AbsoluteContentSize] = function(rbx)
setHeight(rbx.AbsoluteContentSize.Y)
end,
}),
Enabled = React.createElement(StoryButton, {
Text = props.Text,
HasIcon = props.HasIcon,
}),
-- Disabled = React.createElement(StoryButton, {
-- Text = props.Text,
-- HasIcon = props.HasIcon,
-- Disabled = true,
-- }),
})
end
local function Story()
return React.createElement(React.Fragment, {}, {
Icon = React.createElement(StoryItem, {
LayoutOrder = 1,
HasIcon = true,
}),
Text = React.createElement(StoryItem, {
LayoutOrder = 2,
Text = "Example Text",
}),
TextLonger = React.createElement(StoryItem, {
LayoutOrder = 3,
Text = "Example Longer Text",
}),
TextMulti = React.createElement(StoryItem, {
LayoutOrder = 4,
Text = "Example Text\nover two lines",
}),
IconTextIcon = React.createElement(StoryItem, {
LayoutOrder = 5,
HasIcon = true,
Text = "Example Text with Icon",
}),
})
end
return createStory(Story)
| 636 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/NumberSequencePicker.story.luau | local React = require("@pkg/@jsdotlua/react")
local NumberSequencePicker = require("../Components/NumberSequencePicker")
local createStory = require("./Helpers/createStory")
local function Story()
local value, setValue = React.useState(NumberSequence.new({
NumberSequenceKeypoint.new(0.0, 0.00),
NumberSequenceKeypoint.new(0.4, 0.75, 0.10),
NumberSequenceKeypoint.new(0.5, 0.45, 0.15),
NumberSequenceKeypoint.new(0.8, 0.75),
NumberSequenceKeypoint.new(1.0, 0.50),
}))
return React.createElement("Frame", {
BackgroundTransparency = 1,
Size = UDim2.fromScale(1, 1),
}, {
Picker = React.createElement(NumberSequencePicker, {
Value = value,
OnChanged = setValue,
AnchorPoint = Vector2.new(0.5, 0.5),
Position = UDim2.fromScale(0.5, 0.5),
}),
})
end
return createStory(Story)
| 257 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/NumericInput.story.luau | local React = require("@pkg/@jsdotlua/react")
local Constants = require("../Constants")
local NumericInput = require("../Components/NumericInput")
local createStory = require("./Helpers/createStory")
local function StoryItem(props: {
LayoutOrder: number,
Arrows: boolean?,
Slider: boolean?,
})
local value, setValue = React.useState(5)
local min = 0
local max = 10
local step = 0.25
local function format(n: number)
return string.format("%.2f", n)
end
return React.createElement("Frame", {
LayoutOrder = props.LayoutOrder,
Size = UDim2.new(0, 150, 0, Constants.DefaultInputHeight * 2 + 10),
BackgroundTransparency = 1,
}, {
Enabled = React.createElement(NumericInput, {
LayoutOrder = 1,
Size = UDim2.new(1, 0, 0, Constants.DefaultInputHeight),
Value = value,
Min = min,
Max = max,
Step = step,
ClearTextOnFocus = false,
OnValidChanged = setValue,
FormatValue = format,
Arrows = props.Arrows,
Slider = props.Slider,
}),
Disabled = React.createElement(NumericInput, {
LayoutOrder = 3,
Size = UDim2.new(1, 0, 0, Constants.DefaultInputHeight),
Position = UDim2.fromOffset(0, Constants.DefaultInputHeight + 5),
Value = value,
Min = min,
Max = max,
Step = step,
ClearTextOnFocus = false,
OnValidChanged = function() end,
FormatValue = format,
Arrows = props.Arrows,
Slider = props.Slider,
Disabled = true,
}),
})
end
local function Story()
return React.createElement(React.Fragment, {}, {
Regular = React.createElement(StoryItem, {
LayoutOrder = 1,
}),
Arrows = React.createElement(StoryItem, {
LayoutOrder = 2,
Arrows = true,
}),
Slider = React.createElement(StoryItem, {
LayoutOrder = 3,
Slider = true,
}),
Both = React.createElement(StoryItem, {
LayoutOrder = 4,
Arrows = true,
Slider = true,
}),
})
end
return createStory(Story)
| 551 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/ProgressBar.story.luau | local React = require("@pkg/@jsdotlua/react")
local ProgressBar = require("../Components/ProgressBar")
local createStory = require("./Helpers/createStory")
local HEIGHT = 14
local function StoryItem(props: {
Value: number,
Max: number?,
Formatter: ((number, number) -> string)?,
LayoutOrder: number,
})
return React.createElement("Frame", {
Size = UDim2.new(1, 0, 0, HEIGHT),
LayoutOrder = props.LayoutOrder,
BackgroundTransparency = 1,
}, {
Enabled = React.createElement(ProgressBar, {
Value = props.Value,
Max = props.Max,
Formatter = props.Formatter,
--Size = UDim2.new(0.5, -5, 1, 0),
Size = UDim2.new(0, 225, 1, 0),
Position = UDim2.fromOffset(20, 0),
}),
-- Disabled = React.createElement(ProgressBar, {
-- Value = props.Value,
-- Max = props.Max,
-- Formatter = props.Formatter,
-- AnchorPoint = Vector2.new(1, 0),
-- Position = UDim2.fromScale(1, 0),
-- Size = UDim2.new(0.5, -5, 1, 0),
-- Disabled = true,
-- }),
})
end
local function Story()
return React.createElement(React.Fragment, {}, {
Zero = React.createElement(StoryItem, {
Value = 0,
LayoutOrder = 1,
}),
Fifty = React.createElement(StoryItem, {
Value = 0.5,
LayoutOrder = 1,
}),
Hundred = React.createElement(StoryItem, {
Value = 1,
LayoutOrder = 2,
}),
Custom = React.createElement(StoryItem, {
Value = 5,
Max = 14,
LayoutOrder = 3,
Formatter = function(value, max)
return `loaded {value} / {max} assets`
end,
}),
})
end
return createStory(Story)
| 493 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/RadioButton.story.luau | local React = require("@pkg/@jsdotlua/react")
local RadioButton = require("../Components/RadioButton")
local createStory = require("./Helpers/createStory")
local function Story()
local value, setValue = React.useState(true)
return React.createElement(React.Fragment, {}, {
Enabled = React.createElement(RadioButton, {
Label = "Enabled",
Value = value,
OnChanged = function()
setValue(not value)
end,
LayoutOrder = 1,
}),
Disabled = React.createElement(RadioButton, {
Label = "Disabled",
Value = value,
Disabled = true,
LayoutOrder = 2,
}),
})
end
return createStory(Story)
| 148 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/ScrollFrame.story.luau | local React = require("@pkg/@jsdotlua/react")
local Constants = require("../Constants")
local ScrollFrame = require("../Components/ScrollFrame")
local createStory = require("./Helpers/createStory")
local numRows = 10
local numCols = 10
local size = Vector2.new(48, 32)
local function StoryRow(props: {
Row: number,
})
local children = {}
for i = 1, numCols do
children[i] = React.createElement("TextLabel", {
LayoutOrder = i,
Text = string.format("%i,%i", i - 1, props.Row - 1),
Font = Constants.DefaultFont,
TextSize = Constants.DefaultTextSize,
TextColor3 = Color3.fromRGB(0, 0, 0),
Size = UDim2.new(0, size.X, 1, 0),
BorderSizePixel = 0,
BackgroundTransparency = 0,
BackgroundColor3 = Color3.fromHSV((i + props.Row) % numCols / numCols, 0.6, 0.8),
})
end
return React.createElement("Frame", {
LayoutOrder = props.Row,
Size = UDim2.fromOffset(numCols * size.X, size.Y),
BackgroundTransparency = 1,
}, {
Layout = React.createElement("UIListLayout", {
FillDirection = Enum.FillDirection.Horizontal,
SortOrder = Enum.SortOrder.LayoutOrder,
}),
}, children)
end
local function StoryScroller(props: {
Size: UDim2,
LayoutOrder: number,
Disabled: boolean?,
})
local rows = {}
for i = 1, numRows do
rows[i] = React.createElement(StoryRow, { Row = i })
end
return React.createElement(ScrollFrame, {
ScrollingDirection = Enum.ScrollingDirection.XY,
Size = props.Size,
Disabled = props.Disabled,
Layout = {
ClassName = "UIListLayout",
SortOrder = Enum.SortOrder.LayoutOrder,
},
}, rows)
end
local function Story()
return React.createElement(React.Fragment, {}, {
Enabled = React.createElement(StoryScroller, {
Size = UDim2.new(1, -10, 0, 220),
LayoutOrder = 1,
}),
Disabled = React.createElement(StoryScroller, {
Size = UDim2.new(1, -10, 0, 220),
LayoutOrder = 2,
Disabled = true,
}),
})
end
return createStory(Story)
| 564 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/Slider.story.luau | local React = require("@pkg/@jsdotlua/react")
local Slider = require("../Components/Slider")
local createStory = require("./Helpers/createStory")
local function StoryItem(props: {
LayoutOrder: number,
Disabled: boolean?,
})
local value, setValue = React.useState(3)
return React.createElement(Slider, {
Value = value,
Min = 0,
Max = 10,
Step = 0,
OnChanged = setValue,
Disabled = props.Disabled,
})
end
local function Story()
return React.createElement(React.Fragment, {}, {
Enabled = React.createElement(StoryItem, {
LayoutOrder = 1,
}),
Disabled = React.createElement(StoryItem, {
LayoutOrder = 2,
Disabled = true,
}),
})
end
return createStory(Story)
| 183 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/Splitter.story.luau | local React = require("@pkg/@jsdotlua/react")
local Label = require("../Components/Label")
local Splitter = require("../Components/Splitter")
local createStory = require("./Helpers/createStory")
local useTheme = require("../Hooks/useTheme")
local function StoryItem(props: {
Size: UDim2,
LayoutOrder: number,
Disabled: boolean?,
})
local theme = useTheme()
local alpha0, setAlpha0 = React.useState(0.5)
local alpha1, setAlpha1 = React.useState(0.5)
local postText = if props.Disabled then "\n(Disabled)" else ""
return React.createElement("Frame", {
Size = props.Size,
LayoutOrder = props.LayoutOrder,
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainBackground),
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Border),
BorderMode = Enum.BorderMode.Inset,
}, {
Splitter = React.createElement(Splitter, {
Alpha = alpha0,
OnChanged = setAlpha0,
FillDirection = Enum.FillDirection.Vertical,
Disabled = props.Disabled,
}, {
Side0 = React.createElement(Label, {
Text = "Top" .. postText,
Disabled = props.Disabled,
}),
Side1 = React.createElement(Splitter, {
Alpha = alpha1,
OnChanged = setAlpha1,
FillDirection = Enum.FillDirection.Horizontal,
Disabled = props.Disabled,
}, {
Side0 = React.createElement(Label, {
Text = "Bottom Left" .. postText,
Disabled = props.Disabled,
}),
Side1 = React.createElement(Label, {
Text = "Bottom Right" .. postText,
Disabled = props.Disabled,
}),
}),
}),
})
end
local function Story()
return React.createElement(React.Fragment, {}, {
Enabled = React.createElement(StoryItem, {
Size = UDim2.new(1, 0, 0.5, -5),
LayoutOrder = 1,
}),
Disabled = React.createElement(StoryItem, {
Size = UDim2.new(1, 0, 0.5, -5),
LayoutOrder = 2,
Disabled = true,
}),
})
end
return createStory(Story)
| 510 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/TabContainer.story.luau | local React = require("@pkg/@jsdotlua/react")
local TabContainer = require("../Components/TabContainer")
local createStory = require("./Helpers/createStory")
local function StoryItemContent(props: {
BackgroundColor3: Color3,
})
return React.createElement("Frame", {
Position = UDim2.fromOffset(10, 10),
Size = UDim2.fromOffset(50, 50),
BackgroundColor3 = props.BackgroundColor3,
})
end
local function StoryItem(props: {
LayoutOrder: number,
Disabled: boolean?,
})
local selected, setSelected = React.useState("First")
return React.createElement(TabContainer, {
Size = UDim2.new(1, -50, 0.5, -50),
LayoutOrder = props.LayoutOrder,
SelectedTab = selected,
OnTabSelected = setSelected,
Disabled = props.Disabled,
}, {
First = {
LayoutOrder = 1,
Content = React.createElement(StoryItemContent, {
BackgroundColor3 = Color3.fromRGB(255, 0, 255),
}),
},
Second = {
LayoutOrder = 2,
Content = React.createElement(StoryItemContent, {
BackgroundColor3 = Color3.fromRGB(255, 255, 0),
}),
},
Third = {
LayoutOrder = 3,
Content = React.createElement(StoryItemContent, {
BackgroundColor3 = Color3.fromRGB(0, 255, 255),
}),
Disabled = true,
},
})
end
local function Story()
return React.createElement(React.Fragment, {}, {
Enabled = React.createElement(StoryItem, {
LayoutOrder = 1,
}),
Disabled = React.createElement(StoryItem, {
LayoutOrder = 2,
Disabled = true,
}),
})
end
return createStory(Story)
| 419 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/Stories/TextInput.story.luau | local React = require("@pkg/@jsdotlua/react")
local TextInput = require("../Components/TextInput")
local createStory = require("./Helpers/createStory")
local function StoryItem(props: {
Label: string,
LayoutOrder: number,
Disabled: boolean?,
Filter: ((s: string) -> string)?,
})
local text, setText = React.useState(if props.Disabled then props.Label else "")
return React.createElement("Frame", {
Size = UDim2.fromOffset(175, 20),
LayoutOrder = props.LayoutOrder,
BackgroundTransparency = 1,
}, {
Input = React.createElement(TextInput, {
Text = text,
PlaceholderText = props.Label,
Disabled = props.Disabled,
OnChanged = function(newText)
local filtered = newText
if props.Filter then
filtered = props.Filter(newText)
end
setText(filtered)
end,
}),
})
end
local function Story()
return React.createElement(React.Fragment, {}, {
Enabled = React.createElement(StoryItem, {
Label = "Any text allowed",
LayoutOrder = 1,
}),
Filtered = React.createElement(StoryItem, {
Label = "Numbers only",
LayoutOrder = 2,
Filter = function(text)
return (string.gsub(text, "%D", ""))
end,
}),
Disabled = React.createElement(StoryItem, {
Label = "Disabled",
LayoutOrder = 3,
Disabled = true,
}),
})
end
return createStory(Story)
| 336 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/getTextSize.luau | local TextService = game:GetService("TextService")
local Constants = require("./Constants")
local TEXT_SIZE = Constants.DefaultTextSize
local FONT = Constants.DefaultFont
local FRAME_SIZE = Vector2.one * math.huge
local function getTextSize(text: string)
local size = TextService:GetTextSize(text, TEXT_SIZE, FONT, FRAME_SIZE)
return Vector2.new(math.ceil(size.X), math.ceil(size.Y)) + Vector2.one
end
return getTextSize
| 97 |
sircfenner/StudioComponents | sircfenner-StudioComponents-ceb9d45/src/init.luau | return {
Constants = require("./Constants"),
Background = require("./Components/Background"),
Button = require("./Components/Button"),
Checkbox = require("./Components/Checkbox"),
ColorPicker = require("./Components/ColorPicker"),
DatePicker = require("./Components/DatePicker"),
Dropdown = require("./Components/Dropdown"),
DropShadowFrame = require("./Components/DropShadowFrame"),
Label = require("./Components/Label"),
LoadingDots = require("./Components/LoadingDots"),
MainButton = require("./Components/MainButton"),
NumberSequencePicker = require("./Components/NumberSequencePicker"),
NumericInput = require("./Components/NumericInput"),
PluginProvider = require("./Components/PluginProvider"),
ProgressBar = require("./Components/ProgressBar"),
RadioButton = require("./Components/RadioButton"),
ScrollFrame = require("./Components/ScrollFrame"),
Slider = require("./Components/Slider"),
Splitter = require("./Components/Splitter"),
TabContainer = require("./Components/TabContainer"),
TextInput = require("./Components/TextInput"),
ThemeContext = require("./Contexts/ThemeContext"),
useTheme = require("./Hooks/useTheme"),
usePlugin = require("./Hooks/usePlugin"),
useMouseIcon = require("./Hooks/useMouseIcon"),
}
| 251 |
ffrostfall/crunchyroll | ffrostfall-crunchyroll-736bdb0/.lune/build-rbxm.luau | local process = require("@lune/process")
process.exec("rojo", { "build", "--output", "crunchyroll.rbxm" }, { stdio = "forward" })
| 40 |
ffrostfall/crunchyroll | ffrostfall-crunchyroll-736bdb0/.lune/clone-mirrors.luau | local fs = require("@lune/fs")
local process = require("@lune/process")
local serde = require("@lune/serde")
local mirror_configs = fs.readDir("./benches/mirror_list")
-- thank you nick from lute
local function get_git_version(): { major: number, minor: number, path: number }
local git_ver_string = process.exec("git", { "--version" }).stdout
local git_ver = string.split(git_ver_string, " ")[3]
local components = string.split(git_ver, ".")
return {
major = tonumber(components[1]) or 0,
minor = tonumber(components[2]) or 0,
path = tonumber(components[3]) or 0,
}
end
local git_version = get_git_version()
for _, file_name in mirror_configs do
local path = "./benches/mirror_list/" .. file_name
local config: unknown = serde.decode("toml", fs.readFile(path))
assert(type(config) == "table", `[mirror] {path} must be a table`)
-- Lovely type errors :3
assert(type(config.revision) == "string", `[mirror] {path} config.revision must be a string`)
assert(type(config.branch) == "string", `[mirror] {path} config.branch must be a string`)
assert(type(config.name) == "string", `[mirror] {path} config.name must be a string`)
assert(type(config.remote) == "string", `[mirror] {path} config.remote must be a string`)
local mirror_path = "./benches/mirrors/" .. config.name
local full_mirror_path = mirror_path .. "/src/"
if fs.isDir(mirror_path) then
process.exec(
"git",
{ "fetch", "--depth=1", "origin", config.revision },
{ stdio = "forward", cwd = full_mirror_path }
)
process.exec(
"git",
{ "checkout", config.revision },
{ stdio = "forward", cwd = full_mirror_path }
)
continue
end
if git_version.major >= 3 or (git_version.major == 2 and git_version.minor >= 49) then
process.exec("git", {
"clone",
"--depth=1",
"--revision",
config.revision,
config.remote,
full_mirror_path,
})
else
process.exec("git", {
"clone",
"--depth=1",
"--branch",
config.branch,
config.remote,
full_mirror_path,
})
end
end
| 557 |
ffrostfall/crunchyroll | ffrostfall-crunchyroll-736bdb0/.lune/dev.luau | local process = require("@lune/process")
local task = require("@lune/task")
task.spawn(function()
process.exec("rojo", {
"sourcemap",
"roblox-tests.project.json",
"--output",
"sourcemap.json",
"--watch",
"--include-non-scripts",
}, {
stdio = "forward",
})
end)
task.spawn(function()
process.exec("rojo", { "serve", "roblox-tests.project.json" }, { stdio = "forward" })
end)
| 116 |
ffrostfall/crunchyroll | ffrostfall-crunchyroll-736bdb0/.lune/styling.luau | local process = require("@lune/process")
local directories = { ".lune", "src", "tests" }
-- kinda cursed but, easiest way to do this.
table.insert(directories, "--check")
local result = process.exec("stylua", directories, {
stdio = "forward",
})
process.exit(result.code)
| 68 |
ffrostfall/crunchyroll | ffrostfall-crunchyroll-736bdb0/benches/create_bench.luau | export type Profiler = { Begin: (label: string) -> (), stop: () -> () }
local function create_bench<T...>(
parameter_generator: () -> T...,
bench_table: {
[string]: (profiler: Profiler, T...) -> (),
}
): any
return {
Functions = bench_table,
ParameterGenerator = parameter_generator,
}
end
return create_bench
| 89 |
ffrostfall/crunchyroll | ffrostfall-crunchyroll-736bdb0/benches/create_entry.luau | local ReplicatedStorage = game:GetService("ReplicatedStorage")
local create_bench = require(ReplicatedStorage.benches.create_bench)
local rig_template = require(ReplicatedStorage.client.rig) :: any
local SAMPLES = 500
local ANIMATION_TEMPLATE = ReplicatedStorage.benches.assets.orange_justice
type Rig = { __symbol: "RigSymbol" }
type Animation = { __symbol: "AnimationSymbol" }
type Profiler = create_bench.Profiler
export type Crunchyroll = {
create_rig: (root: typeof(rig_template)) -> Rig,
solve_animation: (
rig: Rig,
animations: {
[Animation]: {
start_fade_time: number,
stop_fade_time: number,
weight: number,
priority: number,
alpha: number,
},
},
root: CFrame
) -> (),
load_keyframe_sequence: (keyframe_sequence: KeyframeSequence, rig: Rig?) -> Animation,
}
local function create_entry<T...>(library: Crunchyroll): (Profiler, T...) -> ()
local rig = library.create_rig(rig_template)
local animation = library.load_keyframe_sequence(ANIMATION_TEMPLATE, rig)
return function(Profiler: Profiler, ...)
for index = 1, SAMPLES do
library.solve_animation(rig, {
[animation] = {
priority = 1,
start_fade_time = 0,
stop_fade_time = 0,
weight = 1,
alpha = (index / SAMPLES),
},
}, CFrame.identity)
end
end
end
return create_entry
| 363 |
ffrostfall/crunchyroll | ffrostfall-crunchyroll-736bdb0/benches/solver.bench.luau | local ReplicatedStorage = game:GetService("ReplicatedStorage")
local create_bench = require(ReplicatedStorage.benches.create_bench)
local create_entry = require(ReplicatedStorage.benches.create_entry)
type Crunchyroll = create_entry.Crunchyroll
local entries = {
latest = create_entry(require(ReplicatedStorage.crunchyroll:Clone()) :: Crunchyroll),
}
for _, mirror in ReplicatedStorage.benches.mirrors:GetChildren() do
local label = mirror.Name
assert(entries[label] == nil, `duplicate bench entry "{label}"`)
local module = assert(mirror:FindFirstChild("crunchyroll"))
local library = (require)(module:Clone()) :: Crunchyroll
entries[label] = create_entry(library)
end
return create_bench(function() end, entries)
| 176 |
ffrostfall/crunchyroll | ffrostfall-crunchyroll-736bdb0/src/animation_solver.luau | local animation_asset = require("./roblox/animation_asset")
local create_rig = require("./rig")
export type AnimationTrack = {
-- 0-1
alpha: number,
-- 0-1
start_fade_time: number,
stop_fade_time: number,
weight: number,
-- arbitrary number
priority: number,
}
local function quat_dot(a_vector: vector, a_scalar: number, b_vector: vector, b_scalar: number)
return vector.dot(a_vector, b_vector) + (a_scalar * b_scalar)
end
local function quat_nlerp(
a_vector: vector,
a_scalar: number,
b_vector: vector,
b_scalar: number,
t: number
): (vector, number)
if quat_dot(a_vector, a_scalar, b_vector, b_scalar) < 0 then
b_vector, b_scalar = -b_vector, -b_scalar
end
local quat_vector = vector.lerp(a_vector, b_vector, t)
local quat_scalar = math.lerp(a_scalar, b_scalar, t)
local magnitude =
math.sqrt((vector.dot(quat_vector, quat_vector) + (quat_scalar * quat_scalar)))
return quat_vector / magnitude, quat_scalar / magnitude
end
local function solve_fade_time_influence(
real_time: number,
animation_length: number,
start_fade_time: number,
stop_fade_time: number
): number
if real_time <= start_fade_time then
return math.min(1, 1 - ((start_fade_time - real_time) / start_fade_time))
elseif real_time >= (animation_length + stop_fade_time) then
return math.min(
1,
1 - ((real_time - (animation_length - stop_fade_time)) / stop_fade_time)
)
else
return 1
end
end
local function animation_solver(
rig: create_rig.Identity,
tracks: {
[animation_asset.Identity]: AnimationTrack,
},
root: CFrame,
skip_result_coordinate_frames: boolean?
)
local limb_transforms = rig.limb_transforms
for _, limb in limb_transforms do
limb.priority = -1
end
local total_weight = 0
for _, track in tracks do
total_weight += track.weight
end
for animation, playback in tracks do
local priority = playback.priority
local real_time = animation.length * playback.alpha
local influence = (playback.weight / total_weight)
* solve_fade_time_influence(
real_time,
animation.length,
playback.start_fade_time,
playback.stop_fade_time
)
-- Figure out which keyframes to interpolate between
local keyframe_times = animation.keyframe_times
local high: number = #keyframe_times
local low: number = 1
while high > low do
local index: number = bit32.rshift(low + high, 1)
if keyframe_times[index + 1] >= real_time then
high = index
else
low = index + 1
end
end
local pose_time_after: number? = keyframe_times[high + 1]
local pose_time_before: number? = keyframe_times[high]
local poses_before: animation_asset.Poses? = animation.keyframe_poses[high]
local poses_after: animation_asset.Poses? = animation.keyframe_poses[high + 1]
-- Solve limb transforms
for index, node in limb_transforms do
if node.priority > priority then
continue
end
-- find holes in the animation
local left_pose = poses_before and poses_before[index]
local time_before = pose_time_before
if left_pose == nil then
local left_pose_pointer = if animation.keyframe_holes[index]
then animation.keyframe_holes[index][high][1]
else 1
left_pose = animation.keyframe_poses[left_pose_pointer][index]
time_before = keyframe_times[left_pose_pointer]
end
local right_pose = poses_after and poses_after[index]
local time_after = pose_time_after
local pointer = animation.keyframe_holes[index]
and animation.keyframe_holes[index][high + 1]
local right_pose_pointer = pointer and pointer[2]
if right_pose_pointer then
right_pose = animation.keyframe_poses[right_pose_pointer][index]
time_after = keyframe_times[right_pose_pointer]
end
--stylua: ignore start
if left_pose and right_pose then
local alpha = left_pose.easing_function((real_time - (time_before :: number)) / ((time_after :: number) - (time_before :: number)))
local position = vector.lerp(left_pose.position, right_pose.position, alpha)
local quat_vector, quat_scalar = quat_nlerp(
left_pose.quat_vector, left_pose.quat_scalar,
right_pose.quat_vector, right_pose.quat_scalar,
alpha
)
node.position = vector.lerp(node.position, position, influence)
node.quat_vector, node.quat_scalar = quat_nlerp(
node.quat_vector, node.quat_scalar,
quat_vector, quat_scalar,
influence
)
node.priority = priority
elseif left_pose then
node.position = vector.lerp(node.position, left_pose.position, influence)
node.quat_vector, node.quat_scalar = quat_nlerp(
node.quat_vector, node.quat_scalar,
left_pose.quat_vector, left_pose.quat_scalar, influence
)
node.priority = priority
end
--stylua: ignore end
end
end
if not skip_result_coordinate_frames then
local result_coordinate_frames: { [string]: CFrame } = rig.result_coordinate_frames
result_coordinate_frames["root"] = root
for index, limb in rig.limbs do
local limb_transform = limb_transforms[index]
local position = limb_transform.position
local quat_vector = limb_transform.quat_vector
local quat_scalar = limb_transform.quat_scalar
--stylua: ignore
local transform = CFrame.new(
position.x, position.y, position.z,
quat_vector.x, quat_vector.y, quat_vector.z, quat_scalar
)
result_coordinate_frames[limb.name] = result_coordinate_frames[limb.depends_on]
* limb.c0
* transform
* limb.c1
end
end
end
return {
solve_fade_time_influence = solve_fade_time_influence,
solver = animation_solver,
}
| 1,439 |
ffrostfall/crunchyroll | ffrostfall-crunchyroll-736bdb0/src/easings.luau | --!native
local function linear(value: number): number
return value
end
local function cubic_in(alpha: number): number
return alpha ^ 3
end
local function cubic_out(alpha: number): number
return 1 - ((1 - alpha) ^ 3)
end
local function cubic_in_out(alpha: number): number
if alpha < 0.5 then
return 4 * (alpha ^ 3)
end
return 1 - ((-2 * alpha + 2) ^ 3) * 0.5
end
local function bounce_in(alpha: number): number
local Compliment = 1 - alpha
if Compliment < 0.36363636363636365 then
return 1 - 7.5625 * Compliment * Compliment
end
if Compliment < 0.7272727272727273 then
local Base = Compliment - 0.5454545454545454
return 1 - 7.5625 * Base * Base + 0.75
end
if Compliment < 0.9090909090909091 then
local Base = Compliment - 0.9090909090909091
return 1 - 7.5625 * Base * Base + 0.9375
end
local Base = Compliment - 0.9545454545454546
return 1 - 7.5625 * Base * Base + 0.984375
end
local function bounce_out(alpha: number): number
if alpha < 0.36363636363636365 then
return 7.5625 * alpha * alpha
end
if alpha < 0.7272727272727273 then
local Base = alpha - 0.5454545454545454
return 7.5625 * Base * Base + 0.75
end
if alpha < 0.9090909090909091 then
local Base = alpha - 0.9090909090909091
return 7.5625 * Base * Base + 0.9375
end
local Base = alpha - 0.9545454545454546
return 7.5625 * Base * Base + 0.984375
end
local function bounce_in_out(Value: number): number
if Value < 0.5 then
local Compliment = 1 - 2 * Value
if Compliment < 0.36363636363636365 then
return (1 - 7.5625 * Compliment * Compliment) * 0.5
end
if Compliment < 0.7272727272727273 then
local Base = Compliment - 0.5454545454545454
return (1 - 7.5625 * Base * Base + 0.75) * 0.5
end
if Compliment < 0.9090909090909091 then
local Base = Compliment - 0.9090909090909091
return (1 - 7.5625 * Base * Base + 0.9375) * 0.5
end
local Base = Compliment - 0.9545454545454546
return (1 - 7.5625 * Base * Base + 0.984375) * 0.5
end
local Compliment = 2 * Value - 1
if Compliment < 0.36363636363636365 then
return (1 + 7.5625 * Compliment * Compliment) * 0.5
end
if Compliment < 0.7272727272727273 then
local Base = Compliment - 0.5454545454545454
return (1 + 7.5625 * Base * Base + 0.75) * 0.5
end
if Compliment < 0.9090909090909091 then
local Base = Compliment - 0.9090909090909091
return (1 + 7.5625 * Base * Base + 0.9375) * 0.5
end
local Base = Compliment - 0.9545454545454546
return (1 + 7.5625 * Base * Base + 0.984375) * 0.5
end
local function elastic_in(alpha: number): number
return -2 ^ (10 * alpha - 10) * math.sin((alpha * 10 - 10.75) * 2.0943951023931953)
end
local function elastic_out(Value: number): number
return 2 ^ (-10 * Value) * math.sin((Value * 10 - 0.75) * 2.0943951023931953) + 1
end
local function elastic_in_out(Value: number): number
if Value < 0.5 then
return -2 ^ (20 * Value - 10) * math.sin((20 * Value - 11.125) * 1.3962634015954636) * 0.5
end
return 2 ^ -20 * Value + 10 * math.sin(20 * Value - 11.125 * 1.3962634015954636) * 0.5 + 1
end
local function constant(Value: number): number
return 0
end
return {
linear = linear,
constant = constant,
cubic_in = cubic_in,
cubic_out = cubic_out,
cubic_in_out = cubic_in_out,
bounce_in = bounce_in,
bounce_out = bounce_out,
bounce_in_out = bounce_in_out,
elastic_in = elastic_in,
elastic_out = elastic_out,
elastic_in_out = elastic_in_out,
}
| 1,286 |
ffrostfall/crunchyroll | ffrostfall-crunchyroll-736bdb0/src/init.luau | local animation_asset = require("@self/roblox/animation_asset")
local animation_solver = require("@self/animation_solver")
local rig = require("@self/rig")
--[=[
@class Crunchyroll
The root module.
]=]
--[=[
@function load_keyframe_sequence
@within Crunchyroll
Load a keyframe sequence from Roblox. This will return an AnimationAsset.
@param keyframe_sequence KeyframeSequence
@return AnimationAsset
]=]
--[=[
@function create_rig
@within Crunchyroll
Create a rig from a model. This will return a Rig.
@param rig_hierarchy Limb
@return Rig
]=]
--[=[
@function solve_animation
@within Crunchyroll
The primary function of the module. This will solve the animation for a rig.
Example:
```lua
crunchyroll.solve_animation(rig, {
[animation] = {
priority = 1,
start_fade_time = 0,
stop_fade_time = 0,
weight = 1,
alpha = 0.5,
},
}, character.HumanoidRootPart.CFrame)
```
@param rig Rig
@param tracks { [AnimationAsset]: AnimationTrack }
@param root CFrame
@param skip_result_coordinate_frames boolean?
]=]
--[=[
@class Rig
An animated rig. Pass this into the animation solver.
]=]
--[=[
@prop result_coordinate_frames { [string]: CFrame }
@within Rig
The result table of the rig. Structured as { [limb name]: CFrame }
]=]
--[=[
@class AnimationAsset
An animation asset. This stores the animation length, and the keyframes.
]=]
--[=[
@interface AnimationTrack
@within Crunchyroll
.stop_fade_time number
.start_fade_time number
.weight number
.alpha number
.priority number
This table describes the state of an animation. It is agnostic to the animation asset.
]=]
--[=[
@interface Limb
@within Crunchyroll
.name string
.c0 CFrame
.c1 CFrame
.depends_on string
This is the Crunchyroll equivalent of a Roblox Motor6D.
`depends_on` is how the hierarchy works; for example "Head" depends on "Torso"
]=]
export type LimbInfo = rig.LimbInfo
export type Rig = rig.Identity
export type AnimationTrack = animation_solver.AnimationTrack
export type AnimationAsset = animation_asset.Identity
return {
load_keyframe_sequence = animation_asset.load_keyframe_sequence,
create_rig = rig.create_rig,
solve_animation = animation_solver.solver,
}
| 579 |
ffrostfall/crunchyroll | ffrostfall-crunchyroll-736bdb0/src/rig.luau | export type LimbInfo = {
c0: CFrame,
c1: CFrame,
name: string,
children: { LimbInfo }?,
}
export type Limb = {
name: string,
c0: CFrame,
c1: CFrame,
depends_on: string,
}
export type LimbTransform = {
priority: number,
position: vector,
quat_vector: vector,
quat_scalar: number,
}
export type Identity = {
limbs: { Limb },
limb_transforms: { LimbTransform },
--- used in animation loading to quickly map pose name to limb index
limb_name_to_index: { [string]: number },
result_coordinate_frames: { [string]: CFrame },
}
local function topological_sort(array: { Limb }, node: LimbInfo)
if not node.children then
return
end
for _, value in node.children do
table.insert(array, {
name = value.name,
depends_on = node.name,
c0 = value.c0,
c1 = value.c1:Inverse(),
})
topological_sort(array, value)
end
end
local function create_rig(root: LimbInfo): Identity
local limbs: { Limb } = {}
table.insert(limbs, {
name = root.name,
depends_on = "root",
c0 = root.c0,
c1 = root.c1:Inverse(),
})
topological_sort(limbs, root)
local limb_transforms: { LimbTransform } = {}
local limb_name_to_index: { [string]: number } = {}
for index, limb in limbs do
limb_transforms[index] = {
priority = -1,
position = vector.zero,
quat_vector = vector.zero,
quat_scalar = 1,
}
limb_name_to_index[limb.name] = index
end
return {
limbs = limbs,
limb_transforms = limb_transforms,
limb_name_to_index = limb_name_to_index,
result_coordinate_frames = {},
}
end
return {
create_rig = create_rig,
}
| 462 |
ffrostfall/crunchyroll | ffrostfall-crunchyroll-736bdb0/src/roblox/animation_asset.luau | local easing = require("../easings")
local easing_enum_map = require("./easing_enum_map")
local rig = require("../rig")
export type PoseNode = {
position: vector,
quat_vector: vector,
quat_scalar: number,
easing_function: (alpha: number) -> number,
}
--- [1] = previous keyframe index
--- [2] = (next keyframe index)?
export type KeyframeHole = { number }
export type Poses = { PoseNode }
type KeyframeNode = {
time: number,
poses: { [string]: PoseNode },
}
export type Identity = {
keyframe_times: { number },
keyframe_poses: { Poses },
keyframe_holes: { [number]: { KeyframeHole } },
length: number,
}
local function recursive_tree_from_pose(poses: { [string]: PoseNode }, root_pose: Pose)
local sub_poses = root_pose:GetSubPoses() :: { Pose }
for _, sub_pose in sub_poses do
recursive_tree_from_pose(poses, sub_pose)
end
-- example, a keyframe that is deeply nested. but ancestor(s) is not animated, roblox will indicate this with .Weight == 0
if root_pose.Weight == 0 then
return
end
local cframe = root_pose.CFrame
local axis, angle = cframe:ToAxisAngle()
local half_angle = angle * 0.5
local position = cframe.Position :: any
local quat_vector = math.sin(half_angle) * axis :: any
local quat_scalar = math.cos(half_angle)
poses[root_pose.Name] = {
position = position,
quat_vector = quat_vector,
quat_scalar = quat_scalar,
easing_function = easing_enum_map[root_pose.EasingStyle][root_pose.EasingDirection],
}
end
local animation_asset = {}
function animation_asset.load_keyframe_sequence(
keyframe_sequence: KeyframeSequence,
rig: rig.Identity
): Identity
local keyframes = keyframe_sequence:GetKeyframes() :: { Keyframe }
local markers = {}
local keyframe_nodes: { KeyframeNode } = {}
for keyframe_index, keyframe in keyframes do
for _, marker in keyframe:GetMarkers() :: { KeyframeMarker } do
markers[marker.Name] = keyframe_index
end
local poses: { [string]: PoseNode } = {}
for _, pose_instance in keyframe:GetPoses() do
recursive_tree_from_pose(poses, pose_instance :: Pose)
end
table.insert(keyframe_nodes, {
time = keyframe.Time,
poses = poses,
})
end
table.sort(keyframe_nodes, function(left: KeyframeNode, right: KeyframeNode)
return left.time < right.time
end)
local limb_name_to_index = rig.limb_name_to_index
local keframe_holes: { [number]: { KeyframeHole } } = {}
-- previous keyframe that had no holes, [limb_index]: keyframe_node_index
local no_holes: { [number]: number } = {}
local future_right: { [number]: true | nil } = {}
for index, node in keyframe_nodes do
for limb_name, limb_index in limb_name_to_index do
-- if we are the first keyframe, we should fill in the default pose
if index == 1 and node.poses[limb_name] == nil then
node.poses[limb_name] = {
position = vector.zero,
quat_vector = vector.zero,
quat_scalar = 1,
easing_function = easing.linear,
}
end
if node.poses[limb_name] then
no_holes[limb_index] = index
future_right[limb_index] = nil
elseif not node.poses[limb_name] and future_right[limb_index] == nil then
-- there's a holes, find the left and right keyframes and fill the indexes between
-- left should always be avaliable
local left_pointer = no_holes[limb_index]
assert(left_pointer, "there should always be a left pointer keyframe")
local right_pointer
for right_pose_counter = index + 1, #keyframe_nodes do
if keyframe_nodes[right_pose_counter].poses[limb_name] then
right_pointer = right_pose_counter
break
end
end
future_right[limb_index] = true
local hole = {
left_pointer,
right_pointer,
}
local limb_holes = keframe_holes[limb_index]
if limb_holes == nil then
limb_holes = {}
keframe_holes[limb_index] = limb_holes
end
-- if left_pointer, the limb does not have any future keyframes
for fill_in = left_pointer + 1, (right_pointer or #keyframe_nodes) do
limb_holes[fill_in] = hole
end
end
end
end
local length = keyframe_nodes[#keyframe_nodes].time
local keyframe_times = {}
local keyframe_poses = {}
for index, keyframe_node in keyframe_nodes do
local mapped_poses: Poses = {}
for name, pose in keyframe_node.poses do
local limb_index = limb_name_to_index[name]
if limb_index ~= nil then
mapped_poses[limb_index] = pose
end
end
keyframe_poses[index] = mapped_poses
keyframe_times[index] = keyframe_node.time
end
return {
keyframe_times = keyframe_times,
keyframe_poses = keyframe_poses,
length = length,
keyframe_holes = keframe_holes,
}
end
return animation_asset
| 1,274 |
ffrostfall/crunchyroll | ffrostfall-crunchyroll-736bdb0/src/roblox/easing_enum_map.luau | local Enum = Enum or (require("@lune/roblox").Enum :: any) :: typeof(Enum)
local easings = require("../easings")
local EASING_IN = Enum.PoseEasingDirection.In
local EASING_OUT = Enum.PoseEasingDirection.Out
local EASING_IN_OUT = Enum.PoseEasingDirection.InOut
local LINEAR = Enum.PoseEasingStyle.Linear
local CUBIC = Enum.PoseEasingStyle.Cubic
local BOUNCE = Enum.PoseEasingStyle.Bounce
local ELASTIC = Enum.PoseEasingStyle.Elastic
local CONSTANT = Enum.PoseEasingStyle.Constant
return {
[LINEAR] = {
[EASING_IN] = easings.linear,
[EASING_OUT] = easings.linear,
[EASING_IN_OUT] = easings.linear,
},
[CUBIC] = {
[EASING_IN] = easings.cubic_in,
[EASING_OUT] = easings.cubic_out,
[EASING_IN_OUT] = easings.cubic_in_out,
},
[BOUNCE] = {
[EASING_IN] = easings.bounce_in,
[EASING_OUT] = easings.bounce_out,
[EASING_IN_OUT] = easings.bounce_in_out,
},
[ELASTIC] = {
[EASING_IN] = easings.elastic_in,
[EASING_OUT] = easings.elastic_out,
[EASING_IN_OUT] = easings.elastic_in_out,
},
[CONSTANT] = {
[EASING_IN] = easings.constant,
[EASING_OUT] = easings.constant,
[EASING_IN_OUT] = easings.constant,
},
}
| 396 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/MainModule.luau | --Wraps the Nexus VR Character Model main module for loading.
--When required with an id, the main module's source isn't
--included, which makes the client see an empty script.
--!strict
local REQUIRED_LIBRARIES = {
Enigma = "enigma",
NexusAppendage = "nexus-appendage",
NexusBufferedReplication = "nexus-buffered-replication",
NexusButton = "nexus-button",
NexusInstance = "nexus-instance",
NexusVRCore = "nexus-vr-core",
}
--Copy the dependencies if it is a Wally package.
--This is meant to provide backward compatibility with the expected final module location.
local SourcePackages = script.Parent
if SourcePackages then
local TargetPackages = script:WaitForChild("NexusVRCharacterModel"):WaitForChild("Packages")
if not TargetPackages:FindFirstChild("_Index") then
local Index = Instance.new("Folder")
Index.Name = "_Index"
Index.Parent = TargetPackages
for PackageName, WallyPackageName in REQUIRED_LIBRARIES do
local SourceReference = SourcePackages:FindFirstChild(PackageName)
local SourcePackage = SourcePackages:FindFirstChild(WallyPackageName, true)
local TargetPackage = TargetPackages:FindFirstChild(PackageName)
if SourceReference and SourcePackage and TargetPackage then
SourceReference:Clone().Parent = TargetPackages
SourcePackage.Parent:Clone().Parent = Index
TargetPackage:Destroy()
end
end
end
end
--Load the module.
return require(script:WaitForChild("NexusVRCharacterModel")) | 344 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/Api.luau | --Main module for creating the usable API.
--!strict
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
return function()
local NexusVRCharacterModel = script.Parent
local TypedEvent = require(NexusVRCharacterModel:WaitForChild("Packages"):WaitForChild("NexusInstance")).TypedEvent
local API = {} :: any
API.Registered = TypedEvent.new()
--[[
Stores an API that can be referenced. If the API is already stored,
an error will be thrown.
--]]
function API:Register(ApiName: string, Api: any): ()
if self[ApiName] ~= nil then
error(`API already registered: {ApiName}`)
end
self[ApiName] = Api
self.Registered:Fire(ApiName)
end
--[[
Waits for an API to be registered and returns the API. If it was
already registered, it returns the API without waiting. Similar
to instances, this would be treated like WaitForChild where the
usage is optional instead of indexing (ex: API:WaitFor("MyApi")
vs API.MyApi) as long as the consequences of an API not
being registered are accepted.
--]]
function API:WaitFor(ApiName: string): any
while not self[ApiName] do
self.Registered:Wait()
end
return self[ApiName]
end
--[[
Invokes a callback when an API is registered with a given
name. If it is already registered, the callback will run
asynchronously. This is intended for setting up an API
call without blocking for WaitFor.
--]]
function API:OnRegistered(ApiName: string, RegisteredCallback: (any) -> ()): ()
--Run the callback immediately if the API is loaded.
if self[ApiName] then
task.spawn(function()
RegisteredCallback(self[ApiName])
end)
return
end
--Connect the registered event.
self.Registered:Connect(function(RegisteredFunctionName)
if ApiName ~= RegisteredFunctionName then return end
RegisteredCallback(self[ApiName])
end)
end
--Create the client API.
--Done in a task to resolve recurisve requiring.
if RunService:IsClient() then
task.defer(function()
--Create the camera API.
local CameraService = require(NexusVRCharacterModel:WaitForChild("State"):WaitForChild("CameraService")).GetInstance()
local CameraAPI = {}
function CameraAPI:SetActiveCamera(Name: string): ()
CameraService:SetActiveCamera(Name)
end
function CameraAPI:GetActiveCamera(): string
return CameraService.ActiveCamera
end
API:Register("Camera", CameraAPI)
--Create the controller API.
local ActiveControllers = {}
local ControlService = require(NexusVRCharacterModel:WaitForChild("State"):WaitForChild("ControlService")).GetInstance()
local ControllerAPI = {}
function ControllerAPI:SetActiveController(Name: string): ()
ControlService:SetActiveController(Name)
end
function ControllerAPI:GetActiveController(): (string)
return ControlService.ActiveController
end
function ControllerAPI:SetControllerInputEnabled(Hand: Enum.UserCFrame, Enabled: boolean): ()
if Hand ~= Enum.UserCFrame.LeftHand and Hand ~= Enum.UserCFrame.RightHand then
error(`The following UserCFrame is invalid and can't be disabled: {Hand}`)
end
ActiveControllers[Hand] = (Enabled ~= false)
end
function ControllerAPI:EnableControllerInput(Hand: Enum.UserCFrame): ()
self:SetControllerInputEnabled(Hand, true)
end
function ControllerAPI:DisableControllerInput(Hand: Enum.UserCFrame): ()
self:SetControllerInputEnabled(Hand, false)
end
function ControllerAPI:IsControllerInputEnabled(Hand: Enum.UserCFrame): boolean
if Hand ~= Enum.UserCFrame.LeftHand and Hand ~= Enum.UserCFrame.RightHand then
error(`The following UserCFrame is invalid and can't be disabled: {Hand}`)
end
return ActiveControllers[Hand] ~= false
end
API:Register("Controller", ControllerAPI)
--Create the input API.
local VRInputService = require(NexusVRCharacterModel:WaitForChild("State"):WaitForChild("VRInputService")).GetInstance()
local InputAPI = {}
InputAPI.Recentered = VRInputService.Recentered
InputAPI.EyeLevelSet = VRInputService.EyeLevelSet
function InputAPI:Recenter(): ()
VRInputService:Recenter()
end
function InputAPI:SetEyeLevel(): ()
VRInputService:SetEyeLevel()
end
API:Register("Input", InputAPI)
--Create the Menu API.
--The Menu API does not work outside of VR.
--Release 454 and later has/had a bug that made VREnabled false on start. This mitigates that now and in the future if VR loads dynamically.
local MenuAPI = {} :: any
local function GetMainMenu(): any
if not MenuAPI.Enabled then
error("Menu API is not enabled for non-VR players. Check Api.Menu.Enabled before calling.")
end
return require(NexusVRCharacterModel:WaitForChild("UI"):WaitForChild("MainMenu")).GetInstance()
end
if UserInputService.VREnabled then
MenuAPI.Enabled = true
else
MenuAPI.Enabled = false
UserInputService:GetPropertyChangedSignal("VREnabled"):Connect(function()
MenuAPI.Enabled = UserInputService.VREnabled
end)
end
MenuAPI.CreateView = function(_, ...)
return GetMainMenu():CreateView(...)
end
MenuAPI.IsOpen = function()
return GetMainMenu().ScreenGui.Enabled
end
MenuAPI.Open = function(self)
if self:IsOpen() then return end
GetMainMenu():Toggle()
end
MenuAPI.Close = function(self)
if not self:IsOpen() then return end
GetMainMenu():Toggle()
end
API:Register("Menu", MenuAPI)
--Create the settings API.
local SettingsService = require(NexusVRCharacterModel:WaitForChild("State"):WaitForChild("Settings")).GetInstance()
local SettingsAPI = {}
function SettingsAPI:GetSetting(Setting: string): any
return SettingsService:GetSetting(Setting)
end
function SettingsAPI:SetSetting(Setting: string, Value: any): ()
SettingsService:SetSetting(Setting, Value)
end
function SettingsAPI:GetSettingsChangedSignal(Setting: string)
return SettingsService:GetSettingsChangedSignal(Setting)
end
API:Register("Settings", SettingsAPI)
end)
end
--Return the APIs.
return API
end | 1,489 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/Character/Appendage.luau | --Stores information about an appendage, such as an arm or a leg.
--!strict
local NexusAppendage = require(script.Parent.Parent:WaitForChild("Packages"):WaitForChild("NexusAppendage"))
local Limb = NexusAppendage.Limb
local Appendage = {}
Appendage.__index = Appendage
setmetatable(Appendage, Limb)
export type Appendage = {
UpperLimb: BasePart,
LowerLimb: BasePart,
LimbEnd: BasePart,
StartAttachment: string,
LimbJointAttachment: string,
LimbEndAttachment: string,
LimbHoldAttachment: string,
InvertBendDirection: boolean,
PreventDisconnection: boolean,
} & typeof(setmetatable({}, Appendage)) & NexusAppendage.Limb
--[[
Creates an appendage.
--]]
function Appendage.new(UpperLimb: BasePart, LowerLimb: BasePart, LimbEnd: BasePart, StartAttachment: string, LimbJointAttachment: string, LimbEndAttachment: string, LimbHoldAttachment: string, PreventDisconnection: boolean?): Appendage
local self = setmetatable(Limb.new() :: any, Appendage)
self.UpperLimb = UpperLimb
self.LowerLimb = LowerLimb
self.LimbEnd = LimbEnd
self.StartAttachment = StartAttachment
self.LimbJointAttachment = LimbJointAttachment
self.LimbEndAttachment = LimbEndAttachment
self.LimbHoldAttachment = LimbHoldAttachment
self.InvertBendDirection = false
self.PreventDisconnection = PreventDisconnection or false
return setmetatable(self, Appendage)
end
--[[
Attempts to solve a joint. This uses
the "naive" approach for inverse kinematics.
--]]
function Appendage.SolveJoint(self: Appendage, OriginCFrame: CFrame, TargetPosition: Vector3, Length1: number, Length2: number): (CFrame, number, number)
local LocalizedPosition = OriginCFrame:PointToObjectSpace(TargetPosition)
local LocalizedUnit = LocalizedPosition.Unit
local Hypotenuse = LocalizedPosition.Magnitude
--Get the axis and correct it if it is 0.
local Axis = Vector3.new(0, 0, -1):Cross(LocalizedUnit)
if Axis == Vector3.new(0, 0, 0) then
if LocalizedPosition.Z < 0 then
Axis = Vector3.new(0, 0, 0.001)
else
Axis = Vector3.new(0, 0, -0.001)
end
end
--Calculate and return the angles.
local PlaneRotation = math.acos(-LocalizedUnit.Z)
local PlaneCFrame = OriginCFrame * CFrame.fromAxisAngle(Axis, PlaneRotation)
if Hypotenuse < math.max(Length2, Length1) - math.min(Length2, Length1) then
local ShoulderAngle, ElbowAngle = -math.pi / 2, math.pi
if self.PreventDisconnection then
return PlaneCFrame, ShoulderAngle, ElbowAngle
else
return PlaneCFrame * CFrame.new(0, 0, math.max(Length2, Length1) - math.min(Length2, Length1) - Hypotenuse), ShoulderAngle, ElbowAngle
end
elseif Hypotenuse > Length1 + Length2 then
local ShoulderAngle, ElbowAngle = math.pi / 2, 0
if self.PreventDisconnection then
return PlaneCFrame, ShoulderAngle, ElbowAngle
else
return PlaneCFrame * CFrame.new(0, 0, Length1 + Length2 - Hypotenuse), ShoulderAngle, ElbowAngle
end
else
local Angle1 = -math.acos((-(Length2 * Length2) + (Length1 * Length1) + (Hypotenuse * Hypotenuse)) / (2 * Length1 * Hypotenuse))
local Angle2 = math.acos(((Length2 * Length2) - (Length1 * Length1) + (Hypotenuse * Hypotenuse)) / (2 * Length2 * Hypotenuse))
if self.InvertBendDirection then
Angle1 = -Angle1
Angle2 = -Angle2
end
return PlaneCFrame , Angle1 + math.pi / 2, Angle2 - Angle1
end
end
--[[
Returns the rotation offset relative to the Y axis
to an end CFrame.
--]]
function Appendage.RotationTo(self: Appendage, StartCFrame: CFrame, EndCFrame: CFrame): CFrame
local Offset = (StartCFrame:Inverse() * EndCFrame).Position
return CFrame.Angles(math.atan2(Offset.Z, Offset.Y), 0, -math.atan2(Offset.X, Offset.Y))
end
--[[
Returns the CFrames of the appendage for
the starting and holding CFrames. The implementation
works, but could be improved.
--]]
function Appendage.GetAppendageCFrames(self: Appendage, StartCFrame: CFrame, HoldCFrame: CFrame): (CFrame, CFrame, CFrame)
--Get the attachment CFrames.
local LimbHoldCFrame = self:GetAttachmentCFrame(self.LimbEnd, self.LimbHoldAttachment)
local LimbEndCFrame = self:GetAttachmentCFrame(self.LimbEnd, self.LimbEndAttachment)
local UpperLimbStartCFrame = self:GetAttachmentCFrame(self.UpperLimb, self.StartAttachment)
local UpperLimbJointCFrame = self:GetAttachmentCFrame(self.UpperLimb, self.LimbJointAttachment)
local LowerLimbJointCFrame = self:GetAttachmentCFrame(self.LowerLimb, self.LimbJointAttachment)
local LowerLimbEndCFrame = self:GetAttachmentCFrame(self.LowerLimb, self.LimbEndAttachment)
--Calculate the appendage lengths.
local UpperLimbLength = (UpperLimbStartCFrame.Position - UpperLimbJointCFrame.Position).Magnitude
local LowerLimbLength = (LowerLimbJointCFrame.Position - LowerLimbEndCFrame.Position).Magnitude
--Calculate the end point of the limb.
local AppendageEndJointCFrame = HoldCFrame * LimbHoldCFrame:Inverse() * LimbEndCFrame
--Solve the join.
local PlaneCFrame,UpperAngle,CenterAngle = self:SolveJoint(StartCFrame, AppendageEndJointCFrame.Position, UpperLimbLength, LowerLimbLength)
--Calculate the CFrame of the limb join before and after the center angle.
local JointUpperCFrame = PlaneCFrame * CFrame.Angles(UpperAngle, 0, 0) * CFrame.new(0, -UpperLimbLength, 0)
local JointLowerCFrame = JointUpperCFrame * CFrame.Angles(CenterAngle, 0, 0)
--Calculate the part CFrames.
--The appendage end is not calculated with hold CFrame directly since it can ignore PreventDisconnection = true.
local UpperLimbCFrame = JointUpperCFrame * self:RotationTo(UpperLimbJointCFrame, UpperLimbStartCFrame):Inverse() * UpperLimbJointCFrame:Inverse()
local LowerLimbCFrame = JointLowerCFrame * self:RotationTo(LowerLimbEndCFrame, LowerLimbJointCFrame):Inverse() * LowerLimbJointCFrame:Inverse()
local AppendageEndCFrame = CFrame.new((LowerLimbCFrame * LowerLimbEndCFrame).Position) * (CFrame.new(-AppendageEndJointCFrame.Position) * AppendageEndJointCFrame) * LimbEndCFrame:Inverse()
--Return the part CFrames.
return UpperLimbCFrame, LowerLimbCFrame, AppendageEndCFrame
end
return Appendage | 1,746 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/Character/Camera/CommonCamera.luau | --Common camera functionality.
--!strict
local Workspace = game:GetService("Workspace")
local VRService = game:GetService("VRService")
local NexusVRCharacterModel = script.Parent.Parent.Parent
local Settings = require(NexusVRCharacterModel:WaitForChild("State"):WaitForChild("Settings")).GetInstance()
local CommonCamera = {}
CommonCamera.__index = CommonCamera
export type CommonCamera = typeof(setmetatable({}, CommonCamera))
--[[
Creates the common camera.
--]]
function CommonCamera.new(): CommonCamera
return setmetatable({}, CommonCamera)
end
--[[
Enables the camera.
--]]
function CommonCamera.Enable(self: CommonCamera): ()
end
--[[
Disables the camera.
--]]
function CommonCamera.Disable(self: CommonCamera): ()
end
--[[
Updates the camera.
--]]
function CommonCamera.UpdateCamera(self: CommonCamera, HeadsetCFrameWorld: CFrame): ()
end
--[[
Sets the camera CFrame.
--]]
function CommonCamera.SetCFrame(self: CommonCamera, HeadsetCFrameWorld: CFrame): ()
--Lock HeadLocked to false.
--The default behavior is to do it for backwards compatibility with 2.6.0 and earlier.
local Camera = Workspace.CurrentCamera
if Settings:GetSetting("Camera.DisableHeadLocked") ~= false then
Camera.HeadLocked = false
end
--Set the camera CFrame.
local TargetCFrame = HeadsetCFrameWorld
if Camera.HeadLocked then
local HeadCFrame = VRService:GetUserCFrame(Enum.UserCFrame.Head)
TargetCFrame = HeadsetCFrameWorld * (CFrame.new(HeadCFrame.Position * (Workspace.CurrentCamera.HeadScale - 1)) * HeadCFrame):Inverse()
Camera.VRTiltAndRollEnabled = true
end
Camera.CameraType = Enum.CameraType.Scriptable
Camera.CFrame = TargetCFrame
Camera.Focus = TargetCFrame
end
return CommonCamera | 415 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/Character/Camera/DefaultCamera.luau | --Default camera that follows the character.
--!strict
local BUMP_DEFAULT_TRANSPARENCY_WORKAROUND = true
local HIDDEN_ACCESSORIES = {
[Enum.AccessoryType.Hat] = true;
[Enum.AccessoryType.Hair] = true;
[Enum.AccessoryType.Face] = true;
[Enum.AccessoryType.Eyebrow] = true;
[Enum.AccessoryType.Eyelash] = true;
}
local Players = game:GetService("Players")
local VRService = game:GetService("VRService")
local NexusVRCharacterModel = script.Parent.Parent.Parent
local CommonCamera = require(NexusVRCharacterModel:WaitForChild("Character"):WaitForChild("Camera"):WaitForChild("CommonCamera"))
local Settings = require(NexusVRCharacterModel:WaitForChild("State"):WaitForChild("Settings")).GetInstance()
local DefaultCamera = {}
DefaultCamera.__index = DefaultCamera
setmetatable(DefaultCamera, CommonCamera)
export type DefaultCamera = {
TransparencyEvents: {RBXScriptConnection}?,
} & typeof(setmetatable({}, DefaultCamera)) & CommonCamera.CommonCamera
--[[
Returns true if the provided part should be hidden in first person.
--]]
function DefaultCamera.ShouldHidePart(Part: BasePart): boolean
local Parent: Instance? = Part.Parent
if Parent then
if Parent:IsA("Accessory") then
local AccessoryType = Parent.AccessoryType
return HIDDEN_ACCESSORIES[AccessoryType] or false
elseif Parent:IsA("Model") then
return false
else
return not Parent:IsA("Tool")
end
end
if Part:FindFirstChildWhichIsA("WrapLayer") then
return false
end
return true
end
--[[
Creates a default camera object.
--]]
function DefaultCamera.new(): DefaultCamera
return setmetatable(CommonCamera.new() :: any, DefaultCamera) :: DefaultCamera
end
--[[
Enables the camera.
--]]
function DefaultCamera.Enable(self: DefaultCamera): ()
local TransparencyEvents = {}
self.TransparencyEvents = TransparencyEvents
if Players.LocalPlayer.Character then
--Connect children being added.
local Transparency = Settings:GetSetting("Appearance.LocalCharacterTransparency")
if BUMP_DEFAULT_TRANSPARENCY_WORKAROUND then
if Transparency == 0.5 then
Transparency = 0.501
elseif Transparency < 0.5 then
warn("Values of <0.5 with Appearance.LocalCharacterTransparency are currently known to cause black screen issues. This will hopefully be resolved by Roblox in a future update: https://devforum.roblox.com/t/vr-screen-becomes-black-due-to-non-transparent-character/2215099")
end
end
table.insert(TransparencyEvents, Players.LocalPlayer.Character.DescendantAdded:Connect(function(Part: BasePart)
if Part:IsA("BasePart") then
local PartTransparency = Transparency
if Part:FindFirstAncestorOfClass("Tool") then
PartTransparency = 0
elseif DefaultCamera.ShouldHidePart(Part) then
PartTransparency = 1
end
Part.LocalTransparencyModifier = PartTransparency
table.insert(TransparencyEvents, Part:GetPropertyChangedSignal("LocalTransparencyModifier"):Connect(function()
Part.LocalTransparencyModifier = PartTransparency
end))
end
end))
for _, Part in Players.LocalPlayer.Character:GetDescendants() do
if Part:IsA("BasePart") then
local PartTransparency = Transparency
if Part:FindFirstAncestorOfClass("Tool") then
PartTransparency = 0
elseif DefaultCamera.ShouldHidePart(Part) then
PartTransparency = 1
end
Part.LocalTransparencyModifier = PartTransparency
table.insert(TransparencyEvents, Part:GetPropertyChangedSignal("LocalTransparencyModifier"):Connect(function()
Part.LocalTransparencyModifier = PartTransparency
end))
end
end
end
--Connect the character and local transparency changing.
table.insert(TransparencyEvents, Players.LocalPlayer:GetPropertyChangedSignal("Character"):Connect(function()
self:Disable()
self:Enable()
end))
table.insert(TransparencyEvents, Settings:GetSettingsChangedSignal("Appearance.LocalCharacterTransparency"):Connect(function()
self:Disable()
self:Enable()
end) :: any)
--Keep the camera in first person.
if VRService.AvatarGestures then
Players.LocalPlayer.CameraMaxZoomDistance = Players.LocalPlayer.CameraMinZoomDistance
end
end
--[[
Disables the camera.
--]]
function DefaultCamera.Disable(self: DefaultCamera): ()
--Disconnect the character events.
if self.TransparencyEvents then
for _, Event in self.TransparencyEvents do
Event:Disconnect()
end
self.TransparencyEvents = {}
end
--Reset the local transparency modifiers.
if Players.LocalPlayer.Character then
for _, Part in Players.LocalPlayer.Character:GetDescendants() do
if Part:IsA("BasePart") then
Part.LocalTransparencyModifier = 0
end
end
end
end
--[[
Updates the camera.
--]]
function DefaultCamera.UpdateCamera(self: DefaultCamera, HeadsetCFrameWorld: CFrame): ()
if VRService.AvatarGestures then return end
self:SetCFrame(HeadsetCFrameWorld)
end
return DefaultCamera
| 1,172 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/Character/Camera/ThirdPersonTrackCamera.luau | --Third person camera that moves with the player.
--!strict
local THIRD_PERSON_ZOOM = 10
local Players = game:GetService("Players")
local NexusVRCharacterModel = script.Parent.Parent.Parent
local CommonCamera = require(NexusVRCharacterModel:WaitForChild("Character"):WaitForChild("Camera"):WaitForChild("CommonCamera"))
local ThirdPersonTrackCamera = {}
ThirdPersonTrackCamera.__index = ThirdPersonTrackCamera
setmetatable(ThirdPersonTrackCamera, CommonCamera)
export type ThirdPersonTrackCamera = {
FetchInitialCFrame: boolean?,
BaseFaceAngleY: number?,
BaseCFrame: CFrame?,
} & typeof(setmetatable({}, ThirdPersonTrackCamera)) & CommonCamera.CommonCamera
--[[
Creates a third-person camera object.
--]]
function ThirdPersonTrackCamera.new(): ThirdPersonTrackCamera
return setmetatable(CommonCamera.new() :: any, ThirdPersonTrackCamera) :: ThirdPersonTrackCamera
end
--[[
Enables the camera.
--]]
function ThirdPersonTrackCamera.Enable(self: ThirdPersonTrackCamera): ()
self.FetchInitialCFrame = true
end
--[[
Disables the camera.
--]]
function ThirdPersonTrackCamera.Disable(self: ThirdPersonTrackCamera): ()
self.FetchInitialCFrame = nil
end
--[[
Updates the camera.
--]]
function ThirdPersonTrackCamera.UpdateCamera(self: ThirdPersonTrackCamera, HeadsetCFrameWorld: CFrame): ()
--Set the initial CFrame to use.
if self.FetchInitialCFrame then
local BaseFaceAngleY = math.atan2(-HeadsetCFrameWorld.LookVector.X, -HeadsetCFrameWorld.LookVector.Z)
self.BaseFaceAngleY = BaseFaceAngleY
self.BaseCFrame = CFrame.new(HeadsetCFrameWorld.Position) * CFrame.Angles(0, BaseFaceAngleY, 0)
self.FetchInitialCFrame = nil
end
--Get the scale.
local Scale = 1
local Character = Players.LocalPlayer.Character
if Character then
local Humanoid = Character:FindFirstChildOfClass("Humanoid")
if Humanoid then
local BodyHeightScale = Humanoid:FindFirstChild("BodyHeightScale")
if BodyHeightScale then
Scale = BodyHeightScale.Value
end
end
end
--Calculate the third person CFrame.
local BaseCFrame = self.BaseCFrame :: CFrame
local HeadsetRelative = BaseCFrame:Inverse() * HeadsetCFrameWorld
local TargetCFrame = BaseCFrame * CFrame.new(0, 0, -THIRD_PERSON_ZOOM * Scale) * CFrame.Angles(0, math.pi, 0) * HeadsetRelative
--Update the camera.
self:SetCFrame(TargetCFrame)
end
return ThirdPersonTrackCamera | 606 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/Character/Controller/BaseController.luau | --Base class for controlling the local character.
--!strict
local THUMBSTICK_INPUT_START_RADIUS = 0.6
local THUMBSTICK_INPUT_RELEASE_RADIUS = 0.4
local THUMBSTICK_SNAP_ROTATION_ANGLE = math.rad(30) --Roblox's snap rotation is 30 degrees.
local THUMBSTICK_SMOOTH_LOCOMOTION_DEADZONE = 0.2
local THUMBSTICK_MANUAL_SMOOTH_ROTATION_RATE = math.rad(360) --May or may not be accurate for Roblox's player scripts.
local BLUR_TWEEN_INFO = TweenInfo.new(0.25, Enum.EasingStyle.Quad)
local USER_CFRAME_TO_THUMBSTICK = {
[Enum.UserCFrame.LeftHand] = Enum.KeyCode.Thumbstick1,
[Enum.UserCFrame.RightHand] = Enum.KeyCode.Thumbstick2,
}
local Workspace = game:GetService("Workspace")
local Players = game:GetService("Players")
local HttpService = game:GetService("HttpService")
local ContextActionService = game:GetService("ContextActionService")
local TweenService = game:GetService("TweenService")
local VRService = game:GetService("VRService")
local NexusVRCharacterModel = script.Parent.Parent.Parent
local NexusVRCharacterModelApi = require(NexusVRCharacterModel).Api
local Character = require(NexusVRCharacterModel:WaitForChild("Character"))
local CameraService = require(NexusVRCharacterModel:WaitForChild("State"):WaitForChild("CameraService")).GetInstance()
local CharacterService = require(NexusVRCharacterModel:WaitForChild("State"):WaitForChild("CharacterService")).GetInstance()
local Settings = require(NexusVRCharacterModel:WaitForChild("State"):WaitForChild("Settings")).GetInstance()
local VRInputService = require(NexusVRCharacterModel:WaitForChild("State"):WaitForChild("VRInputService")).GetInstance()
local BaseController = {}
BaseController.__index = BaseController
export type BaseController = {
Active: boolean,
ActionsToLock: {Enum.KeyCode},
ActionsToUnbind: {Enum.KeyCode}?,
Character: Character.Character?,
Connections: {RBXScriptConnection}?,
LastHeadCFrame: CFrame?,
LastRotationUpdateTick: number?,
} & typeof(setmetatable({}, BaseController))
--[[
Returns the Y-axis angle of the given CFrame.
--]]
local function GetAngleToGlobalY(CF: CFrame): number
return math.atan2(-CF.LookVector.X, -CF.LookVector.Z)
end
--[[
Creates a base controller object.
--]]
function BaseController.new(): BaseController
return setmetatable({
Active = false,
ActionsToLock = {Enum.KeyCode.ButtonR3},
}, BaseController) :: BaseController
end
--[[
Updates the character. Returns if it changed.
--]]
function BaseController.UpdateCharacterReference(self: BaseController): boolean
local LastCharacter = self.Character
self.Character = CharacterService:GetCharacter(Players.LocalPlayer)
if not self.Character then
return false
end
return LastCharacter ~= self.Character
end
--[[
Enables the controller.
--]]
function BaseController.Enable(self: BaseController): ()
if not self.Connections then self.Connections = {} end
self.Active = true
--Bind the actions to sink inputs from the PlayerScripts.
if not self.ActionsToUnbind then self.ActionsToUnbind = {} end
for _, KeyCode in self.ActionsToLock do
local ActionName = HttpService:GenerateGUID()
ContextActionService:BindActionAtPriority(ActionName, function()
return self.Active and Enum.ContextActionResult.Sink or Enum.ContextActionResult.Pass
end, false, Enum.ContextActionPriority.High.Value, KeyCode)
table.insert(self.ActionsToUnbind :: {Enum.KeyCode}, ActionName)
end
--Update the character and return if the character is nil.
self:UpdateCharacterReference()
if not self.Character then
return
end
--Connect the eye level being set.
local Connections = self.Connections :: {RBXScriptConnection}
table.insert(Connections, VRInputService.EyeLevelSet:Connect(function()
local LastHeadCFrame = self.LastHeadCFrame
if LastHeadCFrame and LastHeadCFrame.Y > 0 then
self.LastHeadCFrame = CFrame.new(0, -LastHeadCFrame.Y, 0) * LastHeadCFrame
end
end) :: any)
--Connect the character entering a seat.
table.insert(Connections, self.Character.Humanoid:GetPropertyChangedSignal("SeatPart"):Connect(function()
local SeatPart = self.Character:GetHumanoidSeatPart()
if SeatPart then
self:PlayBlur()
VRInputService:Recenter()
end
end))
--Disable auto rotate so that the default controls work.
self.Character.Humanoid.AutoRotate = false
end
--[[
Disables the controller.
--]]
function BaseController.Disable(self: BaseController): ()
self.Active = false
self.Character = nil
self.LastHeadCFrame = nil
self.LastRotationUpdateTick = nil
if self.Connections then
for _, Connection in self.Connections do
Connection:Disconnect()
end
end
if self.ActionsToUnbind then
for _, ActionName in self.ActionsToUnbind do
ContextActionService:UnbindAction(ActionName)
end
end
self.Connections = nil
end
--[[
Scales the local-space input CFrame based on
the height multiplier of the character.
--]]
function BaseController.ScaleInput(self: BaseController, InputCFrame: CFrame): CFrame
--Return the original CFrame if there is no character.
if not self.Character or not InputCFrame then
return InputCFrame
end
--Return the modified CFrame.
return CFrame.new(InputCFrame.Position * (self.Character:GetHumanoidScale("BodyHeightScale") - 1)) * InputCFrame
end
--[[
Updates the provided 'Store' table with the state of its
Thumbstick (Enum.KeyCode.ThumbstickX) field. Returns the
direction state, radius state, and overall state change.
--]]
function BaseController.GetJoystickState(self: BaseController, Store: any): (string, string, string)
local InputPosition = VRInputService:GetThumbstickPosition(Store.Thumbstick)
local InputRadius = ((InputPosition.X ^ 2) + (InputPosition.Y ^ 2)) ^ 0.5
local InputAngle = math.atan2(InputPosition.X, InputPosition.Y)
local DirectionState, RadiusState
if InputAngle >= math.rad(-135) and InputAngle <= math.rad(-45) then
DirectionState = "Left"
elseif InputAngle >= math.rad(-45) and InputAngle <= math.rad(45) then
DirectionState = "Forward"
elseif InputAngle >= math.rad(45) and InputAngle <= math.rad(135) then
DirectionState = "Right"
end
if InputRadius >= THUMBSTICK_INPUT_START_RADIUS then
RadiusState = "Extended"
elseif InputRadius <= THUMBSTICK_INPUT_RELEASE_RADIUS then
RadiusState = "Released"
else
RadiusState = "InBetween"
end
--Update the stored state.
local StateChange = nil
if RadiusState == "Released" then
if Store.RadiusState == "Extended" then
StateChange = "Released"
end
Store.RadiusState = "Released"
Store.DirectionState = nil
elseif RadiusState == "Extended" then
if Store.RadiusState == nil or Store.RadiusState == "Released" then
if Store.RadiusState ~= "Extended" then
StateChange = "Extended"
end
Store.RadiusState = "Extended"
Store.DirectionState = DirectionState
elseif Store.DirectionState ~= DirectionState then
if Store.RadiusState ~= "Cancelled" then
StateChange = "Cancel"
end
Store.RadiusState = "Cancelled"
Store.DirectionState = nil
end
end
return DirectionState, RadiusState, StateChange
end
--[[
Plays a temporary blur effect to make
teleports and snap turns less jarring.
]]--
function BaseController.PlayBlur(self: BaseController): ()
local SnapTeleportBlur = Settings:GetSetting("Movement.SnapTeleportBlur")
SnapTeleportBlur = (if SnapTeleportBlur == nil then true else SnapTeleportBlur)
if not SnapTeleportBlur then
return
end
local Blur = Instance.new("BlurEffect")
Blur.Parent = workspace.CurrentCamera
Blur.Size = 56
local BlurTween = TweenService:Create(Blur, BLUR_TWEEN_INFO, { Size = 0 })
BlurTween:Play()
BlurTween.Completed:Connect(function()
Blur:Destroy()
end)
end
--[[
Updates the reference world CFrame.
--]]
function BaseController.UpdateCharacter(self: BaseController): ()
--Return if the character is nil.
local CharacterChanged = self:UpdateCharacterReference()
if not self.Character then
return
end
if CharacterChanged then
self:Enable()
end
--Get the VR inputs.
local VRInputs = VRInputService:GetVRInputs()
local VRHeadCFrame = self:ScaleInput(VRInputs[Enum.UserCFrame.Head])
local VRLeftHandCFrame,VRRightHandCFrame = self:ScaleInput(VRInputs[Enum.UserCFrame.LeftHand]), self:ScaleInput(VRInputs[Enum.UserCFrame.RightHand])
local HeadToLeftHandCFrame = VRHeadCFrame:Inverse() * VRLeftHandCFrame
local HeadToRightHandCFrame = VRHeadCFrame:Inverse() * VRRightHandCFrame
--Update the character.
local SeatPart = self.Character:GetHumanoidSeatPart()
if not SeatPart then
--Offset the character by the change in the head input.
if self.LastHeadCFrame then
--Get the eye CFrame of the current character, except the Y offset from the HumanoidRootPart.
--The Y position will be added absolutely since doing it relatively will result in floating or short characters.
local HumanoidRootPartCFrame = self.Character.Parts.HumanoidRootPart.CFrame
local LowerTorsoCFrame = HumanoidRootPartCFrame * self.Character.Attachments.HumanoidRootPart.RootRigAttachment.CFrame * CFrame.new(0, -self.Character.Motors.Root.Transform.Position.Y, 0) * self.Character.Motors.Root.Transform * self.Character.Attachments.LowerTorso.RootRigAttachment.CFrame:Inverse()
local UpperTorsoCFrame = LowerTorsoCFrame * self.Character.Attachments.LowerTorso.WaistRigAttachment.CFrame * self.Character.Motors.Waist.Transform * self.Character.Attachments.UpperTorso.WaistRigAttachment.CFrame:Inverse()
local HeadCFrame = UpperTorsoCFrame * self.Character.Attachments.UpperTorso.NeckRigAttachment.CFrame * self.Character.Motors.Neck.Transform * self.Character.Attachments.Head.NeckRigAttachment.CFrame:Inverse()
local EyesOffset = self.Character.Head:GetEyesOffset()
local CharacterEyeCFrame = HeadCFrame * EyesOffset
--Determine the input components.
local InputDelta = self.LastHeadCFrame:Inverse() * VRHeadCFrame
if VRHeadCFrame.UpVector.Y < 0 then
InputDelta = CFrame.Angles(0,math.pi,0) * InputDelta
end
local HeadRotationXZ = (CFrame.new(VRHeadCFrame.Position) * CFrame.Angles(0, math.atan2(-VRHeadCFrame.LookVector.X, -VRHeadCFrame.LookVector.Z), 0)):Inverse() * VRHeadCFrame
local LastHeadAngleY = GetAngleToGlobalY(self.LastHeadCFrame)
local HeadAngleY = GetAngleToGlobalY(VRHeadCFrame)
local HeightOffset = CFrame.new(0, (CFrame.new(0, EyesOffset.Y, 0) * (VRHeadCFrame * EyesOffset:Inverse())).Y, 0)
--Offset the character eyes for the current input.
local CurrentCharacterAngleY = GetAngleToGlobalY(CharacterEyeCFrame)
local RotationY = CFrame.Angles(0, CurrentCharacterAngleY + (HeadAngleY - LastHeadAngleY), 0)
local NewCharacterEyePosition = (HeightOffset * CFrame.new((RotationY * CFrame.new(InputDelta.X, 0, InputDelta.Z)).Position) * CharacterEyeCFrame).Position
local NewCharacterEyeCFrame = CFrame.new(NewCharacterEyePosition) * RotationY * HeadRotationXZ
--Update the character.
self.Character:UpdateFromInputs(NewCharacterEyeCFrame, NewCharacterEyeCFrame * HeadToLeftHandCFrame,NewCharacterEyeCFrame * HeadToRightHandCFrame)
end
else
--Set the absolute positions of the character.
self.Character:UpdateFromInputsSeated(VRHeadCFrame, VRHeadCFrame * HeadToLeftHandCFrame,VRHeadCFrame * HeadToRightHandCFrame)
end
--Update the camera.
if self.Character.Parts.HumanoidRootPart:IsDescendantOf(Workspace) and self.Character.Humanoid.Health > 0 then
--Update the camera based on the character.
--Done based on the HumanoidRootPart instead of the Head because of Motors not updating the same frame, leading to a delay.
local HumanoidRootPartCFrame = self.Character.Parts.HumanoidRootPart.CFrame
local LowerTorsoCFrame = HumanoidRootPartCFrame * self.Character.Attachments.HumanoidRootPart.RootRigAttachment.CFrame * self.Character.Motors.Root.Transform * self.Character.Attachments.LowerTorso.RootRigAttachment.CFrame:Inverse()
local UpperTorsoCFrame = LowerTorsoCFrame * self.Character.Attachments.LowerTorso.WaistRigAttachment.CFrame * self.Character.Motors.Waist.Transform * self.Character.Attachments.UpperTorso.WaistRigAttachment.CFrame:Inverse()
local HeadCFrame = UpperTorsoCFrame * self.Character.Attachments.UpperTorso.NeckRigAttachment.CFrame * self.Character.Motors.Neck.Transform * self.Character.Attachments.Head.NeckRigAttachment.CFrame:Inverse()
CameraService:UpdateCamera(HeadCFrame * self.Character.Head:GetEyesOffset())
self.LastHeadCFrame = VRHeadCFrame
elseif not Workspace.CurrentCamera.HeadLocked then
--Update the camera based on the last CFrame if the motors can't update (not in Workspace).
local CurrentCameraCFrame = Workspace.CurrentCamera:GetRenderCFrame()
local LastHeadCFrame = self.LastHeadCFrame or CFrame.new()
local HeadCFrame = self:ScaleInput(VRInputService:GetVRInputs()[Enum.UserCFrame.Head])
CameraService:UpdateCamera(CurrentCameraCFrame * LastHeadCFrame:Inverse() * HeadCFrame)
self.LastHeadCFrame = HeadCFrame
end
end
--[[
Performs snap or smooth rotating based on the thumbstick input.
--]]
function BaseController.UpdateRotating(self: BaseController, Hand: Enum.UserCFrame, Direction: string, StateChange: string): ()
if VRService.AvatarGestures then
self.LastRotationUpdateTick = nil
return
end
if not self.Character or self.Character.Humanoid.Sit then
self.LastRotationUpdateTick = nil
return
end
if Direction ~= "Left" and Direction ~= "Right" then
self.LastRotationUpdateTick = nil
return
end
--Return if the input is inactive.
if NexusVRCharacterModelApi.Controller and not NexusVRCharacterModelApi.Controller:IsControllerInputEnabled(Hand) then
return
end
--Rotate the character.
local HumanoidRootPart = self.Character.Parts.HumanoidRootPart
if UserSettings():GetService("UserGameSettings").VRSmoothRotationEnabled then
--Smoothly rotate the character.
local InputPosition = VRInputService:GetThumbstickPosition(USER_CFRAME_TO_THUMBSTICK[Hand])
if math.abs(InputPosition.X) >= THUMBSTICK_SMOOTH_LOCOMOTION_DEADZONE then
local LastRotationUpdateTick = self.LastRotationUpdateTick or tick()
local CurrentRotationUpdateTick = tick()
local RotationUpdateDeltaTime = (CurrentRotationUpdateTick - LastRotationUpdateTick)
HumanoidRootPart.CFrame = CFrame.new(HumanoidRootPart.Position) * CFrame.Angles(0, -InputPosition.X * THUMBSTICK_MANUAL_SMOOTH_ROTATION_RATE * RotationUpdateDeltaTime, 0) * (CFrame.new(-HumanoidRootPart.Position) * HumanoidRootPart.CFrame)
self.LastRotationUpdateTick = CurrentRotationUpdateTick
else
self.LastRotationUpdateTick = nil
end
else
--Snap rotate the character.
if StateChange == "Extended" then
if Direction == "Left" then
--Turn the player to the left.
self:PlayBlur()
HumanoidRootPart.CFrame = CFrame.new(HumanoidRootPart.Position) * CFrame.Angles(0, THUMBSTICK_SNAP_ROTATION_ANGLE, 0) * (CFrame.new(-HumanoidRootPart.Position) * HumanoidRootPart.CFrame)
elseif Direction == "Right" then
--Turn the player to the right.
self:PlayBlur()
HumanoidRootPart.CFrame = CFrame.new(HumanoidRootPart.Position) * CFrame.Angles(0, -THUMBSTICK_SNAP_ROTATION_ANGLE, 0) * (CFrame.new(-HumanoidRootPart.Position) * HumanoidRootPart.CFrame)
end
end
end
end
return BaseController | 3,889 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/Character/Controller/SmoothLocomotionController.luau | --Local character controller using teleporting.
--!strict
local BaseController = require(script.Parent:WaitForChild("BaseController"))
local SmoothLocomotionController = {}
SmoothLocomotionController.__index = SmoothLocomotionController
setmetatable(SmoothLocomotionController, BaseController)
export type SmoothLocomotionController = {
JoystickState: {[string]: Enum.KeyCode}?,
} & typeof(setmetatable({}, SmoothLocomotionController)) & BaseController.BaseController
--[[
Creates a smooth locomotion controller object.
--]]
function SmoothLocomotionController.new(): SmoothLocomotionController
return setmetatable(BaseController.new(), SmoothLocomotionController) :: SmoothLocomotionController
end
--[[
Enables the controller.
--]]
function SmoothLocomotionController.Enable(self: SmoothLocomotionController): ()
BaseController.Enable(self)
self.JoystickState = {Thumbstick = Enum.KeyCode.Thumbstick2}
end
--[[
Disables the controller.
--]]
function SmoothLocomotionController.Disable(self: SmoothLocomotionController): ()
BaseController.Disable(self)
self.JoystickState = nil
end
--[[
Updates the local character. Must also update the camara.
--]]
function SmoothLocomotionController.UpdateCharacter(self: SmoothLocomotionController): ()
--Update the base character.
BaseController.UpdateCharacter(self)
if not self.Character then
return
end
--Rotate the character.
local DirectionState, _, StateChange = self:GetJoystickState(self.JoystickState)
self:UpdateRotating(Enum.UserCFrame.RightHand, DirectionState, StateChange)
end
return SmoothLocomotionController | 349 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/Character/Controller/TeleportController.luau | --Local character controller using teleporting.
--!strict
local Workspace = game:GetService("Workspace")
local NexusVRCharacterModel = script.Parent.Parent.Parent
local NexusVRCharacterModelApi = require(NexusVRCharacterModel).Api
local BaseController = require(script.Parent:WaitForChild("BaseController"))
local ArcWithBeacon = require(script.Parent:WaitForChild("Visual"):WaitForChild("ArcWithBeacon"))
local VRInputService = require(NexusVRCharacterModel:WaitForChild("State"):WaitForChild("VRInputService")).GetInstance()
local TeleportController = {}
TeleportController.__index = TeleportController
setmetatable(TeleportController, BaseController)
export type TeleportController = {
LeftArc: ArcWithBeacon.ArcWithBeacon,
RightArc: ArcWithBeacon.ArcWithBeacon,
ArcControls: {
{
Thumbstick: Enum.KeyCode,
UserCFrame: Enum.UserCFrame,
Arc: ArcWithBeacon.ArcWithBeacon,
WaitForRelease: boolean?,
RadiusState: ("Forward" | "Released")?,
LastHitPart: BasePart?,
LastHitPosition: Vector3?,
}
},
IgnoreNextExternalTeleport: boolean?,
} & typeof(setmetatable({}, TeleportController)) & BaseController.BaseController
--[[
Creates a teleport controller object.
--]]
function TeleportController.new(): TeleportController
local self = setmetatable(BaseController.new(), TeleportController) :: TeleportController
self.ActionsToLock = {Enum.KeyCode.Thumbstick1, Enum.KeyCode.ButtonR3}
return self
end
--[[
Enables the controller.
--]]
function TeleportController.Enable(self: TeleportController): ()
BaseController.Enable(self)
--Create the arcs.
self.LeftArc = ArcWithBeacon.new()
self.RightArc = ArcWithBeacon.new()
self.ArcControls = {
{
Thumbstick = Enum.KeyCode.Thumbstick1,
UserCFrame = Enum.UserCFrame.LeftHand,
Arc = self.LeftArc,
},
{
Thumbstick = Enum.KeyCode.Thumbstick2,
UserCFrame = Enum.UserCFrame.RightHand,
Arc = self.RightArc,
},
}
end
--[[
Disables the controller.
--]]
function TeleportController.Disable(self: TeleportController): ()
BaseController.Disable(self)
--Destroy the arcs.
self.LeftArc:Destroy()
self.RightArc:Destroy()
end
--[[
Updates the local character. Must also update the camara.
--]]
function TeleportController.UpdateCharacter(self: TeleportController): ()
--Update the base character.
BaseController.UpdateCharacter(self)
if not self.Character then
return
end
--Get the VR inputs.
local VRInputs = VRInputService:GetVRInputs()
for _, InputEnum in Enum.UserCFrame:GetEnumItems() do
VRInputs[InputEnum] = self:ScaleInput(VRInputs[InputEnum])
end
--Update the arcs.
local SeatPart = self.Character:GetHumanoidSeatPart()
for _, ArcData in self.ArcControls do
--Reset the left arc if the player is in a vehicle seat.
if ArcData.Thumbstick == Enum.KeyCode.Thumbstick1 and SeatPart and SeatPart:IsA("VehicleSeat") then
ArcData.Arc:Hide()
continue
end
--Update and fetch the current state.
local InputActive = (not NexusVRCharacterModelApi.Controller or NexusVRCharacterModelApi.Controller:IsControllerInputEnabled(ArcData.UserCFrame))
local DirectionState, RadiusState, StateChange = self:GetJoystickState(ArcData)
if not InputActive then
ArcData.Arc:Hide()
ArcData.WaitForRelease = false
ArcData.RadiusState = nil
continue
end
--Update from the state.
local HumanoidRootPart = self.Character.Parts.HumanoidRootPart
if DirectionState ~= "Forward" or RadiusState == "Released" then
ArcData.Arc:Hide()
end
if StateChange == "Released" then
ArcData.Arc:Hide()
if DirectionState == "Forward" then
--Teleport the player.
local LastHitPart = ArcData.LastHitPart
if LastHitPart and ArcData.LastHitPosition then
--Unsit the player.
--The teleport event is set to ignored since the CFrame will be different when the player gets out of the seat.
local WasSitting = false
self:PlayBlur()
if SeatPart then
WasSitting = true
self.IgnoreNextExternalTeleport = true
self.Character.Humanoid.Sit = false
end
if (LastHitPart:IsA("Seat") or LastHitPart:IsA("VehicleSeat")) and not LastHitPart.Occupant and not LastHitPart.Disabled then
--Sit in the seat.
--Waiting is done if the player was in an existing seat because the player no longer sitting will prevent sitting.
local LastHitSeat = (LastHitPart :: Seat)
if WasSitting then
task.spawn(function()
while self.Character.Humanoid.SeatPart do task.wait() end
LastHitSeat:Sit(self.Character.Humanoid)
end)
else
LastHitSeat:Sit(self.Character.Humanoid)
end
else
--Teleport the player.
--Waiting is done if the player was in an existing seat because the player will teleport the seat.
if WasSitting then
task.spawn(function()
while self.Character.Humanoid.SeatPart do task.wait() end
HumanoidRootPart.CFrame = CFrame.new(ArcData.LastHitPosition) * CFrame.new(0, 4.5 * self.Character:GetHumanoidScale("BodyHeightScale"), 0) * (CFrame.new(-HumanoidRootPart.Position) * HumanoidRootPart.CFrame)
end)
else
HumanoidRootPart.CFrame = CFrame.new(ArcData.LastHitPosition) * CFrame.new(0, 4.5 * self.Character:GetHumanoidScale("BodyHeightScale"), 0) * (CFrame.new(-HumanoidRootPart.Position) * HumanoidRootPart.CFrame)
end
end
end
end
elseif StateChange == "Cancel" then
ArcData.Arc:Hide()
elseif DirectionState == "Forward" and RadiusState == "Extended" then
ArcData.LastHitPart, ArcData.LastHitPosition = ArcData.Arc:Update(Workspace.CurrentCamera:GetRenderCFrame() * VRInputs[Enum.UserCFrame.Head]:Inverse() * VRInputs[ArcData.UserCFrame])
end
--Rotate the character.
self:UpdateRotating(ArcData.UserCFrame, DirectionState, StateChange)
end
end
return TeleportController | 1,484 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/Character/Controller/Visual/Arc.luau | --Visual indicator aiming with an arc.
--!strict
local MAX_SEGMENTS = 100
local SEGMENT_SEPARATION = 2
local BASE_POINTER_ANGLE = math.rad(60)
local POINTER_PARABOLA_HEIGHT_MULTIPLIER = -0.2
local Workspace = game:GetService("Workspace")
local Players = game:GetService("Players")
local NexusVRCharacterModel = script.Parent.Parent.Parent.Parent
local FindCollidablePartOnRay = require(NexusVRCharacterModel:WaitForChild("Util"):WaitForChild("FindCollidablePartOnRay"))
local Arc = {}
Arc.__index = Arc
export type Arc = {
BeamParts: {BasePart},
} & typeof(setmetatable({}, Arc))
--[[
Creates an arc.
--]]
function Arc.new(): Arc
local self = setmetatable({
BeamParts = {},
}, Arc) :: Arc
self:Hide()
return self
end
--[[
Updates the arc. Returns the part and
position that were hit.
--]]
function Arc.Update(self: Arc, StartCFrame: CFrame): (BasePart?, Vector3?)
--Calculate the starting angle.
local StartPosition = StartCFrame.Position
local FaceAngle = math.atan2(-StartCFrame.LookVector.X, -StartCFrame.LookVector.Z)
local StartAngle = math.asin(StartCFrame.LookVector.Y)
StartAngle = StartAngle + (BASE_POINTER_ANGLE * ((math.pi / 2) - math.abs(StartAngle)) / (math.pi / 2))
--Calculate the start CFrame and start offset of the parabola.
--The start is the where the derivative of POINTER_PARABOLA_HEIGHT_MULTIPLIER * x^2 is tan(StartAngle).
local StartCF = CFrame.new(StartPosition) * CFrame.Angles(0, FaceAngle, 0)
local StartOffset = math.tan(StartAngle) / (POINTER_PARABOLA_HEIGHT_MULTIPLIER * 2)
local StartValue = POINTER_PARABOLA_HEIGHT_MULTIPLIER * (StartOffset ^ 2)
--Create the parts until the limit is reached.
for i = 0, MAX_SEGMENTS - 1 do
--Calculate the current and next position.
local SegmentStartPosition = (StartCF * CFrame.new(0, POINTER_PARABOLA_HEIGHT_MULTIPLIER * ((i + StartOffset) ^ 2) - StartValue, -SEGMENT_SEPARATION * i)).Position
local SegmentEndPosition = (StartCF * CFrame.new(0, POINTER_PARABOLA_HEIGHT_MULTIPLIER * ((i + 1 + StartOffset) ^ 2) - StartValue, -SEGMENT_SEPARATION * (i + 1))).Position
--Create the parts if they don't exist.
if not self.BeamParts[i] then
self.BeamParts[i] = Instance.new("Part")
self.BeamParts[i].Transparency = 1
self.BeamParts[i].Size = Vector3.new(0, 0, 0)
self.BeamParts[i].Anchored = true
self.BeamParts[i].CanCollide = false
self.BeamParts[i].CanQuery = false
self.BeamParts[i].Parent = Workspace.CurrentCamera
local Attachment = Instance.new("Attachment")
Attachment.Name = "BeamAttachment"
Attachment.CFrame = CFrame.Angles(0, 0, math.pi / 2)
Attachment.Parent = self.BeamParts[i]
end
if not self.BeamParts[i + 1] then
--Create the part and attachment.
self.BeamParts[i + 1] = Instance.new("Part")
self.BeamParts[i + 1].Transparency = 1
self.BeamParts[i + 1].Size = Vector3.new(0, 0, 0)
self.BeamParts[i + 1].Anchored = true
self.BeamParts[i + 1].CanCollide = false
self.BeamParts[i + 1].CanQuery = false
self.BeamParts[i + 1].Parent = Workspace.CurrentCamera
local Attachment = Instance.new("Attachment")
Attachment.Name = "BeamAttachment"
Attachment.CFrame = CFrame.Angles(0, 0, math.pi / 2)
Attachment.Parent = self.BeamParts[i + 1]
--Create the beam.
local Beam = Instance.new("Beam")
Beam.Name = "Beam"
Beam.Attachment0 = (self.BeamParts[i] :: any).BeamAttachment
Beam.Attachment1 = Attachment
Beam.Segments = 1
Beam.Width0 = 0.1
Beam.Width1 = 0.1
Beam.Parent = self.BeamParts[i + 1]
end
--Cast the ray to the end.
--Return if an end was hit and make the arc blue.
local HitPart, HitPosition = FindCollidablePartOnRay(SegmentStartPosition, SegmentEndPosition - SegmentStartPosition, Players.LocalPlayer and Players.LocalPlayer.Character,Players.LocalPlayer and Players.LocalPlayer.Character and Players.LocalPlayer.Character:FindFirstChild("HumanoidRootPart"))
self.BeamParts[i].CFrame = CFrame.new(SegmentStartPosition) * CFrame.Angles(0, FaceAngle, 0);
(self.BeamParts[i + 1] :: any).Beam.Enabled = true
if HitPart then
self.BeamParts[i + 1].CFrame = CFrame.new(HitPosition)
for j = 0, i do
(self.BeamParts[j + 1] :: any).Beam.Color = ColorSequence.new(Color3.fromRGB(0, 170, 255))
end
for j = i + 1, #self.BeamParts - 1 do
(self.BeamParts[j + 1] :: any).Beam.Enabled = false
end
return HitPart, HitPosition
else
self.BeamParts[i + 1].CFrame = CFrame.new(SegmentEndPosition)
end
end
--Set the beams to red.
for i = 0, #self.BeamParts - 1 do
(self.BeamParts[i + 1] :: any).Beam.Color = ColorSequence.new(Color3.fromRGB(200, 0, 0))
end
return nil, nil
end
--[[
Hides the arc.
--]]
function Arc.Hide(self: Arc): ()
for i = 0, #self.BeamParts - 1 do
(self.BeamParts[i + 1] :: any).Beam.Enabled = false
end
end
--[[
Destroys the arc.
--]]
function Arc.Destroy(self: Arc): ()
for _, BeamPart in self.BeamParts do
BeamPart:Destroy()
end
self.BeamParts = {}
end
return Arc | 1,492 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/Character/Controller/Visual/ArcWithBeacon.luau | --Extension of the arc to add a beacon.
--!strict
local Arc = require(script.Parent:WaitForChild("Arc"))
local Beacon = require(script.Parent:WaitForChild("Beacon"))
local ArcWithBeacon = {}
ArcWithBeacon.__index = ArcWithBeacon
setmetatable(ArcWithBeacon, Arc)
export type ArcWithBeacon = {
Beacon: Beacon.Beacon,
} & typeof(setmetatable({}, ArcWithBeacon)) & Arc.Arc
--[[
Creates an arc.
--]]
function ArcWithBeacon.new(): ArcWithBeacon
local self = setmetatable(Arc.new() :: any, ArcWithBeacon) :: ArcWithBeacon
self.Beacon = Beacon.new()
self:Hide()
return self :: ArcWithBeacon
end
--[[
Updates the arc. Returns the part and
position that were hit.
--]]
function ArcWithBeacon.Update(self: ArcWithBeacon, StartCFrame: CFrame): (BasePart?, Vector3?)
--Update the arc.
local HitPart, HitPosition = Arc.Update(self, StartCFrame)
--Update the beacon.
local Beacon = (self :: any).Beacon :: Beacon.Beacon
if HitPart then
Beacon:Update(CFrame.new(HitPosition :: Vector3) * CFrame.new(0, 0.001, 0), HitPart)
else
Beacon:Hide()
end
--Return the arc's returns.
return HitPart, HitPosition
end
--[[
Hides the arc.
--]]
function ArcWithBeacon.Hide(self: ArcWithBeacon): ()
Arc.Hide(self);
self.Beacon:Hide()
end
--[[
Destroys the arc.
--]]
function ArcWithBeacon.Destroy(self: ArcWithBeacon): ()
Arc.Destroy(self);
self.Beacon:Destroy()
end
return ArcWithBeacon | 409 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/Character/Controller/Visual/Beacon.luau | --Visual indicator for the end of aiming.
--!strict
local BEACON_SPEED_MULTIPLIER = 2
local Workspace = game:GetService("Workspace")
local Beacon = {}
Beacon.__index = Beacon
export type Beacon = {
Sphere: Part,
ConstantRing: ImageHandleAdornment,
MovingRing: ImageHandleAdornment,
} & typeof(setmetatable({}, Beacon))
--[[
Creates a beacon.
--]]
function Beacon.new(): Beacon
--Create the object.
local self = {}
setmetatable(self, Beacon)
--Create the parts.
local Sphere = Instance.new("Part")
Sphere.Transparency = 1
Sphere.Material = Enum.Material.Neon
Sphere.Anchored = true
Sphere.CanCollide = false
Sphere.CanQuery = false
Sphere.Size = Vector3.new(0.5, 0.5, 0.5)
Sphere.Shape = Enum.PartType.Ball
Sphere.Parent = Workspace.CurrentCamera
local ConstantRing = Instance.new("ImageHandleAdornment")
ConstantRing.Adornee = Sphere
ConstantRing.Size = Vector2.new(2, 2)
ConstantRing.Image = "rbxasset://textures/ui/VR/VRPointerDiscBlue.png"
ConstantRing.Visible = false
ConstantRing.Parent = Sphere
local MovingRing = Instance.new("ImageHandleAdornment")
MovingRing.Adornee = Sphere
MovingRing.Size = Vector2.new(2, 2)
MovingRing.Image = "rbxasset://textures/ui/VR/VRPointerDiscBlue.png"
MovingRing.Visible = false
MovingRing.Parent = Sphere
--Return the object.
return setmetatable({
Sphere = Sphere,
ConstantRing = ConstantRing,
MovingRing = MovingRing,
}, Beacon) :: Beacon
end
--[[
Updates the beacon at a given CFrame.
--]]
function Beacon.Update(self: Beacon, CenterCFrame: CFrame, HoverPart: BasePart): ()
--Calculate the size for the current time.
local Height = 0.4 + (-math.cos(tick() * 2 * BEACON_SPEED_MULTIPLIER) / 8)
local BeaconSize = 2 * ((tick() * BEACON_SPEED_MULTIPLIER) % math.pi) / math.pi
--Update the size and position of the beacon.
self.Sphere.CFrame = CenterCFrame * CFrame.new(0, Height, 0)
self.ConstantRing.CFrame = CFrame.new(0, -Height, 0) * CFrame.Angles(math.pi / 2, 0, 0)
self.MovingRing.CFrame = CFrame.new(0, -Height, 0) * CFrame.Angles(math.pi / 2, 0, 0)
self.MovingRing.Transparency = BeaconSize / 2
self.MovingRing.Size = Vector2.new(BeaconSize, BeaconSize)
--Update the beacon color.
local BeaconColor = Color3.fromRGB(0, 170, 0)
if HoverPart then
local VRBeaconColor = HoverPart:FindFirstChild("VRBeaconColor") :: Color3Value
if VRBeaconColor then
BeaconColor = VRBeaconColor.Value
elseif (HoverPart:IsA("Seat") or HoverPart:IsA("VehicleSeat")) and not HoverPart.Disabled then
BeaconColor = Color3.fromRGB(0, 170, 255)
end
end
self.Sphere.Color = BeaconColor
--Show the beacon.
self.Sphere.Transparency = 0
self.ConstantRing.Visible = true
self.MovingRing.Visible = true
end
--[[
Hides the beacon.
--]]
function Beacon.Hide(self: Beacon): ()
--Hide the beacon.
self.Sphere.Transparency = 1
self.ConstantRing.Visible = false
self.MovingRing.Visible = false
end
--[[
Destroys the beacon.
--]]
function Beacon.Destroy(self: Beacon): ()
self.Sphere:Destroy()
end
return Beacon | 874 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/Character/FootPlanter.luau | --[[
Attempts to solve footplanting.
This code is heavily "zombified" off of a project by
Stravant, and is taken from Nexus VR Character Model V1
with minimal changes. It really needs to be replaced by
someone who better unstands foot placement. No automated
tests are done on this code.
--]]
local FootPlanter = {}
local CFnew,CFAngles = CFrame.new,CFrame.Angles
local V3new = Vector3.new
local rad,atan2,acos = math.rad,math.atan2,math.acos
local min,max,abs,log = math.min,math.max,math.abs,math.log
function FootPlanter:CreateSolver(CenterPart,ScaleValue)
--Heavily modified code from Stravant
local FootPlanterClass = {}
local ignoreModel = CenterPart.Parent
local LEG_GAP = 1.2
--
local STRIDE_FORWARD = 1.7 / 2
local STRIDE_BACKWARD = 3.3 / 2
local STRIDE_HEIGHT = 0.6
local STRIDE_RESTING = 1
--
local WALK_SPEED_VR_THRESHOLD = 2
local FOOT_MAX_SPEED_FACTOR = 2
--
local WALK_CYCLE_POWER = 1
--
local FOOT_ANGLE = rad(5)
local function flatten(CF)
local X,Y,Z = CF.X,CF.Y,CF.Z
local LX,LZ = CF.lookVector.X,CF.lookVector.Z
return CFnew(X,Y,Z) * CFAngles(0,atan2(LX,LZ),0)
end
local lastPosition,lastPollTime
local overrideVelocityWithZero = false
local function getVelocity(CF)
if overrideVelocityWithZero then
overrideVelocityWithZero = true
local curTime = tick()
lastPosition = CF.p
return V3new()
end
if lastPollTime then
local curTime = tick()
local newPosition = CF.p
local velocity = (newPosition - lastPosition) * 1/(curTime - lastPollTime)
lastPollTime = curTime
lastPosition = newPosition
return velocity
else
lastPollTime = tick()
lastPosition = CF.p
return V3new()
end
end
local function getWalkSpeed(velocity)
return V3new(velocity.x,0,velocity.z).magnitude
end
local function getWalkDirection(velocity)
if velocity.magnitude > 0. then
return velocity.unit
else
return V3new(0,0,-1)
end
end
local function isWalking(velocity)
return getWalkSpeed(velocity) > WALK_SPEED_VR_THRESHOLD
end
local CurrentScale = 1
local function getBaseCFrame()
return CenterPart.CFrame * CFnew(0,-CenterPart.Size.Y/2 - (CurrentScale * 2),0)
end
local function getBaseRotationY()
local lookVector = getBaseCFrame().lookVector
return atan2(lookVector.X,lookVector.Z)
end
local FindCollidablePartOnRay = require(script.Parent.Parent:WaitForChild("Util"):WaitForChild("FindCollidablePartOnRay"))
local function FindPartOnRay(ray,ignore)
return FindCollidablePartOnRay(ray.Origin,ray.Direction,ignore,CenterPart)
end
-- Leg data
local mRightLeg, mLeftLeg, mRightArm, mLeftArm;
local mLegs = {}
local lastCF
local function initLegs()
local cf = flatten(getBaseCFrame())
lastCF = cf
mRightLeg = {
OffsetModifier = CFnew(-LEG_GAP/2, 0, 0);
Side = -1;
--
StepCycle = 0;
FootPosition = cf*CFnew(-LEG_GAP/2, 0, 0).p;
LastStepTo = cf*CFnew(-LEG_GAP/2, 0, 0).p;
Takeoff = cf*CFnew(-LEG_GAP/2, 0, 0).p;
}
mLeftLeg = {
OffsetModifier = CFnew( LEG_GAP/2, 0, 0);
Side = 1;
--
StepCycle = 0;
FootPosition = cf*CFnew( LEG_GAP/2, 0, 0).p;
LastStepTo = cf*CFnew(-LEG_GAP/2, 0, 0).p;
Takeoff = cf*CFnew(-LEG_GAP/2, 0, 0).p;
}
mRightLeg.OtherLeg = mLeftLeg
mLeftLeg.OtherLeg = mRightLeg
mLegs = {mLeftLeg, mRightLeg}
end
local LastScale = 1
local function UpdateScaling()
local CurrentScaleValue = (ScaleValue and ScaleValue.Value or 1)
local Multiplier = CurrentScaleValue / LastScale
LastScale = CurrentScaleValue
LEG_GAP = LEG_GAP * Multiplier
STRIDE_FORWARD = STRIDE_FORWARD * Multiplier
STRIDE_BACKWARD = STRIDE_BACKWARD * Multiplier
STRIDE_HEIGHT = STRIDE_HEIGHT * Multiplier
STRIDE_RESTING = STRIDE_RESTING * Multiplier
mRightLeg.OffsetModifier = CFnew(-LEG_GAP/2, 0, 0)
--[[mRightLeg.FootPosition
mRightLeg.LastStepTo
mRightLeg.Takeoff
= ;
Side = -1;
--
StepCycle = 0;
= lastCF*CFnew(-LEG_GAP/2, 0, 0).p;
= lastCF*CFnew(-LEG_GAP/2, 0, 0).p;
= lastCF*CFnew(-LEG_GAP/2, 0, 0).p;
}
mLeftLeg = {
OffsetModifier = CFnew( LEG_GAP/2, 0, 0);
Side = 1;
--
StepCycle = 0;
FootPosition = lastCF*CFnew( LEG_GAP/2, 0, 0).p;
LastStepTo = lastCF*CFnew(-LEG_GAP/2, 0, 0).p;
Takeoff = lastCF*CFnew(-LEG_GAP/2, 0, 0).p;
}]]
end
if ScaleValue then
ScaleValue.Changed:Connect(function()
if mRightLeg then
UpdateScaling()
end
end)
end
local mAirborneFraction = 0
local mLandedFraction = 0
local mCurrentSpeed = 1
local mStableStanding = false
local function getStrideForward()
if mCurrentSpeed > 0 then
return STRIDE_FORWARD + STRIDE_FORWARD*1*mCurrentSpeed
else
return STRIDE_FORWARD + STRIDE_FORWARD*0.5*mCurrentSpeed
end
end
local function getStrideFull()
if mCurrentSpeed > 0 then
return (STRIDE_FORWARD + STRIDE_BACKWARD) + (STRIDE_FORWARD + STRIDE_BACKWARD)*1.5*mCurrentSpeed
else
return (STRIDE_FORWARD + STRIDE_BACKWARD) + (STRIDE_FORWARD + STRIDE_BACKWARD)*0.5*mCurrentSpeed
end
end
local function snapDown(pos)
local orig, dir = (pos + V3new(0, 2, 0)), V3new(0, -500, 0)
local hit, at = FindPartOnRay(Ray.new(orig, dir), ignoreModel)
if hit then
local hit1, at1 = FindPartOnRay(Ray.new(orig + V3new(0, 0, 0.01), dir), ignoreModel)
local hit2, at2 = FindPartOnRay(Ray.new(orig + V3new(0, 0, -0.01), dir), ignoreModel)
local hit3, at3 = FindPartOnRay(Ray.new(orig + V3new(0.01, 0, 0 ), dir), ignoreModel)
local norm;
if hit1 and hit2 and hit3 then
norm = (at1 - at2):Cross(at2 - at3).unit
if norm.Y < 0 then
norm = -norm
end
end
return at, norm
else
return pos, V3new(0, 1, 0)
end
end
local function fixFeetPositionsY()
for _,leg in pairs(mLegs) do
local targetPos,norm = snapDown(leg.FootPosition)
leg.FootPosition = targetPos
end
end
local lastTime
function FootPlanterClass:GetFeetCFrames()
if not mLeftLeg then
initLegs()
UpdateScaling()
end
local curTime = tick()
if not lastTime then lastTime = curTime end
local dt = curTime - lastTime
lastTime = curTime
local velocity = getVelocity(CenterPart.CFrame)
local speed = getWalkSpeed(velocity)
local realBaseCF = flatten(CenterPart.CFrame)
local baseCF = realBaseCF
local baseAxis = baseCF.lookVector
local baseAxisPerp = baseAxis:Cross(V3new(0, 1, 0))
local walkAxis = getWalkDirection(velocity)
local walkAxisPerp = walkAxis:Cross(V3new(0, 1, 0))
--
mCurrentSpeed = max(-1, min(1, log(speed/16)/log(2)))
--
local leftStepping = mLeftLeg.StepCycle > 0
local rightStepping = mRightLeg.StepCycle > 0
--
local function spline(t2, n, p)
if n == 1 then
return p[1]
else
local t1 = (1 - t2)
for i = 1, n-1 do
p[i] = t1*p[i] + t2*p[i+1]
end
return spline(t2, n-1, p)
end
end
local function positionFootByCycle(leg, stepTarget)
local baseVector = stepTarget - leg.Takeoff
local sideVector = walkAxisPerp*leg.Side
local baseLen = baseVector.magnitude
local towardsSide = sideVector*(LEG_GAP/2)*0.3
local towardsTop = V3new(0, 1.3*STRIDE_HEIGHT*(1 / leg.StepSpeedMod), 0)
local topPoint = leg.Takeoff + baseVector * 1/2 + towardsTop + towardsSide
local nextPoint = leg.Takeoff + baseVector * 0.9 + towardsTop + towardsSide
--local a, b, c = leg.Takeoff, topPoint, stepTarget
--local fb = leg.StepCycle
--fb = fb^(_G.A or WALK_CYCLE_POWER)
--local fa = 1-fb
--
--local footDesiredPos = fa*fa*a + 2*fa*fb*b + fb*fb*c
local fb = leg.StepCycle^(_G.A or WALK_CYCLE_POWER)
local footDesiredPos = spline(fb, 4, {leg.Takeoff, topPoint, nextPoint, stepTarget})
--makeP(CFnew(footDesiredPos))
if (footDesiredPos - leg.FootPosition).magnitude > dt*speed*FOOT_MAX_SPEED_FACTOR then
local forcePos = (1 - leg.StepCycle) * leg.FootPosition + leg.StepCycle * footDesiredPos
local movePos = leg.FootPosition + (footDesiredPos - leg.FootPosition).unit * dt*speed*FOOT_MAX_SPEED_FACTOR
if (forcePos - footDesiredPos).magnitude < (movePos - footDesiredPos).magnitude then
footDesiredPos = forcePos
else
footDesiredPos = movePos
end
end
leg.FootPosition = footDesiredPos
leg.LastStepTo = stepTarget
end
--
local isCharacterWalking = isWalking(velocity)
if isCharacterWalking then
mStableStanding = false
end
--
if isCharacterWalking then
-- Get the desired ahead step
local centeringMod = walkAxisPerp * (LEG_GAP/2) * 0.5
local rightDesiredAheadStep = (baseCF * mRightLeg.OffsetModifier + getStrideForward()*walkAxis - mRightLeg.Side*centeringMod).p
local leftDesiredAheadStep = (baseCF * mLeftLeg.OffsetModifier + getStrideForward()*walkAxis - mLeftLeg.Side*centeringMod).p
local rightNorm, leftNorm;
rightDesiredAheadStep, rightNorm = snapDown(rightDesiredAheadStep)
leftDesiredAheadStep, leftNorm = snapDown(leftDesiredAheadStep)
if not rightStepping or not mRightLeg.AheadStep or (rightDesiredAheadStep - mRightLeg.AheadStep).magnitude < dt*speed then
mRightLeg.AheadStep = rightDesiredAheadStep
else
mRightLeg.AheadStep = mRightLeg.AheadStep + (rightDesiredAheadStep - mRightLeg.AheadStep).unit * dt*speed*2
end
mRightLeg.NormalHint = rightNorm
if not leftStepping or not mLeftLeg.AheadStep or (leftDesiredAheadStep - mLeftLeg.AheadStep).magnitude < dt*speed then
mLeftLeg.AheadStep = leftDesiredAheadStep
else
mLeftLeg.AheadStep = mLeftLeg.AheadStep + (leftDesiredAheadStep - mLeftLeg.AheadStep).unit * dt*speed*2
end
mLeftLeg.NormalHint = leftNorm
local strideFactor = 0.9 - 0.3*max(0, mCurrentSpeed)
local stepSpeed = speed / getStrideFull() * strideFactor
-- Which legs are stepping?
if not leftStepping and not rightStepping then
-- Neither leg is stepping pick up the closer leg into the step
if mAirborneFraction < 0.8 then -- don't pick up feet if we just landed
if (mLeftLeg.FootPosition - mLeftLeg.AheadStep).magnitude < (mRightLeg.FootPosition - mRightLeg.AheadStep).magnitude then
-- step p1
local fracThere = min(0.9, max(0, (mLeftLeg.FootPosition - mLeftLeg.AheadStep).magnitude / getStrideFull()))
mLeftLeg.StepSpeedMod = 1 / (1 - fracThere)
mLeftLeg.StepCycle = dt
mLeftLeg.Takeoff = mLeftLeg.FootPosition
else
-- step p2
local fracThere = min(0.9, max(0, (mRightLeg.FootPosition - mRightLeg.AheadStep).magnitude / getStrideFull()))
mRightLeg.StepSpeedMod = 1 / (1 - fracThere)
mRightLeg.StepCycle = dt
mRightLeg.Takeoff = mRightLeg.FootPosition
end
end
elseif leftStepping and rightStepping then
-- Both legs are stepping
-- just step both legs
-- The leg closer to |aheadStep| should step there, and the
-- other leg should
for _, leg in pairs(mLegs) do
leg.StepCycle = min(1, leg.StepCycle + dt*stepSpeed*leg.StepSpeedMod)
positionFootByCycle(leg, leg.AheadStep)
if leg.StepCycle == 1 then
leg.StepCycle = 0
end
end
else
-- One leg is stepping.
-- Step the one leg, and see if the other needs to enter a step
for _, leg in pairs(mLegs) do
if leg.StepCycle > 0 then
-- Step this leg
leg.StepCycle = min(1, leg.StepCycle + dt*stepSpeed*leg.StepSpeedMod)
positionFootByCycle(leg, leg.AheadStep)
-- Check if leg.Other needs to start a step
if leg.StepCycle > strideFactor then
leg.OtherLeg.StepSpeedMod = 1
leg.OtherLeg.StepCycle = dt
leg.OtherLeg.Takeoff = leg.OtherLeg.FootPosition
positionFootByCycle(leg.OtherLeg, leg.AheadStep)
end
if leg.StepCycle == 1 then
leg.StepCycle = 0
end
break
end
end
end
else
local stepSpeed = 2
-- Not walking, we need to try to get to a suitable base position
if leftStepping or rightStepping then
for _, leg in pairs(mLegs) do
if leg.StepCycle > 0 then
leg.StepCycle = min(1, leg.StepCycle + dt*stepSpeed)
local restingPos = (baseCF * leg.OffsetModifier).p
local toVec = (leg.LastStepTo - restingPos)
local targetPos;
if toVec.magnitude > STRIDE_RESTING then
targetPos = restingPos + (toVec.unit * STRIDE_RESTING)
else
targetPos = leg.LastStepTo
end
local norm;
targetPos, norm = snapDown(targetPos)
leg.AheadStep = targetPos
leg.NormalHint = norm
positionFootByCycle(leg, targetPos)
if leg.StepCycle == 1 then
leg.StepCycle = 0
end
else
end
end
else
fixFeetPositionsY()
end
-- Now, we stepped both legs. If both legs are resting now. See if
-- they are on roughly opposite offsets from where they should be.
if mRightLeg.StepCycle == 0 and mLeftLeg.StepCycle == 0 then
local rightResting = (baseCF * mRightLeg.OffsetModifier).p
local leftResting = (baseCF * mLeftLeg.OffsetModifier).p
local rightSep = mRightLeg.FootPosition - rightResting
local leftSep = mLeftLeg.FootPosition - leftResting
--
local tooFar = abs(rightSep:Dot(baseAxis) - leftSep:Dot(baseAxis)) > 3
local thetaBetweenFeet = acos(min(1, max(-1, rightSep.unit:Dot(leftSep.unit))))
local distBetweenFeet = abs(rightSep.magnitude - leftSep.magnitude)
--
if rightSep:Dot(baseAxisPerp) > LEG_GAP/4 then
mStableStanding = false
mRightLeg.Takeoff = mRightLeg.FootPosition
mRightLeg.StepCycle = dt
--mRightLeg.LastStepTo = rightResting - baseAxisPerp*0.5
local modLeftSep = leftSep.unit * 0.5
if leftSep.magnitude == 0 then
modLeftSep = -baseAxisPerp*0.5
elseif leftSep:Dot(baseAxisPerp) > 0 then
modLeftSep = (leftSep - 2*baseAxisPerp*leftSep:Dot(baseAxisPerp)).unit*0.5
end
mRightLeg.LastStepTo = rightResting + modLeftSep
if (mRightLeg.LastStepTo - mRightLeg.Takeoff).magnitude < 0.5 then
mRightLeg.StepCycle = 0
end
local fracThere = min(0.9, max(0, (mRightLeg.FootPosition - mRightLeg.LastStepTo).magnitude / getStrideFull()))
mRightLeg.StepSpeedMod = 1 / (1 - fracThere)
elseif leftSep:Dot(baseAxisPerp) < -LEG_GAP/4 then
mStableStanding = false
mLeftLeg.Takeoff = mLeftLeg.FootPosition
mLeftLeg.StepCycle = dt
--mLeftLeg.LastStepTo = leftResting + baseAxisPerp*0.5
local modRightSep = rightSep.unit * 0.5
if rightSep.magnitude == 0 then
modRightSep = baseAxisPerp*0.5
elseif rightSep:Dot(baseAxisPerp) < 0 then
modRightSep = (rightSep - 2*baseAxisPerp*rightSep:Dot(baseAxisPerp)).unit*0.5
end
mLeftLeg.LastStepTo = leftResting + modRightSep
if (mRightLeg.LastStepTo - mRightLeg.Takeoff).magnitude < 0.5 then
mRightLeg.StepCycle = 0
end
local fracThere = min(0.9, max(0, (mLeftLeg.FootPosition - mLeftLeg.LastStepTo).magnitude / getStrideFull()))
mLeftLeg.StepSpeedMod = 1 / (1 - fracThere)
elseif not mStableStanding and (thetaBetweenFeet < rad(150) or distBetweenFeet > 0.2 or tooFar) and mAirborneFraction < 0.5 then
mStableStanding = true
-- Step the foot further from the rest pos
local furtherLeg, furtherResting, otherSep;
if rightSep.magnitude > leftSep.magnitude then
furtherLeg = mRightLeg
furtherResting = rightResting
otherSep = leftSep
else
furtherLeg = mLeftLeg
furtherResting = leftResting
otherSep = rightSep
end
--
furtherLeg.StepCycle = dt
furtherLeg.Takeoff = furtherLeg.FootPosition
furtherLeg.StepSpeedMod = 1
if tooFar then
furtherLeg.LastStepTo = furtherResting - 0.5*otherSep
else
furtherLeg.LastStepTo = furtherResting - otherSep
end
if (furtherLeg.Takeoff - furtherLeg.LastStepTo).magnitude < 0.2 then
furtherLeg.StepCycle = 0
end
end
end
fixFeetPositionsY()
end
local leftFootPosition,rightFootPosition = mLeftLeg.FootPosition,mRightLeg.FootPosition
local footAngle = getBaseRotationY()
local leftFootRotation = CFAngles(0,FOOT_ANGLE + footAngle,0)
local rightFootRotation = CFAngles(0,-FOOT_ANGLE + footAngle,0)
return CFnew(leftFootPosition) * leftFootRotation,CFnew(rightFootPosition) * rightFootRotation
end
function FootPlanterClass:OffsetFeet(Offset)
overrideVelocityWithZero = true
for _,leg in pairs(mLegs) do
leg.FootPosition = leg.FootPosition + Offset
leg.LastStepTo = leg.LastStepTo + Offset
if leg.Takeoff then leg.Takeoff = leg.Takeoff + Offset end
if leg.AheadStep then leg.AheadStep = leg.AheadStep + Offset end
end
overrideVelocityWithZero = true
end
return FootPlanterClass
end
return FootPlanter
| 5,274 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/Character/Head.luau | --Stores information about the head of a character.
--!strict
local NexusVRCharacterModel = script.Parent.Parent
local NexusAppendage = require(script.Parent.Parent:WaitForChild("Packages"):WaitForChild("NexusAppendage"))
local Settings = require(NexusVRCharacterModel:WaitForChild("State"):WaitForChild("Settings")).GetInstance()
local Limb = NexusAppendage.Limb
local Head = {}
Head.__index = Head
setmetatable(Head, Limb)
export type Head = {
Head: BasePart,
LastNeckRotationGlobal: number?,
} & typeof(setmetatable({}, Head)) & NexusAppendage.Limb
--[[
Creates a head.
--]]
function Head.new(HeadPart: BasePart): Head
local self = setmetatable(Limb.new() :: any, Head) :: Head
self.Head = HeadPart
return self
end
--[[
Returns the offset from the head to
the location of the eyes.
--]]
function Head.GetEyesOffset(self: Head): CFrame
return (self:GetAttachmentCFrame(self.Head, "FaceFrontAttachment") :: CFrame) * CFrame.new(0, (self.Head :: BasePart).Size.Y / 4, 0)
end
--[[
Returns the head CFrame for the
given VR input in global world space.
--]]
function Head.GetHeadCFrame(self: Head, VRHeadCFrame: CFrame): CFrame
return VRHeadCFrame * self:GetEyesOffset():Inverse()
end
--[[
Returns the neck CFrame for the
given VR input in global world space.
--]]
function Head.GetNeckCFrame(self: Head, VRHeadCFrame: CFrame, TargetAngle: number?): CFrame
--Get the base neck CFrame and angles.
local BaseNeckCFrame = (self:GetHeadCFrame(VRHeadCFrame) :: CFrame) * (self:GetAttachmentCFrame(self.Head, "NeckRigAttachment") :: CFrame)
local BaseNeckLookVector = BaseNeckCFrame.LookVector
local BaseNeckLook,BaseNeckTilt = math.atan2(BaseNeckLookVector.X, BaseNeckLookVector.Z) + math.pi, math.asin(BaseNeckLookVector.Y)
--Clamp the new neck tilt.
local NewNeckTilt = 0
local MaxNeckTilt = Settings:GetSetting("Appearance.MaxNeckTilt") or math.rad(60)
if BaseNeckTilt > MaxNeckTilt then
NewNeckTilt = BaseNeckTilt - MaxNeckTilt
elseif BaseNeckTilt < -MaxNeckTilt then
NewNeckTilt = BaseNeckTilt + MaxNeckTilt
end
--Clamp the neck rotation if it is turning.
if TargetAngle then
--Determine the minimum angle difference.
--Modulus is not used as it guarentees a positive answer, not the minimum answer, which can be negative.
local RotationDifference = (BaseNeckLook - TargetAngle)
while RotationDifference > math.pi do RotationDifference = RotationDifference - (2 * math.pi) end
while RotationDifference < -math.pi do RotationDifference = RotationDifference + (2 * math.pi) end
--Set the angle based on if it is over the limit or not.
local MaxNeckSeatedRotation = Settings:GetSetting("Appearance.MaxNeckSeatedRotation") or math.rad(60)
if RotationDifference > MaxNeckSeatedRotation then
BaseNeckLook = RotationDifference - MaxNeckSeatedRotation
elseif RotationDifference < -MaxNeckSeatedRotation then
BaseNeckLook = RotationDifference + MaxNeckSeatedRotation
else
BaseNeckLook = 0
end
else
local MaxNeckRotation = Settings:GetSetting("Appearance.MaxNeckRotation") or math.rad(35)
local LastNeckRotationGlobal = self.LastNeckRotationGlobal
if LastNeckRotationGlobal then
--Determine the minimum angle difference.
--Modulus is not used as it guarentees a positive answer, not the minimum answer, which can be negative.
local RotationDifference = (BaseNeckLook - LastNeckRotationGlobal)
while RotationDifference > math.pi do RotationDifference = RotationDifference - (2 * math.pi) end
while RotationDifference < -math.pi do RotationDifference = RotationDifference + (2 * math.pi) end
--Set the angle based on if it is over the limit or not.
--Ignore if there is no previous stored rotation or if the rotation is "big" (like teleporting).
if math.abs(RotationDifference) < 1.5 * MaxNeckRotation then
if RotationDifference > MaxNeckRotation then
BaseNeckLook = BaseNeckLook - MaxNeckRotation
elseif RotationDifference < -MaxNeckRotation then
BaseNeckLook = BaseNeckLook + MaxNeckRotation
else
BaseNeckLook = LastNeckRotationGlobal
end
end
end
end
self.LastNeckRotationGlobal = BaseNeckLook
--Return the new neck CFrame.
return CFrame.new(BaseNeckCFrame.Position) * CFrame.Angles(0, BaseNeckLook, 0) * CFrame.Angles(NewNeckTilt, 0, 0)
end
return Head | 1,191 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/Character/Torso.luau | --Stores information about the torso of a character.
--!strict
local NexusVRCharacterModel = script.Parent.Parent
local NexusAppendage = require(script.Parent.Parent:WaitForChild("Packages"):WaitForChild("NexusAppendage"))
local Settings = require(NexusVRCharacterModel:WaitForChild("State"):WaitForChild("Settings")).GetInstance()
local Limb = NexusAppendage.Limb
local Torso = {}
Torso.__index = Torso
setmetatable(Torso, Limb)
export type Torso = {
LowerTorso: BasePart,
UpperTorso: BasePart,
} & typeof(setmetatable({}, Torso)) & NexusAppendage.Limb
--[[
Creates a torso.
--]]
function Torso.new(LowerTorso: BasePart, UpperTorso: BasePart): Torso
local self = setmetatable(Limb.new() :: any, Torso) :: Torso
self.LowerTorso = LowerTorso
self.UpperTorso = UpperTorso
return self
end
--[[
Returns the lower and upper torso CFrames
for the given neck CFrame in global world space.
--]]
function Torso.GetTorsoCFrames(self: Torso, NeckCFrame: CFrame): (CFrame, CFrame)
--Determine the upper torso CFrame.
local UpperTorsoCFrame = NeckCFrame * self:GetAttachmentCFrame(self.UpperTorso, "NeckRigAttachment"):Inverse()
--Determine the center CFrame with bending.
local MaxTorsoBend = Settings:GetSetting("Appearance.MaxTorsoBend") or math.rad(10)
local NeckTilt = math.asin(NeckCFrame.LookVector.Y)
local LowerTorsoAngle = math.sign(NeckTilt) * math.min(math.abs(NeckTilt), MaxTorsoBend)
local TorsoCenterCFrame = UpperTorsoCFrame * self:GetAttachmentCFrame(self.UpperTorso, "WaistRigAttachment") * CFrame.Angles(-LowerTorsoAngle, 0, 0)
--Return the lower and upper CFrames.
return TorsoCenterCFrame * self:GetAttachmentCFrame(self.LowerTorso, "WaistRigAttachment"):Inverse(), UpperTorsoCFrame
end
--[[
Returns the CFrames of the joints for
the appendages.
--]]
function Torso.GetAppendageJointCFrames(self: Torso, LowerTorsoCFrame: CFrame, UpperTorsoCFrame: CFrame): {[string]: CFrame}
return {
RightShoulder = UpperTorsoCFrame * self:GetAttachmentCFrame(self.UpperTorso, "RightShoulderRigAttachment"),
LeftShoulder = UpperTorsoCFrame * self:GetAttachmentCFrame(self.UpperTorso, "LeftShoulderRigAttachment"),
LeftHip = LowerTorsoCFrame * self:GetAttachmentCFrame(self.LowerTorso, "LeftHipRigAttachment"),
RightHip = LowerTorsoCFrame * self:GetAttachmentCFrame(self.LowerTorso, "RightHipRigAttachment"),
}
end
return Torso | 677 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/Character/init.luau | --Manipulates a character model.
--!strict
local SMOOTHING_DURATION_SECONDS = 1 / 30
local Players = game:GetService("Players")
local TweenService = game:GetService("TweenService")
local VRService = game:GetService("VRService")
local NexusVRCharacterModel = script.Parent
local Head = require(NexusVRCharacterModel:WaitForChild("Character"):WaitForChild("Head"))
local Torso = require(NexusVRCharacterModel:WaitForChild("Character"):WaitForChild("Torso"))
local AppendageLegacy = require(NexusVRCharacterModel:WaitForChild("Character"):WaitForChild("Appendage"))
local FootPlanter = require(NexusVRCharacterModel:WaitForChild("Character"):WaitForChild("FootPlanter"))
local EnigmaService = require(NexusVRCharacterModel:WaitForChild("State"):WaitForChild("EnigmaService")).GetInstance()
local Settings = require(NexusVRCharacterModel:WaitForChild("State"):WaitForChild("Settings")).GetInstance()
local VRInputService = require(NexusVRCharacterModel:WaitForChild("State"):WaitForChild("VRInputService")).GetInstance()
local NexusAppendage = require(NexusVRCharacterModel:WaitForChild("Packages"):WaitForChild("NexusAppendage"))
local UpdateInputs = NexusVRCharacterModel:WaitForChild("UpdateInputs") :: UnreliableRemoteEvent
local Appendage = NexusAppendage.Appendage
local Character = {}
Character.__index = Character
export type Character = {
CharacterModel: Model,
Humanoid: Humanoid,
Head: Head.Head,
Torso: Torso.Torso,
LeftArm: NexusAppendage.Appendage,
RightArm: NexusAppendage.Appendage,
LeftLeg: NexusAppendage.Appendage,
RightLeg: NexusAppendage.Appendage,
FootPlanter: any,
CurrentWalkspeed: number,
TweenComponents: boolean,
UseIKControl: boolean,
PreventArmDisconnection: boolean,
Parts: {[string]: BasePart},
Motors: {[string]: Motor6D},
Attachments: {[string]: {[string]: Attachment}},
CurrentMotor6DTransforms: {[Motor6D]: CFrame},
LastMotor6DTransforms: {[Motor6D]: CFrame},
LastRefreshTime: number,
ReplicationCFrames: {[string]: CFrame}?,
LastReplicationCFrames: {[string]: CFrame}?,
ReplicationTrackerData: {[string]: CFrame}?,
LastReplicationTrackerData: {[string]: CFrame}?,
AppearanceChangedConnection: RBXScriptConnection?,
} & typeof(setmetatable({}, Character))
--[[
Creates a character.
--]]
function Character.new(CharacterModel: Model): Character
local self = setmetatable({
CharacterModel = CharacterModel,
TweenComponents = (CharacterModel ~= Players.LocalPlayer.Character),
UseIKControl = Settings:GetSetting("Extra.TEMPORARY_UseIKControl"),
}, Character) :: Character
--Determine if the arms can be disconnected.
--Checking for the setting to be explicitly false is done in case the setting is undefined (default is true).
local PreventArmDisconnection = false
if Players.LocalPlayer and Players.LocalPlayer.Character == CharacterModel then
local Setting = Settings:GetSetting("Appearance.LocalAllowArmDisconnection")
if Setting == false then
PreventArmDisconnection = true
end
else
local Setting = Settings:GetSetting("Appearance.NonLocalAllowArmDisconnection")
if Setting == false then
PreventArmDisconnection = true
end
end
--Store the body parts.
self.Humanoid = CharacterModel:WaitForChild("Humanoid") :: Humanoid
self.CurrentWalkspeed = 0
self.Humanoid.Running:Connect(function(WalkSpeed)
if VRService.AvatarGestures and VRInputService:GetThumbstickPosition(Enum.KeyCode.Thumbstick1).Magnitude < 0.2 then
WalkSpeed = 0
end
self.CurrentWalkspeed = WalkSpeed
end)
--Set up the character parts.
self.PreventArmDisconnection = PreventArmDisconnection
self:SetUpVRParts()
--Set up a connection for Character Appearance changes.
self.AppearanceChangedConnection = nil :: RBXScriptConnection?
self:SetUpAppearanceChanged()
self.CurrentMotor6DTransforms = {}
self.LastMotor6DTransforms = {}
self.LastRefreshTime = tick()
--Set up replication at 30hz.
if Players.LocalPlayer and Players.LocalPlayer.Character == CharacterModel then
task.spawn(function()
while (self.Humanoid :: Humanoid).Health > 0 do
--Send the new CFrames if the CFrames changed.
local ReplicationCFrames = self.ReplicationCFrames
local ReplicationTrackerData = self.ReplicationTrackerData
if ReplicationCFrames and self.LastReplicationCFrames ~= ReplicationCFrames and self.LastReplicationTrackerData ~= ReplicationTrackerData then
self.LastReplicationCFrames = ReplicationCFrames
self.LastReplicationTrackerData = ReplicationTrackerData
local NewTrackerData = {
UpdateTime = tick(),
CurrentWalkspeed = self.CurrentWalkspeed,
LeftFootCFrame = ReplicationTrackerData and ReplicationTrackerData.LeftFoot,
RightFootCFrame = ReplicationTrackerData and ReplicationTrackerData.RightFoot,
}
if not VRService.AvatarGestures then
NewTrackerData.HeadCFrame = ReplicationCFrames.HeadCFrame
NewTrackerData.LeftHandCFrame = ReplicationCFrames.LeftHandCFrame
NewTrackerData.RightHandCFrame = ReplicationCFrames.RightHandCFrame
end
UpdateInputs:FireServer(NewTrackerData)
end
--Wait 1/30th of a second to send the next set of CFrames.
task.wait(1 / 30)
end
end)
end
return self
end
--[[
Set up Character Parts for VR.
This is also used, to refresh character parts.
--]]
function Character.SetUpVRParts(self: Character): ()
local CharacterModel = self.CharacterModel
local PreventArmDisconnection = self.PreventArmDisconnection
self.Parts = {
Head = CharacterModel:WaitForChild("Head") :: BasePart,
UpperTorso = CharacterModel:WaitForChild("UpperTorso") :: BasePart,
LowerTorso = CharacterModel:WaitForChild("LowerTorso") :: BasePart,
HumanoidRootPart = CharacterModel:WaitForChild("HumanoidRootPart") :: BasePart,
RightUpperArm = CharacterModel:WaitForChild("RightUpperArm") :: BasePart,
RightLowerArm = CharacterModel:WaitForChild("RightLowerArm") :: BasePart,
RightHand = CharacterModel:WaitForChild("RightHand") :: BasePart,
LeftUpperArm = CharacterModel:WaitForChild("LeftUpperArm") :: BasePart,
LeftLowerArm = CharacterModel:WaitForChild("LeftLowerArm") :: BasePart,
LeftHand = CharacterModel:WaitForChild("LeftHand") :: BasePart,
RightUpperLeg = CharacterModel:WaitForChild("RightUpperLeg") :: BasePart,
RightLowerLeg = CharacterModel:WaitForChild("RightLowerLeg") :: BasePart,
RightFoot = CharacterModel:WaitForChild("RightFoot") :: BasePart,
LeftUpperLeg = CharacterModel:WaitForChild("LeftUpperLeg") :: BasePart,
LeftLowerLeg = CharacterModel:WaitForChild("LeftLowerLeg") :: BasePart,
LeftFoot = CharacterModel:WaitForChild("LeftFoot") :: BasePart,
}
self.Motors = {
Neck = self.Parts.Head:WaitForChild("Neck") :: Motor6D,
Waist = self.Parts.UpperTorso:WaitForChild("Waist") :: Motor6D,
Root = self.Parts.LowerTorso:WaitForChild("Root") :: Motor6D,
RightShoulder = self.Parts.RightUpperArm:WaitForChild("RightShoulder") :: Motor6D,
RightElbow = self.Parts.RightLowerArm:WaitForChild("RightElbow") :: Motor6D,
RightWrist = self.Parts.RightHand:WaitForChild("RightWrist") :: Motor6D,
LeftShoulder = self.Parts.LeftUpperArm:WaitForChild("LeftShoulder") :: Motor6D,
LeftElbow = self.Parts.LeftLowerArm:WaitForChild("LeftElbow") :: Motor6D,
LeftWrist = self.Parts.LeftHand:WaitForChild("LeftWrist") :: Motor6D,
RightHip = self.Parts.RightUpperLeg:WaitForChild("RightHip") :: Motor6D,
RightKnee = self.Parts.RightLowerLeg:WaitForChild("RightKnee") :: Motor6D,
RightAnkle = self.Parts.RightFoot:WaitForChild("RightAnkle") :: Motor6D,
LeftHip = self.Parts.LeftUpperLeg:WaitForChild("LeftHip") :: Motor6D,
LeftKnee = self.Parts.LeftLowerLeg:WaitForChild("LeftKnee") :: Motor6D,
LeftAnkle = self.Parts.LeftFoot:WaitForChild("LeftAnkle") :: Motor6D,
}
self.Attachments = {
Head = {
NeckRigAttachment = self.Parts.Head:WaitForChild("NeckRigAttachment") :: Attachment,
},
UpperTorso = {
NeckRigAttachment = self.Parts.UpperTorso:WaitForChild("NeckRigAttachment") :: Attachment,
LeftShoulderRigAttachment = self.Parts.UpperTorso:WaitForChild("LeftShoulderRigAttachment") :: Attachment,
RightShoulderRigAttachment = self.Parts.UpperTorso:WaitForChild("RightShoulderRigAttachment") :: Attachment,
WaistRigAttachment = self.Parts.UpperTorso:WaitForChild("WaistRigAttachment") :: Attachment,
},
LowerTorso = {
WaistRigAttachment = self.Parts.LowerTorso:WaitForChild("WaistRigAttachment") :: Attachment,
LeftHipRigAttachment = self.Parts.LowerTorso:WaitForChild("LeftHipRigAttachment") :: Attachment,
RightHipRigAttachment = self.Parts.LowerTorso:WaitForChild("RightHipRigAttachment") :: Attachment,
RootRigAttachment = self.Parts.LowerTorso:WaitForChild("RootRigAttachment") :: Attachment,
},
HumanoidRootPart = {
RootRigAttachment = self.Parts.HumanoidRootPart:WaitForChild("RootRigAttachment") :: Attachment,
},
RightUpperArm = {
RightShoulderRigAttachment = self.Parts.RightUpperArm:WaitForChild("RightShoulderRigAttachment") :: Attachment,
RightElbowRigAttachment = self.Parts.RightUpperArm:WaitForChild("RightElbowRigAttachment") :: Attachment,
},
RightLowerArm = {
RightElbowRigAttachment = self.Parts.RightLowerArm:WaitForChild("RightElbowRigAttachment") :: Attachment,
RightWristRigAttachment = self.Parts.RightLowerArm:WaitForChild("RightWristRigAttachment") :: Attachment,
},
RightHand = {
RightWristRigAttachment = self.Parts.RightHand:WaitForChild("RightWristRigAttachment") :: Attachment,
},
LeftUpperArm = {
LeftShoulderRigAttachment = self.Parts.LeftUpperArm:WaitForChild("LeftShoulderRigAttachment") :: Attachment,
LeftElbowRigAttachment = self.Parts.LeftUpperArm:WaitForChild("LeftElbowRigAttachment") :: Attachment,
},
LeftLowerArm = {
LeftElbowRigAttachment = self.Parts.LeftLowerArm:WaitForChild("LeftElbowRigAttachment") :: Attachment,
LeftWristRigAttachment = self.Parts.LeftLowerArm:WaitForChild("LeftWristRigAttachment") :: Attachment,
},
LeftHand = {
LeftWristRigAttachment = self.Parts.LeftHand:WaitForChild("LeftWristRigAttachment") :: Attachment,
},
RightUpperLeg = {
RightHipRigAttachment = self.Parts.RightUpperLeg:WaitForChild("RightHipRigAttachment") :: Attachment,
RightKneeRigAttachment = self.Parts.RightUpperLeg:WaitForChild("RightKneeRigAttachment") :: Attachment,
},
RightLowerLeg = {
RightKneeRigAttachment = self.Parts.RightLowerLeg:WaitForChild("RightKneeRigAttachment") :: Attachment,
RightAnkleRigAttachment = self.Parts.RightLowerLeg:WaitForChild("RightAnkleRigAttachment") :: Attachment,
},
RightFoot = {
RightAnkleRigAttachment = self.Parts.RightFoot:WaitForChild("RightAnkleRigAttachment") :: Attachment,
RightFootAttachment = self.Parts.RightFoot:FindFirstChild("RightFootAttachment") :: Attachment,
},
LeftUpperLeg = {
LeftHipRigAttachment = self.Parts.LeftUpperLeg:WaitForChild("LeftHipRigAttachment") :: Attachment,
LeftKneeRigAttachment = self.Parts.LeftUpperLeg:WaitForChild("LeftKneeRigAttachment") :: Attachment,
},
LeftLowerLeg = {
LeftKneeRigAttachment = self.Parts.LeftLowerLeg:WaitForChild("LeftKneeRigAttachment") :: Attachment,
LeftAnkleRigAttachment = self.Parts.LeftLowerLeg:WaitForChild("LeftAnkleRigAttachment") :: Attachment,
},
LeftFoot = {
LeftAnkleRigAttachment = self.Parts.LeftFoot:WaitForChild("LeftAnkleRigAttachment") :: Attachment,
LeftFootAttachment = self.Parts.LeftFoot:FindFirstChild("LeftFootAttachment") :: Attachment,
},
}
--Force IKControl when AnimationConstraints is active.
if not self.Motors.Neck:IsA("Motor6D") then
self.UseIKControl = true
end
--Add the missing attachments that not all rigs have.
if not self.Attachments.RightFoot.RightFootAttachment then
local NewAttachment = Instance.new("Attachment")
NewAttachment.Position = Vector3.new(0, -(self.Parts.RightFoot :: BasePart).Size.Y / 2, 0)
NewAttachment.Name = "RightFootAttachment"
local OriginalPositionValue = Instance.new("Vector3Value")
OriginalPositionValue.Name = "OriginalPosition"
OriginalPositionValue.Value = NewAttachment.Position
OriginalPositionValue.Parent = NewAttachment
NewAttachment.Parent = self.Parts.RightFoot
self.Attachments.RightFoot.RightFootAttachment = NewAttachment
end
if not self.Attachments.LeftFoot.LeftFootAttachment then
local NewAttachment = Instance.new("Attachment")
NewAttachment.Position = Vector3.new(0, -(self.Parts.LeftFoot :: BasePart).Size.Y / 2, 0)
NewAttachment.Name = "LeftFootAttachment"
local OriginalPositionValue = Instance.new("Vector3Value")
OriginalPositionValue.Name = "OriginalPosition"
OriginalPositionValue.Value = NewAttachment.Position
OriginalPositionValue.Parent = NewAttachment
NewAttachment.Parent = self.Parts.LeftFoot
self.Attachments.LeftFoot.LeftFootAttachment = NewAttachment
end
--Store the limbs.
self.Head = Head.new(self.Parts.Head :: BasePart)
self.Torso = Torso.new(self.Parts.LowerTorso :: BasePart, self.Parts.UpperTorso :: BasePart)
if self.UseIKControl then
self.LeftArm = Appendage.FromPreset("LeftArm", CharacterModel, not PreventArmDisconnection, self.TweenComponents and 0.1 or 0)
self.RightArm = Appendage.FromPreset("RightArm", CharacterModel, not PreventArmDisconnection, self.TweenComponents and 0.1 or 0)
self.LeftLeg = Appendage.FromPreset("LeftLeg", CharacterModel, false, self.TweenComponents and 0.1 or 0)
self.RightLeg = Appendage.FromPreset("RightLeg", CharacterModel, false, self.TweenComponents and 0.1 or 0)
else
local LeftArm = AppendageLegacy.new(CharacterModel:WaitForChild("LeftUpperArm") :: BasePart, CharacterModel:WaitForChild("LeftLowerArm") :: BasePart, CharacterModel:WaitForChild("LeftHand") :: BasePart, "LeftShoulderRigAttachment", "LeftElbowRigAttachment", "LeftWristRigAttachment", "LeftGripAttachment", PreventArmDisconnection)
local RightArm = AppendageLegacy.new(CharacterModel:WaitForChild("RightUpperArm") :: BasePart, CharacterModel:WaitForChild("RightLowerArm") :: BasePart, CharacterModel:WaitForChild("RightHand") :: BasePart, "RightShoulderRigAttachment", "RightElbowRigAttachment", "RightWristRigAttachment", "RightGripAttachment", PreventArmDisconnection)
local LeftLeg = AppendageLegacy.new(CharacterModel:WaitForChild("LeftUpperLeg") :: BasePart, CharacterModel:WaitForChild("LeftLowerLeg") :: BasePart, CharacterModel:WaitForChild("LeftFoot") :: BasePart, "LeftHipRigAttachment", "LeftKneeRigAttachment", "LeftAnkleRigAttachment", "LeftFootAttachment", true)
LeftLeg.InvertBendDirection = true
local RightLeg = AppendageLegacy.new(CharacterModel:WaitForChild("RightUpperLeg") :: BasePart, CharacterModel:WaitForChild("RightLowerLeg") :: BasePart, CharacterModel:WaitForChild("RightFoot") :: BasePart, "RightHipRigAttachment", "RightKneeRigAttachment", "RightAnkleRigAttachment", "RightFootAttachment", true)
RightLeg.InvertBendDirection = true
self.LeftArm = LeftArm :: any
self.RightArm = RightArm :: any
self.LeftLeg = LeftLeg :: any
self.RightLeg = RightLeg :: any
end
self.FootPlanter = FootPlanter:CreateSolver(CharacterModel:WaitForChild("LowerTorso"), self.Humanoid:FindFirstChild("BodyHeightScale"))
end
--[[
This sets up a connection that fires when HumanoidDescription is added
under a Humanoid, to listen for appearance changes to refresh the character parts.
--]]
function Character.SetUpAppearanceChanged(self: Character): ()
local CharacterModel = self.CharacterModel
local Humanoid = CharacterModel:WaitForChild("Humanoid") :: Humanoid
--Reset connection if it already exists
if self.AppearanceChangedConnection then
self.AppearanceChangedConnection:Disconnect()
self.AppearanceChangedConnection = nil
end
self.AppearanceChangedConnection = Humanoid.ChildAdded:Connect(function(Child)
--If a new HumanoidDescription appeared, then something changed on the avatar.
--We should re-ensure that everything is still connected to NexusVR.
if Child:IsA("HumanoidDescription") then
--Refresh character parts
self:SetUpVRParts()
end
end)
end
--[[
Returns the scale value of the humanoid, or the default value.
--]]
function Character.GetHumanoidScale(self: Character, ScaleName: string): number
local Value = self.Humanoid:FindFirstChild(ScaleName) :: NumberValue
if Value then
return Value.Value
end
return (ScaleName == "BodyTypeScale" and 0 or 1)
end
--[[
Returns the SeatPart of the humanoid.
SeatPart is not replicated to new players, which results in
strange movements of character.
https://devforum.roblox.com/t/seat-occupant-and-humanoid-seatpart-not-replicating-to-new-players-to-a-server/261545
--]]
function Character.GetHumanoidSeatPart(self: Character): BasePart?
--Return nil if the Humanoid is not sitting.
if not self.Humanoid.Sit then
return nil
end
--Return if the seat part is defined.
if self.Humanoid.SeatPart then
return self.Humanoid.SeatPart
end
--Iterated through the connected parts and return if a seat exists.
--While SeatPart may not be set, a SeatWeld does exist.
for _, ConnectedPart in self.Parts.HumanoidRootPart:GetConnectedParts() do
if ConnectedPart:IsA("Seat") or ConnectedPart:IsA("VehicleSeat") then
return ConnectedPart
end
end
return nil
end
--[[
Sets a property. The property will either be
set instantly or tweened depending on how
it is configured.
--]]
function Character.SetCFrameProperty(self: Character, Object: Instance, PropertyName: string, PropertyValue: any): ()
if self.TweenComponents and PropertyName ~= "Transform" then
TweenService:Create(
Object,
TweenInfo.new(SMOOTHING_DURATION_SECONDS, Enum.EasingStyle.Quad, Enum.EasingDirection.Out),
{
[PropertyName] = PropertyValue,
}
):Play()
else
(Object :: any)[PropertyName] = PropertyValue
end
if PropertyName == "Transform" then
self.CurrentMotor6DTransforms[Object :: Motor6D] = PropertyValue
end
end
--[[
Sets the transform of a motor.
--]]
function Character.SetTransform(self: Character, MotorName: string, AttachmentName: string, StartLimbName: string, EndLimbName: string, StartCFrame: CFrame, EndCFrame: CFrame): ()
self:SetCFrameProperty(self.Motors[MotorName], "Transform", (StartCFrame * self.Attachments[StartLimbName][AttachmentName].CFrame):Inverse() * (EndCFrame * self.Attachments[EndLimbName][AttachmentName].CFrame))
end
--[[
Refreshes the Motor6D Transforms.
Intended to be run for the local character after Stepped to override the animations.
--]]
function Character.RefreshCharacter(self: Character): ()
if self.TweenComponents then
local CurrentRefreshTime = tick()
local SmoothRatio = math.min((CurrentRefreshTime - self.LastRefreshTime) / SMOOTHING_DURATION_SECONDS, 1)
for Motor6D, Transform in self.CurrentMotor6DTransforms do
local LastTransform = self.LastMotor6DTransforms[Motor6D]
if LastTransform then
Motor6D.Transform = LastTransform:Lerp(Transform, SmoothRatio)
else
Motor6D.Transform = Transform
end
end
else
for Motor6D, Transform in self.CurrentMotor6DTransforms do
Motor6D.Transform = Transform
end
end
end
--[[
Updates the character from the inputs.
--]]
function Character.UpdateFromInputs(self: Character, HeadControllerCFrame: CFrame?, LeftHandControllerCFrame: CFrame?, RightHandControllerCFrame: CFrame?, CurrentWalkspeed: number?, TrackerData: {[string]: CFrame}?): ()
--Return if the humanoid is dead.
if self.Humanoid.Health <= 0 then
return
end
--Call the other method if there is a SeatPart.
--The math below is not used while in seats due to assumptions made while standing.
--The CFrames will already be in local space from the replication.
local SeatPart = self:GetHumanoidSeatPart()
if SeatPart then
self:UpdateFromInputsSeated(HeadControllerCFrame, LeftHandControllerCFrame, RightHandControllerCFrame)
return
end
--Store the current Motor6D transforms.
for Motor6D, _ in self.CurrentMotor6DTransforms do
self.LastMotor6DTransforms[Motor6D] = Motor6D.Transform
end
self.LastRefreshTime = tick()
--Get the CFrames.
local CurrentHeadControllerCFrame = HeadControllerCFrame or (self.Parts.Head.CFrame * self.Head:GetEyesOffset())
local HeadCFrame = self.Head:GetHeadCFrame(CurrentHeadControllerCFrame)
local NeckCFrame = self.Head:GetNeckCFrame(CurrentHeadControllerCFrame)
local LowerTorsoCFrame: CFrame, UpperTorsoCFrame = self.Torso:GetTorsoCFrames(NeckCFrame)
local JointCFrames = self.Torso:GetAppendageJointCFrames(LowerTorsoCFrame, UpperTorsoCFrame)
--Get the tracker CFrames from Enigma and fallback feet CFrames.
local IsLocalCharacter = (Players.LocalPlayer and Players.LocalPlayer.Character == self.CharacterModel)
local LeftFoot: CFrame, RightFoot: CFrame = self.FootPlanter:GetFeetCFrames()
local LeftFootTrackerActive, RightFootTrackerActive = false, false
if TrackerData and TrackerData.LeftFoot then
LeftFoot = TrackerData.LeftFoot
LeftFootTrackerActive = true
else
LeftFoot = LeftFoot * CFrame.Angles(0, math.pi, 0)
end
if TrackerData and TrackerData.RightFoot then
RightFoot = TrackerData.RightFoot
RightFootTrackerActive = true
else
RightFoot = RightFoot * CFrame.Angles(0, math.pi, 0)
end
if IsLocalCharacter then
local NewTrackerCFrames = EnigmaService:GetCFrames(self)
if NewTrackerCFrames.LeftFoot then
LeftFoot = NewTrackerCFrames.LeftFoot
LeftFootTrackerActive = true
end
if NewTrackerCFrames.RightFoot then
RightFoot = NewTrackerCFrames.RightFoot
RightFootTrackerActive = true
end
self.ReplicationTrackerData = {
LeftFoot = NewTrackerCFrames.LeftFoot,
RightFoot = NewTrackerCFrames.RightFoot,
} :: {[string]: CFrame}
end
--Set the character CFrames.
--HumanoidRootParts must always face up. This makes the math more complicated.
--Setting the CFrame directly to something not facing directly up will result in the physics
--attempting to correct that within the next frame, causing the character to appear to move.
local AvatarGesturesEnabled = VRService.AvatarGestures
local IsWalking = ((CurrentWalkspeed or self.CurrentWalkspeed) > 0.1)
local TargetHumanoidRootPartCFrame = LowerTorsoCFrame * self.Attachments.LowerTorso.RootRigAttachment.CFrame * self.Attachments.HumanoidRootPart.RootRigAttachment.CFrame:Inverse()
local ActualHumanoidRootPartCFrame: CFrame = self.Parts.HumanoidRootPart.CFrame
local HumanoidRootPartHeightDifference = ActualHumanoidRootPartCFrame.Y - TargetHumanoidRootPartCFrame.Y
local NewTargetHumanoidRootPartCFrame = CFrame.new(TargetHumanoidRootPartCFrame.Position) * CFrame.Angles(0, math.atan2(TargetHumanoidRootPartCFrame.LookVector.X, TargetHumanoidRootPartCFrame.LookVector.Z) + math.pi, 0)
if not AvatarGesturesEnabled then
self:SetCFrameProperty(self.Parts.HumanoidRootPart, "CFrame", CFrame.new(0, HumanoidRootPartHeightDifference, 0) * NewTargetHumanoidRootPartCFrame)
self:SetCFrameProperty(self.Motors.Root, "Transform", CFrame.new(0, -HumanoidRootPartHeightDifference, 0) * (NewTargetHumanoidRootPartCFrame * self.Attachments.HumanoidRootPart.RootRigAttachment.CFrame):Inverse() * LowerTorsoCFrame * self.Attachments.LowerTorso.RootRigAttachment.CFrame)
self:SetTransform("Neck", "NeckRigAttachment", "UpperTorso", "Head", UpperTorsoCFrame, HeadCFrame)
self:SetTransform("Waist", "WaistRigAttachment", "LowerTorso", "UpperTorso", LowerTorsoCFrame, UpperTorsoCFrame)
end
if self.UseIKControl then
if not AvatarGesturesEnabled and LeftHandControllerCFrame and RightHandControllerCFrame then --CFrames aren't send with AvatarGestures. Checks included for typing.
self.LeftArm:MoveToWorld(LeftHandControllerCFrame)
self.RightArm:MoveToWorld(RightHandControllerCFrame)
end
if not IsWalking and (not AvatarGesturesEnabled or LeftFootTrackerActive) then
self.LeftLeg:MoveToWorld(LeftFoot)
self.LeftLeg:Enable()
else
self.LeftLeg:Disable()
end
if not IsWalking and (not AvatarGesturesEnabled or RightFootTrackerActive) then
self.RightLeg:MoveToWorld(RightFoot)
self.RightLeg:Enable()
else
self.RightLeg:Disable()
end
else
if not AvatarGesturesEnabled then
local LeftUpperArmCFrame, LeftLowerArmCFrame, LeftHandCFrame = (self.LeftArm :: any):GetAppendageCFrames(JointCFrames["LeftShoulder"], LeftHandControllerCFrame)
local RightUpperArmCFrame, RightLowerArmCFrame, RightHandCFrame = (self.RightArm :: any):GetAppendageCFrames(JointCFrames["RightShoulder"], RightHandControllerCFrame)
self:SetTransform("RightShoulder", "RightShoulderRigAttachment", "UpperTorso", "RightUpperArm", UpperTorsoCFrame, RightUpperArmCFrame)
self:SetTransform("RightElbow", "RightElbowRigAttachment", "RightUpperArm", "RightLowerArm", RightUpperArmCFrame, RightLowerArmCFrame)
self:SetTransform("RightWrist", "RightWristRigAttachment", "RightLowerArm", "RightHand", RightLowerArmCFrame, RightHandCFrame)
self:SetTransform("LeftShoulder", "LeftShoulderRigAttachment", "UpperTorso", "LeftUpperArm", UpperTorsoCFrame, LeftUpperArmCFrame)
self:SetTransform("LeftElbow", "LeftElbowRigAttachment", "LeftUpperArm", "LeftLowerArm", LeftUpperArmCFrame, LeftLowerArmCFrame)
self:SetTransform("LeftWrist", "LeftWristRigAttachment", "LeftLowerArm", "LeftHand", LeftLowerArmCFrame, LeftHandCFrame)
end
if not IsWalking and (not AvatarGesturesEnabled or LeftFootTrackerActive) then
local LeftUpperLegCFrame, LeftLowerLegCFrame, LeftFootCFrame = (self.LeftLeg :: any):GetAppendageCFrames(JointCFrames["LeftHip"], LeftFoot)
self:SetTransform("LeftHip", "LeftHipRigAttachment", "LowerTorso", "LeftUpperLeg", LowerTorsoCFrame, LeftUpperLegCFrame)
self:SetTransform("LeftKnee", "LeftKneeRigAttachment", "LeftUpperLeg", "LeftLowerLeg", LeftUpperLegCFrame, LeftLowerLegCFrame)
self:SetTransform("LeftAnkle", "LeftAnkleRigAttachment", "LeftLowerLeg", "LeftFoot", LeftLowerLegCFrame, LeftFootCFrame)
else
self.CurrentMotor6DTransforms[self.Motors.LeftHip] = nil
self.CurrentMotor6DTransforms[self.Motors.LeftKnee] = nil
self.CurrentMotor6DTransforms[self.Motors.LeftAnkle] = nil
end
if not IsWalking and (not AvatarGesturesEnabled or RightFootTrackerActive) then
local RightUpperLegCFrame, RightLowerLegCFrame, RightFootCFrame = (self.RightLeg :: any):GetAppendageCFrames(JointCFrames["RightHip"], RightFoot)
self:SetTransform("RightHip", "RightHipRigAttachment", "LowerTorso", "RightUpperLeg", LowerTorsoCFrame, RightUpperLegCFrame)
self:SetTransform("RightKnee", "RightKneeRigAttachment", "RightUpperLeg", "RightLowerLeg", RightUpperLegCFrame, RightLowerLegCFrame)
self:SetTransform("RightAnkle", "RightAnkleRigAttachment", "RightLowerLeg", "RightFoot", RightLowerLegCFrame, RightFootCFrame)
else
self.CurrentMotor6DTransforms[self.Motors.RightHip] = nil
self.CurrentMotor6DTransforms[self.Motors.RightKnee] = nil
self.CurrentMotor6DTransforms[self.Motors.RightAnkle] = nil
end
end
--Replicate the changes to the server.
if IsLocalCharacter then
self.ReplicationCFrames = {
HeadCFrame = HeadControllerCFrame :: CFrame,
LeftHandCFrame = LeftHandControllerCFrame :: CFrame,
RightHandCFrame = RightHandControllerCFrame :: CFrame,
}
end
end
--[[
Updates the character from the inputs while seated.
The CFrames are in the local space instead of global space
since the seat maintains the global space.
--]]
function Character.UpdateFromInputsSeated(self: Character, HeadControllerCFrame: CFrame?, LeftHandControllerCFrame: CFrame?, RightHandControllerCFrame: CFrame?): ()
--Return if the humanoid is dead.
if self.Humanoid.Health <= 0 then
return
end
if VRService.AvatarGestures or not HeadControllerCFrame or not LeftHandControllerCFrame or not RightHandControllerCFrame then --CFrames aren't send with AvatarGestures. Checks included for typing.
return
end
--Get the CFrames.
local HeadCFrame = self.Head:GetHeadCFrame(HeadControllerCFrame)
local NeckCFrame = self.Head:GetNeckCFrame(HeadControllerCFrame,0)
local LowerTorsoCFrame, UpperTorsoCFrame = self.Torso:GetTorsoCFrames(NeckCFrame)
local JointCFrames = self.Torso:GetAppendageJointCFrames(LowerTorsoCFrame,UpperTorsoCFrame)
local EyesOffset = self.Head:GetEyesOffset()
local HeightOffset = CFrame.new(0, (CFrame.new(0, EyesOffset.Y, 0) * (HeadControllerCFrame * EyesOffset:Inverse())).Y, 0)
--Set the head, toros, and arm CFrames.
self:SetCFrameProperty(self.Motors.Root, "Transform", HeightOffset * CFrame.new(0, -LowerTorsoCFrame.Y, 0) * LowerTorsoCFrame)
self:SetTransform("Neck", "NeckRigAttachment", "UpperTorso", "Head", UpperTorsoCFrame, HeadCFrame)
self:SetTransform("Waist", "WaistRigAttachment", "LowerTorso", "UpperTorso", LowerTorsoCFrame, UpperTorsoCFrame)
if self.UseIKControl then
local HeadWorldSpaceCFrame = (self.Parts.Head.CFrame :: CFrame) * EyesOffset
self.LeftArm:MoveToWorld(HeadWorldSpaceCFrame * HeadControllerCFrame:Inverse() * LeftHandControllerCFrame)
self.RightArm:MoveToWorld(HeadWorldSpaceCFrame * HeadControllerCFrame:Inverse() * RightHandControllerCFrame)
self.LeftLeg:Disable()
self.RightLeg:Disable()
else
local LeftUpperArmCFrame, LeftLowerArmCFrame, LeftHandCFrame = (self.LeftArm:: any):GetAppendageCFrames(JointCFrames["LeftShoulder"], LeftHandControllerCFrame)
local RightUpperArmCFrame, RightLowerArmCFrame, RightHandCFrame = (self.RightArm:: any):GetAppendageCFrames(JointCFrames["RightShoulder"], RightHandControllerCFrame)
self:SetTransform("RightShoulder", "RightShoulderRigAttachment", "UpperTorso", "RightUpperArm", UpperTorsoCFrame, RightUpperArmCFrame)
self:SetTransform("RightElbow", "RightElbowRigAttachment", "RightUpperArm", "RightLowerArm", RightUpperArmCFrame, RightLowerArmCFrame)
self:SetTransform("RightWrist", "RightWristRigAttachment", "RightLowerArm", "RightHand", RightLowerArmCFrame, RightHandCFrame)
self:SetTransform("LeftShoulder", "LeftShoulderRigAttachment", "UpperTorso", "LeftUpperArm", UpperTorsoCFrame, LeftUpperArmCFrame)
self:SetTransform("LeftElbow", "LeftElbowRigAttachment", "LeftUpperArm", "LeftLowerArm", LeftUpperArmCFrame, LeftLowerArmCFrame)
self:SetTransform("LeftWrist", "LeftWristRigAttachment", "LeftLowerArm", "LeftHand", LeftLowerArmCFrame, LeftHandCFrame)
end
--Reset the leg transforms to allow for animations.
self.CurrentMotor6DTransforms[self.Motors.RightHip] = nil
self.CurrentMotor6DTransforms[self.Motors.LeftHip] = nil
self.CurrentMotor6DTransforms[self.Motors.RightKnee] = nil
self.CurrentMotor6DTransforms[self.Motors.LeftKnee] = nil
self.CurrentMotor6DTransforms[self.Motors.RightAnkle] = nil
self.CurrentMotor6DTransforms[self.Motors.LeftAnkle] = nil
--Replicate the changes to the server.
if Players.LocalPlayer and Players.LocalPlayer.Character == self.CharacterModel then
self.ReplicationCFrames = {
HeadCFrame = HeadControllerCFrame,
LeftHandCFrame = LeftHandControllerCFrame,
RightHandCFrame = RightHandControllerCFrame,
}
end
end
return Character | 8,287 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/State/CameraService.luau | --Manages the local camera.
--!strict
local NexusVRCharacterModel = script.Parent.Parent
local CommonCamera = require(NexusVRCharacterModel:WaitForChild("Character"):WaitForChild("Camera"):WaitForChild("CommonCamera"))
local DefaultCamera = require(NexusVRCharacterModel:WaitForChild("Character"):WaitForChild("Camera"):WaitForChild("DefaultCamera"))
local ThirdPersonTrackCamera = require(NexusVRCharacterModel:WaitForChild("Character"):WaitForChild("Camera"):WaitForChild("ThirdPersonTrackCamera"))
local CameraService = {}
CameraService.__index = CameraService
local StaticInstance = nil
export type CameraService = {
ActiveCamera: string,
CurrentCamera: CameraInterface?,
RegisteredCameras: {[string]: CameraInterface},
} & typeof(setmetatable({}, CameraService))
export type CameraInterface = {
Enable: (self: CameraInterface) -> (),
Disable: (self: CameraInterface) -> (),
UpdateCamera: (self: CameraInterface, HeadsetCFrameWorld: CFrame) -> (),
}
--[[
Creates a camera service.
--]]
function CameraService.new(): CameraService
--Create the object.
local self = setmetatable({
RegisteredCameras = {},
}, CameraService) :: CameraService
--Register the default controllers.
self:RegisterCamera("Default", DefaultCamera.new() :: any)
self:RegisterCamera("ThirdPersonTrack", ThirdPersonTrackCamera.new() :: any)
self:RegisterCamera("Disabled", CommonCamera.new() :: any)
--Return the object.
return self
end
--[[
Returns a singleton instance of the camera service.
--]]
function CameraService.GetInstance(): CameraService
if not StaticInstance then
StaticInstance = CameraService.new()
end
return StaticInstance
end
--[[
Registers a camera.
--]]
function CameraService.RegisterCamera(self: CameraService, Name: string, Camera: CameraInterface): ()
self.RegisteredCameras[Name] = Camera
end
--[[
Sets the active camera.
--]]
function CameraService.SetActiveCamera(self: CameraService, Name: string): ()
--Return if the camera didn't change.
if self.ActiveCamera == Name then return end
self.ActiveCamera = Name
--Disable the current camera.
if self.CurrentCamera then
self.CurrentCamera:Disable()
end
--Enable the new camera.
self.CurrentCamera = self.RegisteredCameras[Name]
if self.CurrentCamera then
self.CurrentCamera:Enable()
elseif Name ~= nil then
warn(`Nexus VR Character Model camera \"{Name}\" is not registered.`)
end
end
--[[
Updates the local camera.
--]]
function CameraService.UpdateCamera(self: CameraService,HeadsetCFrameWorld: CFrame): ()
if self.CurrentCamera then
self.CurrentCamera:UpdateCamera(HeadsetCFrameWorld)
end
end
return CameraService | 618 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/State/CharacterService.luau | --Manages VR characters.
--!strict
local Players = game:GetService("Players")
local NexusVRCharacterModel = script.Parent.Parent
local Character = require(NexusVRCharacterModel:WaitForChild("Character"))
local CharacterService = {}
CharacterService.__index = CharacterService
local StaticInstance = nil
export type CharacterService = {
Characters: {[Player]: {
Character: Model,
VRCharacter: Character.Character,
}},
} & typeof(setmetatable({}, CharacterService))
--[[
Creates a character service.
--]]
function CharacterService.new(): CharacterService
--Create the object.
local self = setmetatable({
Characters = {},
}, CharacterService) :: CharacterService
--Connect clearing players.
Players.PlayerRemoving:Connect(function(Player)
self.Characters[Player] = nil
end)
--Return the object.
return self
end
--[[
Returns a singleton instance of the character service.
--]]
function CharacterService.GetInstance(): CharacterService
if not StaticInstance then
StaticInstance = CharacterService.new()
end
return StaticInstance
end
--[[
Returns the VR character for a player.
--]]
function CharacterService.GetCharacter(self: CharacterService, Player: Player): Character.Character?
--Return if the character is nil.
if not Player.Character or not Player.Character:FindFirstChild("Head") then
return nil
end
--Create the VR character if it isn't valid.
local PlayerCharacter = self.Characters[Player]
if not PlayerCharacter or PlayerCharacter.Character ~= Player.Character then
self.Characters[Player] = {
Character = Player.Character,
VRCharacter = Character.new(Player.Character :: Model),
}
end
--Return the stored character.
return self.Characters[Player].VRCharacter
end
--[[
Refreshes all the characters.
--]]
function CharacterService.RefreshAllCharacters(self: CharacterService): ()
for _, Character in self.Characters do
Character.VRCharacter:RefreshCharacter()
end
end
return CharacterService | 429 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/State/ControlService.luau | --Manages controlling the local characters.
--!strict
local NexusVRCharacterModel = script.Parent.Parent
local BaseController = require(NexusVRCharacterModel:WaitForChild("Character"):WaitForChild("Controller"):WaitForChild("BaseController"))
local TeleportController = require(NexusVRCharacterModel:WaitForChild("Character"):WaitForChild("Controller"):WaitForChild("TeleportController"))
local SmoothLocomotionController = require(NexusVRCharacterModel:WaitForChild("Character"):WaitForChild("Controller"):WaitForChild("SmoothLocomotionController"))
local ControlService = {}
ControlService.__index = ControlService
local StaticInstance = nil
export type ControlService = {
RegisteredControllers: {[string]: ControllerInterface},
ActiveController: string,
CurrentController: ControllerInterface?,
} & typeof(setmetatable({}, ControlService))
export type ControllerInterface = {
Disable: (self: ControllerInterface) -> (),
Enable: (self: ControllerInterface) -> (),
UpdateCharacter: (self: ControllerInterface) -> (),
}
--[[
Creates a control service.
--]]
function ControlService.new(): ControlService
--Create the object.
local self = setmetatable({
RegisteredControllers = {},
}, ControlService) :: ControlService
--Register the default controllers.
local EmptyController = BaseController.new()
EmptyController.ActionsToLock = {Enum.KeyCode.Thumbstick1, Enum.KeyCode.Thumbstick2, Enum.KeyCode.ButtonR3, Enum.KeyCode.ButtonA}
self:RegisterController("None", EmptyController :: any)
self:RegisterController("Teleport", TeleportController.new() :: any)
self:RegisterController("SmoothLocomotion", SmoothLocomotionController.new() :: any)
--Return the object.
return self
end
--[[
Returns a singleton instance of the character service.
--]]
function ControlService.GetInstance(): ControlService
if not StaticInstance then
StaticInstance = ControlService.new()
end
return StaticInstance
end
--[[
Registers a controller.
--]]
function ControlService.RegisterController(self: ControlService, Name: string, Controller: ControllerInterface): ()
self.RegisteredControllers[Name] = Controller
end
--[[
Sets the active controller.
--]]
function ControlService.SetActiveController(self: ControlService, Name: string): ()
--Return if the controller didn't change.
if self.ActiveController == Name then return end
self.ActiveController = Name
--Disable the current controller.
if self.CurrentController then
self.CurrentController:Disable()
end
--Enable the new controller.
self.CurrentController = self.RegisteredControllers[Name]
if self.CurrentController then
self.CurrentController:Enable()
elseif Name ~= nil then
warn(`Nexus VR Character Model controller \"{Name}\" is not registered.`)
end
end
--[[
Updates the local character.
--]]
function ControlService:UpdateCharacter()
if self.CurrentController then
self.CurrentController:UpdateCharacter()
end
end
return ControlService | 633 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/State/EnigmaService.luau | --Manages reeading UserCframes from Enigma.
--!strict
local THUMBSTICK_DEADZONE = 0.2
local Workspace = game:GetService("Workspace")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local VRService = game:GetService("VRService")
local NexusVRCharacterModel = script.Parent.Parent
local Enigma = require(NexusVRCharacterModel:WaitForChild("Packages"):WaitForChild("Enigma"))
local Head = require(NexusVRCharacterModel:WaitForChild("Character"):WaitForChild("Head"))
local EnigmaService = {}
EnigmaService.__index = EnigmaService
local StaticInstance = nil
export type EnigmaService = {
Offsets: {
LeftFoot: CFrame?,
RightFoot: CFrame?,
},
} & typeof(setmetatable({}, EnigmaService))
export type TrackerData = {
LeftFoot: CFrame?,
RightFoot: CFrame?,
}
--[[
Creates an Enigma service.
--]]
function EnigmaService.new(): EnigmaService
return setmetatable({
Offsets = {},
}, EnigmaService) :: EnigmaService
end
--[[
Returns a singleton instance of the Enigma service.
--]]
function EnigmaService.GetInstance(): EnigmaService
if not StaticInstance then
StaticInstance = EnigmaService.new()
end
return StaticInstance
end
--[[
Returns the CFrames for the trackers.
--]]
function EnigmaService.GetCFrames(self: EnigmaService, Character: any): TrackerData
if not Enigma.Enabled then return {} end
local HeadsetWorldCFrame = Character.Parts.Head.CFrame * Character.Head:GetEyesOffset()
local OriginWorldCFrame = HeadsetWorldCFrame * UserInputService:GetUserCFrame(Enum.UserCFrame.Head):Inverse()
local LeftFootTrackerCFrame = Enigma:GetUserCFrame("LeftFoot")
local RightFootTrackerCFrame = Enigma:GetUserCFrame("RightFoot")
local Offsets = {}
if LeftFootTrackerCFrame and self.Offsets.LeftFoot then
Offsets.LeftFoot = OriginWorldCFrame * LeftFootTrackerCFrame * self.Offsets.LeftFoot
end
if RightFootTrackerCFrame and self.Offsets.RightFoot then
Offsets.RightFoot = OriginWorldCFrame * RightFootTrackerCFrame * self.Offsets.RightFoot
end
return Offsets
end
--[[
Calibrates any inputs based on the current inputs.
--]]
function EnigmaService.Calibrate(self: EnigmaService, Character: any): ()
if not Enigma.Enabled then return end
local LeftFootTrackerCFrame = Enigma:GetUserCFrame("LeftFoot")
local RightFootTrackerCFrame = Enigma:GetUserCFrame("RightFoot")
if not LeftFootTrackerCFrame and not RightFootTrackerCFrame then return end
local Attachments = Character.Attachments
local HeadsetWorldCFrame = Workspace.CurrentCamera:GetRenderCFrame()
local OriginWorldCFrame = HeadsetWorldCFrame * UserInputService:GetUserCFrame(Enum.UserCFrame.Head):Inverse()
local FloorWorldCFrame = OriginWorldCFrame * UserInputService:GetUserCFrame(Enum.UserCFrame.Floor)
local NewCharacterHead = Head.new(Character.Parts.Head)
local HeadWorldCFrame = NewCharacterHead:GetHeadCFrame(HeadsetWorldCFrame)
local NeckWorldCFrame = NewCharacterHead:GetNeckCFrame(HeadWorldCFrame)
local LowerTorsoCFrame = NeckWorldCFrame * Attachments.UpperTorso.NeckRigAttachment.CFrame:Inverse() * Attachments.UpperTorso.WaistRigAttachment.CFrame * Attachments.LowerTorso.WaistRigAttachment.CFrame:Inverse()
if LeftFootTrackerCFrame then
local LeftFootTrackerWorldCFrame = OriginWorldCFrame * LeftFootTrackerCFrame
local LeftUpperLegCFrame = LowerTorsoCFrame * Attachments.LowerTorso.LeftHipRigAttachment.CFrame * Attachments.LeftUpperLeg.LeftHipRigAttachment.CFrame:Inverse()
local LeftLowerLegCFrame = LeftUpperLegCFrame * Attachments.LeftUpperLeg.LeftKneeRigAttachment.CFrame * Attachments.LeftLowerLeg.LeftKneeRigAttachment.CFrame:Inverse()
local LeftFootCFrame = LeftLowerLegCFrame * Attachments.LeftLowerLeg.LeftAnkleRigAttachment.CFrame * Attachments.LeftFoot.LeftAnkleRigAttachment.CFrame:Inverse()
local LeftFootBottomCFrame = LeftFootCFrame * Attachments.LeftFoot.LeftFootAttachment.CFrame
LeftFootCFrame = CFrame.new(0, FloorWorldCFrame.Y - LeftFootBottomCFrame.Y, 0) * LeftFootCFrame
self.Offsets.LeftFoot = LeftFootTrackerWorldCFrame:Inverse() * LeftFootCFrame
end
if RightFootTrackerCFrame then
local RightFootTrackerWorldCFrame = OriginWorldCFrame * RightFootTrackerCFrame
local RightUpperLegCFrame = LowerTorsoCFrame * Attachments.LowerTorso.RightHipRigAttachment.CFrame * Attachments.RightUpperLeg.RightHipRigAttachment.CFrame:Inverse()
local RightLowerLegCFrame = RightUpperLegCFrame * Attachments.RightUpperLeg.RightKneeRigAttachment.CFrame * Attachments.RightLowerLeg.RightKneeRigAttachment.CFrame:Inverse()
local RightFootCFrame = RightLowerLegCFrame * Attachments.RightLowerLeg.RightAnkleRigAttachment.CFrame * Attachments.RightFoot.RightAnkleRigAttachment.CFrame:Inverse()
local RightFootBottomCFrame = RightFootCFrame * Attachments.RightFoot.RightFootAttachment.CFrame
RightFootCFrame = CFrame.new(0, FloorWorldCFrame.Y - RightFootBottomCFrame.Y, 0) * RightFootCFrame
self.Offsets.RightFoot = RightFootTrackerWorldCFrame:Inverse() * RightFootCFrame
end
end
--[[
Enables Enigma.
--]]
function EnigmaService.Enable(self: EnigmaService): ()
--Enable Enigma.
Enigma:Enable()
--Implement the inputs.
--Pasting data interrupts the gamepad inputs.
local LastLeftThumbstick = Vector3.zero
local ButtonADown = false
UserInputService.InputBegan:Connect(function(Input)
if Input.KeyCode == Enum.KeyCode.ButtonA then
ButtonADown = true
end
end)
UserInputService.InputChanged:Connect(function(Input)
if Input.KeyCode == Enum.KeyCode.Thumbstick1 then
if Input.Position.Magnitude > THUMBSTICK_DEADZONE then
LastLeftThumbstick = Input.Position
else
LastLeftThumbstick = Vector3.zero
end
end
end)
UserInputService.InputEnded:Connect(function(Input)
if Input.KeyCode == Enum.KeyCode.Thumbstick1 then
LastLeftThumbstick = Vector3.zero
elseif Input.KeyCode == Enum.KeyCode.ButtonA then
ButtonADown = false
end
end)
RunService:BindToRenderStep("EnigmaCustomMovement", Enum.RenderPriority.Input.Value + 1, function()
--Return if Enigma isn't active.
if not Enigma:IsActive() then return end
--Return if the character is invalid.
local Character = Players.LocalPlayer.Character
if not Character then return end
local Humanoid = Character:FindFirstChildOfClass("Humanoid")
if not Humanoid or Humanoid.Health <= 0 then return end
--Move the character.
local MovementReferenceWorldCFrame = Workspace.CurrentCamera:GetRenderCFrame()
local MovementReferenceRotation = CFrame.new(-MovementReferenceWorldCFrame.Position) * MovementReferenceWorldCFrame
local MoveDirection = (MovementReferenceRotation * CFrame.new(LastLeftThumbstick.X, 0, -LastLeftThumbstick.Y)).Position
if MoveDirection.Magnitude > 0.01 or not VRService.AvatarGestures then --Move is not overriden with AvatarGestures since it does continous movements when not walking.
Players.LocalPlayer:Move(MoveDirection, false)
end
if ButtonADown then
Humanoid.Jump = true
end
end)
end
return EnigmaService | 1,812 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/State/Settings.luau | --Stores settings.
--!strict
local NexusVRCharacterModel = script.Parent.Parent
local NexusInstance = require(NexusVRCharacterModel:WaitForChild("Packages"):WaitForChild("NexusInstance"))
local TypedEvent = NexusInstance.TypedEvent
local Settings ={}
Settings.__index = Settings
local StaticInstance = nil
export type Settings ={
Defaults: any,
Overrides: any,
SettingsChangeEvents: {[string]: NexusInstance.TypedEvent<>},
SettingsCache: {[string]: any},
} & typeof(setmetatable({}, Settings))
--[[
Creates a settings object.
--]]
function Settings.new(): Settings
return setmetatable({
Defaults = {},
Overrides = {},
SettingsChangeEvents = {},
SettingsCache = {},
}, Settings) :: Settings
end
--[[
Returns a singleton instance of settings.
--]]
function Settings.GetInstance(): Settings
if not StaticInstance then
StaticInstance = Settings.new()
end
return StaticInstance
end
--[[
Returns the value of a setting.
--]]
function Settings.GetSetting(self: Settings, Setting: string): any
--Return a cached entry if one exists.
if self.SettingsCache[Setting] ~= nil then
return self.SettingsCache[Setting]
end
--Get the table containing the setting.
local Defaults, Overrides = self.Defaults, self.Overrides
local SplitSettingNames = string.split(Setting, ".")
for i = 1, #SplitSettingNames - 1 do
Defaults = Defaults[SplitSettingNames[i]] or {}
Overrides = Overrides[SplitSettingNames[i]] or {}
end
--Return the value.
local Value = Overrides[SplitSettingNames[#SplitSettingNames]]
if Value == nil then
Value = Defaults[SplitSettingNames[#SplitSettingNames]]
end
self.SettingsCache[Setting] = Value
return Value
end
--[[
Sets the value of a setting.
--]]
function Settings.SetSetting(self: Settings, Setting: string, Value: any): ()
--Set the setting.
local Overrides = self.Overrides
local SplitSettingNames = string.split(Setting,".")
for i = 1, #SplitSettingNames - 1 do
if not Overrides[SplitSettingNames[i]] then
Overrides[SplitSettingNames[i]] = {}
end
Overrides = Overrides[SplitSettingNames[i]]
end
Overrides[SplitSettingNames[#SplitSettingNames]] = Value
self.SettingsCache[Setting] = Value
--Fire the changed signal.
local Event = self.SettingsChangeEvents[string.lower(Setting)]
if Event then
Event:Fire()
end
end
--[[
Sets all the defaults.
--]]
function Settings.SetDefaults(self: Settings, Defaults: {[string]: any}): ()
--Set the defaults.
self.Defaults = Defaults
self.SettingsCache = {}
--Fire all the event changes.
for _, Event in self.SettingsChangeEvents do
(Event :: NexusInstance.TypedEvent<>):Fire()
end
end
--[[
Sets all the overrides.
--]]
function Settings.SetOverrides(self: Settings, Overrides: {[string]: any}): ()
--Set the overrides.
self.Overrides = Overrides
self.SettingsCache = {}
--Fire all the event changes.
for _, Event in self.SettingsChangeEvents do
(Event :: NexusInstance.TypedEvent<>):Fire()
end
end
--[[
Returns a changed signal for a setting.
--]]
function Settings.GetSettingsChangedSignal(self: Settings, Overrides: string): NexusInstance.TypedEvent<>
Overrides = string.lower(Overrides)
--Create the event if none exists.
if not self.SettingsChangeEvents[Overrides] then
self.SettingsChangeEvents[Overrides] = TypedEvent.new()
end
--Return the event.
return self.SettingsChangeEvents[Overrides]
end
--[[
Destroys the settings.
--]]
function Settings.Destroy(self: Settings): ()
--Disconnect the settings.
for _,Event in self.SettingsChangeEvents do
(Event :: NexusInstance.TypedEvent<>):Destroy()
end
self.SettingsChangeEvents = {}
end
return Settings | 879 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/State/VRInputService.luau | --Manages VR inputs. This normalizes the inputs from
--the headsets as the Y position of the inputs is arbitrary,
--meaning it can be the floor, eye level, or random.
--!strict
local NexusVRCharacterModel = script.Parent.Parent
local NexusInstance = require(NexusVRCharacterModel:WaitForChild("Packages"):WaitForChild("NexusInstance"))
local TypedEvent = NexusInstance.TypedEvent
local VRInputService = {}
VRInputService.__index = VRInputService
local StaticInstance = nil
export type VRInputService = {
RecenterOffset: CFrame,
ManualNormalHeadLevel: number?,
HighestHeadHeight: number?,
ThumbstickValues: {[Enum.KeyCode]: Vector3},
VRService: VRService,
UserInputService: UserInputService,
Recentered: NexusInstance.TypedEvent<>,
EyeLevelSet: NexusInstance.TypedEvent<>,
} & typeof(setmetatable({}, VRInputService))
--[[
Creates a settings object.
--]]
function VRInputService.new(VRService: VRService?, UserInputService: UserInputService?): VRInputService
--Create the object.
local self = setmetatable({
RecenterOffset = CFrame.identity,
ThumbstickValues = {
[Enum.KeyCode.Thumbstick1] = Vector3.zero,
[Enum.KeyCode.Thumbstick2] = Vector3.zero,
},
VRService = VRService or game:GetService("VRService"),
UserInputService = UserInputService or game:GetService("UserInputService"),
Recentered = TypedEvent.new(),
EyeLevelSet = TypedEvent.new(),
}, VRInputService) :: VRInputService
--Connect updating the thumbsticks.
self.UserInputService.InputEnded:Connect(function(Input)
if self.ThumbstickValues[Input.KeyCode] then
self.ThumbstickValues[Input.KeyCode] = Vector3.zero
end
end)
self.UserInputService.InputChanged:Connect(function(Input)
if self.ThumbstickValues[Input.KeyCode] then
self.ThumbstickValues[Input.KeyCode] = Input.Position
end
end)
--Return the object.
return self
end
--[[
Returns a singleton instance of the VR input service.
--]]
function VRInputService.GetInstance(): VRInputService
if not StaticInstance then
StaticInstance = VRInputService.new()
end
return StaticInstance
end
--[[
Returns the VR inputs to use. The inputs are normalized
so that 0 is the head height.
--]]
function VRInputService.GetVRInputs(self: VRInputService): {[Enum.UserCFrame]: CFrame}
--Get the head input.
local VRInputs = {
[Enum.UserCFrame.Head] = self.VRService:GetUserCFrame(Enum.UserCFrame.Head),
} :: {[Enum.UserCFrame]: CFrame}
--Get the hand inputs.
if self.VRService:GetUserCFrameEnabled(Enum.UserCFrame.LeftHand) then
VRInputs[Enum.UserCFrame.LeftHand] = self.VRService:GetUserCFrame(Enum.UserCFrame.LeftHand)
else
VRInputs[Enum.UserCFrame.LeftHand] = VRInputs[Enum.UserCFrame.Head] * CFrame.new(-1, -2.5, 0.5)
end
if self.VRService:GetUserCFrameEnabled(Enum.UserCFrame.RightHand) then
VRInputs[Enum.UserCFrame.RightHand] = self.VRService:GetUserCFrame(Enum.UserCFrame.RightHand)
else
VRInputs[Enum.UserCFrame.RightHand] = VRInputs[Enum.UserCFrame.Head] * CFrame.new(1, -2.5, 0.5)
end
--Determine the height offset.
local HeightOffset = 0
if self.ManualNormalHeadLevel then
--Adjust to normalize the height around the set value.
HeightOffset = -self.ManualNormalHeadLevel
else
--Adjust to normalize the height around the highest value.
--The head CFrame is moved back 0.5 studs for when the headset suddenly goes up (like putting on and taking off).
local CurrentVRHeadHeight = (VRInputs[Enum.UserCFrame.Head] * CFrame.new(0, 0, 0.5)).Y
if not self.HighestHeadHeight or CurrentVRHeadHeight > self.HighestHeadHeight then
self.HighestHeadHeight = CurrentVRHeadHeight
end
HeightOffset = -self.HighestHeadHeight :: number
end
--Normalize the CFrame heights.
--A list of enums is used instead of VRInputs because modifying a table stops pairs().
for _, InputEnum in {Enum.UserCFrame.Head, Enum.UserCFrame.LeftHand, Enum.UserCFrame.RightHand} do
VRInputs[InputEnum] = CFrame.new(0, HeightOffset, 0) * self.RecenterOffset * VRInputs[InputEnum]
end
--Return the CFrames.
return VRInputs
end
--[[
Recenters the service.
Does not alter the Y axis.
--]]
function VRInputService.Recenter(self: VRInputService): ()
local HeadCFrame = self.VRService:GetUserCFrame(Enum.UserCFrame.Head)
self.RecenterOffset = CFrame.Angles(0, -math.atan2(-HeadCFrame.LookVector.X, -HeadCFrame.LookVector.Z), 0) * CFrame.new(-HeadCFrame.X, 0, -HeadCFrame.Z)
self.Recentered:Fire()
end
--[[
Sets the eye level.
--]]
function VRInputService.SetEyeLevel(self: VRInputService): ()
self.ManualNormalHeadLevel = self.VRService:GetUserCFrame(Enum.UserCFrame.Head).Y
self.EyeLevelSet:Fire()
end
--[[
Returns the current value for a thumbstick.
--]]
function VRInputService.GetThumbstickPosition(self: VRInputService, Thumbsick: Enum.KeyCode): Vector3
return self.ThumbstickValues[Thumbsick] or Vector3.zero
end
return VRInputService | 1,314 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/UI/MainMenu.luau | --Main menu for Nexus VR Character Model.
--!strict
local MENU_OPEN_TIME_REQUIREMENT = 1
local MENU_OPEN_TIME = 0.25
local Workspace = game:GetService("Workspace")
local Players = game:GetService("Players")
local GuiService = game:GetService("GuiService")
local RunService = game:GetService("RunService")
local TweenService = game:GetService("TweenService")
local NexusVRCharacterModel = script.Parent.Parent
local NexusButton = require(NexusVRCharacterModel:WaitForChild("Packages"):WaitForChild("NexusButton"))
local NexusVRCore = require(NexusVRCharacterModel:WaitForChild("Packages"):WaitForChild("NexusVRCore"))
local Settings = require(NexusVRCharacterModel:WaitForChild("State"):WaitForChild("Settings")).GetInstance()
local VRInputService = require(NexusVRCharacterModel:WaitForChild("State"):WaitForChild("VRInputService")).GetInstance()
local ApiBaseView = require(NexusVRCharacterModel:WaitForChild("UI"):WaitForChild("View"):WaitForChild("ApiBaseView"))
local EnigmaView = require(NexusVRCharacterModel:WaitForChild("UI"):WaitForChild("View"):WaitForChild("EnigmaView"))
local SettingsView = require(NexusVRCharacterModel:WaitForChild("UI"):WaitForChild("View"):WaitForChild("SettingsView"))
local TextButtonFactory = NexusButton.TextButtonFactory.CreateDefault(Color3.fromRGB(0, 170, 255))
TextButtonFactory:SetDefault("Theme", "RoundedCorners")
local ScreenGui3D = NexusVRCore.ScreenGui3D
local MainMenu = {}
MainMenu.__index = MainMenu
local StaticInstance = nil
export type MainMenu = {
CurrentView: number,
Views: {any},
ScreenGui: NexusVRCore.NexusInstanceScreenGui3D,
ViewAdornFrame: Frame,
LeftButton: NexusButton.NexusInstanceNexusButton,
RightButton: NexusButton.NexusInstanceNexusButton,
ViewTextLabel: TextLabel,
LeftHandHintVisible: boolean,
RightHandHintVisible: boolean,
} & typeof(setmetatable({}, MainMenu))
--[[
Creates the main menu.
--]]
function MainMenu.new(): any
local self = setmetatable({}, MainMenu) :: MainMenu
--Set up the ScreenGui.
local MainMenuScreenGui = ScreenGui3D.new()
MainMenuScreenGui.ResetOnSpawn = false
MainMenuScreenGui.Enabled = false
MainMenuScreenGui.CanvasSize = Vector2.new(500, 605)
MainMenuScreenGui.FieldOfView = 0
MainMenuScreenGui.Easing = 0.25
self.ScreenGui = MainMenuScreenGui
--Create the parent frame, display text, and toggle buttons.
local ViewAdornFrame = Instance.new("Frame")
ViewAdornFrame.BackgroundTransparency = 1
ViewAdornFrame.Size = UDim2.new(0, 500, 0, 500)
ViewAdornFrame.Parent = MainMenuScreenGui:GetContainer()
self.ViewAdornFrame = ViewAdornFrame
local ButtonAdornFrame = Instance.new("Frame")
ButtonAdornFrame.BackgroundColor3 = Color3.fromRGB(0, 0, 0)
ButtonAdornFrame.BackgroundTransparency = 0.6 * GuiService.PreferredTransparency
ButtonAdornFrame.Position = UDim2.new(0, 0, 0, 505)
ButtonAdornFrame.Size = UDim2.new(1, 0, 0, 100)
ButtonAdornFrame.Parent = ViewAdornFrame
GuiService:GetPropertyChangedSignal("PreferredTransparency"):Connect(function()
ButtonAdornFrame.BackgroundTransparency = 0.6 * GuiService.PreferredTransparency
end)
local UICorner = Instance.new("UICorner")
UICorner.CornerRadius = UDim.new(5 * 0.05, 0)
UICorner.Parent = ButtonAdornFrame
local LeftButton, LeftText = TextButtonFactory:Create()
LeftButton.BorderSize = UDim.new(0.075, 0)
LeftButton.Size = UDim2.new(0, 80, 0, 80)
LeftButton.Position = UDim2.new(0, 10, 0, 10)
LeftButton.Parent = ButtonAdornFrame
LeftText.Text = "<"
self.LeftButton = LeftButton
local RightButton, RightText = TextButtonFactory:Create()
RightButton.BorderSize = UDim.new(0.075, 0)
RightButton.Size = UDim2.new(0, 80, 0, 80)
RightButton.Position = UDim2.new(0, 410, 0, 10)
RightButton.Parent = ButtonAdornFrame
RightText.Text = ">"
self.RightButton = RightButton
local ViewTextLabel = Instance.new("TextLabel")
ViewTextLabel.BackgroundTransparency = 1
ViewTextLabel.Size = UDim2.new(0, 300, 0, 60)
ViewTextLabel.Position = UDim2.new(0, 100, 0, 20)
ViewTextLabel.Font = Enum.Font.SourceSansBold
ViewTextLabel.TextScaled = true
ViewTextLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
ViewTextLabel.TextStrokeColor3 = Color3.fromRGB(0, 0, 0)
ViewTextLabel.TextStrokeTransparency = 0
ViewTextLabel.Parent = ButtonAdornFrame
self.ViewTextLabel = ViewTextLabel
--Set up the default views.
self.CurrentView = 1
self.Views = {}
SettingsView.new(self:CreateView("Settings"));
EnigmaView.new(self:CreateView("Enigma"), self);
self:UpdateVisibleView()
--Connect changing views.
local DB = true
LeftButton.MouseButton1Down:Connect(function()
if not DB then return end
DB = false
--De-increment the current view.
self.CurrentView = self.CurrentView - 1
if self.CurrentView == 0 then
self.CurrentView = #self.Views
end
--Update the views.
self:UpdateVisibleView()
task.wait()
DB = true
end)
RightButton.MouseButton1Down:Connect(function()
if not DB then return end
DB = false
--Increment the current view.
self.CurrentView = self.CurrentView + 1
if self.CurrentView > #self.Views then
self.CurrentView = 1
end
--Update the views.
self:UpdateVisibleView()
task.wait()
DB = true
end)
--Parent the menu.
MainMenuScreenGui.Parent = Players.LocalPlayer:WaitForChild("PlayerGui")
return self
end
--[[
Returns a singleton instance of the character service.
--]]
function MainMenu.GetInstance(): MainMenu
if not StaticInstance then
StaticInstance = MainMenu.new()
end
return StaticInstance
end
--[[
Sets up opening based on the controllers
being rotated upwards.
--]]
function MainMenu.SetUpOpening(self: MainMenu): ()
--Create the animation parts.
local InitialMenuToggleGestureActive = Settings:GetSetting("Menu.MenuToggleGestureActive")
if InitialMenuToggleGestureActive == nil then
InitialMenuToggleGestureActive = true
end
local LeftAdornPart = Instance.new("Part")
LeftAdornPart.Transparency = 1
LeftAdornPart.Size = Vector3.new()
LeftAdornPart.Anchored = true
LeftAdornPart.CanCollide = false
LeftAdornPart.CanQuery = false
LeftAdornPart.Parent = Workspace.CurrentCamera
local LeftAdorn = Instance.new("BoxHandleAdornment")
LeftAdorn.Color3 = Color3.fromRGB(0, 170, 255)
LeftAdorn.AlwaysOnTop = true
LeftAdorn.ZIndex = 0
LeftAdorn.Adornee = LeftAdornPart
LeftAdorn.Parent = LeftAdornPart
local RightAdornPart = Instance.new("Part")
RightAdornPart.Transparency = 1
RightAdornPart.Size = Vector3.new()
RightAdornPart.Anchored = true
RightAdornPart.CanCollide = false
RightAdornPart.CanQuery = false
RightAdornPart.Parent = Workspace.CurrentCamera
local RightAdorn = Instance.new("BoxHandleAdornment")
RightAdorn.Color3 = Color3.fromRGB(0, 170 , 255)
RightAdorn.AlwaysOnTop = true
RightAdorn.ZIndex = 0
RightAdorn.Adornee = RightAdornPart
RightAdorn.Parent = RightAdornPart
local LeftMenuToggleHintAdornPart = Instance.new("Part")
LeftMenuToggleHintAdornPart.Transparency = 1
LeftMenuToggleHintAdornPart.Size = Vector3.new(1,1,0)
LeftMenuToggleHintAdornPart.Anchored = true
LeftMenuToggleHintAdornPart.CanCollide = false
LeftMenuToggleHintAdornPart.CanQuery = false
LeftMenuToggleHintAdornPart.Parent = Workspace.CurrentCamera
local RightMenuToggleHintAdornPart = Instance.new("Part")
RightMenuToggleHintAdornPart.Transparency = 1
RightMenuToggleHintAdornPart.Size = Vector3.new(1,1,0)
RightMenuToggleHintAdornPart.Anchored = true
RightMenuToggleHintAdornPart.CanCollide = false
RightMenuToggleHintAdornPart.CanQuery = false
RightMenuToggleHintAdornPart.Parent = Workspace.CurrentCamera
local LeftMenuToggleHintGuiFront = Instance.new("SurfaceGui")
LeftMenuToggleHintGuiFront.Active = false
LeftMenuToggleHintGuiFront.Face = Enum.NormalId.Front
LeftMenuToggleHintGuiFront.CanvasSize = Vector2.new(500,500)
LeftMenuToggleHintGuiFront.LightInfluence = 0
LeftMenuToggleHintGuiFront.Enabled = InitialMenuToggleGestureActive
LeftMenuToggleHintGuiFront.AlwaysOnTop = true
LeftMenuToggleHintGuiFront.Adornee = LeftMenuToggleHintAdornPart
LeftMenuToggleHintGuiFront.Parent = LeftMenuToggleHintAdornPart
local LeftMenuToggleHintFrontArrow = Instance.new("ImageLabel")
LeftMenuToggleHintFrontArrow.ImageTransparency = 1
LeftMenuToggleHintFrontArrow.BackgroundTransparency = 1
LeftMenuToggleHintFrontArrow.Rotation = 180
LeftMenuToggleHintFrontArrow.Size = UDim2.new(1,0,1,0)
LeftMenuToggleHintFrontArrow.Image = "rbxassetid://6537091378"
LeftMenuToggleHintFrontArrow.ImageRectSize = Vector2.new(512,512)
LeftMenuToggleHintFrontArrow.ImageRectOffset = Vector2.new(0,0)
LeftMenuToggleHintFrontArrow.Parent = LeftMenuToggleHintGuiFront
local LeftMenuToggleHintFrontText = Instance.new("ImageLabel")
LeftMenuToggleHintFrontText.ImageTransparency = 1
LeftMenuToggleHintFrontText.BackgroundTransparency = 1
LeftMenuToggleHintFrontText.Size = UDim2.new(1,0,1,0)
LeftMenuToggleHintFrontText.ZIndex = 2
LeftMenuToggleHintFrontText.Image = "rbxassetid://6537091378"
LeftMenuToggleHintFrontText.ImageRectSize = Vector2.new(512,512)
LeftMenuToggleHintFrontText.ImageRectOffset = Vector2.new(0,512)
LeftMenuToggleHintFrontText.Parent = LeftMenuToggleHintGuiFront
local LeftMenuToggleHintGuiBack = Instance.new("SurfaceGui")
LeftMenuToggleHintGuiBack.Active = false
LeftMenuToggleHintGuiBack.Face = Enum.NormalId.Back
LeftMenuToggleHintGuiBack.CanvasSize = Vector2.new(500,500)
LeftMenuToggleHintGuiBack.LightInfluence = 0
LeftMenuToggleHintGuiBack.Enabled = InitialMenuToggleGestureActive
LeftMenuToggleHintGuiBack.AlwaysOnTop = true
LeftMenuToggleHintGuiBack.Adornee = LeftMenuToggleHintAdornPart
LeftMenuToggleHintGuiBack.Parent = LeftMenuToggleHintAdornPart
local LeftMenuToggleHintBackArrow = Instance.new("ImageLabel")
LeftMenuToggleHintBackArrow.ImageTransparency = 1
LeftMenuToggleHintBackArrow.BackgroundTransparency = 1
LeftMenuToggleHintBackArrow.Size = UDim2.new(1,0,1,0)
LeftMenuToggleHintBackArrow.Image = "rbxassetid://6537091378"
LeftMenuToggleHintBackArrow.ImageRectSize = Vector2.new(512,512)
LeftMenuToggleHintBackArrow.ImageRectOffset = Vector2.new(512,0)
LeftMenuToggleHintBackArrow.Parent = LeftMenuToggleHintGuiBack
local LeftMenuToggleHintBackText = Instance.new("ImageLabel")
LeftMenuToggleHintBackText.ImageTransparency = 1
LeftMenuToggleHintBackText.BackgroundTransparency = 1
LeftMenuToggleHintBackText.Size = UDim2.new(1,0,1,0)
LeftMenuToggleHintBackText.ZIndex = 2
LeftMenuToggleHintBackText.Image = "rbxassetid://6537091378"
LeftMenuToggleHintBackText.ImageRectSize = Vector2.new(512,512)
LeftMenuToggleHintBackText.ImageRectOffset = Vector2.new(0,512)
LeftMenuToggleHintBackText.Parent = LeftMenuToggleHintGuiBack
local RightMenuToggleHintGuiFront = Instance.new("SurfaceGui")
RightMenuToggleHintGuiFront.Active = false
RightMenuToggleHintGuiFront.Face = Enum.NormalId.Front
RightMenuToggleHintGuiFront.CanvasSize = Vector2.new(500,500)
RightMenuToggleHintGuiFront.LightInfluence = 0
RightMenuToggleHintGuiFront.Enabled = InitialMenuToggleGestureActive
RightMenuToggleHintGuiFront.AlwaysOnTop = true
RightMenuToggleHintGuiFront.Adornee = RightMenuToggleHintAdornPart
RightMenuToggleHintGuiFront.Parent = RightMenuToggleHintAdornPart
local RightMenuToggleHintFrontArrow = Instance.new("ImageLabel")
RightMenuToggleHintFrontArrow.ImageTransparency = 1
RightMenuToggleHintFrontArrow.BackgroundTransparency = 1
RightMenuToggleHintFrontArrow.Size = UDim2.new(1,0,1,0)
RightMenuToggleHintFrontArrow.Image = "rbxassetid://6537091378"
RightMenuToggleHintFrontArrow.ImageRectSize = Vector2.new(512,512)
RightMenuToggleHintFrontArrow.ImageRectOffset = Vector2.new(512,0)
RightMenuToggleHintFrontArrow.Parent = RightMenuToggleHintGuiFront
local RightMenuToggleHintFrontText = Instance.new("ImageLabel")
RightMenuToggleHintFrontText.ImageTransparency = 1
RightMenuToggleHintFrontText.BackgroundTransparency = 1
RightMenuToggleHintFrontText.Size = UDim2.new(1,0,1,0)
RightMenuToggleHintFrontText.ZIndex = 2
RightMenuToggleHintFrontText.Image = "rbxassetid://6537091378"
RightMenuToggleHintFrontText.ImageRectSize = Vector2.new(512,512)
RightMenuToggleHintFrontText.ImageRectOffset = Vector2.new(0,512)
RightMenuToggleHintFrontText.Parent = RightMenuToggleHintGuiFront
local RightMenuToggleHintGuiBack = Instance.new("SurfaceGui")
RightMenuToggleHintGuiBack.Active = false
RightMenuToggleHintGuiBack.Face = Enum.NormalId.Back
RightMenuToggleHintGuiBack.CanvasSize = Vector2.new(500,500)
RightMenuToggleHintGuiBack.LightInfluence = 0
RightMenuToggleHintGuiBack.Enabled = InitialMenuToggleGestureActive
RightMenuToggleHintGuiBack.AlwaysOnTop = true
RightMenuToggleHintGuiBack.Adornee = RightMenuToggleHintAdornPart
RightMenuToggleHintGuiBack.Parent = RightMenuToggleHintAdornPart
local RightMenuToggleHintBackArrow = Instance.new("ImageLabel")
RightMenuToggleHintBackArrow.ImageTransparency = 1
RightMenuToggleHintBackArrow.BackgroundTransparency = 1
RightMenuToggleHintBackArrow.Size = UDim2.new(1,0,1,0)
RightMenuToggleHintBackArrow.Image = "rbxassetid://6537091378"
RightMenuToggleHintBackArrow.ImageRectSize = Vector2.new(512,512)
RightMenuToggleHintBackArrow.ImageRectOffset = Vector2.new(0,0)
RightMenuToggleHintBackArrow.Parent = RightMenuToggleHintGuiBack
local RightMenuToggleHintBackText = Instance.new("ImageLabel")
RightMenuToggleHintBackText.BackgroundTransparency = 1
RightMenuToggleHintBackText.Rotation = 180
RightMenuToggleHintBackText.ImageTransparency = 1
RightMenuToggleHintBackText.Size = UDim2.new(1,0,1,0)
RightMenuToggleHintBackText.ZIndex = 2
RightMenuToggleHintBackText.Image = "rbxassetid://6537091378"
RightMenuToggleHintBackText.ImageRectSize = Vector2.new(512,512)
RightMenuToggleHintBackText.ImageRectOffset = Vector2.new(0,512)
RightMenuToggleHintBackText.Parent = RightMenuToggleHintGuiBack
--Connect hiding the hints when the setting changes.
Settings:GetSettingsChangedSignal("Menu.MenuToggleGestureActive"):Connect(function()
--Determine if the gesture is active.
local MenuToggleGestureActive = Settings:GetSetting("Menu.MenuToggleGestureActive")
if MenuToggleGestureActive == nil then
MenuToggleGestureActive = true
end
--Update the visibility of the hints.
LeftMenuToggleHintGuiFront.Enabled = MenuToggleGestureActive
LeftMenuToggleHintGuiBack.Enabled = MenuToggleGestureActive
RightMenuToggleHintGuiFront.Enabled = MenuToggleGestureActive
RightMenuToggleHintGuiBack.Enabled = MenuToggleGestureActive
end)
--Start checking for the controllers to be upside down.
--Done in a task since this function is non-yielding.
local BothControllersUpStartTime
local MenuToggleReached = false
task.spawn(function()
while true do
--Determine if the gesture is active.
local MenuToggleGestureActive = Settings:GetSetting("Menu.MenuToggleGestureActive")
if MenuToggleGestureActive == nil then
MenuToggleGestureActive = true
end
--Get the inputs and determine if the hands are both upside down and pointing forward.
local VRInputs = VRInputService:GetVRInputs()
local LeftHandCFrameRelative, RightHandCFrameRelative = VRInputs[Enum.UserCFrame.Head]:Inverse() * VRInputs[Enum.UserCFrame.LeftHand], VRInputs[Enum.UserCFrame.Head]:Inverse() * VRInputs[Enum.UserCFrame.RightHand]
local LeftHandFacingUp, RightHandFacingUp = LeftHandCFrameRelative.UpVector.Y < 0, RightHandCFrameRelative.UpVector.Y < 0
local LeftHandFacingForward, RightHandFacingForward = LeftHandCFrameRelative.LookVector.Z < 0, RightHandCFrameRelative.LookVector.Z < 0
local LeftHandUp, RightHandUp = LeftHandFacingUp and LeftHandFacingForward, RightHandFacingUp and RightHandFacingForward
local BothHandsUp = MenuToggleGestureActive and LeftHandUp and RightHandUp
if BothHandsUp then
BothControllersUpStartTime = BothControllersUpStartTime or tick()
else
BothControllersUpStartTime = nil :: any
MenuToggleReached = false
end
--Update the adorn part CFrames.
local CameraCenterCFrame = Workspace.CurrentCamera:GetRenderCFrame() * VRInputs[Enum.UserCFrame.Head]:Inverse()
LeftAdornPart.CFrame = CameraCenterCFrame * VRInputs[Enum.UserCFrame.LeftHand] * CFrame.new(0, -0.25, 0.25)
RightAdornPart.CFrame = CameraCenterCFrame * VRInputs[Enum.UserCFrame.RightHand] * CFrame.new(0, -0.25, 0.25)
LeftMenuToggleHintAdornPart.CFrame = CameraCenterCFrame * VRInputs[Enum.UserCFrame.LeftHand]
RightMenuToggleHintAdornPart.CFrame = CameraCenterCFrame * VRInputs[Enum.UserCFrame.RightHand]
--Update the progress bars.
if BothControllersUpStartTime and not MenuToggleReached then
local DeltaTimePercent = (tick() - BothControllersUpStartTime) / MENU_OPEN_TIME_REQUIREMENT
LeftAdorn.Size = Vector3.new(0.1, 0, 0.25 * DeltaTimePercent)
RightAdorn.Size = Vector3.new(0.1, 0, 0.25 * DeltaTimePercent)
LeftAdorn.Visible = true
RightAdorn.Visible = true
--Toggle the menu if the time threshold was reached.
if DeltaTimePercent >= 1 then
MenuToggleReached = true
task.spawn(function()
self:Toggle()
end)
end
else
LeftAdorn.Visible = false
RightAdorn.Visible = false
end
--[[
Updates the given hint parts.
--]]
local function UpdateHintParts(Visible,Part,FrontArrow,BackArrow,FrontText,BackText)
local TweenData = TweenInfo.new(0.25)
TweenService:Create(Part,TweenData,{
Size = Visible and Vector3.new(1, 1, 0) or Vector3.new(1.5, 1.5, 0)
}):Play()
TweenService:Create(FrontArrow,TweenData,{
ImageTransparency = Visible and 0 or 1
}):Play()
TweenService:Create(BackArrow,TweenData,{
ImageTransparency = Visible and 0 or 1
}):Play()
TweenService:Create(FrontText,TweenData,{
ImageTransparency = Visible and 0 or 1
}):Play()
TweenService:Create(BackText,TweenData,{
ImageTransparency = Visible and 0 or 1
}):Play()
end
--Update the hints.
local LeftHandHintVisible, RightHandHintVisible = self.ScreenGui.Enabled and not LeftHandUp, self.ScreenGui.Enabled and not RightHandUp
if self.LeftHandHintVisible ~= LeftHandHintVisible then
self.LeftHandHintVisible = LeftHandHintVisible
UpdateHintParts(LeftHandHintVisible, LeftMenuToggleHintAdornPart, LeftMenuToggleHintFrontArrow, LeftMenuToggleHintBackArrow, LeftMenuToggleHintFrontText, LeftMenuToggleHintBackText)
end
if self.RightHandHintVisible ~= RightHandHintVisible then
self.RightHandHintVisible = RightHandHintVisible
UpdateHintParts(RightHandHintVisible, RightMenuToggleHintAdornPart, RightMenuToggleHintFrontArrow, RightMenuToggleHintBackArrow, RightMenuToggleHintFrontText, RightMenuToggleHintBackText)
end
local Rotation = (tick() * 10) % 360
LeftMenuToggleHintFrontArrow.Rotation = Rotation
LeftMenuToggleHintBackArrow.Rotation = -Rotation
RightMenuToggleHintFrontArrow.Rotation = -Rotation
RightMenuToggleHintBackArrow.Rotation = Rotation
--Wait to poll again.
RunService.RenderStepped:Wait()
end
end)
end
--[[
Toggles the menu being open.
--]]
function MainMenu.Toggle(self: MainMenu, Visible: boolean?): ()
if self.ScreenGui.Enabled == Visible then return end
--Determine the start and end values.
local StartFieldOfView, EndFieldOfView = (self.ScreenGui.Enabled and math.rad(40) or 0), (self.ScreenGui.Enabled and 0 or math.rad(40))
--Show the menu if it isn't visible.
if not self.ScreenGui.Enabled then
self.ScreenGui.Enabled = true
end
--Tween the field of view.
local StartTime = tick()
while tick() - StartTime < MENU_OPEN_TIME do
local Delta = (tick() - StartTime) / MENU_OPEN_TIME
Delta = (math.sin((Delta - 0.5) * math.pi) / 2) + 0.5
self.ScreenGui.FieldOfView = StartFieldOfView + ((EndFieldOfView - StartFieldOfView) * Delta)
RunService.RenderStepped:Wait()
end
--Hide thhe menu if it is closed.
if EndFieldOfView == 0 then
self.ScreenGui.Enabled = false
end
end
--[[
Registers a view.
--]]
function MainMenu.RegisterView(self: MainMenu, ViewName: string, ViewInstance: any): ()
warn("MainMenu::RegisterView is deprecated and may be removed in the future. Use MainMenu::CreateView instead.")
--Set up the view instance.
ViewInstance.Visible = false
ViewInstance.Name = ViewName
ViewInstance.Parent = self.ViewAdornFrame
--Store the view.
table.insert(self.Views, ViewInstance)
end
--[[
Creates a menu view.
--]]
function MainMenu.CreateView(self: MainMenu, InitialViewName: string): any
--Create and store the view.
local View = ApiBaseView.new(InitialViewName)
View.Frame.Parent = (self :: any).ViewAdornFrame
table.insert(self.Views, View)
--Connect the events.
View:GetPropertyChangedSignal("Name"):Connect(function()
self:UpdateVisibleView()
end)
View.Destroyed:Connect(function()
for i = 1, #self.Views do
if self.Views[i] == View then
table.remove(self.Views, i)
if self.CurrentView > i then
self.CurrentView += -1
end
break
end
end
self:UpdateVisibleView()
end)
return View
end
--[[
Updates the visible view.
--]]
function MainMenu.UpdateVisibleView(self: MainMenu, NewView: string?): ()
--Update the button visibility.
self.LeftButton.Visible = (#self.Views > 1)
self.RightButton.Visible = (#self.Views > 1)
--Update the display text.
if NewView then
for i, View in self.Views do
if View.Name ~= NewView then continue end
self.CurrentView = i
break
end
end
self.ViewTextLabel.Text = self.Views[self.CurrentView].Name
--Update the view visibilites.
for i, View in self.Views do
View.Visible = (i == self.CurrentView)
end
end
return MainMenu | 5,889 |
TheNexusAvenger/Nexus-VR-Character-Model | TheNexusAvenger-Nexus-VR-Character-Model-c6e3ad0/src/UI/R6Message.luau | --Displays a message if R6 is used.
--!strict
local MESSAGE_OPEN_TIME = 0.25
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local NexusVRCharacterModel = script.Parent.Parent
local NexusButton = require(NexusVRCharacterModel:WaitForChild("Packages"):WaitForChild("NexusButton"))
local NexusVRCore = require(NexusVRCharacterModel:WaitForChild("Packages"):WaitForChild("NexusVRCore"))
local TextButtonFactory = NexusButton.TextButtonFactory.CreateDefault(Color3.fromRGB(0, 170, 255))
TextButtonFactory:SetDefault("Theme", "RoundedCorners")
local ScreenGui3D = NexusVRCore.ScreenGui3D
local R6Message = {}
R6Message.__index = R6Message
export type R6Message = {
ScreenGui: any,
} & typeof(setmetatable({}, R6Message))
--[[
Creates the R6 message.
--]]
function R6Message.new(): R6Message
--Set up the ScreenGui.
local MessageScreenGui = ScreenGui3D.new()
MessageScreenGui.ResetOnSpawn = false
MessageScreenGui.Enabled = false
MessageScreenGui.CanvasSize = Vector2.new(500, 500)
MessageScreenGui.FieldOfView = 0
MessageScreenGui.Easing = 0.25
--Create the object.
local self = setmetatable({
ScreenGui = MessageScreenGui,
}, R6Message) :: R6Message
--Create the logo and message.
local Logo = Instance.new("ImageLabel")
Logo.BackgroundTransparency = 1
Logo.Size = UDim2.new(0.4, 0, 0.4, 0)
Logo.Position = UDim2.new(0.3, 0, -0.1, 0)
Logo.Image = "http://www.roblox.com/asset/?id=1499731139"
Logo.Parent = MessageScreenGui:GetContainer()
local UpperText = Instance.new("TextLabel")
UpperText.BackgroundTransparency = 1
UpperText.Size = UDim2.new(0.8, 0, 0.1, 0)
UpperText.Position = UDim2.new(0.1, 0, 0.25, 0)
UpperText.Font = Enum.Font.SourceSansBold
UpperText.Text = "R6 Not Supported"
UpperText.TextScaled = true
UpperText.TextColor3 = Color3.fromRGB(255, 255, 255)
UpperText.TextStrokeColor3 = Color3.fromRGB(0, 0, 0)
UpperText.TextStrokeTransparency = 0
UpperText.Parent = MessageScreenGui:GetContainer()
local LowerText = Instance.new("TextLabel")
LowerText.BackgroundTransparency = 1
LowerText.Size = UDim2.new(0.8, 0, 0.25, 0)
LowerText.Position = UDim2.new(0.1, 0, 0.4, 0)
LowerText.Font = Enum.Font.SourceSansBold
LowerText.Text = "Nexus VR Character Model does not support using R6. Use R15 instead."
LowerText.TextScaled = true
LowerText.TextColor3 = Color3.fromRGB(255, 255, 255)
LowerText.TextStrokeColor3 = Color3.fromRGB(0, 0, 0)
LowerText.TextStrokeTransparency = 0
LowerText.Parent = MessageScreenGui:GetContainer()
--Create and connect the close button.
local CloseButton, CloseText = TextButtonFactory:Create()
CloseButton.Size = UDim2.new(0.3, 0, 0.1, 0)
CloseButton.Position = UDim2.new(0.35, 0, 0.7, 0)
CloseButton.Parent = MessageScreenGui:GetContainer()
CloseText.Text = "Ok"
CloseButton.MouseButton1Down:Connect(function()
self:SetOpen(false)
MessageScreenGui:Destroy()
end)
--Parent the message.
MessageScreenGui.Parent = Players.LocalPlayer:WaitForChild("PlayerGui")
return self
end
--[[
Sets the window open or closed.
--]]
function R6Message.SetOpen(self: R6Message, Open: boolean): ()
--Determine the start and end values.
local StartFieldOfView, EndFieldOfView = (Open and 0 or math.rad(40)), (Open and math.rad(40) or 0)
--Show the message if it isn't visible.
if Open then
self.ScreenGui.Enabled = true
end
--Tween the field of view.
local StartTime = tick()
while tick() - StartTime < MESSAGE_OPEN_TIME do
local Delta = (tick() - StartTime) / MESSAGE_OPEN_TIME
Delta = (math.sin((Delta - 0.5) * math.pi) / 2) + 0.5
self.ScreenGui.FieldOfView = StartFieldOfView + ((EndFieldOfView - StartFieldOfView) * Delta)
RunService.RenderStepped:Wait()
end
--Hide thhe message if it is closed.
if EndFieldOfView == 0 then
self.ScreenGui.Enabled = false
end
end
--[[
Opens the message.
--]]
function R6Message.Open(self: R6Message): ()
self:SetOpen(true)
end
return R6Message | 1,196 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.