repo
stringclasses
254 values
file_path
stringlengths
29
241
code
stringlengths
100
233k
tokens
int64
14
69.4k
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Panels/ResizablePanel.luau
local DragHandle = require("@root/Panels/DragHandle") local React = require("@pkg/React") local Sift = require("@pkg/Sift") local types = require("@root/Panels/types") local defaultProps = { dragHandleSize = 8, -- px minSize = Vector2.new(0, 0), maxSize = Vector2.new(math.huge, math.huge), } export type Props = { LayoutOrder: number?, children: { [string]: React.Node }?, dragHandles: { types.DragHandle }?, hoverIconX: string?, hoverIconY: string?, initialSize: UDim2, onResize: ((newSize: Vector2) -> ())?, } type InternalProps = Props & typeof(defaultProps) local function ResizablePanel(providedProps: Props) local props: InternalProps = Sift.Dictionary.merge(defaultProps, providedProps) local absoluteSize, setAbsoluteSize = React.useState(nil :: Vector2?) local clampedAbsoluteSize = React.useMemo(function() return if absoluteSize then Vector2.new( math.clamp(absoluteSize.X, props.minSize.X, props.maxSize.X), math.clamp(absoluteSize.Y, props.minSize.Y, props.maxSize.Y) ) else nil end, { absoluteSize }) local isWidthResizable = React.useMemo(function() if props.dragHandles then return Sift.Array.includes(props.dragHandles, "Left") or Sift.Array.includes(props.dragHandles, "Right") end return false end, { props.dragHandles }) local isHeightResizable = React.useMemo(function() if props.dragHandles then return Sift.Array.includes(props.dragHandles, "Top") or Sift.Array.includes(props.dragHandles, "Bottom") end return false end, { props.dragHandles }) local width = React.useMemo(function() return if clampedAbsoluteSize and isWidthResizable then UDim.new(0, clampedAbsoluteSize.X) else props.initialSize.Width end, { clampedAbsoluteSize }) local height = React.useMemo(function() return if clampedAbsoluteSize and isHeightResizable then UDim.new(0, clampedAbsoluteSize.Y) else props.initialSize.Height end, { clampedAbsoluteSize, props.initialSize } :: { unknown }) local onAbsoluteSizeChanged = React.useCallback(function(rbx: Frame) setAbsoluteSize(rbx.AbsoluteSize) end, {}) local onHandleDragged = React.useCallback(function(handle: types.DragHandle, delta: Vector2) setAbsoluteSize(function(prev: Vector2) local x = prev.X + delta.X local y = prev.Y - delta.Y if handle == "Top" or handle == "Bottom" then x = prev.X elseif handle == "Right" or handle == "Left" then y = prev.Y end return Vector2.new(x, y) end) end, { props.minSize, props.maxSize }) React.useEffect(function() if clampedAbsoluteSize and props.onResize then props.onResize(clampedAbsoluteSize) end end, { clampedAbsoluteSize }) local dragHandles: { [string]: React.Node } = {} if props.dragHandles then for _, handle: types.DragHandle in props.dragHandles do dragHandles[handle] = React.createElement(DragHandle, { handle = handle, hoverIconX = props.hoverIconX, hoverIconY = props.hoverIconY, onDrag = function(delta: Vector2) onHandleDragged(handle, delta) end, onDragEnd = function() if clampedAbsoluteSize then setAbsoluteSize(clampedAbsoluteSize) end end, }) end end return React.createElement("Frame", { LayoutOrder = props.LayoutOrder, Size = UDim2.new(width, height), BackgroundTransparency = 1, [React.Change.AbsoluteSize] = onAbsoluteSizeChanged, }, { DragHandles = React.createElement(React.Fragment, nil, dragHandles), Children = React.createElement("Frame", { BackgroundTransparency = 1, Size = UDim2.fromScale(1, 1), }, props.children), }) end return ResizablePanel
938
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Panels/ResizablePanel.story.luau
local React = require("@pkg/React") local ResizablePanel = require("./ResizablePanel") local controls = { minWidth = 200, maxWidth = 500, minHeight = 200, maxHeight = 500, } type Props = { controls: typeof(controls), } return { controls = controls, story = function(props: Props) return React.createElement(ResizablePanel, { initialSize = UDim2.fromOffset(props.controls.maxWidth - props.controls.minWidth, 300), maxSize = Vector2.new(props.controls.maxWidth, props.controls.maxHeight), minSize = Vector2.new(props.controls.minWidth, props.controls.minHeight), dragHandles = { -- Luau FIXME: Type '{string}' could not be converted into '{"Bottom" | "Left" | "Right" | "Top"}' "Right" :: any, "Bottom" :: any, }, }, { Content = React.createElement("Frame", { Size = UDim2.fromScale(1, 1), }), }) end, }
234
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Panels/Sidebar.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local StorybookTreeView = require("@root/Storybook/StorybookTreeView") local Storyteller = require("@pkg/Storyteller") local IconName = Foundation.Enums.IconName local InputSize = Foundation.Enums.InputSize local ScrollView = Foundation.ScrollView local TextInput = Foundation.TextInput local View = Foundation.View local withCommonProps = Foundation.Utility.withCommonProps local e = React.createElement local useCallback = React.useCallback local useState = React.useState type LoadedStorybook = Storyteller.LoadedStorybook type UnavailableStorybook = Storyteller.UnavailableStorybook type SidebarProps = { onStoryChanged: (storyModule: ModuleScript?, storybook: LoadedStorybook?) -> (), onShowErrorPage: (unavailableStorybook: UnavailableStorybook) -> (), } & Foundation.CommonProps local function Sidebar(props: SidebarProps) local searchTerm: string?, setSearchTerm = useState(nil :: string?) local onSearchTermChanged = useCallback(function(newSearchTerm: string) setSearchTerm(if newSearchTerm == "" then nil else newSearchTerm) end, {}) return e( View, withCommonProps(props, { tag = "bg-surface-0 col size-full", }), { Search = e(View, { LayoutOrder = 1, tag = "auto-y padding-medium size-full-0", }, { SearchBar = e(TextInput, { label = "", leadingIcon = IconName.MagnifyingGlass, onChanged = onSearchTermChanged, placeholder = "Search...", size = InputSize.Small, text = "", width = UDim.new(1, 0), }), }), Content = e(ScrollView, { LayoutOrder = 2, scroll = { AutomaticCanvasSize = Enum.AutomaticSize.Y, CanvasSize = UDim2.fromScale(0, 0), ScrollingDirection = Enum.ScrollingDirection.Y, }, layout = { FillDirection = Enum.FillDirection.Vertical, }, tag = "shrink size-full", }, { StorybookTreeView = e(StorybookTreeView, { onShowErrorPage = props.onShowErrorPage, onStoryChanged = props.onStoryChanged, searchTerm = searchTerm, }), }), } ) end return React.memo(Sidebar)
538
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Panels/Sidebar.story.luau
local React = require("@pkg/React") local Storyteller = require("@pkg/Storyteller") local Sidebar = require("./Sidebar") return { summary = "Sidebar containing brand, searchbar, and component tree", controls = {}, story = function() local storybooks = Storyteller.useStorybooks(game) return React.createElement(Sidebar, { storybooks = storybooks, onStoryChanged = function(storyModule, storybook) print("storyModule", storyModule) print("storybook", storybook) end, onShowErrorPage = function(unavailableStorybook) print("unavailableStorybook", unavailableStorybook) end, }) end, }
150
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Panels/Topbar.luau
local Foundation = require("@rbxpkg/Foundation") local LuauPolyfill = require("@pkg/LuauPolyfill") local React = require("@pkg/React") local ReactSignals = require("@pkg/ReactCharm") local AboutView = require("@root/About/AboutView") local FeedbackDialog = require("@root/Feedback/FeedbackDialog") local NavigationContext = require("@root/Navigation/NavigationContext") local StoryActionsContext = require("@root/Storybook/StoryActionsContext") local UserSettingsStore = require("@root/UserSettings/UserSettingsStore") local Object = LuauPolyfill.Object local Dialog = Foundation.Dialog local Divider = Foundation.Divider local Dropdown = Foundation.Dropdown local IconButton = Foundation.IconButton local IconName = Foundation.Enums.IconName local IconVariant = Foundation.Enums.IconVariant local InputSize = Foundation.Enums.InputSize local Menu = Foundation.Menu local Orientation = Foundation.Enums.Orientation local PopoverAlign = Foundation.Enums.PopoverAlign local PopoverSide = Foundation.Enums.PopoverSide local Tooltip = Foundation.Tooltip local View = Foundation.View local withCommonProps = Foundation.Utility.withCommonProps local e = React.createElement local useCallback = React.useCallback local useRef = React.useRef local useState = React.useState local useSignalState = ReactSignals.useSignalState type ItemId = number | string type TopbarProps = {} & Foundation.CommonProps local function Topbar(props: TopbarProps) local helpButtonRef = useRef(nil :: GuiObject?) local isAboutMenuOpen, setIsAboutMenuOpen = useState(false) local isHelpMenuOpen, setIsHelpMenuOpen = useState(false) local isFeedbackDialogOpen, setIsFeedbackDialogOpen = useState(false) local navigation = NavigationContext.use() local storyActions = StoryActionsContext.useStoryActions() local userSettingsStore = useSignalState(UserSettingsStore.get) local userSettings = useSignalState(userSettingsStore.getStorage) local onThemeChanged = useCallback(function(itemId: ItemId) userSettingsStore.setStorage(function(currentValue) return Object.assign({}, currentValue, { theme = itemId, }) end) end, { userSettingsStore.setStorage }) return e( View, withCommonProps(props, { tag = "align-y-center bg-surface-0 flex-x-between padding-right-medium padding-y-medium row size-full-1400", }), { Actions = e(View, { LayoutOrder = 1, tag = "auto-x gap-medium row size-0-full", }, { Zoom = e(View, { LayoutOrder = 1, tag = "auto-x row size-0-full", }, { ZoomIn = e(Tooltip, { LayoutOrder = 1, align = PopoverAlign.Center, side = PopoverSide.Bottom, title = "Zoom In", }, { Trigger = e(IconButton, { icon = IconName.MagnifyingGlassPlus, isDisabled = storyActions.isDisabled, onActivated = storyActions.zoom.zoomIn, size = InputSize.Small, }), }), ZoomOut = e(Tooltip, { LayoutOrder = 2, align = PopoverAlign.Center, side = PopoverSide.Bottom, title = "Zoom Out", }, { Trigger = e(IconButton, { icon = IconName.MagnifyingGlassMinus, isDisabled = storyActions.isDisabled, onActivated = storyActions.zoom.zoomOut, size = InputSize.Small, }), }), }), ZoomDivider = e(Divider, { LayoutOrder = 2, orientation = Orientation.Vertical, }), Views = e(View, { LayoutOrder = 3, tag = "auto-x row size-0-full", }, { Source = e(Tooltip, { LayoutOrder = 1, align = PopoverAlign.Center, side = PopoverSide.Bottom, title = "View Source Code", }, { Trigger = e(IconButton, { icon = IconName.Code, isDisabled = storyActions.isDisabled, onActivated = storyActions.viewCode, size = InputSize.Small, }), }), Viewport = e(Tooltip, { LayoutOrder = 2, align = PopoverAlign.Center, side = PopoverSide.Bottom, title = "Preview in Viewport", }, { Trigger = e(IconButton, { icon = IconName.Eye, isDisabled = storyActions.isDisabled, onActivated = storyActions.viewportPreview, size = InputSize.Small, }), }), Explorer = e(Tooltip, { LayoutOrder = 3, align = PopoverAlign.Center, side = PopoverSide.Bottom, title = "View in Explorer", }, { Trigger = e(IconButton, { icon = IconName.MagnifyingGlass, isDisabled = storyActions.isDisabled, onActivated = storyActions.viewExplorer, size = InputSize.Small, }), }), }), ViewsDivider = e(Divider, { LayoutOrder = 4, orientation = Orientation.Vertical, }), Theme = e(Dropdown.Root, { LayoutOrder = 5, items = { { id = "system", text = "System" }, { id = "dark", text = "Dark" }, { id = "light", text = "Light" }, }, label = "", onItemChanged = onThemeChanged, placeholder = "Theme", size = InputSize.Small, value = userSettings.theme, width = UDim.new(0, 160), }), }), Support = e(View, { LayoutOrder = 2, tag = "auto-x row size-0-full", }, { Help = e(Tooltip, { LayoutOrder = 1, align = PopoverAlign.Center, side = PopoverSide.Bottom, title = "Help", }, { Trigger = e(IconButton, { icon = IconName.CircleQuestion, onActivated = function() setIsHelpMenuOpen(true) end, ref = helpButtonRef, size = InputSize.Small, }), }), Settings = e(Tooltip, { LayoutOrder = 2, align = PopoverAlign.End, side = PopoverSide.Bottom, title = "Settings", }, { Trigger = e(IconButton, { icon = { name = IconName.Gear, variant = if navigation.currentScreen == "Settings" then IconVariant.Filled else IconVariant.Regular, }, onActivated = function() if navigation.currentScreen ~= "Settings" then navigation.navigateTo("Settings") else navigation.navigateTo("Home") end end, size = InputSize.Small, }), }), }), AboutMenu = isAboutMenuOpen and e(Dialog.Root, { disablePortal = false, hasBackdrop = true, onClose = function() setIsAboutMenuOpen(false) end, }, { Title = e(Dialog.Title, { text = "About", }), Content = e(Dialog.Content, nil, { View = e(AboutView), }), }), FeedbackDialog = if isFeedbackDialogOpen then React.createElement(FeedbackDialog, { onClose = function() setIsFeedbackDialogOpen(false) end, }) else nil, HelpMenu = e(Menu, { anchorRef = helpButtonRef, isOpen = isHelpMenuOpen, items = { { id = "About", text = "About", onActivated = function() setIsAboutMenuOpen(true) setIsHelpMenuOpen(false) end, }, { id = "Feedback", text = "Send feedback", onActivated = function() setIsFeedbackDialogOpen(true) setIsHelpMenuOpen(false) end, }, { id = "Logs", text = "Logs", onActivated = function() if navigation.currentScreen ~= "Settings" then navigation.navigateTo("Logs") else navigation.navigateTo("Home") end setIsHelpMenuOpen(false) end, }, }, onPressedOutside = function() setIsHelpMenuOpen(function(currentValue) return not currentValue end) end, }), } ) end return React.memo(Topbar)
1,909
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Permissions/tryGetService.luau
local function tryGetService(serviceName: string): Instance? local service pcall(function() service = game:GetService(serviceName) end) if service then return service end -- Some services cannot be retrieved by GetService but still exist in the DM -- and can be retrieved by name. pcall(function() service = game:FindFirstChild(serviceName) end) return service end return tryGetService
92
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Plugin/LocalStorageStore.luau
local Charm = require("@pkg/Charm") local t = require("@pkg/t") local createPluginSettingsStore = require("@root/Plugin/createPluginSettingsStore") export type LocalStorageStore = { lastOpenedStoryPath: string?, pinnedInstancePaths: { string }?, wasUserPromptedForTelemetry: boolean, } local defaultValue: LocalStorageStore = { wasUserPromptedForTelemetry = false, } local validate = t.interface({ lastOpenedStoryPath = t.optional(t.string), pinnedInstancePaths = t.optional(t.array(t.string)), wasUserPromptedForTelemetry = t.boolean, }) -- Initialize the store eagerly at module level so createPluginSettingsStore's -- internal Charm.effect is a top-level effect, not one nested inside a computed. local get = Charm.signal(createPluginSettingsStore("FlipbookLocalStorage", defaultValue, validate)) return { get = get, }
187
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Plugin/PluginApp.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local ReactCharm = require("@pkg/ReactCharm") local Storyteller = require("@pkg/Storyteller") local NavigationContext = require("@root/Navigation/NavigationContext") local ResizablePanel = require("@root/Panels/ResizablePanel") local Screen = require("@root/Navigation/Screen") local Sidebar = require("@root/Panels/Sidebar") local StoryActionsContext = require("@root/Storybook/StoryActionsContext") local TelemetryOptOutDialog = require("@root/Telemetry/TelemetryOptOutDialog") local Topbar = require("@root/Panels/Topbar") local UserSettingsStore = require("@root/UserSettings/UserSettingsStore") local constants = require("@root/constants") local createLoadedStorybook = require("@root/Storybook/createLoadedStorybook") local fireEventAsync = require("@root/Telemetry/fireEventAsync") local nextLayoutOrder = require("@root/Common/nextLayoutOrder") local useSignalState = ReactCharm.useSignalState type LoadedStorybook = Storyteller.LoadedStorybook type UnavailableStorybook = Storyteller.UnavailableStorybook local defaultStorybook = createLoadedStorybook() local function App() local userSettingsStore = useSignalState(UserSettingsStore.get) local userSettings = useSignalState(userSettingsStore.getStorage) local storyModule: ModuleScript?, setStoryModule = React.useState(nil :: ModuleScript?) local storybook, setStorybook = React.useState(nil :: LoadedStorybook?) local unavailableStorybook: UnavailableStorybook?, setUnavailableStorybook = React.useState(nil :: UnavailableStorybook?) local navigation = NavigationContext.use() local onStoryChanged = React.useCallback(function(newStoryModule: ModuleScript?, newStorybook: LoadedStorybook?) navigation.navigateTo("Home") setUnavailableStorybook(nil) if newStoryModule and not newStorybook then newStorybook = defaultStorybook end task.spawn(function() fireEventAsync({ eventName = "StoryOpened", }) end) setStoryModule(newStoryModule) setStorybook(newStorybook) end, { navigation.navigateTo } :: { unknown }) local onShowErrorPage = React.useCallback(function(newUnavailableStorybook: UnavailableStorybook) setStoryModule(nil) setStorybook(nil) setUnavailableStorybook(newUnavailableStorybook) end, {}) return React.createElement(Foundation.View, { tag = "size-full row align-y-center flex-between", }, { StoryActionsProvider = React.createElement(StoryActionsContext.Provider, { story = storyModule, }, { SidebarWrapper = React.createElement(ResizablePanel, { LayoutOrder = nextLayoutOrder(), initialSize = UDim2.new(0, userSettings.sidebarWidth, 1, 0), dragHandles = { "Right" :: "Right" }, minSize = Vector2.new(constants.SIDEBAR_MIN_WIDTH, 0), maxSize = Vector2.new(constants.SIDEBAR_MAX_WIDTH, math.huge), }, { Sidebar = React.createElement(Sidebar, { onStoryChanged = onStoryChanged, onShowErrorPage = onShowErrorPage, }), }), MainWrapper = React.createElement(Foundation.View, { tag = "size-full col shrink", LayoutOrder = nextLayoutOrder(), }, { Topbar = React.createElement(Topbar, { LayoutOrder = nextLayoutOrder(), }), ScreenWrapper = React.createElement(Foundation.View, { LayoutOrder = nextLayoutOrder(), tag = "size-full shrink", }, { Screen = React.createElement(Screen, { story = storyModule, storybook = storybook, unavailableStorybook = unavailableStorybook, }), }), }), }), TelemetryOptOutDialog = React.createElement(TelemetryOptOutDialog), }) end return App
864
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Plugin/PluginApp.story.luau
local React = require("@pkg/React") local PluginApp = require("./PluginApp") return { summary = "The main component that handles the entire plugin", controls = {}, story = function() return React.createElement(PluginApp) end, }
53
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Plugin/PluginStore/createPluginStore.luau
local Charm = require("@pkg/Charm") local CharmTypes = require("@root/Common/CharmTypes") export type PluginStore = { getPlugin: CharmTypes.Getter<Plugin?>, setPlugin: CharmTypes.Setter<Plugin?>, } --[[ This is a basic store to keep track of the Plugin instance. A quirk of the `plugin` keyword is that it's only defined in top-level scripts, like `init.server.luau`. It must be passed along by reference after that point, as attempting to use `plugin` in a ModuleScript will result in nil value. To work around this, we just toss the plugin instance into this store to share it around other parts of the app ]] local function createPluginStore(): PluginStore local getPlugin, setPlugin = Charm.signal(nil :: Plugin?) return { getPlugin = getPlugin, setPlugin = setPlugin, } end return createPluginStore
197
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Plugin/PluginStore/init.luau
local Charm = require("@pkg/Charm") local createPluginStore = require("@self/createPluginStore") return { get = Charm.computed(createPluginStore), }
34
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Plugin/createFlipbookPlugin.luau
local React = require("@pkg/React") local ReactRoblox = require("@pkg/ReactRoblox") local ContextProviders = require("@root/Common/ContextProviders") local PluginApp = require("@root/Plugin/PluginApp") local fireEventAsync = require("@root/Telemetry/fireEventAsync") local logger = require("@root/logger") local function stopwatch(callback: () -> ()): string local start = os.clock() callback() return ("%.2fms"):format((os.clock() - start) * 1000) end local function createFlipbookPlugin(plugin: Plugin, widget: DockWidgetPluginGui, button: PluginToolbarButton?) local connections: { RBXScriptConnection } = {} local root = ReactRoblox.createRoot(widget) -- FIXME: ContextProviders having an error won't fail tests. We really need -- a smoketest for this file local app = React.createElement(ContextProviders, { plugin = plugin, overlayGui = widget :: GuiBase2d, }, { PluginApp = React.createElement(PluginApp), }) local function unmount() logger:Info("unmounting app...") local elapsedMs = stopwatch(function() root:unmount() end) logger:Info(`unmounted app in {elapsedMs}`) task.spawn(function() fireEventAsync({ eventName = "AppClosed", }) end) end local function mount() logger:Info("mounting app...") local elapsedMs = stopwatch(function() root:render(app) end) logger:Info(`mounted app in {elapsedMs}`) task.spawn(function() fireEventAsync({ eventName = "AppOpened", }) end) end if button ~= nil then table.insert( connections, button.Click:Connect(function() widget.Enabled = not widget.Enabled end) ) table.insert( connections, widget:GetPropertyChangedSignal("Enabled"):Connect(function() button:SetActive(widget.Enabled) end) ) end table.insert( connections, widget:GetPropertyChangedSignal("Enabled"):Connect(function() if widget.Enabled then mount() else unmount() end end) ) if widget.Enabled then mount() end local function destroy() logger:Info("destroying app...") local elapsedMs = stopwatch(function() unmount() for _, connection in connections do connection:Disconnect() end end) logger:Info(`destroyed app in {elapsedMs}`) end return { mount = mount, unmount = unmount, destroy = destroy, } end return createFlipbookPlugin
579
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Plugin/createPluginSettingsStore.luau
local HttpService = game:GetService("HttpService") local Charm = require("@pkg/Charm") local CharmTypes = require("@root/Common/CharmTypes") local PluginStore = require("@root/Plugin/PluginStore") local logger = require("@root/logger") export type PluginSettingsStore<T> = { getStorage: CharmTypes.Getter<T>, setStorage: CharmTypes.Setter<T>, isSettingDefault: (settingName: string) -> boolean, getIsLoading: CharmTypes.Getter<boolean>, getErr: CharmTypes.Getter<string?>, waitForLoaded: () -> (), } --[[ Creates a store to manage plugin settings. Settings are persisted using Plugin:SetSetting and Plugin:GetSetting, and are stored as JSON strings. The settings are loaded once when the store is first created, and any changes to the settings are automatically saved. ]] local function createPluginSettingsStore<T>( storageKey: string, defaultValue: T, validate: (value: any) -> (boolean, string) ): PluginSettingsStore<T> local getStorage, setStorageSignal = Charm.signal(defaultValue) local getIsLoading, setIsLoading = Charm.signal(true) local getErr, setErr = Charm.signal(nil :: string?) local getIsInitialized, setIsInitialized = Charm.signal(false) local prevStorage: T? local function readPluginSettingsAsync(plugin: Plugin): T? logger:Info(`reading plugin settings for {storageKey} from disk...`) local data local success, err = pcall(function() data = plugin:GetSetting(storageKey) end) if success then logger:Info(`read raw plugin settings for {storageKey}:`, data) else logger:Warn(`failed to read plugin settings for {storageKey}: {err}`) setErr(err) return nil end if typeof(data) == "string" then logger:Info(`deserializing plugin settings for {storageKey} to object...`) local json success, err = pcall(function() json = HttpService:JSONDecode(data) end) if not success then logger:Warn(`failed to load plugin settings for {storageKey}: {err}`) setErr(err) return nil end success, err = validate(json) if not success then logger:Warn(`plugin settings are malformed for {storageKey}: {err}`) setErr(err) return nil end logger:Info(`got plugin settings for {storageKey}:`, json) return json end logger:Info("no plugin settings to read") return nil end local function writePluginSettingsAsync(plugin: Plugin, storage: T) logger:Info("writing plugin settings to disk...") local data local success, err = pcall(function() data = HttpService:JSONEncode(storage) end) if success then logger:Info(`parsed storage value into JSON: {data}`) else logger:Warn(`failed to parse storage value into JSON: {err}`) setErr(err) return end if data then success, err = pcall(function() plugin:SetSetting(storageKey, data) end) if success then logger:Info(`wrote plugin settings to disk: {data}`) else logger:Warn(`failed to write plugin settings to disk: {err}`) end end end local function setStorageInternal(newValue: CharmTypes.Update<T>): T setStorageSignal(newValue) local newStorage = Charm.untracked(getStorage) if newStorage ~= prevStorage then local plugin = Charm.untracked(function() return PluginStore.get().getPlugin() end) if plugin then task.spawn(function() writePluginSettingsAsync(plugin, newStorage) end) end else logger:Debug("skipping disk write since storage value did not change") end prevStorage = newStorage return newStorage end local function setStorage(newValue: CharmTypes.Update<T>): T assert( not Charm.untracked(getIsLoading), "attempt to set storage while PluginSettingsStore is still loading. Call `PluginSettingsStore.waitForLoaded()` before setting storage" ) return setStorageInternal(newValue) end local function waitForLoaded() while getIsLoading() do task.wait() end end local function loadInitialSettings(plugin: Plugin) if not getIsLoading() then logger:Warn("attempt to load initial plugin settings after loading has already finished") return end if getIsInitialized() then logger:Warn("attempt to load initial settings after they've already been initialized") return end logger:Debug("loading initial plugin settings") task.spawn(function() local data = readPluginSettingsAsync(plugin) if data then setStorageInternal(data) logger:Debug("finished loading plugin settings") else logger:Debug("no data on disk") end setIsLoading(false) setIsInitialized(true) end) end local function isSettingDefault(settingName: string): boolean local storage = Charm.untracked(getStorage) if typeof(defaultValue) ~= "table" or typeof(storage) ~= "table" then return true end local settingDefaultValue = defaultValue[settingName] local storedValue = storage[settingName] return storedValue == nil or storedValue == settingDefaultValue end Charm.effect(function() local plugin = PluginStore.get().getPlugin() if plugin and not getIsInitialized() then loadInitialSettings(plugin) end end) return { getIsLoading = getIsLoading, getErr = getErr, getStorage = getStorage, setStorage = setStorage, isSettingDefault = isSettingDefault, waitForLoaded = waitForLoaded, } end return createPluginSettingsStore
1,274
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/NoStorySelected.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local nextLayoutOrder = require("@root/Common/nextLayoutOrder") local useTokens = Foundation.Hooks.useTokens local e = React.createElement local function NoStorySelected() local tokens = useTokens() return e(Foundation.View, { tag = "size-full col bg-surface-200 gap-medium align-y-center align-x-center", }, { Icon = e(Foundation.Icon, { name = Foundation.Enums.IconName.SquareBooks, style = tokens.Color.ActionStandard.Foreground, size = Foundation.Enums.IconSize.Large, LayoutOrder = nextLayoutOrder(), }), Message = e(Foundation.Text, { tag = "auto-xy text-heading-medium", Text = "Select a story to preview it", LayoutOrder = nextLayoutOrder(), }), }) end return NoStorySelected
197
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/NoStorySelected.story.luau
local React = require("@pkg/React") local NoStorySelected = require("./NoStorySelected") return { story = function() return React.createElement(NoStorySelected) end, }
39
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/PinnedInstanceStore/createPinnedInstanceStore.luau
local Charm = require("@pkg/Charm") local Sift = require("@pkg/Sift") local LocalStorageStore = require("@root/Plugin/LocalStorageStore") local fireEventAsync = require("@root/Telemetry/fireEventAsync") local getInstanceFromPath = require("@root/Common/getInstanceFromPath") local getInstancePath = require("@root/Common/getInstancePath") export type PinnedInstance = { path: string, instance: Instance?, } export type PinnedInstanceStore = { getPinnedInstances: () -> { PinnedInstance }, isPinned: (instance: Instance) -> boolean, pin: (instance: Instance) -> (), unpin: (instance: Instance) -> (), waitForLoaded: () -> (), } local function createPinnedInstanceStore(): PinnedInstanceStore local localStorageStore = LocalStorageStore.get() local getPinnedPaths = Charm.computed(function() local storage = localStorageStore.getStorage() return storage.pinnedInstancePaths or {} end) local function setPinnedPaths(update: (prev: { string }) -> { string }) localStorageStore.setStorage(function(prev) return Sift.Dictionary.join(prev, { pinnedInstancePaths = update(prev.pinnedInstancePaths or {}), }) end) end local getPinnedInstances = Charm.computed(function() local pinnedPaths = getPinnedPaths() return Sift.List.map(pinnedPaths, function(pinnedPath) return { path = pinnedPath, instance = getInstanceFromPath(pinnedPath), } :: PinnedInstance end) end) local function pin(instance: Instance) task.spawn(function() fireEventAsync({ eventName = "NodePinned", }) end) setPinnedPaths(function(prev) return Sift.List.append(prev, getInstancePath(instance)) end) end local function unpin(instance: Instance) task.spawn(function() fireEventAsync({ eventName = "NodeUnpinned", }) end) setPinnedPaths(function(prev) return Sift.List.removeValue(prev, getInstancePath(instance)) end) end local function isPinned(instance: Instance) return Sift.List.has(getPinnedPaths(), getInstancePath(instance)) end local function waitForLoaded() return localStorageStore.waitForLoaded() end return { pin = pin, unpin = unpin, isPinned = isPinned, getPinnedInstances = getPinnedInstances, waitForLoaded = waitForLoaded, } end return createPinnedInstanceStore
536
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/PinnedInstanceStore/init.luau
local Charm = require("@pkg/Charm") local createPinnedInstanceStore = require("@self/createPinnedInstanceStore") return { get = Charm.computed(createPinnedInstanceStore), }
40
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/StoryActionsContext.luau
local Selection = game:GetService("Selection") local PluginStore = require("@root/Plugin/PluginStore") local React = require("@pkg/React") local ReactSignals = require("@pkg/ReactCharm") local useZoom = require("@root/Common/useZoom") local e = React.createElement local useRef = React.useRef local useCallback = React.useCallback local useContext = React.useContext local useState = React.useState local useSignalState = ReactSignals.useSignalState export type StoryActionsContext = { isDisabled: boolean, isMountedInViewport: boolean, storyContainerRef: { current: GuiObject? }?, viewportPreview: () -> (), viewCode: () -> (), viewExplorer: () -> (), zoom: { value: number, zoomIn: () -> (), zoomOut: () -> (), }, } local StoryActionsContext = React.createContext({} :: StoryActionsContext) export type StoryActionsProviderProps = { children: React.ReactNode, story: ModuleScript?, } local function StoryActionsProvider(props: StoryActionsProviderProps) local pluginStore = useSignalState(PluginStore.get) local plugin = useSignalState(pluginStore.getPlugin) local isMountedInViewport, setIsMountedInViewport = useState(false) local storyContainerRef = useRef(nil :: GuiObject?) local zoom = useZoom(props.story) local viewportPreview = useCallback(function() setIsMountedInViewport(function(currentValue) return not currentValue end) end, {}) local viewCode = useCallback(function() if props.story == nil then return end Selection:Set({ props.story }) if plugin ~= nil then plugin:OpenScript(props.story) end end, { plugin, props.story } :: { any }) local viewExplorer = useCallback(function() if storyContainerRef.current == nil then return end Selection:Set({ storyContainerRef.current:FindFirstAncestorWhichIsA("GuiObject") or storyContainerRef.current }) end, {}) return e(StoryActionsContext.Provider, { value = { isDisabled = props.story == nil, isMountedInViewport = isMountedInViewport, storyContainerRef = storyContainerRef, viewportPreview = viewportPreview, viewCode = viewCode, viewExplorer = viewExplorer, zoom = zoom, }, }, props.children) end local function useStoryActions(): StoryActionsContext return useContext(StoryActionsContext) end return { Context = StoryActionsContext, Provider = StoryActionsProvider, useStoryActions = useStoryActions, }
549
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/StoryControls.luau
local Constants = require("@root/constants") local Foundation = require("@rbxpkg/Foundation") local LuauPolyfill = require("@pkg/LuauPolyfill") local React = require("@pkg/React") local ReactSignals = require("@pkg/ReactCharm") local ResizablePanel = require("@root/Panels/ResizablePanel") local UserSettingsStore = require("@root/UserSettings/UserSettingsStore") local useSortedControls = require("@root/Storybook/useSortedControls") local Checkbox = Foundation.Checkbox local Divider = Foundation.Divider local Dropdown = Foundation.Dropdown local InputSize = Foundation.Enums.InputSize local NumberInput = Foundation.NumberInput local ScrollView = Foundation.ScrollView local Text = Foundation.Text local TextInput = Foundation.TextInput local View = Foundation.View local useTokens = Foundation.Hooks.useTokens local withCommonProps = Foundation.Utility.withCommonProps local Array = LuauPolyfill.Array local e = React.createElement local useState = React.useState local useSignalState = ReactSignals.useSignalState type StoryControlsProps = { controls: { [string]: any }, modifiedControls: { [string]: any }, setControl: (key: string, value: any) -> (), } & Foundation.CommonProps -- NOTE(Paul): In the future, we'll want to store more than just -- controls here, we'll also want to have tabs for stuff like -- accessibility as well. I was planning to use the <Foundation.Tabs /> -- component to show-off the Accessibility tab for future purposes, -- but turns out it doesn't work when in a `col` with a `shrink size-full` -- as it's sibling. local function StoryControls(props: StoryControlsProps) local tokens = useTokens() local userSettingsStore = useSignalState(UserSettingsStore.get) local userSettings = useSignalState(userSettingsStore.getStorage) local sortedControls = useSortedControls(props.controls) local pendingControl, setPendingControl = useState(nil :: string?) local controlElements: { [string]: React.ReactNode } = {} for index, control in sortedControls do local function setControl(newValue: any) local newValueAsNumber = tonumber(newValue) if newValueAsNumber ~= nil then newValue = newValueAsNumber end props.setControl(control.key, newValue) end local controlType = typeof(control.value) local controlInput: React.ReactNode = nil if controlType == "boolean" then controlInput = e(Checkbox, { isChecked = control.value, label = "", onActivated = setControl, size = InputSize.Small, }) elseif controlType == "number" then controlInput = e(NumberInput, { label = "", onChanged = setControl, size = InputSize.Small, step = 1, value = control.value, width = UDim.new(1, 0), }) elseif controlType == "string" then controlInput = e(TextInput, { label = "", onChanged = function(newText) setPendingControl(newText) end, onFocusLost = function() setControl(pendingControl) end, onReturnPressed = function() setControl(pendingControl) end, text = control.value, size = InputSize.Small, width = UDim.new(1, 0), }) elseif controlType == "table" and Array.isArray(control.value) then local changedValue = props.modifiedControls[control.key] local controlItems = Array.map(control.value, function(value): Foundation.DropdownItem return { id = value, text = tostring(value), } end) controlInput = e(Dropdown.Root, { items = controlItems, label = "", onItemChanged = setControl, size = InputSize.Small, value = if changedValue ~= nil then changedValue else control.value[1], width = UDim.new(1, 0), }) end controlElements[control.key] = e(View, { LayoutOrder = index, tag = "auto-y col size-full-0", }, { Content = e(View, { LayoutOrder = 1, tag = "align-y-center auto-y gap-medium padding-medium row size-full-0", }, { Title = e(Text, { LayoutOrder = 1, Size = UDim2.fromScale(0.2, 0), Text = control.key, tag = "auto-y text-align-x-left text-label-medium", }), Option = e(View, { LayoutOrder = 2, tag = "align-x-left auto-y fill row", }, { -- Keying by the identity of sortedControls fixes a bug where -- the options visually do not update when two stories have the -- exact same controls. [`Option_{sortedControls}`] = controlInput, }), }), Divider = index < #sortedControls and e(Divider, { LayoutOrder = 2, }), }) end return e( ResizablePanel, withCommonProps(props, { dragHandles = { "Top" :: "Top" }, initialSize = UDim2.new(1, 0, 0, userSettings.controlsHeight), maxSize = Vector2.new(0, Constants.CONTROLS_MAX_HEIGHT), minSize = Vector2.new(0, Constants.CONTROLS_MIN_HEIGHT), }), { Content = e(View, { tag = "bg-surface-100 col size-full", }, { -- NOTE(Paul): Adding a temporary pseudo-tab element for the time -- being so that we have separation between the controls panel -- and the story view. Tabs = e(View, { LayoutOrder = 1, tag = "auto-y col size-full-0", }, { Tab = e(View, { LayoutOrder = 1, onActivated = function() end, tag = "col size-2000-1100", }, { Content = e(View, { tag = "align-x-center align-y-center row size-full", }, { Text = e(Text, { Text = "Controls", tag = "anchor-center-center auto-xy content-emphasis position-center-center text-label-medium", }), }), Border = e(View, { Size = UDim2.new(1, 0, 0, tokens.Stroke.Thick), backgroundStyle = tokens.Color.System.Contrast, tag = "anchor-bottom-center position-bottom-center", }), }), Divider = e(Divider, { LayoutOrder = 2, }), }), ScrollContent = e(ScrollView, { LayoutOrder = 2, scroll = { AutomaticCanvasSize = Enum.AutomaticSize.Y, CanvasSize = UDim2.fromScale(0, 0), ScrollingDirection = Enum.ScrollingDirection.Y, }, layout = { FillDirection = Enum.FillDirection.Vertical, }, tag = "shrink size-full", }, { Header = e(View, { LayoutOrder = 0, tag = "auto-y col size-full-0", }, { Content = e(View, { LayoutOrder = 1, tag = "auto-y align-y-center gap-medium padding-medium row size-full-0", }, { Name = e(Text, { LayoutOrder = 1, Size = UDim2.fromScale(0.2, 0), Text = "Name", tag = "auto-y content-muted text-align-x-left text-title-medium", }), Control = e(Text, { LayoutOrder = 2, Text = "Control", tag = "auto-y content-muted fill text-align-x-left text-title-medium", }), }), Divider = e(Divider, { LayoutOrder = 2, }), }), Controls = e(React.Fragment, nil, controlElements), }), }), } ) end return React.memo(StoryControls)
1,814
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/StoryControls.story.luau
local React = require("@pkg/React") local StoryControls = require("@root/Storybook/StoryControls") return { summary = "Panel for configuring the controls of a story", story = function() return React.createElement(StoryControls, { controls = { foo = "bar", checkbox = false, number = 10, dropdown = { "Option 1", "Option 2", "Option 3", }, onlyTwentyCharacters = "OnlyTwentyCharacters", badControlType = function() end, }, modifiedControls = {}, setControl = function() end, }) end, }
149
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/StoryError.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local CodeBlock = require("@root/Common/CodeBlock") local useTokens = Foundation.Hooks.useTokens export type Props = { LayoutOrder: number?, errorMessage: string, } local function StoryError(props: Props) local tokens = useTokens() return React.createElement(Foundation.ScrollView, { LayoutOrder = props.LayoutOrder, scroll = { ScrollingDirection = Enum.ScrollingDirection.Y, AutomaticCanvasSize = Enum.AutomaticSize.Y, CanvasSize = UDim2.new(1, 0), }, layout = { FillDirection = Enum.FillDirection.Vertical, }, tag = "size-full padding-small gap-medium", }, { CodeBlock = React.createElement(CodeBlock, { source = props.errorMessage, sourceColor = tokens.Color.ActionAlert.Foreground.Color3, }), }) end return StoryError
208
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/StoryError.story.luau
local React = require("@pkg/React") local StoryError = require("@root/Storybook/StoryError") return { summary = "Component for displaying error messages to the user", story = function() local _, result = xpcall(function() error("Oops!") end, debug.traceback) return React.createElement(StoryError, { errorMessage = result, }) end, }
86
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/StoryMeta.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local Storyteller = require("@pkg/Storyteller") local nextLayoutOrder = require("@root/Common/nextLayoutOrder") local MAX_SUMMARY_SIZE = 600 local e = React.createElement type LoadedStory = Storyteller.LoadedStory<unknown> export type Props = { story: LoadedStory, layoutOrder: number?, } local function StoryMeta(props: Props) return e(Foundation.View, { tag = "size-full-0 auto-y col gap-medium", LayoutOrder = props.layoutOrder, }, { Title = e(Foundation.Text, { tag = "auto-xy text-heading-large", Text = props.story.name, LayoutOrder = nextLayoutOrder(), }), Summary = props.story.summary and e(Foundation.Text, { tag = "auto-xy text-body-medium text-wrap", LayoutOrder = nextLayoutOrder(), Text = props.story.summary, sizeConstraint = { MaxSize = Vector2.new(MAX_SUMMARY_SIZE, math.huge), }, }), }) end return StoryMeta
252
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/StoryMeta.story.luau
local React = require("@pkg/React") local Storyteller = require("@pkg/Storyteller") local StoryMeta = require("./StoryMeta") return { story = function() local storybooks = Storyteller.useStorybooks(game) local story, setStory = React.useState(nil :: Storyteller.LoadedStory<any>?) React.useEffect(function() local storybook = storybooks.available[1] if storybook then local storyModule = Storyteller.findStoryModulesForStorybook(storybook)[1] if storyModule then setStory(Storyteller.loadStoryModule(storyModule, storybook)) end end end, { storybooks.available }) if not story then return end return React.createElement(StoryMeta, { story = story, }) end, }
185
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/StoryPreview.luau
local CoreGui = game:GetService("CoreGui") local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local ReactRoblox = require("@pkg/ReactRoblox") local Storyteller = require("@pkg/Storyteller") local StoryActionsContext = require("@root/Storybook/StoryActionsContext") local StoryError = require("@root/Storybook/StoryError") local e = React.createElement local useState = React.useState local useEffect = React.useEffect type LoadedStory = Storyteller.LoadedStory<unknown> export type Props = { LayoutOrder: number?, story: LoadedStory, controls: Storyteller.StoryControls, extraProps: Storyteller.StoryControls, -- TODO: Change to ExtraStoryProps } local function StoryPreview(props: Props): React.Node local storyActions = StoryActionsContext.useStoryActions() local err: string?, setErr = useState(nil :: string?) useEffect(function() setErr(nil) end, { props.story }) if err then return e(StoryError, { LayoutOrder = props.LayoutOrder, errorMessage = err, }) end if storyActions.isMountedInViewport then return ReactRoblox.createPortal({ Story = e("ScreenGui", { ZIndexBehavior = Enum.ZIndexBehavior.Sibling, ref = storyActions.storyContainerRef, }, { StoryContainer = e(Storyteller.StoryContainer, { story = props.story, controls = props.controls, extraProps = props.extraProps, onError = setErr, }), }), }, CoreGui) end return e(Foundation.ScrollView, { tag = "size-full", scroll = { ScrollingDirection = Enum.ScrollingDirection.XY, AutomaticCanvasSize = Enum.AutomaticSize.XY, CanvasSize = UDim2.new(0, 0), }, layout = { FillDirection = Enum.FillDirection.Vertical, }, LayoutOrder = props.LayoutOrder, ref = storyActions.storyContainerRef, }, { Scale = e("UIScale", { Scale = 1 + storyActions.zoom.value, }), StoryContainer = e(Storyteller.StoryContainer, { story = props.story, controls = props.controls, extraProps = props.extraProps, onError = setErr, }), }) end return StoryPreview
543
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/StoryView.luau
local Foundation = require("@rbxpkg/Foundation") local LuauPolyfill = require("@pkg/LuauPolyfill") local React = require("@pkg/React") local ReactCharm = require("@pkg/ReactCharm") local Storyteller = require("@pkg/Storyteller") local PluginStore = require("@root/Plugin/PluginStore") local StoryControls = require("@root/Storybook/StoryControls") local StoryError = require("@root/Storybook/StoryError") local StoryPreview = require("@root/Storybook/StoryPreview") local useThemeName = require("@root/Common/useThemeName") local Divider = Foundation.Divider local Text = Foundation.Text local View = Foundation.View local Object = LuauPolyfill.Object local e = React.createElement local useCallback = React.useCallback local useEffect = React.useEffect local useMemo = React.useMemo local useState = React.useState local useSignalState = ReactCharm.useSignalState local useStory = Storyteller.useStory type LoadedStorybook = Storyteller.LoadedStorybook type StoryViewProps = { storyModule: ModuleScript, storybook: LoadedStorybook, } local function StoryView(props: StoryViewProps) local story, storyError = useStory(props.storyModule, props.storybook) local theme = useThemeName() local pluginStore = useSignalState(PluginStore.get) local plugin = useSignalState(pluginStore.getPlugin) local modifiedControls, setModifiedControls = useState({}) local controls = useMemo(function() local newControls = {} if story ~= nil and story.controls ~= nil then for key, value in story.controls do if modifiedControls[key] ~= nil and typeof(value) ~= "table" then newControls[key] = modifiedControls[key] else newControls[key] = value end end end return newControls end, { story, modifiedControls } :: { any }) local extraProps: Storyteller.StoryProps = useMemo(function() return { theme = theme :: useThemeName.ThemeName, locale = "en-us", plugin = plugin, } end, { theme, plugin } :: { unknown }) local setControl = useCallback(function(key: string, value: any) setModifiedControls(function(currentValue) return Object.assign({}, currentValue, { [key] = value, }) end) end, {}) useEffect(function() setModifiedControls({}) end, { story }) return e(View, { tag = "size-full bg-surface-200", }, { Error = storyError ~= nil and e(StoryError, { errorMessage = storyError, }), Story = story ~= nil and e(View, { tag = "col size-full", }, { Info = e(View, { LayoutOrder = 1, tag = "auto-y col gap-small padding-large size-full-0", }, { Title = e(Text, { LayoutOrder = 1, Text = story.name, tag = { -- NOTE (Paul): Super nitpick-y, but keeping all this on -- one line made for some really weird formatting that I -- couldn't accept. ["auto-y content-emphasis size-full-0"] = true, ["text-align-x-left text-align-y-top text-heading-large text-wrap"] = true, }, }), Summary = story.summary ~= nil and e(Text, { LayoutOrder = 2, Text = story.summary, sizeConstraint = { MaxSize = Vector2.new(600, math.huge) }, tag = "auto-y size-full-0 text-align-x-left text-align-y-top text-body-medium text-wrap", }), }), Divider = e(Divider, { LayoutOrder = 2, }), Preview = e(View, { LayoutOrder = 3, tag = "padding-large shrink size-full", }, { StoryPreview = React.createElement(StoryPreview, { story = story, controls = controls, extraProps = extraProps, }), }), Controls = next(controls) ~= nil and e(StoryControls, { LayoutOrder = 4, controls = controls, modifiedControls = modifiedControls, setControl = setControl, }), }), }) end return React.memo(StoryView)
974
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/StoryViewNavbar.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local ReactCharm = require("@pkg/ReactCharm") local Sift = require("@pkg/Sift") local UserSettingsStore = require("@root/UserSettings/UserSettingsStore") local nextLayoutOrder = require("@root/Common/nextLayoutOrder") local e = React.createElement local noop = function() end local useSignalState = ReactCharm.useSignalState local useCallback = React.useCallback type Props = { layoutOrder: number?, onPreviewInViewport: (() -> ())?, onZoomIn: (() -> ())?, onZoomOut: (() -> ())?, onViewCode: (() -> ())?, onExplorer: (() -> ())?, } local function StoryViewNavbar(props: Props) local userSettingsStore = useSignalState(UserSettingsStore.get) local userSettings = useSignalState(userSettingsStore.getStorage) local onThemeChanged = useCallback(function(itemId: string | number) userSettingsStore.setStorage(function(prev) return Sift.Dictionary.join(prev, { theme = itemId, }) end) end, { userSettingsStore.setStorage }) return e(Foundation.View, { tag = "size-full-0 auto-y row gap-small align-y-center", LayoutOrder = props.layoutOrder, }, { Zoom = e(Foundation.View, { tag = "auto-xy row", LayoutOrder = nextLayoutOrder(), }, { Magnify = e(Foundation.IconButton, { icon = Foundation.Enums.IconName.MagnifyingGlassPlus, onActivated = props.onZoomIn or noop, LayoutOrder = nextLayoutOrder(), }), Minify = e(Foundation.IconButton, { icon = Foundation.Enums.IconName.MagnifyingGlassMinus, onActivated = props.onZoomOut or noop, LayoutOrder = nextLayoutOrder(), }), }), -- Need to wrap the divider to constrain its height. Without this -- the divider will expand to the full height of the viewport VerticalDivider = e(Foundation.View, { tag = "size-0-800 auto-x", LayoutOrder = nextLayoutOrder(), }, { Divider = e(Foundation.Divider, { orientation = Foundation.Enums.DividerOrientation.Vertical, }), }), Explorer = e(Foundation.Button, { text = "Explorer", size = Foundation.Enums.ButtonSize.Small, onActivated = props.onExplorer or noop, LayoutOrder = nextLayoutOrder(), }), ViewCode = e(Foundation.Button, { text = "View Code", size = Foundation.Enums.ButtonSize.Small, onActivated = props.onViewCode or noop, LayoutOrder = nextLayoutOrder(), }), PreviewInViewport = e(Foundation.Button, { text = "Preview in Viewport", size = Foundation.Enums.ButtonSize.Small, onActivated = props.onPreviewInViewport or noop, LayoutOrder = nextLayoutOrder(), }), ThemeSelection = e(Foundation.Dropdown.Root, { size = Foundation.Enums.InputSize.Small, label = "", onItemChanged = onThemeChanged, width = UDim.new(0, 150), value = userSettings.theme, items = { { id = "system", text = "System", }, { id = "dark", text = "Dark", }, { id = "light", text = "Light", }, }, LayoutOrder = nextLayoutOrder(), }), }) end return StoryViewNavbar
793
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/StorybookError.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local Storyteller = require("@pkg/Storyteller") local CodeBlock = require("@root/Common/CodeBlock") local nextLayoutOrder = require("@root/Common/nextLayoutOrder") local useTokens = Foundation.Hooks.useTokens type UnavailableStorybook = Storyteller.UnavailableStorybook export type Props = { unavailableStorybook: UnavailableStorybook, layoutOrder: number?, } local function StorybookError(props: Props) local tokens = useTokens() local storybookSource = props.unavailableStorybook.storybook.source.Source return React.createElement(Foundation.ScrollView, { tag = "size-full padding-large gap-large", scroll = { ScrollingDirection = Enum.ScrollingDirection.XY, AutomaticCanvasSize = Enum.AutomaticSize.XY, CanvasSize = UDim2.fromScale(0, 0), }, layout = { FillDirection = Enum.FillDirection.Vertical, }, LayoutOrder = props.layoutOrder, }, { MainText = React.createElement(Foundation.Text, { tag = "auto-xy text-body-medium text-align-x-left", Text = `Failed to load {props.unavailableStorybook.storybook.name}`, LayoutOrder = nextLayoutOrder(), }), Problem = React.createElement(Foundation.View, { tag = "auto-xy gap-medium col", LayoutOrder = nextLayoutOrder(), }, { Title = React.createElement(Foundation.Text, { tag = "auto-xy text-heading-medium", Text = "Error", LayoutOrder = nextLayoutOrder(), }), CodeBlock = React.createElement(CodeBlock, { source = props.unavailableStorybook.problem, sourceColor = tokens.Color.ActionAlert.Foreground.Color3, layoutOrder = nextLayoutOrder(), }), }), StorybookSource = React.createElement(Foundation.View, { tag = "auto-xy gap-medium col", LayoutOrder = nextLayoutOrder(), }, { Title = React.createElement(Foundation.Text, { tag = "auto-xy text-heading-medium", Text = "Storybook Source", LayoutOrder = nextLayoutOrder(), }), CodeBlock = React.createElement(CodeBlock, { source = storybookSource, layoutOrder = nextLayoutOrder(), }), }), }) end return StorybookError
530
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/StorybookError.story.luau
local React = require("@pkg/React") local Storyteller = require("@pkg/Storyteller") local StorybookError = require("@root/Storybook/StorybookError") type UnavailableStorybook = Storyteller.UnavailableStorybook return { summary = "Component for displaying error messages to the user", story = function() local storybookModule = script.Parent.Parent["init.storybook"] local unavailableStorybook: UnavailableStorybook = { problem = "Something went wrong!", storybook = { name = storybookModule.Name, source = storybookModule, loader = {} :: any, storyRoots = {}, }, } return React.createElement(StorybookError, { unavailableStorybook = unavailableStorybook, }) end, }
175
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/StorybookTreeView.luau
local React = require("@pkg/React") local ReactCharm = require("@pkg/ReactCharm") local Sift = require("@pkg/Sift") local Storyteller = require("@pkg/Storyteller") local TreeView = require("@root/TreeView") local PinnedInstanceStore = require("@root/Storybook/PinnedInstanceStore") local createTreeNodeForStoryModule = require("@root/Storybook/createTreeNodeForStoryModule") local createTreeNodesForStorybook = require("@root/Storybook/createTreeNodesForStorybook") local useLastOpenedStory = require("@root/Storybook/useLastOpenedStory") local usePrevious = require("@root/Common/usePrevious") type TreeNodeStore = TreeView.TreeNodeStore type LoadedStorybook = Storyteller.LoadedStorybook type UnavailableStorybook = Storyteller.UnavailableStorybook type LoadedStory<T> = Storyteller.LoadedStory<T> local useCallback = React.useCallback local useEffect = React.useEffect local useMemo = React.useMemo local useRef = React.useRef local useSignalState = ReactCharm.useSignalState local useStorybooks = Storyteller.useStorybooks local useOrphanedStoryModules = Storyteller.useOrphanedStoryModules export type Props = { searchTerm: string?, onStoryChanged: ((storyModule: ModuleScript?, storybook: LoadedStorybook?) -> ())?, onShowErrorPage: ((unavailableStorybook: UnavailableStorybook) -> ())?, layoutOrder: number?, } local function StorybookTreeView(props: Props) local storybookByNodeId = useRef({} :: { [string]: LoadedStorybook }) local unavailableStorybookByNodeId = useRef({} :: { [string]: UnavailableStorybook }) local lastOpenedStory, setLastOpenedStory = useLastOpenedStory() local storybooks = useStorybooks() local orphanedStoryModules = useOrphanedStoryModules() local nodesByInstance = useRef({} :: { [Instance]: TreeNodeStore }) local pinnedInstanceStore = useSignalState(PinnedInstanceStore.get) local rootNode = useMemo(function() local node = TreeView.createTreeNodeStore() node.setName("<root>") return node end, {}) local pinned = useMemo(function() local node = TreeView.createTreeNodeStore() node.setName("Pinned") node.setIcon(TreeView.TreeNodeIcon.Pin) node.setIsExpanded(true) node.setIsVisible(false) node.parentTo(rootNode) return node end, { rootNode }) local unavailableStorybooks = useMemo(function() local node = TreeView.createTreeNodeStore() node.setName("Unavailable Storybooks") node.setIcon(TreeView.TreeNodeIcon.Folder) node.setIsVisible(false) node.parentTo(rootNode) return node end, { rootNode }) local unknownStories = useMemo(function() local node = TreeView.createTreeNodeStore() node.setName("Unknown Stories") node.setIcon(TreeView.TreeNodeIcon.Folder) node.setIsVisible(false) node.parentTo(rootNode) return node end, { rootNode }) local pinnedChildren = useSignalState(pinned.getChildren) local pinnedNodes = useSignalState(rootNode.getPinnedDescendants) local prevPinnedNodes = usePrevious(pinnedNodes) local selectedNode = useSignalState(rootNode.getSelectedDescendants)[1] local prevSelectedNode: TreeNodeStore? = usePrevious(selectedNode) local filter = useCallback(function(node: TreeNodeStore) if not props.searchTerm or props.searchTerm == "" then return false end return node.getName():lower():match(props.searchTerm:lower()) == nil end, { props.searchTerm }) -- There can be pinned paths that were never apart of the current DataModel, -- so only add the "Pinned" root if there are children to show useEffect(function() pinned.setIsVisible(#pinnedChildren > 0) end, { pinnedChildren } :: { unknown }) -- This handles automatically moving a node under the Pinned node once the -- node's instance becomes pinned useEffect(function() if pinnedNodes ~= prevPinnedNodes then -- Put any previously pinned nodes back to the root if prevPinnedNodes then for _, node in prevPinnedNodes do if not node.getIsPinned() then node.parentTo(rootNode) end end end for _, node in pinnedNodes do node.parentTo(pinned) end end end, { pinnedNodes, prevPinnedNodes, pinned, rootNode } :: { unknown }) -- Convert available storybooks into nodes useEffect(function() for _, storybook in storybooks.available do if nodesByInstance.current[storybook.source] then continue end local node = createTreeNodesForStorybook(storybook :: any) nodesByInstance.current[storybook.source] = node storybookByNodeId.current[node.id] = storybook :: any if pinnedInstanceStore.isPinned(storybook.source) then node.setIsPinned(true) node.parentTo(pinned) else node.parentTo(rootNode) end end end, { storybooks.available, pinnedInstanceStore.isPinned, pinned, rootNode } :: { unknown }) -- Convert unavailable storybooks into nodes useEffect(function() unavailableStorybooks.setIsVisible(#storybooks.unavailable > 0) for _, unavailableStorybook in storybooks.unavailable do local source = unavailableStorybook.storybook.source if nodesByInstance.current[source] then continue end local node = TreeView.createTreeNodeStore() node.setName(unavailableStorybook.storybook.name) node.setIcon(TreeView.TreeNodeIcon.Alert) node.parentTo(unavailableStorybooks) nodesByInstance.current[source] = node unavailableStorybookByNodeId.current[node.id] = unavailableStorybook end end, { storybooks.unavailable, unavailableStorybooks }) -- Convert orphaned stories into nodes useEffect(function() unknownStories.setIsVisible(#orphanedStoryModules > 0) for _, orphan in orphanedStoryModules do if nodesByInstance.current[orphan] then continue end local node = createTreeNodeForStoryModule(orphan) node.parentTo(unknownStories) nodesByInstance.current[orphan] = node end end, { orphanedStoryModules, unknownStories } :: { unknown }) -- Handle the removal of any nodes when instances get removed useEffect(function() local instances: { Instance } = Sift.List.join( Sift.List.map(storybooks.available, function(storybook) return storybook.source end), Sift.List.map(storybooks.unavailable, function(unavailableStorybook) return unavailableStorybook.storybook.source end), orphanedStoryModules ) for instance, node in nodesByInstance.current do if not table.find(instances, instance) then node.parentTo(nil) nodesByInstance.current[instance] = nil end end end, { storybooks.available, storybooks.unavailable, orphanedStoryModules } :: { unknown }) -- Reopening the story from the previous session local wasLastStoryOpened = useRef(false) local descendants = useSignalState(rootNode.getDescendants) useEffect( function() if wasLastStoryOpened.current then return end if lastOpenedStory then local node = rootNode.findFirstDescendant(function(descendant) return descendant.getInstance() == lastOpenedStory end) if node then wasLastStoryOpened.current = true node.activate() node.expandUp() end end end, { lastOpenedStory, rootNode, -- This value isn't used in the effect body but is necessary so that -- the effect will run again if the last opened story has not but -- found yet descendants, } :: { unknown } ) useEffect( function() if selectedNode ~= prevSelectedNode then if props.onStoryChanged then if selectedNode then local icon = selectedNode.getIcon() local instance = selectedNode.getInstance() if icon == TreeView.TreeNodeIcon.Story and instance and instance:IsA("ModuleScript") then local storybookNode = selectedNode.findFirstAncestor(function(ancestor) return ancestor.getIcon() == TreeView.TreeNodeIcon.Storybook end) local storybook = if storybookNode then storybookByNodeId.current[storybookNode.id] else nil props.onStoryChanged(instance, storybook) setLastOpenedStory(instance) end else props.onStoryChanged(nil, nil) end end if props.onShowErrorPage then if selectedNode and selectedNode.getIcon() == TreeView.TreeNodeIcon.Alert then local unavailableStorybook = unavailableStorybookByNodeId.current[selectedNode.id] if unavailableStorybook then props.onShowErrorPage(unavailableStorybook) end end end end end, { props.onShowErrorPage, props.onStoryChanged, selectedNode, prevSelectedNode, setLastOpenedStory, } :: { unknown } ) return React.createElement(TreeView.TreeView, { root = rootNode, filter = filter, layoutOrder = props.layoutOrder, }) end return StorybookTreeView
2,043
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/StorybookTreeView.story.luau
local React = require("@pkg/React") local Storyteller = require("@pkg/Storyteller") local StorybookTreeView = require("./StorybookTreeView") return { story = function() local storybooks = Storyteller.useStorybooks(game) return React.createElement("Frame", { Size = UDim2.fromOffset(300, 0), AutomaticSize = Enum.AutomaticSize.Y, BackgroundTransparency = 1, }, { StorybookTreeView = React.createElement(StorybookTreeView, { storybooks = storybooks, onStoryChanged = function(storyModule) if storyModule then print("selected", storyModule:GetFullName()) end end, }), }) end, }
163
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/createLoadedStorybook.luau
local ModuleLoader = require("@pkg/ModuleLoader") local Storyteller = require("@pkg/Storyteller") type LoadedStorybook = Storyteller.LoadedStorybook local function createLoadedStorybook(): LoadedStorybook return { name = "Storybook", loader = ModuleLoader.new(), source = Instance.new("ModuleScript"), storyRoots = {}, } end return createLoadedStorybook
91
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/createTreeNodeForStoryModule.luau
local TreeView = require("@root/TreeView") type TreeNodeStore = TreeView.TreeNodeStore local function createTreeNodeForStoryModule(storyModule: ModuleScript): TreeNodeStore local name = storyModule.Name:gsub("%.story", "") local node = TreeView.createTreeNodeStore() node.setName(name) node.setIcon(TreeView.TreeNodeIcon.Story) node.setInstance(storyModule) return node end return createTreeNodeForStoryModule
91
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/createTreeNodesForStorybook.luau
local Storyteller = require("@pkg/Storyteller") local TreeView = require("@root/TreeView") local createTreeNodeForStoryModule = require("@root/Storybook/createTreeNodeForStoryModule") local getAncestors = require("@root/Common/getAncestors") type TreeNodeStore = TreeView.TreeNodeStore type LoadedStorybook = Storyteller.LoadedStorybook type LoadedStory<any> = Storyteller.LoadedStory<any> local function createTreeNodesForStorybook(storybook: LoadedStorybook): TreeNodeStore local root = TreeView.createTreeNodeStore() root.setName(if storybook.name then storybook.name else "Unnamed Storybook") root.setIcon(TreeView.TreeNodeIcon.Storybook) root.setInstance(storybook.source) for _, storyModule in Storyteller.findStoryModulesForStorybook(storybook) do local currentNode = createTreeNodeForStoryModule(storyModule) for _, ancestor in getAncestors(storyModule) do -- This is probably expensive to be doing so frequently but it seems -- to be fine for now. May hit a point where this bit in particular -- becomes a bottleneck though local existingNode = root.findFirstDescendant(function(descendant) return descendant.getInstance() == ancestor end) if existingNode then currentNode.parentTo(existingNode) break end if table.find(storybook.storyRoots, ancestor) then currentNode.parentTo(root) break end local node = TreeView.createTreeNodeStore() node.setName(ancestor.Name) node.setIcon(TreeView.TreeNodeIcon.Folder) node.setInstance(ancestor) currentNode.parentTo(node) currentNode = node end end return root end return createTreeNodesForStorybook
387
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/useLastOpenedStory.luau
local React = require("@pkg/React") local ReactCharm = require("@pkg/ReactCharm") local Sift = require("@pkg/Sift") local LocalStorageStore = require("@root/Plugin/LocalStorageStore") local UserSettingsStore = require("@root/UserSettings/UserSettingsStore") local getInstanceFromPath = require("@root/Common/getInstanceFromPath") local getInstancePath = require("@root/Common/getInstancePath") local useCallback = React.useCallback local useMemo = React.useMemo local useSignalState = ReactCharm.useSignalState local function useLastOpenedStory(): (ModuleScript?, (storyModule: ModuleScript?) -> ()) local localStorageStore = useSignalState(LocalStorageStore.get) local localStorage = useSignalState(localStorageStore.getStorage) local userSettingsStore = useSignalState(UserSettingsStore.get) local userSettings = useSignalState(userSettingsStore.getStorage) local setLastOpenedStory = useCallback(function(storyModule: ModuleScript?) localStorageStore.setStorage(function(prev) return Sift.Dictionary.join(prev, { lastOpenedStoryPath = if storyModule then getInstancePath(storyModule) else nil, }) end) end, { localStorageStore }) local lastOpenedStory = useMemo(function(): ModuleScript? local rememberLastOpenedStory = userSettings.rememberLastOpenedStory if not rememberLastOpenedStory then return nil end local lastOpenedStoryPath = localStorage.lastOpenedStoryPath if lastOpenedStoryPath then local instance = getInstanceFromPath(lastOpenedStoryPath) if instance and instance:IsA("ModuleScript") then return instance end end return nil end, { userSettings, localStorage } :: { unknown }) return lastOpenedStory, setLastOpenedStory end return useLastOpenedStory
377
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Storybook/useSortedControls.luau
local React = require("@pkg/React") local Sift = require("@pkg/Sift") local Array = Sift.Array local Dictionary = Sift.Dictionary local useMemo = React.useMemo export type Control = { key: string, value: any, } local function filterControls(controlA: Control, controlB: Control) return controlA.key < controlB.key end local function useSortedControls(controls: { [string]: any }): { Control } return useMemo(function() return Array.sort( Array.map(Dictionary.entries(controls), function(entry) return { key = entry[1], value = entry[2] } end), filterControls ) end, { controls }) end return useSortedControls
154
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Telemetry/TelemetryOptOutDialog.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local ReactCharm = require("@pkg/ReactCharm") local Sift = require("@pkg/Sift") local LocalStorageStore = require("@root/Plugin/LocalStorageStore") local UserSettingsStore = require("@root/UserSettings/UserSettingsStore") local fireEventAsync = require("@root/Telemetry/fireEventAsync") local nextLayoutOrder = require("@root/Common/nextLayoutOrder") local useSignalState = ReactCharm.useSignalState local useCallback = React.useCallback local useState = React.useState local function TelemetryOptOutDialog(): React.Node? local userSettingsStore = useSignalState(UserSettingsStore.get) local localStorageStore = useSignalState(LocalStorageStore.get) local storage = useSignalState(localStorageStore.getStorage) local isStorageLoading = useSignalState(localStorageStore.getIsLoading) local isOptedIn, setIsOptedIn = useState(true) local onClose = useCallback(function() localStorageStore.setStorage(function(prev) return Sift.Dictionary.join(prev, { wasUserPromptedForTelemetry = true, }) end) userSettingsStore.setStorage(function(prev) return Sift.Dictionary.join(prev, { collectAnonymousUsageData = isOptedIn, }) end) task.spawn(function() if isOptedIn then fireEventAsync({ eventName = "TelemetryOptedIn", }) else fireEventAsync({ eventName = "TelemetryOptedOut", }) end end) end, { localStorageStore.setStorage, userSettingsStore.setStorage, isOptedIn } :: { unknown }) -- We check `isStorageLoading` to prevent the dialog from briefly flashing -- on screen if isStorageLoading or storage.wasUserPromptedForTelemetry then return nil end return React.createElement(Foundation.Dialog.Root, { disablePortal = false, hasBackdrop = true, onClose = onClose, onPressedOutside = onClose, }, { Title = React.createElement(Foundation.Dialog.Title, { text = "Help us improve Flipbook", }), Content = React.createElement(Foundation.Dialog.Content, { LayoutOrder = nextLayoutOrder(), }, { Wrapper = React.createElement(Foundation.View, { tag = "auto-xy col gap-large", }, { MainParagraph = React.createElement(Foundation.Dialog.Text, { tag = "auto-xy text-wrap text-body-medium", Text = "Flipbook would like to send anonymized usage data to help us improve the quality of the plugin.", LayoutOrder = nextLayoutOrder(), }), WhereToOptOut = React.createElement(Foundation.Dialog.Text, { tag = "auto-xy text-wrap text-body-medium", Text = "You can opt out at any time in the settings.", LayoutOrder = nextLayoutOrder(), }), Checkbox = React.createElement(Foundation.Checkbox, { label = "Help improve Flipbook by sending anonymous usage data", isChecked = isOptedIn, onActivated = setIsOptedIn, LayoutOrder = nextLayoutOrder(), }), }), }), Actions = React.createElement(Foundation.Dialog.Actions, { actions = { { text = "Done", variant = Foundation.Enums.ButtonVariant.Emphasis, onActivated = onClose, }, }, LayoutOrder = nextLayoutOrder(), }), }) end return TelemetryOptOutDialog
771
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Telemetry/TelemetryOptOutDialog.story.luau
local React = require("@pkg/React") local TelemetryOptOutDialog = require("./TelemetryOptOutDialog") return { story = function(props) return React.createElement(TelemetryOptOutDialog) end, }
46
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Telemetry/fireEventAsync.luau
local UserSettingsStore = require("@root/UserSettings/UserSettingsStore") local getAnonymizedUserId = require("@root/Telemetry/getAnonymizedUserId") local logger = require("@root/logger") local requestAsync = require("@root/Http/requestAsync") local types = require("@root/Telemetry/types") type TelemetryEvent = types.TelemetryEvent local function fireEventAsync(event: TelemetryEvent) local userSettingsStore = UserSettingsStore.get() local userSettings = userSettingsStore.getStorage() if not userSettings.collectAnonymousUsageData then return end local body = { eventName = event.eventName, properties = (event :: any).properties, anonymizedUserId = getAnonymizedUserId(), buildVersion = _G.BUILD_VERSION, buildChannel = _G.BUILD_CHANNEL, buildHash = _G.BUILD_HASH, } logger:Info(`firing event {event.eventName}`) return requestAsync(`{_G.BASE_URL}/telemetry`, { method = "POST", body = body, }) end return fireEventAsync
231
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Telemetry/getAnonymizedUserId.luau
local sha256 = require("@pkg/sha256") local getLocalUserId = require("@root/Telemetry/getLocalUserId") --[[ The events we send to the backend need some persistent identifier so we can group them by the user they come from. However, we do not collect PII so we first need to anonymize the UserId before sending it off. That's what this function is for. ]] local function getAnonymizedUserId(): string local plainUserId = getLocalUserId() local hash = sha256(tostring(plainUserId)) return hash end return getAnonymizedUserId
126
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Telemetry/getLocalUserId.luau
local Players = game:GetService("Players") local RunService = game:GetService("RunService") local StudioService = if RunService:IsStudio() then game:GetService("StudioService") else nil local function getLocalUserId(): number if StudioService then return StudioService:GetUserId() end if Players.LocalPlayer then return Players.LocalPlayer.UserId end return -1 end return getLocalUserId
89
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Telemetry/types.luau
-- The events in this file mirror the TelementryEventName enum in the backend. -- The backend must be updated first before adding new events. export type AppOpened = { eventName: "AppOpened", } export type AppClosed = { eventName: "AppClosed", } export type NodePinned = { eventName: "NodePinned", } export type NodeUnpinned = { eventName: "NodeUnpinned", } export type PageChanged = { eventName: "PageChanged", properties: { page: string, }, } export type StoryOpened = { eventName: "StoryOpened", } export type StoryClosed = { eventName: "StoryClosed", } export type TelemetryOptedIn = { eventName: "TelemetryOptedIn", } export type TelemetryOptedOut = { eventName: "TelemetryOptedOut", } export type FeedbackDialogOpened = { eventName: "FeedbackDialogOpened", } export type FeedbackSubmitted = { eventName: "FeedbackSubmitted", } export type FeedbackDiscarded = { eventName: "FeedbackDiscarded", } export type TelemetryEvent = AppOpened | AppClosed | NodePinned | NodeUnpinned | PageChanged | StoryClosed | StoryOpened | TelemetryOptedIn | TelemetryOptedOut | FeedbackDialogOpened | FeedbackSubmitted | FeedbackDiscarded return nil
308
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/TreeView/TreeNode.luau
local Selection = game:GetService("Selection") local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local ReactCharm = require("@pkg/ReactCharm") local PinnedInstanceStore = require("@root/Storybook/PinnedInstanceStore") local Types = require("@root/TreeView/types") local useTreeNodeIcon = require("@root/TreeView/useTreeNodeIcon") local Icon = Foundation.Icon local IconName = Foundation.Enums.IconName local IconSize = Foundation.Enums.IconSize local IconVariant = Foundation.Enums.IconVariant local Text = Foundation.Text local View = Foundation.View local useTokens = Foundation.Hooks.useTokens local withCommonProps = Foundation.Utility.withCommonProps local e = React.createElement local useCallback = React.useCallback local useMemo = React.useMemo local useState = React.useState local useRef = React.useRef local useSignalState = ReactCharm.useSignalState type TreeNodeStore = Types.TreeNodeStore type TreeNodeProps = { node: TreeNodeStore, onActivated: (node: TreeNodeStore) -> ()?, } & Foundation.CommonProps local function TreeNode(props: TreeNodeProps) local ancestors = useSignalState(props.node.getAncestors) local icon = useSignalState(props.node.getIcon) local instance = useSignalState(props.node.getInstance) local isExpanded = useSignalState(props.node.getIsExpanded) local isSelected = useSignalState(props.node.getIsSelected) local isVisible = useSignalState(props.node.getIsVisible) local isFiltered = useSignalState(props.node.getIsFiltered) local name = useSignalState(props.node.getName) local nodeChildren = useSignalState(props.node.getChildren) local iconName, iconStyle = useTreeNodeIcon(icon :: Types.TreeNodeIcon) local isContextMenuOpen, setIsContextMenuOpen = useState(false) local ref = useRef(nil :: GuiObject?) local tokens = useTokens() local pinnedInstanceStore = useSignalState(PinnedInstanceStore.get) local isPinned = if instance then pinnedInstanceStore.isPinned(instance) else false local children = useMemo(function() local elements: { [string]: React.ReactNode } = {} for index, childNode in nodeChildren do elements[childNode.getName()] = e(TreeNode, { LayoutOrder = index, node = childNode, onActivated = props.onActivated, }) end return elements end, { nodeChildren }) local onActivated = useCallback(function() props.node.activate() if props.onActivated ~= nil then props.onActivated(props.node) end end, { props.onActivated, props.node } :: { unknown }) local onSecondaryActivated = useCallback(function() setIsContextMenuOpen(true) end, {}) local onTogglePin = useCallback( function() if instance then if isPinned then pinnedInstanceStore.unpin(instance) props.node.setIsPinned(false) else pinnedInstanceStore.pin(instance) props.node.setIsPinned(true) end end end, { instance, isPinned, pinnedInstanceStore.pin, pinnedInstanceStore.unpin, props.node.setIsPinned, } :: { unknown } ) local contextMenuItems = useMemo(function() local items: { Foundation.MenuItem } = {} if icon == Types.TreeNodeIcon.Storybook then table.insert(items, { id = "pin", text = if isPinned then "Unpin" else "Pin", onActivated = function() onTogglePin() setIsContextMenuOpen(false) end, }) end if instance then table.insert(items, { id = "select-in-explorer", text = "Select in Explorer", onActivated = function() Selection:Set({ instance }) setIsContextMenuOpen(false) end, }) end if #nodeChildren > 0 then table.insert(items, { id = "expand-all", text = "Expand all", onActivated = function() props.node.expandDown() setIsContextMenuOpen(false) end, }) table.insert(items, { id = "collapse-all", text = "Collapse all", onActivated = function() props.node.collapseDown() setIsContextMenuOpen(false) end, }) end return items end, { isPinned, icon, instance, nodeChildren, props.node } :: { unknown }) if isVisible == false or isFiltered == true then return nil end return e( View, withCommonProps(props, { tag = "auto-y col size-full-0", }), { Node = e(View, { LayoutOrder = 1, backgroundStyle = if isSelected then tokens.Color.ActionEmphasis.Background else nil, onActivated = onActivated, onSecondaryActivated = onSecondaryActivated, padding = { left = UDim.new(0, tokens.Padding.Medium * #ancestors), }, tag = "align-y-center auto-y gap-medium padding-right-medium padding-y-medium row size-full-0", ref = ref, }, { Icon = e(Icon, { LayoutOrder = 1, name = iconName, size = IconSize.Small, style = iconStyle, variant = if isSelected then IconVariant.Filled else nil, }), Title = e(Text, { LayoutOrder = 2, Text = name, tag = { ["auto-y shrink size-full-0 text-align-x-left text-label-medium text-truncate-end"] = true, ["content-emphasis"] = isSelected, }, }), Arrow = #nodeChildren > 0 and e(Icon, { LayoutOrder = 3, name = if isExpanded then IconName.ChevronSmallUp else IconName.ChevronSmallDown, size = IconSize.XSmall, }), }), ContextMenu = if isContextMenuOpen and #contextMenuItems > 0 then React.createElement(Foundation.Menu, { isOpen = true, size = Foundation.Enums.InputSize.Medium, items = contextMenuItems, onPressedOutside = function() setIsContextMenuOpen(false) end, anchorRef = ref, }) else nil, Children = isExpanded and e(View, { LayoutOrder = 2, tag = "auto-xy col", }, children), } ) end return React.memo(TreeNode)
1,405
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/TreeView/TreeView.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local ReactCharm = require("@pkg/ReactCharm") local TreeNode = require("@root/TreeView/TreeNode") local types = require("@root/TreeView/types") local useTreeNodeFilter = require("@root/TreeView/useTreeNodeFilter") local useSignalState = ReactCharm.useSignalState local useEffect = React.useEffect type TreeNodeStore = types.TreeNodeStore type TreeNodeFilter = types.TreeNodeFilter export type Props = { root: TreeNodeStore, filter: TreeNodeFilter?, layoutOrder: number?, } local function TreeView(props: Props) local rootNodeChildren = useSignalState(props.root.getChildren) useTreeNodeFilter(props.root, props.filter) useEffect(function() props.root.setSortOrder(function(a: TreeNodeStore, b: TreeNodeStore) if a.getIcon() ~= b.getIcon() then -- Sort by type return a.getIcon() < b.getIcon() else -- Sort alphabetically return a.getName():lower() < b.getName():lower() end end) end, { props.root }) local children: { [string]: React.Node } = {} for index, node in rootNodeChildren do children[node.id] = React.createElement(TreeNode, { node = node, LayoutOrder = index, }) end return React.createElement(Foundation.View, { tag = "auto-xy col", LayoutOrder = props.layoutOrder, }, children) end return TreeView
325
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/TreeView/TreeView.story.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local TreeView = require("@root/TreeView/TreeView") local createTreeNodeStore = require("@root/TreeView/createTreeNodeStore") local types = require("@root/TreeView/types") local useTreeNodeFilter = require("@root/TreeView/useTreeNodeFilter") local useCallback = React.useCallback local useState = React.useState type TreeNodeStore = types.TreeNodeStore local root = createTreeNodeStore() root.setName("<root>") local deepStory do local pins = createTreeNodeStore() pins.setName("Pinned Storybooks") pins.setIcon(types.TreeNodeIcon.Pin) pins.parentTo(root) local storybook = createTreeNodeStore() storybook.setName("Storybook 1") storybook.setIcon(types.TreeNodeIcon.Storybook) storybook.parentTo(root) local folder1 = createTreeNodeStore() folder1.setName("Folder 1") folder1.setIcon(types.TreeNodeIcon.Folder) folder1.parentTo(storybook) local folder2 = createTreeNodeStore() folder2.setName("Folder 2") folder2.setIcon(types.TreeNodeIcon.Folder) folder2.parentTo(folder1) local folder3 = createTreeNodeStore() folder3.setName("Folder 3") folder3.setIcon(types.TreeNodeIcon.Folder) folder3.parentTo(folder2) end do local storybook = createTreeNodeStore() storybook.setName("Storybook 2") storybook.setIcon(types.TreeNodeIcon.Storybook) storybook.parentTo(root) local folder1 = createTreeNodeStore() folder1.setName("Folder 1") folder1.setIcon(types.TreeNodeIcon.Folder) folder1.parentTo(storybook) local folder2 = createTreeNodeStore() folder2.setName("Folder 2") folder2.setIcon(types.TreeNodeIcon.Folder) folder2.parentTo(folder1) local folder3 = createTreeNodeStore() folder3.setName("Folder 3") folder3.setIcon(types.TreeNodeIcon.Folder) folder3.parentTo(folder2) deepStory = createTreeNodeStore() deepStory.setName("Deeply Nested Story") deepStory.setIcon(types.TreeNodeIcon.Story) deepStory.parentTo(folder3) end do local storybook = createTreeNodeStore() storybook.setName("Storybook 3") storybook.setIcon(types.TreeNodeIcon.Storybook) storybook.parentTo(root) local folder = createTreeNodeStore() folder.setName("Folder") folder.setIcon(types.TreeNodeIcon.Folder) folder.parentTo(storybook) local siblingStory1 = createTreeNodeStore() siblingStory1.setName("Story 1") siblingStory1.setIcon(types.TreeNodeIcon.Story) siblingStory1.parentTo(folder) local siblingStory2 = createTreeNodeStore() siblingStory2.setName("Story 2") siblingStory2.setIcon(types.TreeNodeIcon.Story) siblingStory2.parentTo(folder) local story1 = createTreeNodeStore() story1.setName("Story 1") story1.setIcon(types.TreeNodeIcon.Story) story1.parentTo(storybook) local story2 = createTreeNodeStore() story2.setName("Story 2") story2.setIcon(types.TreeNodeIcon.Story) story2.parentTo(storybook) local story3 = createTreeNodeStore() story3.setName("Story 3") story3.setIcon(types.TreeNodeIcon.Story) story3.parentTo(storybook) end do local storybook = createTreeNodeStore() storybook.setName("Storybook 4") storybook.setIcon(types.TreeNodeIcon.Storybook) storybook.parentTo(root) end return { story = function() local searchTerm: string?, setSearchTerm = useState(nil :: string?) local onExpand = useCallback(function() local node = root.findFirstDescendant(function(descendant) return descendant.id == deepStory.id end) if node then node.activate() node.expandUp() end end, {}) useTreeNodeFilter( root, useCallback(function(node: TreeNodeStore) if not searchTerm or searchTerm == "" then return false end return node.getName():lower():match(searchTerm:lower()) == nil end, { searchTerm }) ) return React.createElement(Foundation.View, { tag = "auto-y col gap-large", Size = UDim2.fromOffset(300, 0), }, { Topbar = React.createElement(Foundation.View, { tag = "size-full-0 auto-y row gap-large", LayoutOrder = 1, }, { Search = React.createElement(Foundation.TextInput, { text = "", label = "", placeholder = "Search...", size = Foundation.Enums.InputSize.Medium, width = UDim.new(1, 0), iconLeading = Foundation.Enums.IconName.MagnifyingGlass, onChanged = setSearchTerm, LayoutOrder = 1, }), ExpandToNode = React.createElement(Foundation.Button, { text = "Expand", size = Foundation.Enums.ButtonSize.Small, onActivated = onExpand, LayoutOrder = 2, }), }), TreeView = React.createElement(TreeView, { root = root, layoutOrder = 2, }), }) end, }
1,148
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/TreeView/createTreeNodeStore.luau
local HttpService = game:GetService("HttpService") local Charm = require("@pkg/Charm") local Sift = require("@pkg/Sift") local CharmTypes = require("@root/Common/CharmTypes") local types = require("@root/TreeView/types") type TreeNodeStore = types.TreeNodeStore type TreeNodeSnapshot = types.TreeNodeSnapshot type TreeNodeIcon = types.TreeNodeIcon type TreeNodeSort = types.TreeNodeSort local function createTreeNodeStore(): TreeNodeStore local id = HttpService:GenerateGUID() local getName, setName = Charm.signal("Node") local getIcon, setIcon = Charm.signal(nil :: TreeNodeIcon?) local getIsSelected, setIsSelected = Charm.signal(false) local getIsExpanded, setIsExpanded = Charm.signal(false) local getIsVisible, setIsVisible = Charm.signal(true) local getIsFiltered, setIsFiltered = Charm.signal(false) local getIsPinned, setIsPinned = Charm.signal(false) local getInstance, setInstance = Charm.signal(nil :: Instance?) local getParent, setParent = Charm.signal(nil :: TreeNodeStore?) local getUnsortedChildren, setUnsortedChildren = Charm.signal({} :: { TreeNodeStore }) local getSortOrder, setSortOrderSignal = Charm.signal(nil :: TreeNodeSort?) local self: TreeNodeStore local getChildren = Charm.computed(function() local children = table.clone(getUnsortedChildren()) local sort = getSortOrder() if sort then table.sort(children, function(a, b) return sort(a, b) end) end return children end) local getAncestors = Charm.computed(function() local ancestors: { TreeNodeStore } = {} local candidate: TreeNodeStore? = getParent() while candidate do table.insert(ancestors, candidate) candidate = candidate.getParent() end return ancestors end) local getDescendants = Charm.computed(function() local descendants: { TreeNodeStore } = {} local stack = table.clone(getUnsortedChildren()) while #stack > 0 do local candidate = table.remove(stack) if candidate then table.insert(descendants, candidate) stack = Sift.List.join(stack, candidate.getChildren()) end end return descendants end) local function setSortOrder(sort: TreeNodeSort?) setSortOrderSignal(function() -- FIXME: Need to cast to `any` here. It's suspected this is related -- to how Signals types its setter functions, where it can take -- either a value or an update function. Since we _want_ to store a -- function, that might be what's tripping it up return sort :: any end) -- Because this isn't scoped newly added descendants won't have the same -- sorting function. This is aleviated by parentTo assigning the new -- parent's sorting function to the node being moved for _, descendant in Charm.untracked(getDescendants) do descendant.setSortOrder(sort) end end local function createDescendantMatcher(predicate: (descendant: TreeNodeStore) -> boolean?): () -> { TreeNodeStore } return Charm.computed(function() local matches = {} for _, descendant in getDescendants() do local result = predicate(descendant) if result == true then table.insert(matches, descendant) elseif result == false then continue elseif result == nil then break end end return matches end) end local getRoot = Charm.computed(function() local ancestors = getAncestors() return ancestors[#ancestors] end) local getPath = Charm.computed(function() local path = getName() for _, ancestor in getAncestors() do path = `{ancestor.getName()}/{path}` end return path end) local getLeafNodes = createDescendantMatcher(function(descendant) return #descendant.getChildren() == 0 end) local getSelectedDescendants = createDescendantMatcher(function(descendant) return descendant.getIsSelected() end) local getPinnedDescendants = createDescendantMatcher(function(descendant) return descendant.getIsPinned() end) local function findFirstDescendant(predicate: (node: TreeNodeStore) -> boolean): TreeNodeStore? for _, descendant in Charm.untracked(getDescendants) do if predicate(descendant) then return descendant end end return nil end local function findFirstAncestor(predicate: (node: TreeNodeStore) -> boolean): TreeNodeStore? for _, ancestor in Charm.untracked(getAncestors) do if predicate(ancestor) then return ancestor end end return nil end local function parentTo(newParent: TreeNodeStore?) local parent = Charm.untracked(getParent) if parent ~= nil then if newParent == parent then return end parent.setChildren(function(prev) return Sift.List.filter(prev, function(otherNode) return otherNode.id ~= id end) end) end setParent(newParent) if newParent ~= nil then newParent.setChildren(function(prev) return Sift.List.join(prev, { self }) end) -- Inherit the sorting function from the new parent setSortOrder(Charm.untracked(newParent.getSortOrder)) end end local function clearChildren() for _, child in Charm.untracked(getChildren) do child.parentTo(nil) end end local function expandDown() setIsExpanded(true) for _, descendant in Charm.untracked(getDescendants) do descendant.setIsExpanded(true) end end local function expandUp() setIsExpanded(true) for _, ancestor in Charm.untracked(getAncestors) do ancestor.setIsExpanded(true) end end local function collapseDown() setIsExpanded(false) for _, descendant in Charm.untracked(getDescendants) do descendant.setIsExpanded(false) end end local function activate() if #Charm.untracked(getUnsortedChildren) > 0 then setIsExpanded(function(prev) return not prev end) else local root = Charm.untracked(getRoot) if root then for _, selection in Charm.untracked(root.getSelectedDescendants) do if selection ~= self then selection.setIsSelected(false) end end end setIsSelected(function(prev) return not prev end) end end local function snapshot(): TreeNodeSnapshot local root = { id = id, name = Charm.untracked(getName), icon = Charm.untracked(getIcon), isVisible = Charm.untracked(getIsVisible), isSelected = Charm.untracked(getIsSelected), children = {}, } for _, child in Charm.untracked(getUnsortedChildren) do table.insert(root.children, child.snapshot()) end return root end self = { id = id, -- Node properties and states getName = getName, setName = setName, getIcon = getIcon :: () -> TreeNodeIcon?, setIcon = (setIcon :: any) :: CharmTypes.Setter<TreeNodeIcon?>, getIsVisible = getIsVisible, setIsVisible = setIsVisible, getIsSelected = getIsSelected, setIsSelected = setIsSelected, activate = activate, setIsFiltered = setIsFiltered, getIsFiltered = getIsFiltered, setIsPinned = setIsPinned, getIsPinned = getIsPinned, getLeafNodes = getLeafNodes, -- Expand/Collapse collapseDown = collapseDown, expandDown = expandDown, expandUp = expandUp, getIsExpanded = getIsExpanded, setIsExpanded = setIsExpanded, -- Hierarchy getAncestors = getAncestors, getChildren = getChildren, getDescendants = getDescendants, getSelectedDescendants = getSelectedDescendants, getPinnedDescendants = getPinnedDescendants, getParent = getParent, parentTo = parentTo, clearChildren = clearChildren, setChildren = setUnsortedChildren, findFirstAncestor = findFirstAncestor, findFirstDescendant = findFirstDescendant, getSortOrder = getSortOrder, setSortOrder = setSortOrder, getPath = getPath, -- DataModel getInstance = getInstance, setInstance = setInstance, -- Other snapshot = snapshot, } return self end return createTreeNodeStore
1,859
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/TreeView/init.luau
local types = require("@self/types") export type TreeNodeStore = types.TreeNodeStore return { -- Enums TreeNodeIcon = types.TreeNodeIcon, -- Stores createTreeNodeStore = require("@self/createTreeNodeStore"), -- Components TreeView = require("@self/TreeView"), }
62
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/TreeView/types.luau
local CharmTypes = require("@root/Common/CharmTypes") local types = {} export type TreeNodeIcon = "none" | "story" | "storybook" | "folder" | "alert" | "pin" types.TreeNodeIcon = { None = "none" :: "none", Story = "story" :: "story", Storybook = "storybook" :: "storybook", Folder = "folder" :: "folder", Alert = "alert" :: "alert", Pin = "pin" :: "pin", } export type TreeNodeFilter = (node: TreeNodeStore) -> boolean export type TreeNodeSort = (a: TreeNodeStore, b: TreeNodeStore) -> boolean export type TreeNodeStore = { id: string, -- Node properties and states getName: CharmTypes.Getter<string>, setName: CharmTypes.Setter<string>, getIcon: CharmTypes.Getter<TreeNodeIcon?>, setIcon: CharmTypes.Setter<TreeNodeIcon?>, getIsSelected: CharmTypes.Getter<boolean>, setIsSelected: CharmTypes.Setter<boolean>, getIsVisible: CharmTypes.Getter<boolean>, setIsVisible: CharmTypes.Setter<boolean>, activate: () -> (), getIsFiltered: CharmTypes.Getter<boolean>, setIsFiltered: CharmTypes.Setter<boolean>, getIsPinned: CharmTypes.Getter<boolean>, setIsPinned: CharmTypes.Setter<boolean>, -- Expand/Collapse getIsExpanded: CharmTypes.Getter<boolean>, setIsExpanded: CharmTypes.Setter<boolean>, expandDown: () -> (), expandUp: () -> (), collapseDown: () -> (), -- Hierarchy getChildren: CharmTypes.Getter<{ TreeNodeStore }>, setChildren: CharmTypes.Setter<{ TreeNodeStore }>, getAncestors: CharmTypes.Getter<{ TreeNodeStore }>, getDescendants: CharmTypes.Getter<{ TreeNodeStore }>, getLeafNodes: CharmTypes.Getter<{ TreeNodeStore }>, getPath: CharmTypes.Getter<string>, getSelectedDescendants: CharmTypes.Getter<{ TreeNodeStore }>, getPinnedDescendants: CharmTypes.Getter<{ TreeNodeStore }>, getParent: CharmTypes.Getter<TreeNodeStore?>, parentTo: (newParent: TreeNodeStore?) -> (), clearChildren: () -> (), findFirstDescendant: (predicate: (node: TreeNodeStore) -> boolean) -> TreeNodeStore?, findFirstAncestor: (predicate: (node: TreeNodeStore) -> boolean) -> TreeNodeStore?, getSortOrder: CharmTypes.Getter<TreeNodeSort?>, setSortOrder: (sort: TreeNodeSort?) -> (), -- DataModel getInstance: CharmTypes.Getter<Instance?>, setInstance: CharmTypes.Setter<Instance?>, -- Other snapshot: () -> TreeNodeSnapshot, -- destroy: () -> (), } export type TreeNodeSnapshot = { id: string, name: string, icon: string?, isSelected: boolean, isVisible: boolean, instance: Instance?, children: { TreeNodeSnapshot }, } return types
605
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/TreeView/useTreeNodeFilter.luau
local React = require("@pkg/React") local ReactCharm = require("@pkg/ReactCharm") local Sift = require("@pkg/Sift") local types = require("@root/TreeView/types") local useSignalState = ReactCharm.useSignalState local useEffect = React.useEffect type TreeNodeStore = types.TreeNodeStore type TreeNodeFilter = types.TreeNodeFilter local function useTreeNodeFilter(root: TreeNodeStore, filter: TreeNodeFilter?) local leaves = useSignalState(root.getLeafNodes) useEffect(function() if filter then -- Resetting the filtered state to do it all over again for the new -- filter function root.setIsFiltered(false) for _, descendant in root.getDescendants() do descendant.setIsFiltered(false) end local included = {} for _, leaf in leaves do local includeRemainingNodes = false -- This orders the nodes starting from the leaf and then each -- parent going up the ancestry chain. This is useful so when we -- hit at least one node that shouldn't be filtered we know we -- have to keep the remaining items after that point unfiltered -- too. local nodes: { TreeNodeStore } = Sift.List.join({ leaf }, leaf.getAncestors()) for _, node in nodes do -- We've already marked this node as unfiltered, which means -- this node and all of the remaining ancestor nodes we'd be -- iterating through should also be unfiltered. So we just -- exit out here if included[node.id] then break end -- If at least one of the nodes in `nodes` shouldn't be -- filtered, then all ancestors after that point shouldn't -- be filtered either. if includeRemainingNodes then included[node.id] = true node.setIsFiltered(false) continue end if filter(node) then node.setIsFiltered(true) else included[node.id] = true node.setIsFiltered(false) includeRemainingNodes = true end end end end end, { filter, leaves } :: { unknown }) end return useTreeNodeFilter
494
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/TreeView/useTreeNodeIcon.luau
local Foundation = require("@rbxpkg/Foundation") local types = require("./types") local useTokens = Foundation.Hooks.useTokens local IconName = Foundation.Enums.IconName type TreeNodeIcon = types.TreeNodeIcon local function useTreeNodeIcon(icon: TreeNodeIcon): (string, Foundation.ColorStyle) local tokens = useTokens() if icon == types.TreeNodeIcon.Story then return IconName.DiamondSimplified, tokens.Color.Extended.Green.Green_500 elseif icon == types.TreeNodeIcon.Storybook then return IconName.SquareBooks, tokens.Color.Content.Default elseif icon == types.TreeNodeIcon.Folder then return IconName.FileBox, tokens.Color.Extended.Purple.Purple_500 elseif icon == types.TreeNodeIcon.Pin then return IconName.Pin, tokens.Color.Extended.Yellow.Yellow_800 elseif icon == types.TreeNodeIcon.Alert then return IconName.TriangleExclamation, tokens.Color.ActionAlert.Foreground end return "", tokens.Color.Content.Default end return useTreeNodeIcon
218
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/UserSettings/SettingRow.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local ReactCharm = require("@pkg/ReactCharm") local Sift = require("@pkg/Sift") local UserSettingsStore = require("@root/UserSettings/UserSettingsStore") local defaultSettings = require("@root/UserSettings/defaultSettings") local useColors = require("@root/Common/useColors") local useSignalState = ReactCharm.useSignalState local useCallback = React.useCallback local useMemo = React.useMemo type Setting = defaultSettings.Setting type SettingChoice = defaultSettings.SettingChoice export type Props = { setting: Setting, layoutOrder: number?, } local function SettingRow(props: Props) local colors = useColors() local userSettingsStore = useSignalState(UserSettingsStore.get) local userSettings = useSignalState(userSettingsStore.getStorage) local setSetting = useCallback(function(newValue: any) userSettingsStore.setStorage(function(prev) return Sift.Dictionary.join(prev, { [props.setting.name] = newValue, }) end) end, { userSettingsStore.setStorage, props.setting } :: { unknown }) local optionElement = useMemo(function(): React.Node local value = userSettings[props.setting.name] if props.setting.settingType == "checkbox" then return React.createElement(Foundation.Checkbox, { label = props.setting.displayName, hint = props.setting.description, isChecked = value, onActivated = setSetting, }) elseif props.setting.settingType == "dropdown" then local items = Sift.List.map(props.setting.choices, function(choice: SettingChoice): Foundation.DropdownItem return { id = choice.name, text = choice.displayName, } end) return React.createElement(Foundation.Dropdown.Root, { label = props.setting.displayName, hint = props.setting.description, value = value, items = items, onItemChanged = setSetting, }) elseif props.setting.settingType == "number" then local range = props.setting.range return React.createElement(Foundation.NumberInput, { value = value, label = props.setting.displayName, hint = props.setting.description, step = 10, maximum = if range then range.Max else nil, minimum = if range then range.Min else nil, onChanged = setSetting, }) end error(`no handling for setting type {props.setting.settingType}`) end, { props.setting, userSettings } :: { unknown }) local hasBeenChanged = not userSettingsStore.isSettingDefault(props.setting.name) return React.createElement(Foundation.View, { tag = "size-full-0 auto-y", LayoutOrder = props.layoutOrder, }, { ChangedIndicator = if hasBeenChanged then React.createElement(Foundation.View, { tag = "size-50-full", backgroundStyle = colors.accent, }) else nil, OptionWrapper = React.createElement(Foundation.View, { tag = "auto-xy padding-x-medium", }, { Option = optionElement, }), }) end return SettingRow
671
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/UserSettings/SettingsView.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local Sift = require("@pkg/Sift") local NavigationContext = require("@root/Navigation/NavigationContext") local SettingRow = require("@root/UserSettings/SettingRow") local defaultSettings = require("@root/UserSettings/defaultSettings") local nextLayoutOrder = require("@root/Common/nextLayoutOrder") local useMemo = React.useMemo type Setting = defaultSettings.Setting type SettingChoice = defaultSettings.SettingChoice type SettingsGroup = { name: string, settings: { Setting }, } local function SettingsView() local navigation = NavigationContext.use() local settingsByGroup: { SettingsGroup } = useMemo(function() local settings = Sift.Dictionary.values(defaultSettings) local sorted = Sift.Array.sort(settings, function(a: Setting, b: Setting) return a.name < b.name end) local groups = Sift.Array.reduce(sorted, function(accumulator: { [string]: SettingsGroup }, setting: Setting) local group: SettingsGroup if accumulator[setting.group] then group = accumulator[setting.group] else group = { name = setting.group, settings = {}, } accumulator[setting.group] = group end table.insert(group.settings, setting) return accumulator end, {}) return Sift.Array.sort(Sift.Dictionary.values(groups), function(a: SettingsGroup, b: SettingsGroup) return a.name < b.name end) end, { defaultSettings }) local children: { [string]: React.Node } = {} for _, group in settingsByGroup do children[group.name] = React.createElement(Foundation.Text, { tag = "auto-xy text-heading-medium padding-medium", Text = group.name, LayoutOrder = nextLayoutOrder(), }) for _, setting in group.settings do children[setting.name] = React.createElement(SettingRow, { setting = setting, layoutOrder = nextLayoutOrder(), }) end end return React.createElement(Foundation.ScrollView, { tag = "size-full bg-surface-200 gap-large padding-y-large", scroll = { AutomaticCanvasSize = Enum.AutomaticSize.Y, CanvasSize = UDim2.fromScale(1, 0), ScrollingDirection = Enum.ScrollingDirection.Y, }, layout = { FillDirection = Enum.FillDirection.Vertical, }, }, { Title = React.createElement(Foundation.View, { LayoutOrder = nextLayoutOrder(), tag = "align-y-center auto-y padding-right-medium row size-full-0", }, { Title = React.createElement(Foundation.Text, { LayoutOrder = nextLayoutOrder(), Text = "Settings", tag = "auto-y size-full-0 shrink text-align-x-left text-heading-large padding-medium", }), Close = React.createElement(Foundation.IconButton, { LayoutOrder = nextLayoutOrder(), icon = "x", isCircular = true, onActivated = function() navigation.navigateTo("Home") end, variant = Foundation.Enums.ButtonVariant.OverMedia, }), }), Settings = React.createElement(Foundation.View, { tag = "size-full shrink col gap-xlarge", LayoutOrder = nextLayoutOrder(), }, children), }) end return SettingsView
733
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/UserSettings/SettingsView.story.luau
local React = require("@pkg/React") local SettingsView = require("./SettingsView") return { story = function() return React.createElement(SettingsView) end, }
35
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/UserSettings/UserSettingsStore.luau
local Charm = require("@pkg/Charm") local t = require("@pkg/t") local createPluginSettingsStore = require("@root/Plugin/createPluginSettingsStore") local defaultSettings = require("@root/UserSettings/defaultSettings") export type UserSettings = { rememberLastOpenedStory: boolean, theme: string, sidebarWidth: number, controlsHeight: number, collectAnonymousUsageData: boolean, } local defaultValue: UserSettings = { rememberLastOpenedStory = defaultSettings.rememberLastOpenedStory.value, theme = defaultSettings.theme.choices[1].name, sidebarWidth = defaultSettings.sidebarWidth.value, controlsHeight = defaultSettings.controlsHeight.value, collectAnonymousUsageData = defaultSettings.collectAnonymousUsageData.value, } local validate = t.interface({ rememberLastOpenedStory = t.boolean, theme = t.string, sidebarWidth = t.number, controlsHeight = t.number, collectAnonymousUsageData = t.boolean, }) -- defaultValue needs to be kept in sync with the keys in defaultSettings for key in defaultSettings do assert(defaultValue[key] ~= nil, "setting with key {key} is missing from UserSettingsStore") end -- Initialize the store eagerly at module level so createPluginSettingsStore's -- internal Charm.effect is a top-level effect, not one nested inside a computed. local get = Charm.signal(createPluginSettingsStore("FlipbookUserSettings", defaultValue, validate)) return { get = get, }
304
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/UserSettings/defaultSettings.luau
local constants = require("@root/constants") export type SettingType = "checkbox" | "dropdown" | "number" local SettingType = { Checkbox = "checkbox" :: "checkbox", Dropdown = "dropdown" :: "dropdown", Number = "number" :: "number", } export type SettingGroup = "UI" | "Stories" | "Telemetry" local SettingGroup = { UI = "UI" :: "UI", Stories = "Stories" :: "Stories", Telemetry = "Telemetry" :: "Telemetry", } export type SettingChoice = { description: string, displayName: string, name: string, } type BaseSetting = { name: string, group: SettingGroup, displayName: string, description: string, settingType: SettingType, } type CheckboxSetting = BaseSetting & { settingType: "checkbox", value: boolean, } type DropdownSetting = BaseSetting & { settingType: "dropdown", choices: { SettingChoice }, } type NumberSetting = BaseSetting & { settingType: "number", range: NumberRange?, value: number, } export type Setting = CheckboxSetting | DropdownSetting | NumberSetting -- local expandNodesOnStart: Setting = { -- name = "expandNodesOnStart", -- displayName = "Expand nodes on start", -- description = "Re-open the storybooks and folders from before", -- settingType = SettingType.Dropdown, -- choices = { -- { -- name = "off", -- description = "Keep all explorer nodes closed on startup", -- }, -- { -- name = "all", -- description = "All explorer nodes are opened on startup", -- }, -- { -- name = "lastOpened", -- description = "Reopen the nodes that were opened from previous sessions on startup", -- }, -- }, -- } local rememberLastOpenedStory: CheckboxSetting = { name = "rememberLastOpenedStory", group = SettingGroup.Stories, displayName = "Remember last opened story", description = "Open the last viewed story when starting", settingType = SettingType.Checkbox, value = true, } local theme: DropdownSetting = { name = "theme", group = SettingGroup.UI, displayName = "UI theme", description = "Select the UI theme to use. By default, Flipbook will use the same theme as Studio", settingType = SettingType.Dropdown, choices = { { name = "system", displayName = "System", description = "Match the theme selected for Studio", }, { name = "dark", displayName = "Dark", description = "Force the theme to use dark mode", }, { name = "light", displayName = "Light", description = "Force the theme to use light mode", }, }, } local sidebarWidth: NumberSetting = { group = SettingGroup.UI, name = "sidebarWidth", displayName = "Sidebar panel width", description = `The default width (in pixels) of the sidebar. This can be between {constants.SIDEBAR_MIN_WIDTH}-{constants.SIDEBAR_MAX_WIDTH} px`, settingType = SettingType.Number, range = NumberRange.new(constants.SIDEBAR_MIN_WIDTH, constants.SIDEBAR_MAX_WIDTH), value = constants.SIDEBAR_INITIAL_WIDTH, } local controlsHeight: NumberSetting = { group = SettingGroup.UI, name = "controlsHeight", displayName = "Controls panel height", description = `The default height (in pixels) of the 'Controls' panel. This can be between {constants.CONTROLS_MIN_HEIGHT}-{constants.CONTROLS_MAX_HEIGHT} px`, settingType = SettingType.Number, range = NumberRange.new(constants.CONTROLS_MIN_HEIGHT, constants.CONTROLS_MAX_HEIGHT), value = constants.CONTROLS_INITIAL_HEIGHT, } local collectAnonymousUsageData: CheckboxSetting = { name = "collectAnonymousUsageData", group = SettingGroup.Telemetry, displayName = "Help improve Flipbook by sending anonymous usage data", description = "Allow Flipbook to collect anonymous usage data to help improve the product. No personal data or story content is collected", settingType = SettingType.Checkbox, value = true, } local settings = { -- expandNodesOnStart = expandNodesOnStart, rememberLastOpenedStory = rememberLastOpenedStory, theme = theme, sidebarWidth = sidebarWidth, controlsHeight = controlsHeight, collectAnonymousUsageData = collectAnonymousUsageData, } export type Settings = typeof(settings) return settings
972
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/init.luau
local constants = require("@self/constants") return { FLIPBOOK_LOGO = constants.FLIPBOOK_LOGO, createFlipbookPlugin = require("@self/Plugin/createFlipbookPlugin"), }
41
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/init.storybook.luau
local React = require("@pkg/React") local ReactRoblox = require("@pkg/ReactRoblox") local ContextProviders = require("@root/Common/ContextProviders") local MockPlugin = require("@root/Testing/MockPlugin") return { name = "FlipbookCore", storyRoots = { script.Parent, }, packages = { React = React, ReactRoblox = ReactRoblox, }, mapStory = function(Story) return function(props) return React.createElement(ContextProviders, { plugin = MockPlugin.new(), overlayGui = props.container, }, { Story = React.createElement(Story, props), }) end end, }
150
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/jest.config.luau
return { testMatch = { "**/*.spec" }, testPathIgnorePatterns = { "Packages", "RobloxPackages" }, }
27
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/logger.luau
local Log = require("@pkg/Log") local LogsStore = require("@root/Logs/LogsStore") local function stringToLogLevel(logLevel: string) if logLevel == "info" then return Log.LogLevel.Information elseif logLevel == "warn" or logLevel == "warning" then return Log.LogLevel.Warning elseif logLevel == "debug" then return Log.LogLevel.Debugging elseif logLevel == "err" or logLevel == "error" then return Log.LogLevel.Error end return Log.LogLevel.Warning end local sinks = { Log.LogSink.new(function(event) LogsStore.get().addLine(event) end), } if _G.ENABLE_OUTPUT_LOGGING == "true" then table.insert(sinks, Log.Common.RobloxLogSink()) end local logger = Log.Logger.new( { Log.Common.Enrichers.LogLevelEnricher(), Log.Common.Enrichers.DynSourceEnricher(true), }, sinks, { Log.Common.Filters.MinLevelFilter(stringToLogLevel(_G.LOG_LEVEL)), } ) return logger
237
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-next/src/Components/App/App.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local FoundationProvider = Foundation.FoundationProvider local Image = Foundation.Image local function App() return React.createElement(FoundationProvider, nil, { Background = React.createElement(Image, { Image = "rbxassetid://109801102767935", ScaleType = Enum.ScaleType.Tile, TileSize = UDim2.fromOffset(4, 4), imageStyle = { Color3 = Color3.new(1, 1, 1), Transparency = 0.975 }, tag = "bg-surface-0 padding-medium size-full", }), }) end return React.memo(App)
150
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-next/src/Constants.luau
local SHADOW_IMAGE = "component_assets/dropshadow_17_8" local SHADOW_SIZE = 16 local SHADOW_RECT = Rect.new(SHADOW_SIZE, SHADOW_SIZE, SHADOW_SIZE + 1, SHADOW_SIZE + 1) local Constants = { SHADOW_IMAGE = SHADOW_IMAGE, SHADOW_RECT = SHADOW_RECT, SHADOW_SIZE = SHADOW_SIZE, } return Constants
89
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-next/src/Utility/createPlugin.luau
local App = require("@root/Components/App") local React = require("@pkg/React") local ReactRoblox = require("@pkg/ReactRoblox") local function createPlugin(plugin: Plugin, widget: DockWidgetPluginGui, button: PluginToolbarButton?) local connections: { RBXScriptConnection } = {} local root = ReactRoblox.createRoot(widget) local app = React.createElement(App) local function mount() root:render(app) end local function unmount() root:unmount() end if button ~= nil then table.insert( connections, button.Click:Connect(function() widget.Enabled = not widget.Enabled end) ) table.insert( connections, widget:GetPropertyChangedSignal("Enabled"):Connect(function() button:SetActive(widget.Enabled) end) ) end table.insert( connections, widget:GetPropertyChangedSignal("Enabled"):Connect(function() if widget.Enabled then mount() else unmount() end end) ) if widget.Enabled then mount() end local function destroy() unmount() for _, connection in connections do connection:Disconnect() end end return { destroy = destroy, mount = mount, unmount = unmount, } end return createPlugin
284
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-next/src/init.luau
local FlipbookNext = { Utility = { createPlugin = require("@root/Utility/createPlugin"), }, } return FlipbookNext
30
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-next/src/init.storybook.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local ReactRoblox = require("@pkg/ReactRoblox") local FoundationProvider = Foundation.FoundationProvider return { name = "FlipbookNext", mapStory = function(Story) return function(storyProps) return React.createElement(FoundationProvider, nil, { Story = React.createElement(Story, storyProps) }) end end, packages = { React = React, ReactRoblox = ReactRoblox }, storyRoots = { script.Parent } }
120
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Enums/Action/Flags.lua
--!strict return { STATIONARY = bit32.lshift(1, 9), MOVING = bit32.lshift(1, 10), AIR = bit32.lshift(1, 11), INTANGIBLE = bit32.lshift(1, 12), SWIMMING = bit32.lshift(1, 13), METAL_WATER = bit32.lshift(1, 14), SHORT_HITBOX = bit32.lshift(1, 15), RIDING_SHELL = bit32.lshift(1, 16), INVULNERABLE = bit32.lshift(1, 17), BUTT_OR_STOMACH_SLIDE = bit32.lshift(1, 18), DIVING = bit32.lshift(1, 19), ON_POLE = bit32.lshift(1, 20), HANGING = bit32.lshift(1, 21), IDLE = bit32.lshift(1, 22), ATTACKING = bit32.lshift(1, 23), ALLOW_VERTICAL_WIND_ACTION = bit32.lshift(1, 24), CONTROL_JUMP_HEIGHT = bit32.lshift(1, 25), ALLOW_FIRST_PERSON = bit32.lshift(1, 26), PAUSE_EXIT = bit32.lshift(1, 27), SWIMMING_OR_FLYING = bit32.lshift(1, 28), WATER_OR_TEXT = bit32.lshift(1, 29), THROWING = bit32.lshift(1, 31), }
339
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Enums/Action/Groups.lua
--!strict return { -- Group Flags STATIONARY = bit32.lshift(0, 6), MOVING = bit32.lshift(1, 6), AIRBORNE = bit32.lshift(2, 6), SUBMERGED = bit32.lshift(3, 6), CUTSCENE = bit32.lshift(4, 6), AUTOMATIC = bit32.lshift(5, 6), OBJECT = bit32.lshift(6, 6), -- Mask for capturing these Flags GROUP_MASK = 0b_000000111000000, }
134
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Enums/Action/init.lua
--!strict return { UNINITIALIZED = 0x00000000, -- (0x000) -- group 0x000: stationary actions IDLE = 0x0C400201, -- (0x001 | FLAG_STATIONARY | FLAG_IDLE | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) START_SLEEPING = 0x0C400202, -- (0x002 | FLAG_STATIONARY | FLAG_IDLE | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) SLEEPING = 0x0C000203, -- (0x003 | FLAG_STATIONARY | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) WAKING_UP = 0x0C000204, -- (0x004 | FLAG_STATIONARY | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) PANTING = 0x0C400205, -- (0x005 | FLAG_STATIONARY | FLAG_IDLE | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) HOLD_PANTING_UNUSED = 0x08000206, -- (0x006 | FLAG_STATIONARY | FLAG_PAUSE_EXIT) HOLD_IDLE = 0x08000207, -- (0x007 | FLAG_STATIONARY | FLAG_PAUSE_EXIT) HOLD_HEAVY_IDLE = 0x08000208, -- (0x008 | FLAG_STATIONARY | FLAG_PAUSE_EXIT) STANDING_AGAINST_WALL = 0x0C400209, -- (0x009 | FLAG_STATIONARY | FLAG_IDLE | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) COUGHING = 0x0C40020A, -- (0x00A | FLAG_STATIONARY | FLAG_IDLE | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) SHIVERING = 0x0C40020B, -- (0x00B | FLAG_STATIONARY | FLAG_IDLE | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) IN_QUICKSAND = 0x0002020D, -- (0x00D | FLAG_STATIONARY | FLAG_INVULNERABLE) UNKNOWN_0002020E = 0x0002020E, -- (0x00E | FLAG_STATIONARY | FLAG_INVULNERABLE) CROUCHING = 0x0C008220, -- (0x020 | FLAG_STATIONARY | FLAG_SHORT_HITBOX | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) START_CROUCHING = 0x0C008221, -- (0x021 | FLAG_STATIONARY | FLAG_SHORT_HITBOX | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) STOP_CROUCHING = 0x0C008222, -- (0x022 | FLAG_STATIONARY | FLAG_SHORT_HITBOX | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) START_CRAWLING = 0x0C008223, -- (0x023 | FLAG_STATIONARY | FLAG_SHORT_HITBOX | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) STOP_CRAWLING = 0x0C008224, -- (0x024 | FLAG_STATIONARY | FLAG_SHORT_HITBOX | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) SLIDE_KICK_SLIDE_STOP = 0x08000225, -- (0x025 | FLAG_STATIONARY | FLAG_PAUSE_EXIT) SHOCKWAVE_BOUNCE = 0x00020226, -- (0x026 | FLAG_STATIONARY | FLAG_INVULNERABLE) FIRST_PERSON = 0x0C000227, -- (0x027 | FLAG_STATIONARY | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) BACKFLIP_LAND_STOP = 0x0800022F, -- (0x02F | FLAG_STATIONARY | FLAG_PAUSE_EXIT) JUMP_LAND_STOP = 0x0C000230, -- (0x030 | FLAG_STATIONARY | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) DOUBLE_JUMP_LAND_STOP = 0x0C000231, -- (0x031 | FLAG_STATIONARY | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) FREEFALL_LAND_STOP = 0x0C000232, -- (0x032 | FLAG_STATIONARY | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) SIDE_FLIP_LAND_STOP = 0x0C000233, -- (0x033 | FLAG_STATIONARY | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) HOLD_JUMP_LAND_STOP = 0x08000234, -- (0x034 | FLAG_STATIONARY | FLAG_PAUSE_EXIT) HOLD_FREEFALL_LAND_STOP = 0x08000235, -- (0x035 | FLAG_STATIONARY | FLAG_PAUSE_EXIT) AIR_THROW_LAND = 0x80000A36, -- (0x036 | FLAG_STATIONARY | FLAG_AIR | FLAG_THROWING) TWIRL_LAND = 0x18800238, -- (0x038 | FLAG_STATIONARY | FLAG_ATTACKING | FLAG_PAUSE_EXIT | FLAG_SWIMMING_OR_FLYING) LAVA_BOOST_LAND = 0x08000239, -- (0x039 | FLAG_STATIONARY | FLAG_PAUSE_EXIT) TRIPLE_JUMP_LAND_STOP = 0x0800023A, -- (0x03A | FLAG_STATIONARY | FLAG_PAUSE_EXIT) LONG_JUMP_LAND_STOP = 0x0800023B, -- (0x03B | FLAG_STATIONARY | FLAG_PAUSE_EXIT) GROUND_POUND_LAND = 0x0080023C, -- (0x03C | FLAG_STATIONARY | FLAG_ATTACKING) BRAKING_STOP = 0x0C00023D, -- (0x03D | FLAG_STATIONARY | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) BUTT_SLIDE_STOP = 0x0C00023E, -- (0x03E | FLAG_STATIONARY | FLAG_ALLOW_FIRST_PERSON | FLAG_PAUSE_EXIT) HOLD_BUTT_SLIDE_STOP = 0x0800043F, -- (0x03F | FLAG_MOVING | FLAG_PAUSE_EXIT) -- group 0x040: moving (ground) actions WALKING = 0x04000440, -- (0x040 | FLAG_MOVING | FLAG_ALLOW_FIRST_PERSON) HOLD_WALKING = 0x00000442, -- (0x042 | FLAG_MOVING) TURNING_AROUND = 0x00000443, -- (0x043 | FLAG_MOVING) FINISH_TURNING_AROUND = 0x00000444, -- (0x044 | FLAG_MOVING) BRAKING = 0x04000445, -- (0x045 | FLAG_MOVING | FLAG_ALLOW_FIRST_PERSON) RIDING_SHELL_GROUND = 0x20810446, -- (0x046 | FLAG_MOVING | FLAG_RIDING_SHELL | FLAG_ATTACKING | FLAG_WATER_OR_TEXT) HOLD_HEAVY_WALKING = 0x00000447, -- (0x047 | FLAG_MOVING) CRAWLING = 0x04008448, -- (0x048 | FLAG_MOVING | FLAG_SHORT_HITBOX | FLAG_ALLOW_FIRST_PERSON) BURNING_GROUND = 0x00020449, -- (0x049 | FLAG_MOVING | FLAG_INVULNERABLE) DECELERATING = 0x0400044A, -- (0x04A | FLAG_MOVING | FLAG_ALLOW_FIRST_PERSON) HOLD_DECELERATING = 0x0000044B, -- (0x04B | FLAG_MOVING) BEGIN_SLIDING = 0x00000050, -- (0x050) HOLD_BEGIN_SLIDING = 0x00000051, -- (0x051) BUTT_SLIDE = 0x00840452, -- (0x052 | FLAG_MOVING | FLAG_BUTT_OR_STOMACH_SLIDE | FLAG_ATTACKING) STOMACH_SLIDE = 0x008C0453, -- (0x053 | FLAG_MOVING | FLAG_BUTT_OR_STOMACH_SLIDE | FLAG_DIVING | FLAG_ATTACKING) HOLD_BUTT_SLIDE = 0x00840454, -- (0x054 | FLAG_MOVING | FLAG_BUTT_OR_STOMACH_SLIDE | FLAG_ATTACKING) HOLD_STOMACH_SLIDE = 0x008C0455, -- (0x055 | FLAG_MOVING | FLAG_BUTT_OR_STOMACH_SLIDE | FLAG_DIVING | FLAG_ATTACKING) DIVE_SLIDE = 0x00880456, -- (0x056 | FLAG_MOVING | FLAG_DIVING | FLAG_ATTACKING) MOVE_PUNCHING = 0x00800457, -- (0x057 | FLAG_MOVING | FLAG_ATTACKING) CROUCH_SLIDE = 0x04808459, -- (0x059 | FLAG_MOVING | FLAG_SHORT_HITBOX | FLAG_ATTACKING | FLAG_ALLOW_FIRST_PERSON) SLIDE_KICK_SLIDE = 0x0080045A, -- (0x05A | FLAG_MOVING | FLAG_ATTACKING) HARD_BACKWARD_GROUND_KB = 0x00020460, -- (0x060 | FLAG_MOVING | FLAG_INVULNERABLE) HARD_FORWARD_GROUND_KB = 0x00020461, -- (0x061 | FLAG_MOVING | FLAG_INVULNERABLE) BACKWARD_GROUND_KB = 0x00020462, -- (0x062 | FLAG_MOVING | FLAG_INVULNERABLE) FORWARD_GROUND_KB = 0x00020463, -- (0x063 | FLAG_MOVING | FLAG_INVULNERABLE) SOFT_BACKWARD_GROUND_KB = 0x00020464, -- (0x064 | FLAG_MOVING | FLAG_INVULNERABLE) SOFT_FORWARD_GROUND_KB = 0x00020465, -- (0x065 | FLAG_MOVING | FLAG_INVULNERABLE) GROUND_BONK = 0x00020466, -- (0x066 | FLAG_MOVING | FLAG_INVULNERABLE) DEATH_EXIT_LAND = 0x00020467, -- (0x067 | FLAG_MOVING | FLAG_INVULNERABLE) JUMP_LAND = 0x04000470, -- (0x070 | FLAG_MOVING | FLAG_ALLOW_FIRST_PERSON) FREEFALL_LAND = 0x04000471, -- (0x071 | FLAG_MOVING | FLAG_ALLOW_FIRST_PERSON) DOUBLE_JUMP_LAND = 0x04000472, -- (0x072 | FLAG_MOVING | FLAG_ALLOW_FIRST_PERSON) SIDE_FLIP_LAND = 0x04000473, -- (0x073 | FLAG_MOVING | FLAG_ALLOW_FIRST_PERSON) HOLD_JUMP_LAND = 0x00000474, -- (0x074 | FLAG_MOVING) HOLD_FREEFALL_LAND = 0x00000475, -- (0x075 | FLAG_MOVING) QUICKSAND_JUMP_LAND = 0x00000476, -- (0x076 | FLAG_MOVING) HOLD_QUICKSAND_JUMP_LAND = 0x00000477, -- (0x077 | FLAG_MOVING) TRIPLE_JUMP_LAND = 0x04000478, -- (0x078 | FLAG_MOVING | FLAG_ALLOW_FIRST_PERSON) LONG_JUMP_LAND = 0x00000479, -- (0x079 | FLAG_MOVING) BACKFLIP_LAND = 0x0400047A, -- (0x07A | FLAG_MOVING | FLAG_ALLOW_FIRST_PERSON) -- group 0x080: airborne actions JUMP = 0x03000880, -- (0x080 | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION | FLAG_CONTROL_JUMP_HEIGHT) DOUBLE_JUMP = 0x03000881, -- (0x081 | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION | FLAG_CONTROL_JUMP_HEIGHT) TRIPLE_JUMP = 0x01000882, -- (0x082 | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION) BACKFLIP = 0x01000883, -- (0x083 | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION) STEEP_JUMP = 0x03000885, -- (0x085 | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION | FLAG_CONTROL_JUMP_HEIGHT) WALL_KICK_AIR = 0x03000886, -- (0x086 | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION | FLAG_CONTROL_JUMP_HEIGHT) SIDE_FLIP = 0x01000887, -- (0x087 | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION) LONG_JUMP = 0x03000888, -- (0x088 | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION | FLAG_CONTROL_JUMP_HEIGHT) WATER_JUMP = 0x01000889, -- (0x089 | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION) DIVE = 0x0188088A, -- (0x08A | FLAG_AIR | FLAG_DIVING | FLAG_ATTACKING | FLAG_ALLOW_VERTICAL_WIND_ACTION) FREEFALL = 0x0100088C, -- (0x08C | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION) TOP_OF_POLE_JUMP = 0x0300088D, -- (0x08D | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION | FLAG_CONTROL_JUMP_HEIGHT) BUTT_SLIDE_AIR = 0x0300088E, -- (0x08E | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION | FLAG_CONTROL_JUMP_HEIGHT) FLYING_TRIPLE_JUMP = 0x03000894, -- (0x094 | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION | FLAG_CONTROL_JUMP_HEIGHT) SHOT_FROM_CANNON = 0x00880898, -- (0x098 | FLAG_AIR | FLAG_DIVING | FLAG_ATTACKING) FLYING = 0x10880899, -- (0x099 | FLAG_AIR | FLAG_DIVING | FLAG_ATTACKING | FLAG_SWIMMING_OR_FLYING) RIDING_SHELL_JUMP = 0x0281089A, -- (0x09A | FLAG_AIR | FLAG_RIDING_SHELL | FLAG_ATTACKING | FLAG_CONTROL_JUMP_HEIGHT) RIDING_SHELL_FALL = 0x0081089B, -- (0x09B | FLAG_AIR | FLAG_RIDING_SHELL | FLAG_ATTACKING) VERTICAL_WIND = 0x1008089C, -- (0x09C | FLAG_AIR | FLAG_DIVING | FLAG_SWIMMING_OR_FLYING) HOLD_JUMP = 0x030008A0, -- (0x0A0 | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION | FLAG_CONTROL_JUMP_HEIGHT) HOLD_FREEFALL = 0x010008A1, -- (0x0A1 | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION) HOLD_BUTT_SLIDE_AIR = 0x010008A2, -- (0x0A2 | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION) HOLD_WATER_JUMP = 0x010008A3, -- (0x0A3 | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION) TWIRLING = 0x108008A4, -- (0x0A4 | FLAG_AIR | FLAG_ATTACKING | FLAG_SWIMMING_OR_FLYING) FORWARD_ROLLOUT = 0x010008A6, -- (0x0A6 | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION) AIR_HIT_WALL = 0x000008A7, -- (0x0A7 | FLAG_AIR) RIDING_HOOT = 0x000004A8, -- (0x0A8 | FLAG_MOVING) GROUND_POUND = 0x008008A9, -- (0x0A9 | FLAG_AIR | FLAG_ATTACKING) SLIDE_KICK = 0x018008AA, -- (0x0AA | FLAG_AIR | FLAG_ATTACKING | FLAG_ALLOW_VERTICAL_WIND_ACTION) AIR_THROW = 0x830008AB, -- (0x0AB | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION | FLAG_CONTROL_JUMP_HEIGHT | FLAG_THROWING) JUMP_KICK = 0x018008AC, -- (0x0AC | FLAG_AIR | FLAG_ATTACKING | FLAG_ALLOW_VERTICAL_WIND_ACTION) BACKWARD_ROLLOUT = 0x010008AD, -- (0x0AD | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION) CRAZY_BOX_BOUNCE = 0x000008AE, -- (0x0AE | FLAG_AIR) SPECIAL_TRIPLE_JUMP = 0x030008AF, -- (0x0AF | FLAG_AIR | FLAG_ALLOW_VERTICAL_WIND_ACTION | FLAG_CONTROL_JUMP_HEIGHT) BACKWARD_AIR_KB = 0x010208B0, -- (0x0B0 | FLAG_AIR | FLAG_INVULNERABLE | FLAG_ALLOW_VERTICAL_WIND_ACTION) FORWARD_AIR_KB = 0x010208B1, -- (0x0B1 | FLAG_AIR | FLAG_INVULNERABLE | FLAG_ALLOW_VERTICAL_WIND_ACTION) HARD_FORWARD_AIR_KB = 0x010208B2, -- (0x0B2 | FLAG_AIR | FLAG_INVULNERABLE | FLAG_ALLOW_VERTICAL_WIND_ACTION) HARD_BACKWARD_AIR_KB = 0x010208B3, -- (0x0B3 | FLAG_AIR | FLAG_INVULNERABLE | FLAG_ALLOW_VERTICAL_WIND_ACTION) BURNING_JUMP = 0x010208B4, -- (0x0B4 | FLAG_AIR | FLAG_INVULNERABLE | FLAG_ALLOW_VERTICAL_WIND_ACTION) BURNING_FALL = 0x010208B5, -- (0x0B5 | FLAG_AIR | FLAG_INVULNERABLE | FLAG_ALLOW_VERTICAL_WIND_ACTION) SOFT_BONK = 0x010208B6, -- (0x0B6 | FLAG_AIR | FLAG_INVULNERABLE | FLAG_ALLOW_VERTICAL_WIND_ACTION) LAVA_BOOST = 0x010208B7, -- (0x0B7 | FLAG_AIR | FLAG_INVULNERABLE | FLAG_ALLOW_VERTICAL_WIND_ACTION) GETTING_BLOWN = 0x010208B8, -- (0x0B8 | FLAG_AIR | FLAG_INVULNERABLE | FLAG_ALLOW_VERTICAL_WIND_ACTION) THROWN_FORWARD = 0x010208BD, -- (0x0BD | FLAG_AIR | FLAG_INVULNERABLE | FLAG_ALLOW_VERTICAL_WIND_ACTION) THROWN_BACKWARD = 0x010208BE, -- (0x0BE | FLAG_AIR | FLAG_INVULNERABLE | FLAG_ALLOW_VERTICAL_WIND_ACTION) -- group 0x0C0: submerged actions WATER_IDLE = 0x380022C0, -- (0x0C0 | FLAG_STATIONARY | FLAG_SWIMMING | FLAG_PAUSE_EXIT | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) HOLD_WATER_IDLE = 0x380022C1, -- (0x0C1 | FLAG_STATIONARY | FLAG_SWIMMING | FLAG_PAUSE_EXIT | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) WATER_ACTION_END = 0x300022C2, -- (0x0C2 | FLAG_STATIONARY | FLAG_SWIMMING | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) HOLD_WATER_ACTION_END = 0x300022C3, -- (0x0C3 | FLAG_STATIONARY | FLAG_SWIMMING | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) DROWNING = 0x300032C4, -- (0x0C4 | FLAG_STATIONARY | FLAG_INTANGIBLE | FLAG_SWIMMING | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) BACKWARD_WATER_KB = 0x300222C5, -- (0x0C5 | FLAG_STATIONARY | FLAG_SWIMMING | FLAG_INVULNERABLE | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) FORWARD_WATER_KB = 0x300222C6, -- (0x0C6 | FLAG_STATIONARY | FLAG_SWIMMING | FLAG_INVULNERABLE | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) WATER_DEATH = 0x300032C7, -- (0x0C7 | FLAG_STATIONARY | FLAG_INTANGIBLE | FLAG_SWIMMING | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) WATER_SHOCKED = 0x300222C8, -- (0x0C8 | FLAG_STATIONARY | FLAG_SWIMMING | FLAG_INVULNERABLE | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) BREASTSTROKE = 0x300024D0, -- (0x0D0 | FLAG_MOVING | FLAG_SWIMMING | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) SWIMMING_END = 0x300024D1, -- (0x0D1 | FLAG_MOVING | FLAG_SWIMMING | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) FLUTTER_KICK = 0x300024D2, -- (0x0D2 | FLAG_MOVING | FLAG_SWIMMING | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) HOLD_BREASTSTROKE = 0x300024D3, -- (0x0D3 | FLAG_MOVING | FLAG_SWIMMING | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) HOLD_SWIMMING_END = 0x300024D4, -- (0x0D4 | FLAG_MOVING | FLAG_SWIMMING | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) HOLD_FLUTTER_KICK = 0x300024D5, -- (0x0D5 | FLAG_MOVING | FLAG_SWIMMING | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) WATER_SHELL_SWIMMING = 0x300024D6, -- (0x0D6 | FLAG_MOVING | FLAG_SWIMMING | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) WATER_THROW = 0x300024E0, -- (0x0E0 | FLAG_MOVING | FLAG_SWIMMING | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) WATER_PUNCH = 0x300024E1, -- (0x0E1 | FLAG_MOVING | FLAG_SWIMMING | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) WATER_PLUNGE = 0x300022E2, -- (0x0E2 | FLAG_STATIONARY | FLAG_SWIMMING | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) CAUGHT_IN_WHIRLPOOL = 0x300222E3, -- (0x0E3 | FLAG_STATIONARY | FLAG_SWIMMING | FLAG_INVULNERABLE | FLAG_SWIMMING_OR_FLYING | FLAG_WATER_OR_TEXT) METAL_WATER_STANDING = 0x080042F0, -- (0x0F0 | FLAG_STATIONARY | FLAG_METAL_WATER | FLAG_PAUSE_EXIT) HOLD_METAL_WATER_STANDING = 0x080042F1, -- (0x0F1 | FLAG_STATIONARY | FLAG_METAL_WATER | FLAG_PAUSE_EXIT) METAL_WATER_WALKING = 0x000044F2, -- (0x0F2 | FLAG_MOVING | FLAG_METAL_WATER) HOLD_METAL_WATER_WALKING = 0x000044F3, -- (0x0F3 | FLAG_MOVING | FLAG_METAL_WATER) METAL_WATER_FALLING = 0x000042F4, -- (0x0F4 | FLAG_STATIONARY | FLAG_METAL_WATER) HOLD_METAL_WATER_FALLING = 0x000042F5, -- (0x0F5 | FLAG_STATIONARY | FLAG_METAL_WATER) METAL_WATER_FALL_LAND = 0x000042F6, -- (0x0F6 | FLAG_STATIONARY | FLAG_METAL_WATER) HOLD_METAL_WATER_FALL_LAND = 0x000042F7, -- (0x0F7 | FLAG_STATIONARY | FLAG_METAL_WATER) METAL_WATER_JUMP = 0x000044F8, -- (0x0F8 | FLAG_MOVING | FLAG_METAL_WATER) HOLD_METAL_WATER_JUMP = 0x000044F9, -- (0x0F9 | FLAG_MOVING | FLAG_METAL_WATER) METAL_WATER_JUMP_LAND = 0x000044FA, -- (0x0FA | FLAG_MOVING | FLAG_METAL_WATER) HOLD_METAL_WATER_JUMP_LAND = 0x000044FB, -- (0x0FB | FLAG_MOVING | FLAG_METAL_WATER) -- group 0x100: cutscene actions DISAPPEARED = 0x00001300, -- (0x100 | FLAG_STATIONARY | FLAG_INTANGIBLE) INTRO_CUTSCENE = 0x04001301, -- (0x101 | FLAG_STATIONARY | FLAG_INTANGIBLE | FLAG_ALLOW_FIRST_PERSON) STAR_DANCE_EXIT = 0x00001302, -- (0x102 | FLAG_STATIONARY | FLAG_INTANGIBLE) STAR_DANCE_WATER = 0x00001303, -- (0x103 | FLAG_STATIONARY | FLAG_INTANGIBLE) FALL_AFTER_STAR_GRAB = 0x00001904, -- (0x104 | FLAG_AIR | FLAG_INTANGIBLE) READING_AUTOMATIC_DIALOG = 0x20001305, -- (0x105 | FLAG_STATIONARY | FLAG_INTANGIBLE | FLAG_WATER_OR_TEXT) READING_NPC_DIALOG = 0x20001306, -- (0x106 | FLAG_STATIONARY | FLAG_INTANGIBLE | FLAG_WATER_OR_TEXT) STAR_DANCE_NO_EXIT = 0x00001307, -- (0x107 | FLAG_STATIONARY | FLAG_INTANGIBLE) READING_SIGN = 0x00001308, -- (0x108 | FLAG_STATIONARY | FLAG_INTANGIBLE) JUMBO_STAR_CUTSCENE = 0x00001909, -- (0x109 | FLAG_AIR | FLAG_INTANGIBLE) WAITING_FOR_DIALOG = 0x0000130A, -- (0x10A | FLAG_STATIONARY | FLAG_INTANGIBLE) DEBUG_FREE_MOVE = 0x0000130F, -- (0x10F | FLAG_STATIONARY | FLAG_INTANGIBLE) STANDING_DEATH = 0x00021311, -- (0x111 | FLAG_STATIONARY | FLAG_INTANGIBLE | FLAG_INVULNERABLE) QUICKSAND_DEATH = 0x00021312, -- (0x112 | FLAG_STATIONARY | FLAG_INTANGIBLE | FLAG_INVULNERABLE) ELECTROCUTION = 0x00021313, -- (0x113 | FLAG_STATIONARY | FLAG_INTANGIBLE | FLAG_INVULNERABLE) SUFFOCATION = 0x00021314, -- (0x114 | FLAG_STATIONARY | FLAG_INTANGIBLE | FLAG_INVULNERABLE) DEATH_ON_STOMACH = 0x00021315, -- (0x115 | FLAG_STATIONARY | FLAG_INTANGIBLE | FLAG_INVULNERABLE) DEATH_ON_BACK = 0x00021316, -- (0x116 | FLAG_STATIONARY | FLAG_INTANGIBLE | FLAG_INVULNERABLE) EATEN_BY_BUBBA = 0x00021317, -- (0x117 | FLAG_STATIONARY | FLAG_INTANGIBLE | FLAG_INVULNERABLE) END_PEACH_CUTSCENE = 0x00001918, -- (0x118 | FLAG_AIR | FLAG_INTANGIBLE) CREDITS_CUTSCENE = 0x00001319, -- (0x119 | FLAG_STATIONARY | FLAG_INTANGIBLE) END_WAVING_CUTSCENE = 0x0000131A, -- (0x11A | FLAG_STATIONARY | FLAG_INTANGIBLE) PULLING_DOOR = 0x00001320, -- (0x120 | FLAG_STATIONARY | FLAG_INTANGIBLE) PUSHING_DOOR = 0x00001321, -- (0x121 | FLAG_STATIONARY | FLAG_INTANGIBLE) WARP_DOOR_SPAWN = 0x00001322, -- (0x122 | FLAG_STATIONARY | FLAG_INTANGIBLE) EMERGE_FROM_PIPE = 0x00001923, -- (0x123 | FLAG_AIR | FLAG_INTANGIBLE) SPAWN_SPIN_AIRBORNE = 0x00001924, -- (0x124 | FLAG_AIR | FLAG_INTANGIBLE) SPAWN_SPIN_LANDING = 0x00001325, -- (0x125 | FLAG_STATIONARY | FLAG_INTANGIBLE) EXIT_AIRBORNE = 0x00001926, -- (0x126 | FLAG_AIR | FLAG_INTANGIBLE) EXIT_LAND_SAVE_DIALOG = 0x00001327, -- (0x127 | FLAG_STATIONARY | FLAG_INTANGIBLE) DEATH_EXIT = 0x00001928, -- (0x128 | FLAG_AIR | FLAG_INTANGIBLE) UNUSED_DEATH_EXIT = 0x00001929, -- (0x129 | FLAG_AIR | FLAG_INTANGIBLE) FALLING_DEATH_EXIT = 0x0000192A, -- (0x12A | FLAG_AIR | FLAG_INTANGIBLE) SPECIAL_EXIT_AIRBORNE = 0x0000192B, -- (0x12B | FLAG_AIR | FLAG_INTANGIBLE) SPECIAL_DEATH_EXIT = 0x0000192C, -- (0x12C | FLAG_AIR | FLAG_INTANGIBLE) FALLING_EXIT_AIRBORNE = 0x0000192D, -- (0x12D | FLAG_AIR | FLAG_INTANGIBLE) UNLOCKING_KEY_DOOR = 0x0000132E, -- (0x12E | FLAG_STATIONARY | FLAG_INTANGIBLE) UNLOCKING_STAR_DOOR = 0x0000132F, -- (0x12F | FLAG_STATIONARY | FLAG_INTANGIBLE) ENTERING_STAR_DOOR = 0x00001331, -- (0x131 | FLAG_STATIONARY | FLAG_INTANGIBLE) SPAWN_NO_SPIN_AIRBORNE = 0x00001932, -- (0x132 | FLAG_AIR | FLAG_INTANGIBLE) SPAWN_NO_SPIN_LANDING = 0x00001333, -- (0x133 | FLAG_STATIONARY | FLAG_INTANGIBLE) BBH_ENTER_JUMP = 0x00001934, -- (0x134 | FLAG_AIR | FLAG_INTANGIBLE) BBH_ENTER_SPIN = 0x00001535, -- (0x135 | FLAG_MOVING | FLAG_INTANGIBLE) TELEPORT_FADE_OUT = 0x00001336, -- (0x136 | FLAG_STATIONARY | FLAG_INTANGIBLE) TELEPORT_FADE_IN = 0x00001337, -- (0x137 | FLAG_STATIONARY | FLAG_INTANGIBLE) SHOCKED = 0x00020338, -- (0x138 | FLAG_STATIONARY | FLAG_INVULNERABLE) SQUISHED = 0x00020339, -- (0x139 | FLAG_STATIONARY | FLAG_INVULNERABLE) HEAD_STUCK_IN_GROUND = 0x0002033A, -- (0x13A | FLAG_STATIONARY | FLAG_INVULNERABLE) BUTT_STUCK_IN_GROUND = 0x0002033B, -- (0x13B | FLAG_STATIONARY | FLAG_INVULNERABLE) FEET_STUCK_IN_GROUND = 0x0002033C, -- (0x13C | FLAG_STATIONARY | FLAG_INVULNERABLE) PUTTING_ON_CAP = 0x0000133D, -- (0x13D | FLAG_STATIONARY | FLAG_INTANGIBLE) -- group 0x140: "automatic" actions HOLDING_POLE = 0x08100340, -- (0x140 | FLAG_STATIONARY | FLAG_ON_POLE | FLAG_PAUSE_EXIT) GRAB_POLE_SLOW = 0x00100341, -- (0x141 | FLAG_STATIONARY | FLAG_ON_POLE) GRAB_POLE_FAST = 0x00100342, -- (0x142 | FLAG_STATIONARY | FLAG_ON_POLE) CLIMBING_POLE = 0x00100343, -- (0x143 | FLAG_STATIONARY | FLAG_ON_POLE) TOP_OF_POLE_TRANSITION = 0x00100344, -- (0x144 | FLAG_STATIONARY | FLAG_ON_POLE) TOP_OF_POLE = 0x00100345, -- (0x145 | FLAG_STATIONARY | FLAG_ON_POLE) START_HANGING = 0x08200348, -- (0x148 | FLAG_STATIONARY | FLAG_HANGING | FLAG_PAUSE_EXIT) HANGING = 0x00200349, -- (0x149 | FLAG_STATIONARY | FLAG_HANGING) HANG_MOVING = 0x0020054A, -- (0x14A | FLAG_MOVING | FLAG_HANGING) LEDGE_GRAB = 0x0800034B, -- (0x14B | FLAG_STATIONARY | FLAG_PAUSE_EXIT) LEDGE_CLIMB_SLOW = 0x0000054C, -- (0x14C | FLAG_MOVING) LEDGE_CLIMB_DOWN = 0x0000054D, -- (0x14D | FLAG_MOVING) LEDGE_CLIMB_FAST = 0x0000054E, -- (0x14E | FLAG_MOVING) GRABBED = 0x00020370, -- (0x170 | FLAG_STATIONARY | FLAG_INVULNERABLE) IN_CANNON = 0x00001371, -- (0x171 | FLAG_STATIONARY | FLAG_INTANGIBLE) TORNADO_TWIRLING = 0x10020372, -- (0x172 | FLAG_STATIONARY | FLAG_INVULNERABLE | FLAG_SWIMMING_OR_FLYING) -- group 0x180: object actions PUNCHING = 0x00800380, -- (0x180 | FLAG_STATIONARY | FLAG_ATTACKING) PICKING_UP = 0x00000383, -- (0x183 | FLAG_STATIONARY) DIVE_PICKING_UP = 0x00000385, -- (0x185 | FLAG_STATIONARY) STOMACH_SLIDE_STOP = 0x00000386, -- (0x186 | FLAG_STATIONARY) PLACING_DOWN = 0x00000387, -- (0x187 | FLAG_STATIONARY) THROWING = 0x80000588, -- (0x188 | FLAG_MOVING | FLAG_THROWING) HEAVY_THROW = 0x80000589, -- (0x189 | FLAG_MOVING | FLAG_THROWING) PICKING_UP_BOWSER = 0x00000390, -- (0x190 | FLAG_STATIONARY) HOLDING_BOWSER = 0x00000391, -- (0x191 | FLAG_STATIONARY) RELEASING_BOWSER = 0x00000392, -- (0x192 | FLAG_STATIONARY) }
7,809
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Enums/Buttons.lua
--!strict return { A_BUTTON = 0x8000, B_BUTTON = 0x4000, L_TRIG = 0x0020, R_TRIG = 0x0010, Z_TRIG = 0x2000, START_BUTTON = 0x1000, U_JPAD = 0x0800, L_JPAD = 0x0200, R_JPAD = 0x0100, D_JPAD = 0x0400, U_CBUTTONS = 0x0008, L_CBUTTONS = 0x0002, R_CBUTTONS = 0x0001, D_CBUTTONS = 0x0004, }
149
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Enums/InputFlags.lua
--!strict return { NONZERO_ANALOG = 0x0001, A_PRESSED = 0x0002, OFF_FLOOR = 0x0004, ABOVE_SLIDE = 0x0008, FIRST_PERSON = 0x0010, NO_MOVEMENT = 0x0020, SQUISHED = 0x0040, A_DOWN = 0x0080, IN_POISON_GAS = 0x0100, IN_WATER = 0x0200, STOMPED = 0x0400, INTERACT_OBJ_GRABBABLE = 0x0800, UNKNOWN_12 = 0x1000, B_PRESSED = 0x2000, Z_DOWN = 0x4000, Z_PRESSED = 0x8000, }
177
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Enums/Mario/Cap.lua
--!strict return { DEFAULT_CAP_ON = 0, DEFAULT_CAP_OFF = 1, WING_CAP_ON = 2, WING_CAP_OFF = 3, }
39
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Enums/Mario/Flags.lua
--!strict local MarioFlags = { NORMAL_CAP = 0x00000001, VANISH_CAP = 0x00000002, METAL_CAP = 0x00000004, WING_CAP = 0x00000008, CAP_ON_HEAD = 0x00000010, CAP_IN_HAND = 0x00000020, METAL_SHOCK = 0x00000040, TELEPORTING = 0x00000080, MOVING_UP_IN_AIR = 0x00000100, ACTION_SOUND_PLAYED = 0x00010000, MARIO_SOUND_PLAYED = 0x00020000, FALLING_FAR = 0x00040000, PUNCHING = 0x00100000, KICKING = 0x00200000, TRIPPING = 0x00400000, } MarioFlags.SPECIAL_CAPS = MarioFlags.VANISH_CAP + MarioFlags.METAL_CAP + MarioFlags.WING_CAP MarioFlags.CAPS = MarioFlags.NORMAL_CAP + MarioFlags.SPECIAL_CAPS return MarioFlags
239
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Enums/Mario/Hands.lua
--!strict return { FISTS = 0, OPEN = 1, PEACE_SIGN = 2, HOLDING_CAP = 3, HOLDING_WING_CAP = 4, RIGHT_OPEN = 5, }
52
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Enums/Mario/Input.lua
--!strict return { NONZERO_ANALOG = 0x0001, A_PRESSED = 0x0002, OFF_FLOOR = 0x0004, ABOVE_SLIDE = 0x0008, FIRST_PERSON = 0x0010, NO_MOVEMENT = 0x0020, SQUISHED = 0x0040, A_DOWN = 0x0080, IN_POISON_GAS = 0x0100, IN_WATER = 0x0200, STOMPED = 0x0400, INTERACT_OBJ_GRABBABLE = 0x0800, B_PRESSED = 0x2000, Z_DOWN = 0x4000, Z_PRESSED = 0x8000, }
166
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Enums/ParticleFlags.lua
--!strict return { DUST = bit32.lshift(1, 0), VERTICAL_STAR = bit32.lshift(1, 1), SPARKLES = bit32.lshift(1, 3), HORIZONTAL_STAR = bit32.lshift(1, 4), BUBBLE = bit32.lshift(1, 5), WATER_SPLASH = bit32.lshift(1, 6), IDLE_WATER_WAVE = bit32.lshift(1, 7), SHALLOW_WATER_WAVE = bit32.lshift(1, 8), PLUNGE_BUBBLE = bit32.lshift(1, 9), WAVE_TRAIL = bit32.lshift(1, 10), FIRE = bit32.lshift(1, 11), SHALLOW_WATER_SPLASH = bit32.lshift(1, 12), LEAF = bit32.lshift(1, 13), SNOW = bit32.lshift(1, 14), DIRT = bit32.lshift(1, 15), MIST_CIRCLE = bit32.lshift(1, 16), BREATH = bit32.lshift(1, 17), TRIANGLE = bit32.lshift(1, 18), }
272
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Enums/Steps/Air.lua
--!strict return { NONE = 0, LANDED = 1, HIT_WALL = 2, GRABBED_LEDGE = 3, GRABBED_CEILING = 4, HIT_LAVA_WALL = 6, CHECK_LEDGE_GRAB = 1, CHECK_HANG = 2, }
72
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Enums/Steps/Ground.lua
--!strict return { LEFT_GROUND = 0, NONE = 1, HIT_WALL = 2, HIT_WALL_STOP_QSTEPS = 2, HIT_WALL_CONTINUE_QSTEPS = 3, }
49
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Enums/SurfaceClass.lua
--!strict return { DEFAULT = 0x0000, VERY_SLIPPERY = 0x0013, SLIPPERY = 0x0014, NOT_SLIPPERY = 0x0015, }
54
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Enums/TerrainType.lua
--!strict local TerrainType = { DEFAULT = 0, GRASS = 1, WATER = 2, STONE = 3, SPOOKY = 4, SNOW = 5, ICE = 6, SAND = 7, METAL = 8, } TerrainType.FROM_MATERIAL = { [Enum.Material.Mud] = TerrainType.GRASS, [Enum.Material.Grass] = TerrainType.GRASS, [Enum.Material.Ground] = TerrainType.GRASS, [Enum.Material.LeafyGrass] = TerrainType.GRASS, [Enum.Material.Ice] = TerrainType.ICE, [Enum.Material.Marble] = TerrainType.ICE, [Enum.Material.Glacier] = TerrainType.ICE, [Enum.Material.Wood] = TerrainType.SPOOKY, [Enum.Material.WoodPlanks] = TerrainType.SPOOKY, [Enum.Material.Foil] = TerrainType.METAL, [Enum.Material.Metal] = TerrainType.METAL, [Enum.Material.DiamondPlate] = TerrainType.METAL, [Enum.Material.CorrodedMetal] = TerrainType.METAL, [Enum.Material.Rock] = TerrainType.STONE, [Enum.Material.Salt] = TerrainType.STONE, [Enum.Material.Brick] = TerrainType.STONE, [Enum.Material.Slate] = TerrainType.STONE, [Enum.Material.Basalt] = TerrainType.STONE, [Enum.Material.Pebble] = TerrainType.STONE, [Enum.Material.Granite] = TerrainType.STONE, [Enum.Material.Sandstone] = TerrainType.STONE, [Enum.Material.Cobblestone] = TerrainType.STONE, [Enum.Material.CrackedLava] = TerrainType.STONE, [Enum.Material.Snow] = TerrainType.SNOW, [Enum.Material.Sand] = TerrainType.SAND, [Enum.Material.Water] = TerrainType.WATER, [Enum.Material.Fabric] = TerrainType.SNOW, } return TerrainType
460
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Enums/init.lua
--!strict local Enums = { Action = require(script.Action), Buttons = require(script.Buttons), ActionFlags = require(script.Action.Flags), ActionGroups = require(script.Action.Groups), MarioCap = require(script.Mario.Cap), MarioEyes = require(script.Mario.Eyes), MarioFlags = require(script.Mario.Flags), MarioHands = require(script.Mario.Hands), MarioInput = require(script.Mario.Input), AirStep = require(script.Steps.Air), WaterStep = require(script.Steps.Water), GroundStep = require(script.Steps.Ground), FloorType = require(script.FloorType), InputFlags = require(script.InputFlags), ModelFlags = require(script.ModelFlags), SurfaceClass = require(script.SurfaceClass), TerrainType = require(script.TerrainType), ParticleFlags = require(script.ParticleFlags), } local nameIndex: { [any]: { [number]: string } } = {} function Enums.GetName(map, value): string if not nameIndex[map] then local index = {} for name, value in pairs(map) do index[value] = name end nameIndex[map] = index end return nameIndex[map][value] end return table.freeze(Enums)
268
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Mario/Airborne/init.server.lua
--!strict local System = require(script.Parent) local Animations = System.Animations local Sounds = System.Sounds local Enums = System.Enums local Util = System.Util local Action = Enums.Action local ActionFlags = Enums.ActionFlags local AirStep = Enums.AirStep local MarioEyes = Enums.MarioEyes local InputFlags = Enums.InputFlags local MarioFlags = Enums.MarioFlags local ParticleFlags = Enums.ParticleFlags type Mario = System.Mario ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -- Helpers ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- local function stopRising(m: Mario) if m.Velocity.Y > 0 then m.Velocity *= Vector3.new(1, 0, 1) end end local function playFlipSounds(m: Mario, frame1: number, frame2: number, frame3: number) local animFrame = m.AnimFrame if animFrame == frame1 or animFrame == frame2 or animFrame == frame3 then m:PlaySound(Sounds.ACTION_SPIN) end end local function playKnockbackSound(m: Mario) if m.ActionArg == 0 and math.abs(m.ForwardVel) >= 28 then m:PlaySoundIfNoFlag(Sounds.MARIO_DOH, MarioFlags.MARIO_SOUND_PLAYED) else m:PlaySoundIfNoFlag(Sounds.MARIO_UH, MarioFlags.MARIO_SOUND_PLAYED) end end local function lavaBoostOnWall(m: Mario) local wall = m.Wall if wall then local angle = Util.Atan2s(wall.Normal.Z, wall.Normal.X) m.FaceAngle = Util.SetY(m.FaceAngle, angle) end if m.ForwardVel < 24 then m.ForwardVel = 24 end if not m.Flags:Has(MarioFlags.METAL_CAP) then m.HurtCounter += if m.Flags:Has(MarioFlags.CAP_ON_HEAD) then 12 else 18 end m:PlaySound(Sounds.MARIO_ON_FIRE) m:SetAction(Action.LAVA_BOOST, 1) end local function checkFallDamage(m: Mario, hardFallAction: number): boolean local fallHeight = m.PeakHeight - m.Position.Y local damageHeight = 1150 if m.Action() == Action.TWIRLING then return false end if m.Velocity.Y < -55 and fallHeight > 3000 then m.HurtCounter += if m.Flags:Has(MarioFlags.CAP_ON_HEAD) then 16 else 24 m:PlaySound(Sounds.MARIO_ATTACKED) m:SetAction(hardFallAction, 4) elseif fallHeight > damageHeight and not m:FloorIsSlippery() then m.HurtCounter += if m.Flags:Has(MarioFlags.CAP_ON_HEAD) then 8 else 12 m:PlaySound(Sounds.MARIO_ATTACKED) m.SquishTimer = 30 end return false end local function checkKickOrDiveInAir(m: Mario): boolean if m.Input:Has(InputFlags.B_PRESSED) then return m:SetAction(if m.ForwardVel > 28 then Action.DIVE else Action.JUMP_KICK) end return false end local function updateAirWithTurn(m: Mario) local dragThreshold = if m.Action() == Action.LONG_JUMP then 48 else 32 m.ForwardVel = Util.ApproachFloat(m.ForwardVel, 0, 0.35) if m.Input:Has(InputFlags.NONZERO_ANALOG) then local intendedDYaw = m.IntendedYaw - m.FaceAngle.Y local intendedMag = m.IntendedMag / 32 m.ForwardVel += 1.5 * Util.Coss(intendedDYaw) * intendedMag m.FaceAngle += Vector3int16.new(0, 512 * Util.Sins(intendedDYaw) * intendedMag, 0) end if m.ForwardVel > dragThreshold then m.ForwardVel -= 1 end if m.ForwardVel < -16 then m.ForwardVel += 2 end m.SlideVelX = m.ForwardVel * Util.Sins(m.FaceAngle.Y) m.SlideVelZ = m.ForwardVel * Util.Coss(m.FaceAngle.Y) m.Velocity = Vector3.new(m.SlideVelX, m.Velocity.Y, m.SlideVelZ) end local function updateAirWithoutTurn(m: Mario) local dragThreshold = 32 if m.Action() == Action.LONG_JUMP then dragThreshold = 48 end local sidewaysSpeed = 0 m.ForwardVel = Util.ApproachFloat(m.ForwardVel, 0, 0.35) if m.Input:Has(InputFlags.NONZERO_ANALOG) then local intendedDYaw = m.IntendedYaw - m.FaceAngle.Y local intendedMag = m.IntendedMag / 32 m.ForwardVel += intendedMag * Util.Coss(intendedDYaw) * 1.5 sidewaysSpeed = intendedMag * Util.Sins(intendedDYaw) * 10 end --! Uncapped air speed. Net positive when moving forward. if m.ForwardVel > dragThreshold then m.ForwardVel -= 1 end if m.ForwardVel < -16 then m.ForwardVel += 2 end m.SlideVelX = m.ForwardVel * Util.Sins(m.FaceAngle.Y) m.SlideVelZ = m.ForwardVel * Util.Coss(m.FaceAngle.Y) m.SlideVelX += sidewaysSpeed * Util.Sins(m.FaceAngle.Y + 0x4000) m.SlideVelZ += sidewaysSpeed * Util.Coss(m.FaceAngle.Y + 0x4000) m.Velocity = Vector3.new(m.SlideVelX, m.Velocity.Y, m.SlideVelZ) end local function updateLavaBoostOrTwirling(m: Mario) if m.Input:Has(InputFlags.NONZERO_ANALOG) then local intendedDYaw = m.IntendedYaw - m.FaceAngle.Y local intendedMag = m.IntendedMag / 32 m.ForwardVel += Util.Coss(intendedDYaw) * intendedMag m.FaceAngle += Vector3int16.new(0, Util.Sins(intendedDYaw) * intendedMag * 1024, 0) if m.ForwardVel < 0 then m.FaceAngle += Vector3int16.new(0, 0x8000, 0) m.ForwardVel *= -1 end if m.ForwardVel > 32 then m.ForwardVel -= 2 end end m.SlideVelX = m.ForwardVel * Util.Sins(m.FaceAngle.Y) m.SlideVelZ = m.ForwardVel * Util.Coss(m.FaceAngle.Y) m.Velocity = Vector3.new(m.SlideVelX, m.Velocity.Y, m.SlideVelZ) end local function updateFlyingYaw(m: Mario) local targetYawVel = -Util.SignedShort(m.Controller.StickX * (m.ForwardVel / 4)) if targetYawVel > 0 then if m.AngleVel.Y < 0 then m.AngleVel += Vector3int16.new(0, 0x40, 0) if m.AngleVel.Y > 0x10 then m.AngleVel = Util.SetY(m.AngleVel, 0x10) end else local y = Util.ApproachInt(m.AngleVel.Y, targetYawVel, 0x10, 0x20) m.AngleVel = Util.SetY(m.AngleVel, y) end elseif targetYawVel < 0 then if m.AngleVel.Y > 0 then m.AngleVel -= Vector3int16.new(0, 0x40, 0) if m.AngleVel.Y < -0x10 then m.AngleVel = Util.SetY(m.AngleVel, -0x10) end else local y = Util.ApproachInt(m.AngleVel.Y, targetYawVel, 0x20, 0x10) m.AngleVel = Util.SetY(m.AngleVel, y) end else local y = Util.ApproachInt(m.AngleVel.Y, 0, 0x40) m.AngleVel = Util.SetY(m.AngleVel, y) end m.FaceAngle += Vector3int16.new(0, m.AngleVel.Y, 0) m.FaceAngle = Util.SetZ(m.FaceAngle, 20 * -m.AngleVel.Y) end local function updateFlyingPitch(m: Mario) local targetPitchVel = -Util.SignedShort(m.Controller.StickY * (m.ForwardVel / 5)) if targetPitchVel > 0 then if m.AngleVel.X < 0 then m.AngleVel += Vector3int16.new(0x40, 0, 0) if m.AngleVel.X > 0x20 then m.AngleVel = Util.SetX(m.AngleVel, 0x20) end else local x = Util.ApproachInt(m.AngleVel.X, targetPitchVel, 0x20, 0x40) m.AngleVel = Util.SetX(m.AngleVel, x) end elseif targetPitchVel < 0 then if m.AngleVel.X > 0 then m.AngleVel -= Vector3int16.new(0x40, 0, 0) if m.AngleVel.X < -0x20 then m.AngleVel = Util.SetX(m.AngleVel, -0x20) end else local x = Util.ApproachInt(m.AngleVel.X, targetPitchVel, 0x40, 0x20) m.AngleVel = Util.SetX(m.AngleVel, x) end else local x = Util.ApproachInt(m.AngleVel.X, 0, 0x40) m.AngleVel = Util.SetX(m.AngleVel, x) end end local function updateFlying(m: Mario) updateFlyingPitch(m) updateFlyingYaw(m) m.ForwardVel -= 2 * (m.FaceAngle.X / 0x4000) + 0.1 m.ForwardVel -= 0.5 * (1 - Util.Coss(m.AngleVel.Y)) if m.ForwardVel < 0 then m.ForwardVel = 0 end if m.ForwardVel > 16 then m.FaceAngle += Vector3int16.new((m.ForwardVel - 32) * 6, 0, 0) elseif m.ForwardVel > 4 then m.FaceAngle += Vector3int16.new((m.ForwardVel - 32) * 10, 0, 0) else m.FaceAngle -= Vector3int16.new(0x400, 0, 0) end m.FaceAngle += Vector3int16.new(m.AngleVel.X, 0, 0) if m.FaceAngle.X > 0x2AAA then m.FaceAngle = Util.SetX(m.FaceAngle, 0x2AAA) end if m.FaceAngle.X < -0x2AAA then m.FaceAngle = Util.SetX(m.FaceAngle, -0x2AAA) end local velX = Util.Coss(m.FaceAngle.X) * Util.Sins(m.FaceAngle.Y) m.SlideVelX = m.ForwardVel * velX local velZ = Util.Coss(m.FaceAngle.X) * Util.Coss(m.FaceAngle.Y) m.SlideVelZ = m.ForwardVel * velZ local velY = Util.Sins(m.FaceAngle.X) m.Velocity = m.ForwardVel * Vector3.new(velX, velY, velZ) end local function commonAirActionStep(m: Mario, landAction: number, anim: Animation, stepArg: number): number local stepResult do updateAirWithoutTurn(m) stepResult = m:PerformAirStep(stepArg) end if stepResult == AirStep.NONE then m:SetAnimation(anim) elseif stepResult == AirStep.LANDED then if not checkFallDamage(m, Action.HARD_BACKWARD_GROUND_KB) then m:SetAction(landAction) end elseif stepResult == AirStep.HIT_WALL then m:SetAnimation(anim) if m.ForwardVel > 16 then m:BonkReflection() m.FaceAngle += Vector3int16.new(0, 0x8000, 0) if m.Wall then m:SetAction(Action.AIR_HIT_WALL) else stopRising(m) if m.ForwardVel >= 38 then m.ParticleFlags:Add(ParticleFlags.VERTICAL_STAR) m:SetAction(Action.BACKWARD_AIR_KB) else if m.ForwardVel > 8 then m:SetForwardVel(-8) end m:SetAction(Action.SOFT_BONK) end end else m:SetForwardVel(0) end elseif stepResult == AirStep.GRABBED_LEDGE then m:SetAnimation(Animations.IDLE_ON_LEDGE) m:SetAction(Action.LEDGE_GRAB) elseif stepResult == AirStep.GRABBED_CEILING then m:SetAction(Action.START_HANGING) elseif stepResult == AirStep.HIT_LAVA_WALL then lavaBoostOnWall(m) end return stepResult end local function commonRolloutStep(m: Mario, anim: Animation) local stepResult if m.ActionState == 0 then m.Velocity = Util.SetY(m.Velocity, 30) m.ActionState = 1 end m:PlaySound(Sounds.ACTION_TERRAIN_JUMP) updateAirWithoutTurn(m) stepResult = m:PerformAirStep() if stepResult == AirStep.NONE then if m.ActionState == 1 then if m:SetAnimation(anim) == 4 then m:PlaySound(Sounds.ACTION_SPIN) end else m:SetAnimation(Animations.GENERAL_FALL) end elseif stepResult == AirStep.LANDED then m:SetAction(Action.FREEFALL_LAND_STOP) m:PlayLandingSound() elseif stepResult == AirStep.HIT_WALL then m:SetForwardVel(0) elseif stepResult == AirStep.HIT_LAVA_WALL then lavaBoostOnWall(m) end if m.ActionState == 1 and m:IsAnimPastEnd() then m.ActionState = 2 end end local function commonAirKnockbackStep( m: Mario, landAction: number, hardFallAction: number, anim: Animation, speed: number ) local stepResult do m:SetForwardVel(speed) stepResult = m:PerformAirStep() end if stepResult == AirStep.NONE then m:SetAnimation(anim) elseif stepResult == AirStep.LANDED then if not checkFallDamage(m, hardFallAction) then local action = m.Action() if action == Action.THROWN_FORWARD or action == Action.THROWN_BACKWARD then m:SetAction(landAction, m.HurtCounter) else m:SetAction(landAction, m.ActionArg) end end elseif stepResult == AirStep.HIT_WALL then m:SetAnimation(Animations.BACKWARD_AIR_KB) m:BonkReflection() stopRising(m) m:SetForwardVel(-speed) elseif stepResult == AirStep.HIT_LAVA_WALL then lavaBoostOnWall(m) end return stepResult end local function checkWallKick(m: Mario) if m.WallKickTimer ~= 0 then if m.Input:Has(InputFlags.A_PRESSED) then if m.PrevAction() == Action.AIR_HIT_WALL then m.FaceAngle += Vector3int16.new(0, 0x8000, 0) end end end return false end ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -- Actions ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- local AIR_STEP_CHECK_BOTH = bit32.bor(AirStep.CHECK_LEDGE_GRAB, AirStep.CHECK_HANG) local DEF_ACTION: (number, (Mario) -> boolean) -> () = System.RegisterAction DEF_ACTION(Action.JUMP, function(m: Mario) if checkKickOrDiveInAir(m) then return true end if m.Input:Has(InputFlags.Z_PRESSED) then return m:SetAction(Action.GROUND_POUND) end m:PlayMarioSound(Sounds.ACTION_TERRAIN_JUMP) commonAirActionStep(m, Action.JUMP_LAND, Animations.SINGLE_JUMP, AIR_STEP_CHECK_BOTH) return false end) DEF_ACTION(Action.DOUBLE_JUMP, function(m: Mario) local anim = if m.Velocity.Y >= 0 then Animations.DOUBLE_JUMP_RISE else Animations.DOUBLE_JUMP_FALL if checkKickOrDiveInAir(m) then return true end if m.Input:Has(InputFlags.Z_PRESSED) then return m:SetAction(Action.GROUND_POUND) end m:PlayMarioSound(Sounds.ACTION_TERRAIN_JUMP, Sounds.MARIO_HOOHOO) commonAirActionStep(m, Action.DOUBLE_JUMP_LAND, anim, AIR_STEP_CHECK_BOTH) return false end) DEF_ACTION(Action.TRIPLE_JUMP, function(m: Mario) if m.Input:Has(InputFlags.B_PRESSED) then return m:SetAction(Action.DIVE) end if m.Input:Has(InputFlags.Z_PRESSED) then return m:SetAction(Action.GROUND_POUND) end m:PlayMarioSound(Sounds.ACTION_TERRAIN_JUMP) commonAirActionStep(m, Action.TRIPLE_JUMP_LAND, Animations.TRIPLE_JUMP, 0) playFlipSounds(m, 2, 8, 20) return false end) DEF_ACTION(Action.BACKFLIP, function(m: Mario) if m.Input:Has(InputFlags.Z_PRESSED) then return m:SetAction(Action.GROUND_POUND) end m:PlayMarioSound(Sounds.ACTION_TERRAIN_JUMP, Sounds.MARIO_YAH_WAH_HOO) commonAirActionStep(m, Action.BACKFLIP_LAND, Animations.BACKFLIP, 0) playFlipSounds(m, 2, 3, 17) return false end) DEF_ACTION(Action.FREEFALL, function(m: Mario) if m.Input:Has(InputFlags.B_PRESSED) then return m:SetAction(Action.DIVE) end if m.Input:Has(InputFlags.Z_PRESSED) then return m:SetAction(Action.GROUND_POUND) end local anim if m.ActionArg == 0 then anim = Animations.GENERAL_FALL elseif m.ActionArg == 1 then anim = Animations.FALL_FROM_SLIDE elseif m.ActionArg == 2 then anim = Animations.FALL_FROM_SLIDE_KICK end commonAirActionStep(m, Action.FREEFALL_LAND, anim, AirStep.CHECK_LEDGE_GRAB) return false end) DEF_ACTION(Action.SIDE_FLIP, function(m: Mario) if m.Input:Has(InputFlags.B_PRESSED) then return m:SetAction(Action.DIVE, 0) end if m.Input:Has(InputFlags.Z_PRESSED) then return m:SetAction(Action.GROUND_POUND) end m:PlayMarioSound(Sounds.ACTION_TERRAIN_JUMP) commonAirActionStep(m, Action.SIDE_FLIP_LAND, Animations.SLIDEFLIP, AirStep.CHECK_LEDGE_GRAB) if m.AnimFrame == 6 then m:PlaySound(Sounds.ACTION_SIDE_FLIP) end return false end) DEF_ACTION(Action.WALL_KICK_AIR, function(m: Mario) if m.Input:Has(InputFlags.B_PRESSED) then return m:SetAction(Action.DIVE) end if m.Input:Has(InputFlags.Z_PRESSED) then return m:SetAction(Action.GROUND_POUND) end m:PlayJumpSound() commonAirActionStep(m, Action.JUMP_LAND, Animations.SLIDEJUMP, AirStep.CHECK_LEDGE_GRAB) return false end) DEF_ACTION(Action.LONG_JUMP, function(m: Mario) local anim = if m.LongJumpIsSlow then Animations.SLOW_LONGJUMP else Animations.FAST_LONGJUMP m:PlayMarioSound(Sounds.ACTION_TERRAIN_JUMP, Sounds.MARIO_YAHOO) commonAirActionStep(m, Action.LONG_JUMP_LAND, anim, AirStep.CHECK_LEDGE_GRAB) return false end) DEF_ACTION(Action.TWIRLING, function(m: Mario) local startTwirlYaw = m.TwirlYaw local yawVelTarget = 0x1000 if m.Input:Has(InputFlags.A_DOWN) then yawVelTarget = 0x2000 end local yVel = Util.ApproachInt(m.AngleVel.Y, yawVelTarget, 0x200) m.AngleVel = Util.SetY(m.AngleVel, yVel) m.TwirlYaw += yVel m:SetAnimation(if m.ActionArg == 0 then Animations.START_TWIRL else Animations.TWIRL) if m:IsAnimPastEnd() then m.ActionArg = 1 end if startTwirlYaw > m.TwirlYaw then m:PlaySound(Sounds.ACTION_TWIRL) end local step = m:PerformAirStep() if step == AirStep.LANDED then m:SetAction(Action.TWIRL_LAND) elseif step == AirStep.HIT_WALL then m:BonkReflection(false) elseif step == AirStep.HIT_LAVA_WALL then lavaBoostOnWall(m) end m.GfxAngle += Vector3int16.new(0, m.TwirlYaw, 0) return false end) DEF_ACTION(Action.DIVE, function(m: Mario) local airStep if m.ActionArg == 0 then m:PlayMarioSound(Sounds.ACTION_THROW, Sounds.MARIO_HOOHOO) else m:PlayMarioSound(Sounds.ACTION_TERRAIN_JUMP) end m:SetAnimation(Animations.DIVE) updateAirWithoutTurn(m) airStep = m:PerformAirStep() if airStep == AirStep.NONE then if m.Velocity.Y < 0 and m.FaceAngle.X > -0x2AAA then m.FaceAngle -= Vector3int16.new(0x200, 0, 0) if m.FaceAngle.X < -0x2AAA then m.FaceAngle = Util.SetX(m.FaceAngle, -0x2AAA) end end m.GfxAngle = Util.SetX(m.GfxAngle, -m.FaceAngle.X) elseif airStep == AirStep.LANDED then if not checkFallDamage(m, Action.HARD_FORWARD_GROUND_KB) then m:SetAction(Action.DIVE_SLIDE) end m.FaceAngle *= Vector3int16.new(0, 1, 1) elseif airStep == AirStep.HIT_WALL then m:BonkReflection(true) m.FaceAngle *= Vector3int16.new(0, 1, 1) stopRising(m) m.ParticleFlags:Add(ParticleFlags.VERTICAL_STAR) m:SetAction(Action.BACKWARD_AIR_KB) elseif airStep == AirStep.HIT_LAVA_WALL then lavaBoostOnWall(m) end return false end) DEF_ACTION(Action.WATER_JUMP, function(m: Mario) if m.ForwardVel < 15 then m:SetForwardVel(15) end m:PlaySound(Sounds.ACTION_WATER_EXIT) m:SetAnimation(Animations.SINGLE_JUMP) local step = m:PerformAirStep(AirStep.CHECK_LEDGE_GRAB) if step == AirStep.LANDED then m:SetAction(Action.JUMP_LAND) elseif step == AirStep.HIT_WALL then m:SetForwardVel(15) elseif step == AirStep.GRABBED_LEDGE then m:SetAnimation(Animations.IDLE_ON_LEDGE) m:SetAction(Action.LEDGE_GRAB) elseif step == AirStep.HIT_LAVA_WALL then lavaBoostOnWall(m) end return false end) DEF_ACTION(Action.STEEP_JUMP, function(m: Mario) local airStep if m.Input:Has(InputFlags.B_PRESSED) then return m:SetAction(Action.DIVE) end m:PlayMarioSound(Sounds.ACTION_TERRAIN_JUMP) m:SetForwardVel(0.98 * m.ForwardVel) airStep = m:PerformAirStep() if airStep == AirStep.LANDED then if not checkFallDamage(m, Action.HARD_BACKWARD_GROUND_KB) then m.FaceAngle *= Vector3int16.new(0, 1, 1) m:SetAction(if m.ForwardVel < 0 then Action.BEGIN_SLIDING else Action.JUMP_LAND) end elseif airStep == AirStep.HIT_WALL then m:SetForwardVel(0) elseif airStep == AirStep.HIT_LAVA_WALL then lavaBoostOnWall(m) end m:SetAnimation(Animations.SINGLE_JUMP) m.GfxAngle = Util.SetY(m.GfxAngle, m.SteepJumpYaw) return false end) DEF_ACTION(Action.GROUND_POUND, function(m: Mario) local stepResult local yOffset m:PlaySoundIfNoFlag(Sounds.ACTION_THROW, MarioFlags.ACTION_SOUND_PLAYED) if m.ActionState == 0 then if m.ActionTimer < 10 then yOffset = 20 - 2 * m.ActionTimer if m.Position.Y + yOffset + 160 < m.CeilHeight then m.Position += Vector3.new(0, yOffset, 0) m.PeakHeight = m.Position.Y end end m.Velocity = Util.SetY(m.Velocity, -50) m:SetForwardVel(0) m:SetAnimation(if m.ActionArg == 0 then Animations.START_GROUND_POUND else Animations.TRIPLE_JUMP_GROUND_POUND) if m.ActionTimer == 0 then m:PlaySound(Sounds.ACTION_SPIN) end m.ActionTimer += 1 m.GfxAngle = Vector3int16.new(0, m.FaceAngle.Y, 0) if m.ActionTimer >= m.AnimFrameCount + 4 then m:PlaySound(Sounds.MARIO_GROUND_POUND_WAH) m.ActionState = 1 end else m:SetAnimation(Animations.GROUND_POUND) stepResult = m:PerformAirStep() if stepResult == AirStep.LANDED then m:PlayHeavyLandingSound(Sounds.ACTION_HEAVY_LANDING) if not checkFallDamage(m, Action.HARD_BACKWARD_GROUND_KB) then m.ParticleFlags:Add(ParticleFlags.MIST_CIRCLE, ParticleFlags.HORIZONTAL_STAR) m:SetAction(Action.GROUND_POUND_LAND) end elseif stepResult == AirStep.HIT_WALL then m:SetForwardVel(-16) stopRising(m) m.ParticleFlags:Add(ParticleFlags.VERTICAL_STAR) m:SetAction(Action.BACKWARD_AIR_KB) end end return false end) DEF_ACTION(Action.BURNING_JUMP, function(m: Mario) m:PlayMarioSound(Sounds.ACTION_TERRAIN_JUMP) m:SetForwardVel(m.ForwardVel) if m:PerformAirStep() == AirStep.LANDED then m:PlayLandingSound() m:SetAction(Action.BURNING_GROUND) end m:SetAnimation(Animations.GENERAL_FALL) m.ParticleFlags:Add(ParticleFlags.FIRE) m:PlaySound(Sounds.MOVING_LAVA_BURN) m.BurnTimer += 3 m.Health -= 10 if m.Health < 0x100 then m.Health = 0xFF end return false end) DEF_ACTION(Action.BURNING_FALL, function(m: Mario) m:SetForwardVel(m.ForwardVel) if m:PerformAirStep() == AirStep.LANDED then m:PlayLandingSound(Sounds.ACTION_TERRAIN_LANDING) m:SetAction(Action.BURNING_GROUND) end m:SetAnimation(Animations.GENERAL_FALL) m.ParticleFlags:Add(ParticleFlags.FIRE) m.BurnTimer += 3 m.Health -= 10 if m.Health < 0x100 then m.Health = 0xFF end return false end) DEF_ACTION(Action.BACKWARD_AIR_KB, function(m: Mario) if checkWallKick(m) then return true end playKnockbackSound(m) commonAirKnockbackStep( m, Action.BACKWARD_GROUND_KB, Action.HARD_BACKWARD_GROUND_KB, Animations.BACKWARD_AIR_KB, -16 ) return false end) DEF_ACTION(Action.FORWARD_AIR_KB, function(m: Mario) if checkWallKick(m) then return true end playKnockbackSound(m) commonAirKnockbackStep(m, Action.FORWARD_GROUND_KB, Action.HARD_FORWARD_GROUND_KB, Animations.FORWARD_AIR_KB, 16) return false end) DEF_ACTION(Action.HARD_BACKWARD_AIR_KB, function(m: Mario) if checkWallKick(m) then return true end playKnockbackSound(m) commonAirKnockbackStep( m, Action.HARD_BACKWARD_GROUND_KB, Action.HARD_BACKWARD_GROUND_KB, Animations.BACKWARD_AIR_KB, -16 ) return false end) DEF_ACTION(Action.HARD_FORWARD_AIR_KB, function(m: Mario) if checkWallKick(m) then return true end playKnockbackSound(m) commonAirKnockbackStep( m, Action.HARD_FORWARD_GROUND_KB, Action.HARD_FORWARD_GROUND_KB, Animations.FORWARD_AIR_KB, 16 ) return false end) DEF_ACTION(Action.THROWN_BACKWARD, function(m: Mario) local landAction = if m.ActionArg ~= 0 then Action.HARD_BACKWARD_GROUND_KB else Action.BACKWARD_GROUND_KB m:PlaySoundIfNoFlag(Sounds.MARIO_WAAAOOOW, MarioFlags.MARIO_SOUND_PLAYED) commonAirKnockbackStep(m, landAction, Action.HARD_BACKWARD_GROUND_KB, Animations.BACKWARD_AIR_KB, m.ForwardVel) m.ForwardVel *= 0.98 return false end) DEF_ACTION(Action.THROWN_FORWARD, function(m: Mario) local landAction = if m.ActionArg ~= 0 then Action.HARD_FORWARD_GROUND_KB else Action.FORWARD_GROUND_KB m:PlaySoundIfNoFlag(Sounds.MARIO_WAAAOOOW, MarioFlags.MARIO_SOUND_PLAYED) if commonAirKnockbackStep(m, landAction, Action.HARD_FORWARD_GROUND_KB, Animations.FORWARD_AIR_KB, m.ForwardVel) == AirStep.NONE then local pitch = Util.Atan2s(m.ForwardVel, -m.Velocity.Y) if pitch > 0x1800 then pitch = 0x1800 end m.GfxAngle = Util.SetX(m.GfxAngle, pitch + 0x1800) end m.ForwardVel *= 0.98 return false end) DEF_ACTION(Action.SOFT_BONK, function(m: Mario) if checkWallKick(m) then return true end playKnockbackSound(m) commonAirKnockbackStep( m, Action.FREEFALL_LAND, Action.HARD_BACKWARD_GROUND_KB, Animations.GENERAL_FALL, m.ForwardVel ) return false end) DEF_ACTION(Action.AIR_HIT_WALL, function(m: Mario) m.ActionTimer += 1 if m.ActionTimer <= 2 then if m.Input:Has(InputFlags.A_PRESSED) then m.Velocity = Util.SetY(m.Velocity, 52) m.FaceAngle += Vector3int16.new(0, 0x8000, 0) return m:SetAction(Action.WALL_KICK_AIR) end elseif m.ForwardVel >= 38 then m.WallKickTimer = 5 if m.Velocity.Y > 0 then m.Velocity = Util.SetY(m.Velocity, 0) end m.ParticleFlags:Add(ParticleFlags.VERTICAL_STAR) return m:SetAction(Action.BACKWARD_AIR_KB) else m.WallKickTimer = 5 if m.Velocity.Y > 0 then m.Velocity = Util.SetY(m.Velocity, 0) end if m.ForwardVel > 8 then m:SetForwardVel(-8) end return m:SetAction(Action.SOFT_BONK) end return m:SetAnimation(Animations.START_WALLKICK) > 0 end) DEF_ACTION(Action.FORWARD_ROLLOUT, function(m: Mario) commonRolloutStep(m, Animations.FORWARD_SPINNING) return false end) DEF_ACTION(Action.BACKWARD_ROLLOUT, function(m: Mario) commonRolloutStep(m, Animations.BACKWARD_SPINNING) return false end) DEF_ACTION(Action.BUTT_SLIDE_AIR, function(m: Mario) local stepResult m.ActionTimer += 1 if m.ActionTimer > 30 and m.Position.Y - m.FloorHeight > 500 then return m:SetAction(Action.FREEFALL, 1) end updateAirWithTurn(m) stepResult = m:PerformAirStep() if stepResult == AirStep.LANDED then if m.ActionState == 0 and m.Velocity.Y < 0 then local floor = m.Floor if floor and floor.Normal.Y > 0.9848077 then m.Velocity *= Vector3.new(1, -0.5, 1) m.ActionState = 1 else m:SetAction(Action.BUTT_SLIDE) end else m:SetAction(Action.BUTT_SLIDE) end m:PlayLandingSound() elseif stepResult == AirStep.HIT_WALL then stopRising(m) m.ParticleFlags:Add(ParticleFlags.VERTICAL_STAR) m:SetAction(Action.BACKWARD_AIR_KB) elseif stepResult == AirStep.HIT_LAVA_WALL then lavaBoostOnWall(m) end m:SetAnimation(Animations.SLIDE) return false end) DEF_ACTION(Action.LAVA_BOOST, function(m: Mario) local stepResult m:PlaySoundIfNoFlag(Sounds.MARIO_ON_FIRE, MarioFlags.MARIO_SOUND_PLAYED) if not m.Input:Has(InputFlags.NONZERO_ANALOG) then m.ForwardVel = Util.ApproachFloat(m.ForwardVel, 0, 0.35) end updateLavaBoostOrTwirling(m) stepResult = m:PerformAirStep() if stepResult == AirStep.LANDED then local floor = m.Floor local floorType: Enum.Material? if floor then floorType = floor.Material end if floorType == Enum.Material.CrackedLava then m.ActionState = 0 if not m.Flags:Has(MarioFlags.METAL_CAP) then m.HurtCounter += if m.Flags:Has(MarioFlags.CAP_ON_HEAD) then 12 else 18 end m.Velocity = Util.SetY(m.Velocity, 84) m:PlaySound(Sounds.MARIO_ON_FIRE) else m:PlayHeavyLandingSound(Sounds.ACTION_TERRAIN_BODY_HIT_GROUND) if m.ActionState < 2 and m.Velocity.Y < 0 then m.Velocity *= Vector3.new(1, -0.4, 1) m:SetForwardVel(m.ForwardVel / 2) m.ActionState += 1 else m:SetAction(Action.LAVA_BOOST_LAND) end end elseif stepResult == AirStep.HIT_WALL then m:BonkReflection() elseif stepResult == AirStep.HIT_LAVA_WALL then lavaBoostOnWall(m) end m:SetAnimation(Animations.FIRE_LAVA_BURN) if not m.Flags:Has(MarioFlags.METAL_CAP) and m.Velocity.Y > 0 then m.ParticleFlags:Add(ParticleFlags.FIRE) if m.ActionState == 0 then m:PlaySound(Sounds.MOVING_LAVA_BURN) end end m.BodyState.EyeState = MarioEyes.DEAD return false end) DEF_ACTION(Action.SLIDE_KICK, function(m: Mario) local stepResult if m.ActionState == 0 and m.ActionTimer == 0 then m:PlayMarioSound(Sounds.ACTION_TERRAIN_JUMP, Sounds.MARIO_HOOHOO) m:SetAnimation(Animations.SLIDE_KICK) end m.ActionTimer += 1 if m.ActionTimer > 30 and m.Position.Y - m.FloorHeight > 500 then return m:SetAction(Action.FREEFALL, 2) end updateAirWithoutTurn(m) stepResult = m:PerformAirStep() if stepResult == AirStep.NONE then if m.ActionState == 0 then local tilt = Util.Atan2s(m.ForwardVel, -m.Velocity.Y) if tilt > 0x1800 then tilt = 0x1800 end m.GfxAngle = Util.SetX(m.GfxAngle, tilt) end elseif stepResult == AirStep.LANDED then if m.ActionState == 0 and m.Velocity.Y < 0 then m.Velocity *= Vector3.new(1, -0.5, 1) m.ActionState = 1 m.ActionTimer = 0 else m:SetAction(Action.SLIDE_KICK_SLIDE) end m:PlayLandingSound() elseif stepResult == AirStep.HIT_WALL then stopRising(m) m.ParticleFlags:Add(ParticleFlags.VERTICAL_STAR) m:SetAction(Action.BACKWARD_AIR_KB) elseif stepResult == AirStep.HIT_LAVA_WALL then lavaBoostOnWall(m) end return false end) DEF_ACTION(Action.JUMP_KICK, function(m: Mario) local stepResult if m.ActionState == 0 then m:PlaySoundIfNoFlag(Sounds.MARIO_PUNCH_HOO, MarioFlags.MARIO_SOUND_PLAYED) m.AnimReset = true m:SetAnimation(Animations.AIR_KICK) m.ActionState = 1 end local animFrame = m.AnimFrame if animFrame == 0 then m.BodyState.PunchType = 2 m.BodyState.PunchTimer = 6 end if animFrame >= 0 and animFrame < 8 then m.Flags:Add(MarioFlags.KICKING) end updateAirWithoutTurn(m) stepResult = m:PerformAirStep() if stepResult == AirStep.LANDED then if not checkFallDamage(m, Action.HARD_BACKWARD_GROUND_KB) then m:SetAction(Action.FREEFALL_LAND) end elseif stepResult == AirStep.HIT_WALL then m:SetForwardVel(0) end return false end) DEF_ACTION(Action.FLYING, function(m: Mario) local startPitch = m.FaceAngle.X if m.Input:Has(InputFlags.Z_PRESSED) then return m:SetAction(Action.GROUND_POUND) end if not m.Flags:Has(MarioFlags.WING_CAP) then return m:SetAction(Action.FREEFALL) end if m.ActionState == 0 then if m.ActionArg == 0 then m:SetAnimation(Animations.FLY_FROM_CANNON) else m:SetAnimation(Animations.FORWARD_SPINNING_FLIP) if m.AnimFrame == 1 then m:PlaySound(Sounds.ACTION_SPIN) end end if m:IsAnimAtEnd() then m:SetAnimation(Animations.WING_CAP_FLY) m.ActionState = 1 end end local stepResult do updateFlying(m) stepResult = m:PerformAirStep() end if stepResult == AirStep.NONE then m.GfxAngle = Util.SetX(m.GfxAngle, -m.FaceAngle.X) m.GfxAngle = Util.SetZ(m.GfxAngle, m.FaceAngle.Z) m.ActionTimer = 0 elseif stepResult == AirStep.LANDED then m:SetAction(Action.DIVE_SLIDE) m:SetAnimation(Animations.DIVE) m:SetAnimToFrame(7) m.FaceAngle *= Vector3int16.new(0, 1, 1) elseif stepResult == AirStep.HIT_WALL then if m.Wall then m:SetForwardVel(-16) m.FaceAngle *= Vector3int16.new(0, 1, 1) stopRising(m) m:PlaySound(if m.Flags:Has(MarioFlags.METAL_CAP) then Sounds.ACTION_METAL_BONK else Sounds.ACTION_BONK) m.ParticleFlags:Add(ParticleFlags.VERTICAL_STAR) m:SetAction(Action.BACKWARD_AIR_KB) else m.ActionTimer += 1 if m.ActionTimer == 0 then m:PlaySound(Sounds.ACTION_HIT) end if m.ActionTimer == 30 then m.ActionTimer = 0 end m.FaceAngle -= Vector3int16.new(0x200, 0, 0) if m.FaceAngle.X < -0x2AAA then m.FaceAngle = Util.SetX(m.FaceAngle, -0x2AAA) end m.GfxAngle = Util.SetX(m.GfxAngle, -m.FaceAngle.X) m.GfxAngle = Util.SetZ(m.GfxAngle, m.FaceAngle.Z) end elseif stepResult == AirStep.HIT_LAVA_WALL then lavaBoostOnWall(m) end if m.FaceAngle.X > 0x800 and m.ForwardVel >= 48 then m.ParticleFlags:Add(ParticleFlags.DUST) end if startPitch <= 0 and m.FaceAngle.X > 0 and m.ForwardVel >= 48 then m:PlaySound(Sounds.ACTION_FLYING_FAST) m:PlaySound(Sounds.MARIO_YAHOO_WAHA_YIPPEE) end m:PlaySound(Sounds.MOVING_FLYING) m:AdjustSoundForSpeed() return false end) DEF_ACTION(Action.FLYING_TRIPLE_JUMP, function(m: Mario) if m.Input:Has(InputFlags.B_PRESSED) then return m:SetAction(Action.DIVE) end if m.Input:Has(InputFlags.Z_PRESSED) then return m:SetAction(Action.GROUND_POUND) end m:PlayMarioSound(Sounds.ACTION_TERRAIN_JUMP, Sounds.MARIO_YAHOO) if m.ActionState == 0 then m:SetAnimation(Animations.TRIPLE_JUMP_FLY) if m.AnimFrame == 7 then m:PlaySound(Sounds.ACTION_SPIN) end if m:IsAnimPastEnd() then m:SetAnimation(Animations.FORWARD_SPINNING) m.ActionState = 1 end end if m.ActionState == 1 and m.AnimFrame == 1 then m:PlaySound(Sounds.ACTION_SPIN) end if m.Velocity.Y < 4 then if m.ForwardVel < 32 then m:SetForwardVel(32) end m:SetAction(Action.FLYING, 1) end m.ActionTimer += 1 local stepResult do updateAirWithoutTurn(m) stepResult = m:PerformAirStep() end if stepResult == AirStep.LANDED then if not checkFallDamage(m, Action.HARD_BACKWARD_GROUND_KB) then m:SetAction(Action.DOUBLE_JUMP_LAND) end elseif stepResult == AirStep.HIT_WALL then m:BonkReflection() elseif stepResult == AirStep.HIT_LAVA_WALL then lavaBoostOnWall(m) end return false end) DEF_ACTION(Action.SPAWN_SPIN_AIRBORNE, function(m: Mario) m:SetForwardVel(m.ForwardVel) if m:PerformAirStep() == AirStep.LANDED then m:PlayLandingSound(Sounds.ACTION_TERRAIN_LANDING) m:SetAction(Action.SPAWN_SPIN_LANDING) end if m.ActionState == 0 and m.Position.Y - m.FloorHeight > 300 then if m:SetAnimation(Animations.FORWARD_SPINNING) == 0 then m:PlaySound(Sounds.ACTION_SPIN) end else m.ActionState = 1 m:SetAnimation(Animations.GENERAL_FALL) end return false end) DEF_ACTION(Action.SPAWN_SPIN_LANDING, function(m: Mario) m:StopAndSetHeightToFloor() m:SetAnimation(Animations.GENERAL_LAND) if m:IsAnimAtEnd() then m:SetAction(Action.IDLE) end return false end) -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
10,003
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Mario/Automatic/init.server.lua
--!strict local System = require(script.Parent) local Animations = System.Animations local Sounds = System.Sounds local Enums = System.Enums local Util = System.Util local Action = Enums.Action local ActionFlags = Enums.ActionFlags local ActionGroup = Enums.ActionGroups local AirStep = Enums.AirStep local MarioEyes = Enums.MarioEyes local InputFlags = Enums.InputFlags local MarioFlags = Enums.MarioFlags local ParticleFlags = Enums.ParticleFlags type Mario = System.Mario ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -- Helpers ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- local function letGoOfLedge(m: Mario) local floorHeight m.Velocity *= Vector3.new(1, 0, 1) m.ForwardVel = -8 local x = 60 * Util.Sins(m.FaceAngle.Y) local z = 60 * Util.Coss(m.FaceAngle.Y) m.Position -= Vector3.new(x, 0, z) floorHeight = Util.FindFloor(m.Position) if floorHeight < m.Position.Y - 100 then m.Position -= (Vector3.yAxis * 100) else m.Position = Util.SetY(m.Position, floorHeight) end return m:SetAction(Action.SOFT_BONK) end local function climbUpLedge(m: Mario) local x = 14 * Util.Sins(m.FaceAngle.Y) local z = 14 * Util.Coss(m.FaceAngle.Y) m:SetAnimation(Animations.IDLE_HEAD_LEFT) m.Position += Vector3.new(x, 0, z) end local function updateLedgeClimb(m: Mario, anim: Animation, endAction: number) m:StopAndSetHeightToFloor() m:SetAnimation(anim) if m:IsAnimAtEnd() then m:SetAction(endAction) if endAction == Action.IDLE then climbUpLedge(m) end end end ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -- Actions ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- local DEF_ACTION: (number, (Mario) -> boolean) -> () = System.RegisterAction DEF_ACTION(Action.LEDGE_GRAB, function(m: Mario) local intendedDYaw = m.IntendedYaw - m.FaceAngle.Y local hasSpaceForMario = m.CeilHeight - m.FloorHeight >= 160 if m.ActionTimer < 10 then m.ActionTimer += 1 end if m.Floor and m.Floor.Normal.Y < 0.9063078 then return letGoOfLedge(m) end if m.Input:Has(InputFlags.Z_PRESSED, InputFlags.OFF_FLOOR) then return letGoOfLedge(m) end if m.Input:Has(InputFlags.A_PRESSED) and hasSpaceForMario then return m:SetAction(Action.LEDGE_CLIMB_FAST) end if m.Input:Has(InputFlags.STOMPED) then return letGoOfLedge(m) end if m.ActionTimer == 10 and m.Input:Has(InputFlags.NONZERO_ANALOG) then if math.abs(intendedDYaw) <= 0x4000 then if hasSpaceForMario then return m:SetAction(Action.LEDGE_CLIMB_SLOW) end else return letGoOfLedge(m) end end local heightAboveFloor = m.Position.Y - m:FindFloorHeightRelativePolar(-0x8000, 30) if hasSpaceForMario and heightAboveFloor < 100 then return m:SetAction(Action.LEDGE_CLIMB_FAST) end if m.ActionArg == 0 then m:PlaySoundIfNoFlag(Sounds.MARIO_WHOA, MarioFlags.MARIO_SOUND_PLAYED) end m:StopAndSetHeightToFloor() m:SetAnimation(Animations.IDLE_ON_LEDGE) return false end) DEF_ACTION(Action.LEDGE_CLIMB_SLOW, function(m: Mario) if m.Input:Has(InputFlags.OFF_FLOOR) then return letGoOfLedge(m) end if m.ActionTimer >= 28 then if m.Input:Has(InputFlags.NONZERO_ANALOG, InputFlags.A_PRESSED, InputFlags.OFF_FLOOR, InputFlags.ABOVE_SLIDE) then climbUpLedge(m) return m:CheckCommonActionExits() end end if m.ActionTimer == 10 then m:PlaySoundIfNoFlag(Sounds.MARIO_EEUH, MarioFlags.MARIO_SOUND_PLAYED) end updateLedgeClimb(m, Animations.SLOW_LEDGE_GRAB, Action.IDLE) return false end) DEF_ACTION(Action.LEDGE_CLIMB_DOWN, function(m: Mario) if m.Input:Has(InputFlags.OFF_FLOOR) then return letGoOfLedge(m) end m:PlaySoundIfNoFlag(Sounds.MARIO_WHOA, MarioFlags.MARIO_SOUND_PLAYED) updateLedgeClimb(m, Animations.CLIMB_DOWN_LEDGE, Action.LEDGE_GRAB) m.ActionArg = 1 return false end) DEF_ACTION(Action.LEDGE_CLIMB_FAST, function(m: Mario) if m.Input:Has(InputFlags.OFF_FLOOR) then return letGoOfLedge(m) end m:PlaySoundIfNoFlag(Sounds.MARIO_UH2, MarioFlags.MARIO_SOUND_PLAYED) updateLedgeClimb(m, Animations.FAST_LEDGE_GRAB, Action.IDLE) if m.AnimFrame == 8 then m:PlayLandingSound(Sounds.ACTION_TERRAIN_LANDING) end return false end)
1,213
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Mario/Submerged/init.server.lua
local System = require(script.Parent) local Animations = System.Animations local Sounds = System.Sounds local Enums = System.Enums local Util = System.Util local Action = Enums.Action local AirStep = Enums.AirStep local WaterStep = Enums.WaterStep local GroundStep = Enums.GroundStep local InputFlags = Enums.InputFlags local MarioFlags = Enums.MarioFlags local ActionFlags = Enums.ActionFlags local ParticleFlags = Enums.ParticleFlags local MIN_SWIM_STRENGTH = 160 local MIN_SWIM_SPEED = 16 local sWasAtSurface = false local sSwimStrength = MIN_SWIM_STRENGTH local sBobTimer = 0 local sBobIncrement = 0 local sBobHeight = 0 type Mario = System.Mario local function setSwimmingAtSurfaceParticles(m: Mario, particleFlag: number) local atSurface = m.Position.Y >= m.WaterLevel - 130 if atSurface then m.ParticleFlags:Add(particleFlag) if atSurface ~= sWasAtSurface then m:PlaySound(Sounds.ACTION_UNKNOWN431) end end sWasAtSurface = atSurface end local function swimmingNearSurface(m: Mario) if m.Flags:Has(MarioFlags.METAL_CAP) then return false end return (m.WaterLevel - 80) - m.Position.Y < 400 end local function getBuoyancy(m: Mario) local buoyancy = 0 if m.Flags:Has(MarioFlags.METAL_CAP) then if m.Action:Has(ActionFlags.INVULNERABLE) then buoyancy = -2 else buoyancy = -18 end elseif swimmingNearSurface(m) then buoyancy = 1.25 elseif not m.Action:Has(ActionFlags.MOVING) then buoyancy = -2 end return buoyancy end local function performWaterFullStep(m: Mario, nextPos: Vector3) local adjusted, wall = Util.FindWallCollisions(nextPos, 10, 110) nextPos = adjusted local floorHeight, floor = Util.FindFloor(nextPos) local ceilHeight = Util.FindCeil(nextPos, floorHeight) if floor == nil then return WaterStep.CANCELLED end if nextPos.Y >= floorHeight then if ceilHeight - nextPos.Y >= 160 then m.Position = nextPos m.Floor = floor m.FloorHeight = floorHeight if wall then return WaterStep.HIT_WALL else return WaterStep.NONE end end if ceilHeight - floorHeight < 160 then return WaterStep.CANCELLED end --! Water ceiling downwarp m.Position = Util.SetY(nextPos, ceilHeight - 160) m.Floor = floor m.FloorHeight = floorHeight return WaterStep.HIT_CEILING else if ceilHeight - floorHeight < 160 then return WaterStep.CANCELLED end m.Position = Util.SetY(nextPos, floorHeight) m.Floor = floor m.FloorHeight = floorHeight return WaterStep.HIT_FLOOR end end local function applyWaterCurrent(m: Mario, step: Vector3): Vector3 -- TODO: Implement if actually needed. -- This normally handles whirlpools and moving -- water, neither of which I think I'll be using. return step end local function performWaterStep(m: Mario) local nextPos = m.Position local step = m.Velocity if m.Action:Has(ActionFlags.SWIMMING) then step = applyWaterCurrent(m, step) end nextPos += step if nextPos.Y > m.WaterLevel - 80 then nextPos = Util.SetY(nextPos, m.WaterLevel - 80) m.Velocity *= Vector3.new(1, 0, 1) end local stepResult = performWaterFullStep(m, nextPos) m.GfxAngle = m.FaceAngle * Vector3int16.new(-1, 1, 1) m.GfxPos = m.Position return stepResult end local function updateWaterPitch(m: Mario) local gfxAngle = m.GfxAngle if gfxAngle.X > 0 then local angle = 60 * Util.Sins(gfxAngle.X) * Util.Sins(gfxAngle.X) m.GfxPos += Vector3.new(0, angle, 0) end if gfxAngle.X < 0 then local x = gfxAngle.X * 6 / 10 gfxAngle = Util.SetX(gfxAngle, x) end if gfxAngle.X > 0 then local x = gfxAngle.X * 10 / 8 gfxAngle = Util.SetX(gfxAngle, x) end m.GfxAngle = gfxAngle end local function stationarySlowDown(m: Mario) local buoyancy = getBuoyancy(m) m.AngleVel *= Vector3int16.new(0, 0, 1) m.ForwardVel = Util.ApproachFloat(m.ForwardVel, 0, 1, 1) local faceY = m.FaceAngle.Y local faceX = Util.ApproachInt(m.FaceAngle.X, 0, 0x200, 0x200) local faceZ = Util.ApproachInt(m.FaceAngle.Z, 0, 0x100, 0x100) local velY = Util.ApproachFloat(m.Velocity.Y, buoyancy, 2, 1) local velX = m.ForwardVel * Util.Coss(faceX) * Util.Sins(faceY) local velZ = m.ForwardVel * Util.Coss(faceX) * Util.Coss(faceY) m.FaceAngle = Vector3int16.new(faceX, faceY, faceZ) m.Velocity = Vector3.new(velX, velY, velZ) end local function updateSwimmingSpeed(m: Mario, maybeDecelThreshold: number?) local buoyancy = getBuoyancy(m) local decelThreshold = maybeDecelThreshold or MIN_SWIM_SPEED if m.Action:Has(ActionFlags.STATIONARY) then m.ForwardVel -= 2 end m.ForwardVel = math.clamp(m.ForwardVel, 0, 28) if m.ForwardVel > decelThreshold then m.ForwardVel -= 0.5 end m.Velocity = Vector3.new( m.ForwardVel * Util.Coss(m.FaceAngle.X) * Util.Sins(m.FaceAngle.Y), m.ForwardVel * Util.Sins(m.FaceAngle.X) + buoyancy, m.ForwardVel * Util.Coss(m.FaceAngle.X) * Util.Coss(m.FaceAngle.Y) ) end local function updateSwimmingYaw(m: Mario) local targetYawVel = -Util.SignedShort(10 * m.Controller.StickX) if targetYawVel > 0 then if m.AngleVel.Y < 0 then m.AngleVel += Vector3int16.new(0, 0x40, 0) if m.AngleVel.Y > 0x10 then m.AngleVel = Util.SetY(m.AngleVel, 0x10) end else local velY = Util.ApproachInt(m.AngleVel.Y, targetYawVel, 0x10, 0x20) m.AngleVel = Util.SetY(m.AngleVel, velY) end elseif targetYawVel < 0 then if m.AngleVel.Y > 0 then m.AngleVel -= Vector3int16.new(0, 0x40, 0) if m.AngleVel.Y < -0x10 then m.AngleVel = Util.SetY(m.AngleVel, -0x10) end else local velY = Util.ApproachInt(m.AngleVel.Y, targetYawVel, 0x20, 0x10) m.AngleVel = Util.SetY(m.AngleVel, velY) end else local velY = Util.ApproachInt(m.AngleVel.Y, 0, 0x40, 0x40) m.AngleVel = Util.SetY(m.AngleVel, velY) end m.FaceAngle += Vector3int16.new(0, m.AngleVel.Y, 0) m.FaceAngle = Util.SetZ(m.FaceAngle, -m.AngleVel.Y * 8) end local function updateSwimmingPitch(m: Mario) local targetPitch = -Util.SignedShort(252 * m.Controller.StickY) -- stylua: ignore local pitchVel = if m.FaceAngle.X < 0 then 0x100 else 0x200 if m.FaceAngle.X < targetPitch then m.FaceAngle += Vector3int16.new(pitchVel, 0, 0) if m.FaceAngle.X > targetPitch then m.FaceAngle = Util.SetX(m.FaceAngle, targetPitch) end elseif m.FaceAngle.X > targetPitch then m.FaceAngle -= Vector3int16.new(pitchVel, 0, 0) if m.FaceAngle.X < targetPitch then m.FaceAngle = Util.SetX(m.FaceAngle, targetPitch) end end end local function commonIdleStep(m: Mario, anim: Animation, maybeAccel: number?) local accel = maybeAccel or 0 local bodyState = m.BodyState local headAngleX = bodyState.HeadAngle.X updateSwimmingYaw(m) updateSwimmingPitch(m) updateSwimmingSpeed(m) performWaterStep(m) updateWaterPitch(m) if m.FaceAngle.X > 0 then headAngleX = Util.ApproachInt(headAngleX, m.FaceAngle.X / 2, 0x80, 0x200) else headAngleX = Util.ApproachInt(headAngleX, 0, 0x200, 0x200) end if accel == 0 then m:SetAnimation(anim) else m:SetAnimationWithAccel(anim, accel) end setSwimmingAtSurfaceParticles(m, ParticleFlags.IDLE_WATER_WAVE) end local function resetBobVariables(m: Mario) sBobTimer = 0 sBobIncrement = 0x800 sBobHeight = m.FaceAngle.X / 256 + 20 end local function surfaceSwimBob(m: Mario) if sBobIncrement ~= 0 and m.Position.Y > m.WaterLevel - 85 and m.FaceAngle.Y >= 0 then sBobTimer += sBobIncrement if sBobTimer >= 0 then m.GfxPos += Vector3.new(0, sBobHeight * Util.Sins(sBobTimer), 0) return end end sBobIncrement = 0 end local function commonSwimmingStep(m: Mario, swimStrength: number) local waterStep updateSwimmingYaw(m) updateSwimmingPitch(m) updateSwimmingSpeed(m, swimStrength / 10) -- do water step waterStep = performWaterStep(m) if waterStep == WaterStep.HIT_FLOOR then local floorPitch = -m:FindFloorSlope(-0x8000) if m.FaceAngle.X < floorPitch then m.FaceAngle = Util.SetX(m.FaceAngle, floorPitch) end elseif waterStep == WaterStep.HIT_CEILING then if m.FaceAngle.Y > -0x3000 then m.FaceAngle -= Vector3int16.new(0, 0x100, 0) end elseif waterStep == WaterStep.HIT_WALL then if m.Controller.StickY == 0 then if m.FaceAngle.X > 0 then m.FaceAngle += Vector3int16.new(0x200, 0, 0) if m.FaceAngle.X > 0x3F00 then m.FaceAngle = Util.SetX(m.FaceAngle, 0x3F00) end else m.FaceAngle -= Vector3int16.new(0x200, 0, 0) if m.FaceAngle.X < -0x3F00 then m.FaceAngle = Util.SetX(m.FaceAngle, -0x3F00) end end end end local headAngle = m.BodyState.HeadAngle updateWaterPitch(m) local angleX = Util.ApproachInt(headAngle.X, 0, 0x200, 0x200) m.BodyState.HeadAngle = Util.SetX(headAngle, angleX) surfaceSwimBob(m) setSwimmingAtSurfaceParticles(m, ParticleFlags.WAVE_TRAIL) end local function playSwimmingNoise(m: Mario) local animFrame = m.AnimFrame if animFrame == 0 or animFrame == 12 then m:PlaySound(Sounds.ACTION_SWIM_KICK) end end local function checkWaterJump(m: Mario) local probe = Util.SignedInt(m.Position.Y + 1.5) if m.Input:Has(InputFlags.A_PRESSED) then if probe >= m.WaterLevel - 80 and m.FaceAngle.X >= 0 and m.Controller.StickY < -60 then m.AngleVel = Vector3int16.new() m.Velocity = Util.SetY(m.Velocity, 62) return m:SetAction(Action.WATER_JUMP) end end return false end local function playMetalWaterJumpingSound(m: Mario, landing: boolean) if not m.Flags:Has(MarioFlags.ACTION_SOUND_PLAYED) then m.ParticleFlags:Add(ParticleFlags.MIST_CIRCLE) end m:PlaySoundIfNoFlag( landing and Sounds.ACTION_METAL_LAND_WATER or Sounds.ACTION_METAL_JUMP_WATER, MarioFlags.ACTION_SOUND_PLAYED ) end local function playMetalWaterWalkingSound(m: Mario) if m:IsAnimPastFrame(10) or m:IsAnimPastFrame(49) then m:PlaySound(Sounds.ACTION_METAL_STEP_WATER) m.ParticleFlags:Add(ParticleFlags.DUST) end end local function updateMetalWaterWalkingSpeed(m: Mario) local val = m.IntendedMag / 1.5 local floor = m.Floor if m.ForwardVel <= 0 then m.ForwardVel += 1.1 elseif m.ForwardVel <= val then m.ForwardVel += 1.1 - m.ForwardVel / 43 elseif floor and floor.Normal.Y >= 0.95 then m.ForwardVel -= 1 end if m.ForwardVel > 32 then m.ForwardVel = 32 end local faceY = m.IntendedYaw - Util.ApproachInt(Util.SignedShort(m.IntendedYaw - m.FaceAngle.Y), 0, 0x800, 0x800) m.FaceAngle = Util.SetY(m.FaceAngle, faceY) m.SlideVelX = m.ForwardVel * Util.Sins(faceY) m.SlideVelZ = m.ForwardVel * Util.Coss(faceY) m.Velocity = Vector3.new(m.SlideVelX, 0, m.SlideVelZ) end local function updateMetalWaterJumpSpeed(m: Mario) local waterSurface = m.WaterLevel - 100 if m.Velocity.Y > 0 and m.Position.Y > waterSurface then return true end if m.Input:Has(InputFlags.NONZERO_ANALOG) then local intendedDYaw = Util.SignedShort(m.IntendedYaw - m.FaceAngle.Y) m.ForwardVel += 0.8 * Util.Coss(intendedDYaw) m.FaceAngle += Vector3int16.new(0, 0x200 * Util.Sins(intendedDYaw), 0) else m.ForwardVel = Util.ApproachFloat(m.ForwardVel, 0, 0.25, 0.25) end if m.ForwardVel > 16 then m.ForwardVel -= 1 end if m.ForwardVel < 0 then m.ForwardVel += 2 end local velY = m.Velocity.Y local velX = m.ForwardVel * Util.Sins(m.FaceAngle.Y) local velZ = m.ForwardVel * Util.Coss(m.FaceAngle.Y) m.SlideVelX = velX m.SlideVelZ = velZ m.Velocity = Vector3.new(velX, velY, velZ) return false end ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- local DEF_ACTION: (number, (Mario) -> boolean) -> () = System.RegisterAction DEF_ACTION(Action.WATER_IDLE, function(m: Mario) local val = 0x10000 if m.Flags:Has(MarioFlags.METAL_CAP) then return m:SetAction(Action.METAL_WATER_FALLING, 1) end if m.Input:Has(InputFlags.B_PRESSED) then return m:SetAction(Action.WATER_PUNCH) end if m.Input:Has(InputFlags.A_PRESSED) then return m:SetAction(Action.BREASTSTROKE) end if m.FaceAngle.X < -0x1000 then val = 0x30000 end commonIdleStep(m, Animations.WATER_IDLE, val) return false end) DEF_ACTION(Action.WATER_ACTION_END, function(m: Mario) if m.Flags:Has(MarioFlags.METAL_CAP) then return m:SetAction(Action.METAL_WATER_FALLING, 1) end if m.Input:Has(InputFlags.B_PRESSED) then return m:SetAction(Action.WATER_PUNCH) end if m.Input:Has(InputFlags.A_PRESSED) then return m:SetAction(Action.BREASTSTROKE) end commonIdleStep(m, Animations.WATER_ACTION_END) if m:IsAnimAtEnd() then m:SetAction(Action.WATER_IDLE) end return false end) DEF_ACTION(Action.BREASTSTROKE, function(m: Mario) if m.ActionArg == 0 then sSwimStrength = MIN_SWIM_STRENGTH end if m.Flags:Has(MarioFlags.METAL_CAP) then return m:SetAction(Action.METAL_WATER_FALLING, 1) end if m.Input:Has(InputFlags.B_PRESSED) then return m:SetAction(Action.WATER_PUNCH) end m.ActionTimer += 1 if m.ActionTimer == 14 then return m:SetAction(Action.FLUTTER_KICK) end if checkWaterJump(m) then return true end if m.ActionTimer < 6 then m.ForwardVel += 0.5 end if m.ActionTimer >= 9 then m.ForwardVel += 1.5 end if m.ActionTimer >= 2 then if m.ActionTimer < 6 and m.Input:Has(InputFlags.A_PRESSED) then m.ActionState = 1 end if m.ActionTimer == 9 and m.ActionState == 1 then m:SetAnimToFrame(0) m.ActionState = 0 m.ActionTimer = 1 sSwimStrength = MIN_SWIM_STRENGTH end end if m.ActionTimer == 1 then m:PlaySound(sSwimStrength == MIN_SWIM_STRENGTH and Sounds.ACTION_SWIM or Sounds.ACTION_SWIM_FAST) resetBobVariables(m) end m:SetAnimation(Animations.SWIM_PART1) commonSwimmingStep(m, sSwimStrength) return false end) DEF_ACTION(Action.SWIMMING_END, function(m: Mario) if m.Flags:Has(MarioFlags.METAL_CAP) then return m:SetAction(Action.METAL_WATER_FALLING, 1) end if m.Input:Has(InputFlags.B_PRESSED) then return m:SetAction(Action.WATER_PUNCH) end if m.ActionTimer >= 15 then return m:SetAction(Action.WATER_ACTION_END) end if checkWaterJump(m) then return true end if m.Input:Has(InputFlags.A_DOWN) and m.ActionTimer >= 7 then if m.ActionTimer == 7 and sSwimStrength < 280 then sSwimStrength += 10 end return m:SetAction(Action.BREASTSTROKE, 1) end if m.ActionTimer >= 7 then sSwimStrength = MIN_SWIM_STRENGTH end m.ActionTimer += 1 m.ForwardVel -= 0.25 m:SetAnimation(Animations.SWIM_PART2) commonSwimmingStep(m, sSwimStrength) return false end) DEF_ACTION(Action.FLUTTER_KICK, function(m: Mario) if m.Flags:Has(MarioFlags.METAL_CAP) then return m:SetAction(Action.METAL_WATER_FALLING, 1) end if m.Input:Has(InputFlags.B_PRESSED) then return m:SetAction(Action.WATER_PUNCH) end if not m.Input:Has(InputFlags.A_DOWN) then if m.ActionTimer == 0 and sSwimStrength < 280 then sSwimStrength += 10 end return m:SetAction(Action.SWIMMING_END) end m.ForwardVel = Util.ApproachFloat(m.ForwardVel, 12, 0.1, 0.15) m.ActionTimer = 1 sSwimStrength = MIN_SWIM_STRENGTH if m.ForwardVel < 14 then playSwimmingNoise(m) m:SetAnimation(Animations.FLUTTERKICK) end commonSwimmingStep(m, sSwimStrength) return false end) DEF_ACTION(Action.WATER_PUNCH, function(m: Mario) if m.ForwardVel < 7 then m.ForwardVel += 1 end updateSwimmingYaw(m) updateSwimmingPitch(m) updateSwimmingSpeed(m) performWaterStep(m) updateWaterPitch(m) local headAngle = m.BodyState.HeadAngle local angleX = Util.ApproachInt(headAngle.X, 0, 0x200, 0x200) m.BodyState.HeadAngle = Util.SetX(headAngle, angleX) m:PlaySoundIfNoFlag(Sounds.ACTION_SWIM, MarioFlags.ACTION_SOUND_PLAYED) if m.ActionState == 0 then m:SetAnimation(Animations.WATER_GRAB_OBJ_PART1) if m:IsAnimAtEnd() then m.ActionState = 1 end elseif m.ActionState == 1 then m:SetAnimation(Animations.WATER_GRAB_OBJ_PART2) if m:IsAnimAtEnd() then m:SetAction(Action.WATER_ACTION_END) end end return false end) DEF_ACTION(Action.WATER_PLUNGE, function(m: Mario) local stepResult local endVSpeed = swimmingNearSurface(m) and 0 or -5 local hasMetalCap = m.Flags:Has(MarioFlags.METAL_CAP) local isDiving = m.PrevAction:Has(ActionFlags.DIVING) or m.Input:Has(InputFlags.A_DOWN) m.ActionTimer += 1 stationarySlowDown(m) stepResult = performWaterStep(m) if m.ActionState == 0 then m:PlaySound(Sounds.ACTION_WATER_ENTER) if m.PeakHeight - m.Position.Y > 1150 then m:PlaySound(Sounds.MARIO_HAHA) end m.ParticleFlags:Add(ParticleFlags.WATER_SPLASH) m.ActionState = 1 end if stepResult == WaterStep.HIT_FLOOR or m.Velocity.Y >= endVSpeed or m.ActionTimer > 20 then if hasMetalCap then m:SetAction(Action.METAL_WATER_FALLING) elseif isDiving then m:SetAction(Action.FLUTTER_KICK) else m:SetAction(Action.WATER_ACTION_END) end sBobIncrement = 0 end if hasMetalCap then m:SetAnimation(Animations.GENERAL_FALL) elseif isDiving then m:SetAnimation(Animations.FLUTTERKICK) else m:SetAnimation(Animations.WATER_ACTION_END) end m.Flags:Add(ParticleFlags.PLUNGE_BUBBLE) return false end) DEF_ACTION(Action.METAL_WATER_STANDING, function(m: Mario) if not m.Flags:Has(MarioFlags.METAL_CAP) then return m:SetAction(Action.WATER_IDLE) end if m.Input:Has(InputFlags.A_PRESSED) then return m:SetAction(Action.METAL_WATER_JUMP) end if m.Input:Has(InputFlags.NONZERO_ANALOG) then return m:SetAction(Action.METAL_WATER_WALKING) end if m.ActionState == 0 then m:SetAnimation(Animations.IDLE_HEAD_LEFT) elseif m.ActionState == 1 then m:SetAnimation(Animations.IDLE_HEAD_RIGHT) elseif m.ActionState == 2 then m:SetAnimation(Animations.IDLE_HEAD_CENTER) end if m:IsAnimAtEnd() then m.ActionState += 1 if m.ActionState == 3 then m.ActionState = 0 end end m:StopAndSetHeightToFloor() if m.Position.Y >= m.WaterLevel - 150 then m.ParticleFlags:Add(ParticleFlags.IDLE_WATER_WAVE) end return false end) DEF_ACTION(Action.METAL_WATER_WALKING, function(m: Mario) if not m.Flags:Has(MarioFlags.METAL_CAP) then return m:SetAction(Action.WATER_IDLE) end if m.Input:Has(InputFlags.A_PRESSED) then return m:SetAction(Action.METAL_WATER_JUMP) end if m.Input:Has(InputFlags.NO_MOVEMENT) then return m:SetAction(Action.METAL_WATER_STANDING) end local accel = Util.SignedInt(m.ForwardVel / 4 * 0x10000) local groundStep if accel < 0x1000 then accel = 0x1000 end m:SetAnimationWithAccel(Animations.WALKING, accel) playMetalWaterWalkingSound(m) updateMetalWaterWalkingSpeed(m) groundStep = m:PerformGroundStep() if groundStep == GroundStep.LEFT_GROUND then m:SetAction(Action.METAL_WATER_FALLING, 1) elseif groundStep == GroundStep.HIT_WALL then m.ForwardVel = 0 end return false end) DEF_ACTION(Action.METAL_WATER_JUMP, function(m: Mario) local airStep if not m.Flags:Has(MarioFlags.METAL_CAP) then return m:SetAction(Action.WATER_IDLE) end if updateMetalWaterJumpSpeed(m) then return m:SetAction(Action.WATER_JUMP, 1) end playMetalWaterJumpingSound(m, false) m:SetAnimation(Animations.SINGLE_JUMP) airStep = m:PerformAirStep() if airStep == AirStep.LANDED then m:SetAction(Action.METAL_WATER_JUMP_LAND) elseif airStep == AirStep.HIT_WALL then m.ForwardVel = 0 end return false end) DEF_ACTION(Action.METAL_WATER_FALLING, function(m: Mario) if not m.Flags:Has(MarioFlags.METAL_CAP) then return m:SetAction(Action.WATER_IDLE) end if m.Input:Has(InputFlags.NONZERO_ANALOG) then m.FaceAngle += Vector3int16.new(0, 0x400 * Util.Sins(m.IntendedYaw - m.FaceAngle.Y), 0) end m:SetAnimation(m.ActionArg == 0 and Animations.GENERAL_FALL or Animations.FALL_FROM_WATER) stationarySlowDown(m) if bit32.btest(performWaterStep(m), WaterStep.HIT_FLOOR) then m:SetAction(Action.METAL_WATER_FALL_LAND) end return false end) DEF_ACTION(Action.METAL_WATER_JUMP_LAND, function(m: Mario) playMetalWaterJumpingSound(m, true) if not m.Flags:Has(MarioFlags.METAL_CAP) then return m:SetAction(Action.WATER_IDLE) end if m.Input:Has(InputFlags.NONZERO_ANALOG) then return m:SetAction(Action.METAL_WATER_WALKING) end m:StopAndSetHeightToFloor() m:SetAnimation(Animations.LAND_FROM_SINGLE_JUMP) if m:IsAnimAtEnd() then return m:SetAction(Action.METAL_WATER_STANDING) end return false end) DEF_ACTION(Action.METAL_WATER_FALL_LAND, function(m: Mario) playMetalWaterJumpingSound(m, true) if not m.Flags:Has(MarioFlags.METAL_CAP) then return m:SetAction(Action.WATER_IDLE) end if m.Input:Has(InputFlags.NONZERO_ANALOG) then return m:SetAction(Action.METAL_WATER_WALKING) end m:StopAndSetHeightToFloor() m:SetAnimation(Animations.GENERAL_LAND) if m:IsAnimAtEnd() then return m:SetAction(Action.METAL_WATER_STANDING) end return false end)
6,401
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Types/Flags.lua
--!strict local Flags = {} Flags.__index = Flags export type Flags = { Value: number } export type Class = typeof(setmetatable({} :: Flags, Flags)) function Flags.new(...: number): Class local flags = { Value = bit32.bor(...) } return setmetatable(flags, Flags) end function Flags.__call(self: Class): number return self.Value end function Flags.Get(self: Class): number return self.Value end function Flags.Set(self: Class, ...: number) self.Value = bit32.bor(...) end function Flags.Copy(self: Class, flags: Class) self.Value = flags.Value end function Flags.Add(self: Class, ...: number) self.Value = bit32.bor(self.Value, ...) end function Flags.Has(self: Class, ...: number): boolean local mask = bit32.bor(...) return bit32.btest(self.Value, mask) end function Flags.Remove(self: Class, ...: number) local mask = bit32.bor(...) local invert = bit32.bnot(mask) self.Value = bit32.band(self.Value, invert) end function Flags.Band(self: Class, ...: number) self.Value = bit32.band(self.Value, ...) end function Flags.Clear(self: Class) self.Value = 0 end return Flags
278
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Types/init.lua
--!strict local Flags = require(script.Flags) export type Flags = Flags.Class export type Controller = { RawStickX: number, RawStickY: number, StickX: number, StickY: number, StickMag: number, ButtonDown: Flags, ButtonPressed: Flags, } export type BodyState = { Action: number, CapState: Flags, EyeState: number, HandState: Flags, WingFlutter: boolean, ModelState: Flags, GrabPos: number, PunchType: number, PunchTimer: number, TorsoAngle: Vector3int16, HeadAngle: Vector3int16, HeldObjLastPos: Vector3, } export type MarioState = { Input: Flags, Flags: Flags, Action: Flags, PrevAction: Flags, ParticleFlags: Flags, HitboxHeight: number, TerrainType: number, HeldObj: Instance?, ActionState: number, ActionTimer: number, ActionArg: number, IntendedMag: number, IntendedYaw: number, InvincTimer: number, FramesSinceA: number, FramesSinceB: number, WallKickTimer: number, DoubleJumpTimer: number, FaceAngle: Vector3int16, AngleVel: Vector3int16, ThrowMatrix: CFrame?, GfxAngle: Vector3int16, GfxPos: Vector3, SlideYaw: number, TwirlYaw: number, Position: Vector3, Velocity: Vector3, ForwardVel: number, SlideVelX: number, SlideVelZ: number, Wall: RaycastResult?, Ceil: RaycastResult?, Floor: RaycastResult?, CeilHeight: number, FloorHeight: number, FloorAngle: number, WaterLevel: number, BodyState: BodyState, Controller: Controller, Health: number, HurtCounter: number, HealCounter: number, SquishTimer: number, CapTimer: number, BurnTimer: number, PeakHeight: number, SteepJumpYaw: number, WalkingPitch: number, QuicksandDepth: number, LongJumpIsSlow: boolean, AnimCurrent: Animation?, AnimFrameCount: number, AnimAccel: number, AnimAccelAssist: number, AnimFrame: number, AnimDirty: boolean, AnimReset: boolean, AnimSetFrame: number, AnimSkipInterp: number, } return table.freeze({ Flags = Flags, })
556
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/init.server.lua
--!strict local Core = script.Parent if Core:GetAttribute("HotLoading") then task.wait(3) end for i, desc in script:GetDescendants() do if desc:IsA("BaseScript") then desc.Enabled = true end end local Players = game:GetService("Players") local RunService = game:GetService("RunService") local StarterGui = game:GetService("StarterGui") local TweenService = game:GetService("TweenService") local UserInputService = game:GetService("UserInputService") local ReplicatedStorage = game:GetService("ReplicatedStorage") local ContextActionService = game:GetService("ContextActionService") local Shared = require(Core.Shared) local Sounds = Shared.Sounds local Enums = require(script.Enums) local Mario = require(script.Mario) local Types = require(script.Types) local Util = require(script.Util) local Action = Enums.Action local Buttons = Enums.Buttons local MarioFlags = Enums.MarioFlags local ParticleFlags = Enums.ParticleFlags type InputType = Enum.UserInputType | Enum.KeyCode type Controller = Types.Controller type Mario = Mario.Class local player: Player = assert(Players.LocalPlayer) local mario: Mario = Mario.new() local STEP_RATE = 30 local NULL_TEXT = `<font color="#FF0000">NULL</font>` local FLIP = CFrame.Angles(0, math.pi, 0) local debugStats = Instance.new("BoolValue") debugStats.Name = "DebugStats" debugStats.Archivable = false debugStats.Parent = game local PARTICLE_CLASSES = { Fire = true, Smoke = true, Sparkles = true, ParticleEmitter = true, } local AUTO_STATS = { "Position", "Velocity", "AnimFrame", "FaceAngle", "ActionState", "ActionTimer", "ActionArg", "ForwardVel", "SlideVelX", "SlideVelZ", "CeilHeight", "FloorHeight", "WaterLevel", } local ControlModule: { GetMoveVector: (self: any) -> Vector3, } while not ControlModule do local inst = player:FindFirstChild("ControlModule", true) if inst then ControlModule = (require :: any)(inst) end task.wait(0.1) end ------------------------------------------------------------------------------------------------------------------------------------------------- -- Input Driver ------------------------------------------------------------------------------------------------------------------------------------------------- -- NOTE: I had to replace the default BindAction via KeyCode and UserInputType -- BindAction forces some mappings (such as R2 mapping to MouseButton1) which you -- can't turn off otherwise. local BUTTON_FEED = {} local BUTTON_BINDS = {} local function toStrictNumber(str: string): number local result = tonumber(str) return assert(result, "Invalid number!") end local function processAction(id: string, state: Enum.UserInputState, input: InputObject) if id == "MarioDebug" and Core:GetAttribute("DebugToggle") then if state == Enum.UserInputState.Begin then local character = player.Character if character then local isDebug = not character:GetAttribute("Debug") character:SetAttribute("Debug", isDebug) end end else local button = toStrictNumber(id:sub(5)) BUTTON_FEED[button] = state end end local function processInput(input: InputObject, gameProcessedEvent: boolean) if gameProcessedEvent then return end if BUTTON_BINDS[input.UserInputType] ~= nil then processAction(BUTTON_BINDS[input.UserInputType], input.UserInputState, input) end if BUTTON_BINDS[input.KeyCode] ~= nil then processAction(BUTTON_BINDS[input.KeyCode], input.UserInputState, input) end end UserInputService.InputBegan:Connect(processInput) UserInputService.InputChanged:Connect(processInput) UserInputService.InputEnded:Connect(processInput) local function bindInput(button: number, label: string, ...: InputType) local id = "BTN_" .. button if UserInputService.TouchEnabled then ContextActionService:BindAction(id, processAction, true) ContextActionService:SetTitle(id, label) end for i, input in { ... } do BUTTON_BINDS[input] = id end end local function updateCollisions() for i, player in Players:GetPlayers() do -- stylua: ignore local character = player.Character local rootPart = character and character.PrimaryPart if rootPart then local parts = rootPart:GetConnectedParts(true) for i, part in parts do if part:IsA("BasePart") then part.CanCollide = false end end end end end local function updateController(controller: Controller, humanoid: Humanoid?) if not humanoid then return end local moveDir = ControlModule:GetMoveVector() local pos = Vector2.new(moveDir.X, -moveDir.Z) local mag = 0 if pos.Magnitude > 0 then if pos.Magnitude > 1 then pos = pos.Unit end mag = pos.Magnitude end controller.StickMag = mag * 64 controller.StickX = pos.X * 64 controller.StickY = pos.Y * 64 humanoid:ChangeState(Enum.HumanoidStateType.Physics) controller.ButtonPressed:Clear() if humanoid.Jump then BUTTON_FEED[Buttons.A_BUTTON] = Enum.UserInputState.Begin elseif controller.ButtonDown:Has(Buttons.A_BUTTON) then BUTTON_FEED[Buttons.A_BUTTON] = Enum.UserInputState.End end local lastButtonValue = controller.ButtonDown() for button, state in pairs(BUTTON_FEED) do if state == Enum.UserInputState.Begin then controller.ButtonDown:Add(button) elseif state == Enum.UserInputState.End then controller.ButtonDown:Remove(button) end end table.clear(BUTTON_FEED) local buttonValue = controller.ButtonDown() controller.ButtonPressed:Set(buttonValue) controller.ButtonPressed:Band(bit32.bxor(buttonValue, lastButtonValue)) local character = humanoid.Parent if (character and character:GetAttribute("TAS")) or Core:GetAttribute("ToolAssistedInput") then if not mario.Action:Has(Enums.ActionFlags.SWIMMING) then if controller.ButtonDown:Has(Buttons.A_BUTTON) then controller.ButtonPressed:Set(Buttons.A_BUTTON) end end end end ContextActionService:BindAction("MarioDebug", processAction, false, Enum.KeyCode.P) bindInput(Buttons.B_BUTTON, "B", Enum.UserInputType.MouseButton1, Enum.KeyCode.ButtonX) bindInput( Buttons.Z_TRIG, "Z", Enum.KeyCode.LeftShift, Enum.KeyCode.RightShift, Enum.KeyCode.ButtonL2, Enum.KeyCode.ButtonR2 ) ------------------------------------------------------------------------------------------------------------------------------------------------------------- -- Network Dispatch ------------------------------------------------------------------------------------------------------------------------------------------------------------- local Commands = {} local soundDecay = {} local lazyNetwork = ReplicatedStorage:WaitForChild("LazyNetwork") assert(lazyNetwork:IsA("RemoteEvent"), "bad lazyNetwork!") local function stepDecay(sound: Sound) local decay = soundDecay[sound] if decay then task.cancel(decay) end soundDecay[sound] = task.delay(0.1, function() sound:Stop() sound:Destroy() soundDecay[sound] = nil end) sound.Playing = true end function Commands.PlaySound(player: Player, name: string) local sound: Sound? = Sounds[name] local character = player.Character local rootPart = character and character.PrimaryPart if rootPart and sound then local oldSound: Instance? = rootPart:FindFirstChild(name) local canPlay = true if oldSound and oldSound:IsA("Sound") then canPlay = false if name:sub(1, 6) == "MOVING" or sound:GetAttribute("Decay") then -- Keep decaying audio alive. stepDecay(oldSound) elseif name:sub(1, 5) == "MARIO" then -- Restart mario sound if a 30hz interval passed. local now = os.clock() local lastPlay = oldSound:GetAttribute("LastPlay") or 0 if now - lastPlay >= 2 / STEP_RATE then oldSound.TimePosition = 0 oldSound:SetAttribute("LastPlay", now) end else -- Allow stacking. canPlay = true end end if canPlay then local newSound: Sound = sound:Clone() newSound.Parent = rootPart newSound:Play() if name:find("MOVING") then -- Audio will decay if PlaySound isn't continuously called. stepDecay(newSound) end newSound.Ended:Connect(function() newSound:Destroy() end) newSound:SetAttribute("LastPlay", os.clock()) end end end function Commands.SetParticle(player: Player, name: string, set: boolean) local character = player.Character local rootPart = character and character.PrimaryPart if rootPart then local particles = rootPart:FindFirstChild("Particles") local inst = particles and particles:FindFirstChild(name, true) if inst and PARTICLE_CLASSES[inst.ClassName] then local particle = inst :: ParticleEmitter local emit = particle:GetAttribute("Emit") if typeof(emit) == "number" then particle:Emit(emit) elseif set ~= nil then particle.Enabled = set end else warn("particle not found:", name) end end end function Commands.SetTorsoAngle(player: Player, angle: Vector3int16) local character = player.Character local waist = character and character:FindFirstChild("Waist", true) if waist and waist:IsA("Motor6D") then local props = { C1 = Util.ToRotation(-angle) + waist.C1.Position } local tween = TweenService:Create(waist, TweenInfo.new(0.1), props) tween:Play() end end function Commands.SetHeadAngle(player: Player, angle: Vector3int16) local character = player.Character local neck = character and character:FindFirstChild("Neck", true) if neck and neck:IsA("Motor6D") then local props = { C1 = Util.ToRotation(-angle) + neck.C1.Position } local tween = TweenService:Create(neck, TweenInfo.new(0.1), props) tween:Play() end end function Commands.SetCamera(player: Player, cf: CFrame?) local camera = workspace.CurrentCamera if cf ~= nil then camera.CameraType = Enum.CameraType.Scriptable camera.CFrame = cf else camera.CameraType = Enum.CameraType.Custom end end local function processCommand(player: Player, cmd: string, ...: any) local command = Commands[cmd] if command then task.spawn(command, player, ...) else warn("Unknown Command:", cmd, ...) end end local function networkDispatch(cmd: string, ...: any) lazyNetwork:FireServer(cmd, ...) processCommand(player, cmd, ...) end local function onNetworkReceive(target: Player, cmd: string, ...: any) if target ~= player then processCommand(target, cmd, ...) end end lazyNetwork.OnClientEvent:Connect(onNetworkReceive) ------------------------------------------------------------------------------------------------------------------------------------------------------------- -- Mario Driver ------------------------------------------------------------------------------------------------------------------------------------------------------------- local lastUpdate = os.clock() local lastHeadAngle: Vector3int16? local lastTorsoAngle: Vector3int16? local activeScale = 1 local subframe = 0 -- 30hz subframe local emptyId = "" local goalCF: CFrame local prevCF: CFrame local activeTrack: AnimationTrack? local reset = Instance.new("BindableEvent") reset.Archivable = false reset.Parent = script reset.Name = "Reset" if RunService:IsStudio() then local dummySequence = Instance.new("KeyframeSequence") local provider = game:GetService("KeyframeSequenceProvider") emptyId = provider:RegisterKeyframeSequence(dummySequence) end while not player.Character do player.CharacterAdded:Wait() end local character = assert(player.Character) local pivot = character:GetPivot() mario.Position = Util.ToSM64(pivot.Position) goalCF = pivot prevCF = pivot local function setDebugStat(key: string, value: any) if typeof(value) == "Vector3" then value = string.format("%.3f, %.3f, %.3f", value.X, value.Y, value.Z) elseif typeof(value) == "Vector3int16" then value = string.format("%i, %i, %i", value.X, value.Y, value.Z) elseif type(value) == "number" then value = string.format("%.3f", value) end debugStats:SetAttribute(key, value) end local function onReset() local roblox = Vector3.yAxis * 100 local sm64 = Util.ToSM64(roblox) local char = player.Character if char then local reset = char:FindFirstChild("Reset") local cf = CFrame.new(roblox) char:PivotTo(cf) goalCF = cf prevCF = cf if reset and reset:IsA("RemoteEvent") then reset:FireServer() end end mario.SlideVelX = 0 mario.SlideVelZ = 0 mario.ForwardVel = 0 mario.IntendedYaw = 0 mario.Position = sm64 mario.Velocity = Vector3.zero mario.FaceAngle = Vector3int16.new() mario:SetAction(Action.SPAWN_SPIN_AIRBORNE) end local function getWaterLevel(pos: Vector3) local terrain = workspace.Terrain local voxelPos = terrain:WorldToCellPreferSolid(pos) local voxelRegion = Region3.new(voxelPos * 4, (voxelPos + Vector3.one + (Vector3.yAxis * 3)) * 4) voxelRegion = voxelRegion:ExpandToGrid(4) local materials, occupancies = terrain:ReadVoxels(voxelRegion, 4) local size: Vector3 = occupancies.Size local waterLevel = -11000 for y = 1, size.Y do local occupancy = occupancies[1][y][1] local material = materials[1][y][1] if occupancy >= 0.9 and material == Enum.Material.Water then local top = ((voxelPos.Y * 4) + (4 * y + 2)) waterLevel = math.max(waterLevel, top / Util.Scale) end end return waterLevel end local function update() local character = player.Character if not character then return end local now = os.clock() local gfxRot = CFrame.identity local scale = character:GetScale() if scale ~= activeScale then local marioPos = Util.ToRoblox(mario.Position) Util.Scale = scale / 20 -- HACK! Should this be instanced? mario.Position = Util.ToSM64(marioPos) activeScale = scale end -- Disabled for now because this causes parallel universes to break. -- TODO: Find a better way to do two-way syncing between these values. -- local pos = character:GetPivot().Position -- local dist = (Util.ToRoblox(mario.Position) - pos).Magnitude -- if dist > (scale * 20) then -- mario.Position = Util.ToSM64(pos) -- end local humanoid = character:FindFirstChildOfClass("Humanoid") local simSpeed = tonumber(character:GetAttribute("TimeScale") or nil) or 1 local robloxPos = Util.ToRoblox(mario.Position) mario.WaterLevel = getWaterLevel(robloxPos) Util.DebugWater(mario.WaterLevel) subframe += (now - lastUpdate) * (STEP_RATE * simSpeed) lastUpdate = now if character:GetAttribute("WingCap") or Core:GetAttribute("WingCap") then mario.Flags:Add(MarioFlags.WING_CAP) else mario.Flags:Remove(MarioFlags.WING_CAP) end if character:GetAttribute("Metal") then mario.Flags:Add(MarioFlags.METAL_CAP) else mario.Flags:Remove(MarioFlags.METAL_CAP) end subframe = math.min(subframe, 4) -- Prevent execution runoff while subframe >= 1 do subframe -= 1 updateCollisions() updateController(mario.Controller, humanoid) mario:ExecuteAction() local gfxPos = Util.ToRoblox(mario.Position) gfxRot = Util.ToRotation(mario.GfxAngle) prevCF = goalCF goalCF = CFrame.new(gfxPos) * FLIP * gfxRot end if character and goalCF then local cf = character:GetPivot() local rootPart = character.PrimaryPart local animator = character:FindFirstChildWhichIsA("Animator", true) if animator and (mario.AnimDirty or mario.AnimReset) and mario.AnimFrame >= 0 then local anim = mario.AnimCurrent local animSpeed = 0.1 / simSpeed if activeTrack and (activeTrack.Animation ~= anim or mario.AnimReset) then if tostring(activeTrack.Animation) == "TURNING_PART1" then if anim and anim.Name == "TURNING_PART2" then mario.AnimSkipInterp = 2 animSpeed *= 2 end end activeTrack:Stop(animSpeed) activeTrack = nil end if not activeTrack and anim then if anim.AnimationId == "" then if RunService:IsStudio() then warn("!! FIXME: Empty AnimationId for", anim.Name, "will break in live games!") end anim.AnimationId = emptyId end local track = animator:LoadAnimation(anim) track:Play(animSpeed, 1, 0) activeTrack = track end if activeTrack then local speed = mario.AnimAccel / 0x10000 if speed > 0 then activeTrack:AdjustSpeed(speed * simSpeed) else activeTrack:AdjustSpeed(simSpeed) end end mario.AnimDirty = false mario.AnimReset = false end if activeTrack and mario.AnimSetFrame > -1 then activeTrack.TimePosition = mario.AnimSetFrame / STEP_RATE mario.AnimSetFrame = -1 end if rootPart then local particles = rootPart:FindFirstChild("Particles") local alignPos = rootPart:FindFirstChildOfClass("AlignPosition") local alignCF = rootPart:FindFirstChildOfClass("AlignOrientation") local actionId = mario.Action() local throw = mario.ThrowMatrix if throw then local throwPos = Util.ToRoblox(throw.Position) goalCF = throw.Rotation * FLIP + throwPos end if alignCF then local nextCF = prevCF:Lerp(goalCF, subframe) -- stylua: ignore cf = if mario.AnimSkipInterp > 0 then cf.Rotation + nextCF.Position else nextCF alignCF.CFrame = cf.Rotation end local isDebug = character:GetAttribute("Debug") local limits = character:GetAttribute("EmulateLimits") script.Util:SetAttribute("Debug", isDebug) debugStats.Value = isDebug if limits ~= nil then Core:SetAttribute("TruncateBounds", limits) end if isDebug then local animName = activeTrack and tostring(activeTrack.Animation) setDebugStat("Animation", animName) local actionName = Enums.GetName(Action, actionId) setDebugStat("Action", actionName) local wall = mario.Wall setDebugStat("Wall", wall and wall.Instance.Name or NULL_TEXT) local floor = mario.Floor setDebugStat("Floor", floor and floor.Instance.Name or NULL_TEXT) local ceil = mario.Ceil setDebugStat("Ceiling", ceil and ceil.Instance.Name or NULL_TEXT) end for _, name in AUTO_STATS do local value = rawget(mario :: any, name) setDebugStat(name, value) end if alignPos then alignPos.Position = cf.Position end local bodyState = mario.BodyState local headAngle = bodyState.HeadAngle local torsoAngle = bodyState.TorsoAngle if actionId ~= Action.BUTT_SLIDE and actionId ~= Action.WALKING then bodyState.TorsoAngle *= 0 end if torsoAngle ~= lastTorsoAngle then networkDispatch("SetTorsoAngle", torsoAngle) lastTorsoAngle = torsoAngle end if headAngle ~= lastHeadAngle then networkDispatch("SetHeadAngle", headAngle) lastHeadAngle = headAngle end if particles then for name, flag in pairs(ParticleFlags) do local inst = particles:FindFirstChild(name, true) if inst and PARTICLE_CLASSES[inst.ClassName] then local particle = inst :: ParticleEmitter local emit = particle:GetAttribute("Emit") local hasFlag = mario.ParticleFlags:Has(flag) if hasFlag then print("SetParticle", name) end if emit then if hasFlag then networkDispatch("SetParticle", name) end elseif particle.Enabled ~= hasFlag then networkDispatch("SetParticle", name, hasFlag) end end end end for name: string, sound: Sound in pairs(Sounds) do local looped = false if sound:IsA("Sound") then if sound.TimeLength == 0 then continue end looped = sound.Looped end if sound:GetAttribute("Play") then networkDispatch("PlaySound", sound.Name) if not looped then sound:SetAttribute("Play", false) end elseif looped then sound:Stop() end end character:PivotTo(cf) end end end reset.Event:Connect(onReset) RunService.Heartbeat:Connect(update) while task.wait(1) do local success = pcall(function() return StarterGui:SetCore("ResetButtonCallback", reset) end) if success then break end end -------------------------------------------------------------------------------------------------------------------------------------------------------------
5,022
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/server/LazyNetworking.server.lua
--!strict local Validators: { [string]: (Player, ...any) -> boolean } = {} type Echo = () -> () local ReplicatedStorage = game:GetService("ReplicatedStorage") local Core = script.Parent.Parent local Shared = require(Core.Shared) local Sounds = Shared.Sounds local lazy = Instance.new("RemoteEvent") lazy.Parent = ReplicatedStorage lazy.Name = "LazyNetwork" lazy.Archivable = false function Validators.PlaySound(player: Player, name: string) local sound: Instance? = Sounds[name] if sound and sound:IsA("Sound") then return true end return false end function Validators.SetParticle(player: Player, name: string, set: boolean?) if typeof(name) ~= "string" then return false end local character = player.Character local rootPart = character and character.PrimaryPart if rootPart then local particles = rootPart:FindFirstChild("Particles") local particle = particles and particles:FindFirstChild(name, true) if particle then return true end end return false end function Validators.SetTorsoAngle(player: Player, angle: Vector3int16) return typeof(angle) == "Vector3int16" end function Validators.SetHeadAngle(player: Player, angle: Vector3int16) return typeof(angle) == "Vector3int16" end local function onNetworkReceive(player: Player, cmd: string, ...) local validate = Validators[cmd] if validate and validate(player, ...) then lazy:FireAllClients(player, cmd, ...) end end lazy.OnServerEvent:Connect(onNetworkReceive)
348
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/server/StarterCharacter/Appearance/init.server.lua
--!strict local Players = game:GetService("Players") local character: Instance = assert(script.Parent) assert(character:IsA("Model"), "Not a character") local player = Players:GetPlayerFromCharacter(character) assert(player, "No player!") local userId = player.UserId local hDesc: HumanoidDescription? local metalPointers = {} :: { [MeshPart]: { Metal: SurfaceAppearance?, }, } local function updateMetal(part: MeshPart) local isMetal = character:GetAttribute("Metal") local ptr = metalPointers[part] if ptr == nil then ptr = {} metalPointers[part] = ptr end if isMetal and not ptr.Metal then local surface = script.METAL_MARIO:Clone() surface.Parent = part ptr.Metal = surface elseif ptr.Metal and not isMetal then ptr.Metal:Destroy() ptr.Metal = nil end end local function onMetalChanged() for meshPart in metalPointers do updateMetal(meshPart) end end local function onDescendantAdded(desc: Instance) if desc:IsA("BasePart") then if desc.CollisionGroup ~= "Player" then local canCollide = desc:GetPropertyChangedSignal("CanCollide") desc.CollisionGroup = "Player" desc.CanQuery = false desc.CanTouch = false desc.Massless = true canCollide:Connect(function() desc.CanCollide = false end) desc.CanCollide = false end if desc:IsA("MeshPart") then updateMetal(desc) end end end local function onDescendantRemoving(desc: Instance) if desc:IsA("MeshPart") then metalPointers[desc] = nil end end local metalListener = character:GetAttributeChangedSignal("Metal") metalListener:Connect(onMetalChanged) for i, desc in character:GetDescendants() do task.spawn(onDescendantAdded, desc) end character:SetAttribute("TimeScale", 1) character.DescendantAdded:Connect(onDescendantAdded) character.DescendantRemoving:Connect(onDescendantRemoving) local function reload() character:ScaleTo(1) task.spawn(function() for i = 1, 5 do character:PivotTo(CFrame.new(0, 100, 0)) task.wait() end end) for retry = 1, 10 do local success, result = pcall(function() return Players:GetHumanoidDescriptionFromUserId(userId) end) if success then hDesc = result break else task.wait(retry / 2) end end if hDesc then hDesc.HeadScale = 1.8 hDesc.WidthScale = 1.3 hDesc.DepthScale = 1.4 hDesc.HeightScale = 1.2 hDesc.BodyTypeScale = 0 hDesc.ProportionScale = 0 else return end local humanoid = character:WaitForChild("Humanoid") assert(hDesc) if humanoid:IsA("Humanoid") then while not humanoid.RootPart do humanoid.Changed:Wait() end local rootPart = humanoid.RootPart assert(rootPart, "No HumanoidRootPart??") local particles = rootPart:FindFirstChild("Particles") humanoid:ApplyDescription(hDesc) if particles and particles:IsA("Attachment") then local floorDec = humanoid.HipHeight + (rootPart.Size.Y / 2) local pos = Vector3.new(0, -floorDec, 0) rootPart.PivotOffset = CFrame.new(pos) particles.Position = pos end end end local reset = Instance.new("RemoteEvent") reset.Parent = character reset.Name = "Reset" reset.OnServerEvent:Connect(function(player) if player == Players:GetPlayerFromCharacter(character) then reload() end end) task.spawn(reload)
883
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/server/StarterCharacter/init.server.lua
--!strict local Players = game:GetService("Players") local StarterPlayer = game:GetService("StarterPlayer") local PhysicsService = game:GetService("PhysicsService") local StarterCharacterScripts = StarterPlayer.StarterCharacterScripts local hDesc = Instance.new("HumanoidDescription") hDesc.HeightScale = 1.3 hDesc.WidthScale = 1.3 hDesc.DepthScale = 1.4 hDesc.HeadScale = 2 local character = Players:CreateHumanoidModelFromDescription(hDesc, Enum.HumanoidRigType.R15) local bodyColors = character:FindFirstChildOfClass("BodyColors") local animate = character:FindFirstChild("Animate") local oldRoot = character.PrimaryPart if animate then animate:Destroy() end if oldRoot then oldRoot:Destroy() end if bodyColors then bodyColors:Destroy() end local newRoot = script.HumanoidRootPart newRoot.Parent = character :: any local humanoid = assert(character:FindFirstChildOfClass("Humanoid")) humanoid:BuildRigFromAttachments() local dummyScripts = { "Animate", "Health", "Sound", } for _, dummy in dummyScripts do local stub = Instance.new("Hole", StarterCharacterScripts) stub.Name = dummy end for _, child in script:GetChildren() do child.Parent = StarterCharacterScripts if child:IsA("Script") then child.Disabled = false end end character.Name = "StarterCharacter" character.PrimaryPart = newRoot character.Parent = StarterPlayer PhysicsService:RegisterCollisionGroup("Player") PhysicsService:CollisionGroupSetCollidable("Default", "Player", false) for _, player in Players:GetPlayers() do task.spawn(player.LoadCharacter, player) end
376
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/tools/ImportAnimations.lua
local AvatarImportService = game:GetService("AvatarImportService") local resume = Instance.new("BindableEvent") for i, anim in pairs(game.ReplicatedFirst.SM64.Assets.Animations:GetChildren()) do local path = "C:/Users/clone/Desktop/MarioAnims/" .. anim.Name .. ".fbx" print("Importing", anim) task.defer(function() local success, err = pcall(function() AvatarImportService:ImportFBXAnimationFromFilePathUserMayChooseModel(path, workspace.Mario, function() local bin = game.ServerStorage.AnimSaves local old = bin:FindFirstChild(anim.Name) if old then old:Destroy() end local kfs = AvatarImportService:ImportLoadedFBXAnimation(false) kfs.Name = anim.Name kfs.Parent = bin resume:Fire() end) end) if not success then warn("ERROR IMPORTING", anim, err) resume:Fire() end end) resume.Event:Wait() end
229
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/tools/RetargetAnimations.lua
-- This script was written (quite rigidly) for use in the provided RetargetAnimations.rbxl place. -- KeyframeSequences are not provided as mentioned in the README, you'll have to extract them yourself :) --!strict local ServerStorage = game:GetService("ServerStorage") local StarterCharacter = workspace.StarterCharacter local MarioAnim = workspace.MarioAnim local MarioBase = workspace.MarioBase local Player = workspace.Player local HIERARCHY: { [string]: { [string]: string }? } = { HumanoidRootPart = { LowerTorso = "Root" }, LowerTorso = { UpperTorso = "Waist", LeftUpperLeg = "LeftHip", RightUpperLeg = "RightHip", }, UpperTorso = { Head = "Neck", LeftUpperArm = "LeftShoulder", RightUpperArm = "RightShoulder", }, LeftUpperArm = { LeftLowerArm = "LeftElbow" }, LeftLowerArm = { LeftHand = "LeftWrist" }, RightUpperArm = { RightLowerArm = "RightElbow" }, RightLowerArm = { RightHand = "RightWrist" }, LeftUpperLeg = { LeftLowerLeg = "LeftKnee" }, LeftLowerLeg = { LeftFoot = "LeftAnkle" }, RightUpperLeg = { RightLowerLeg = "RightKnee" }, RightLowerLeg = { RightFoot = "RightAnkle" }, } local BASE_KEYFRAME = ServerStorage.BASE_KEYFRAME local statusHint = Instance.new("Hint") local statusText = "%s [%d/%d]" statusHint.Parent = workspace statusHint.Name = "Status" local function updateAnim() StarterCharacter.Humanoid.Animator:StepAnimations(0) Player.Humanoid.Animator:StepAnimations(0) task.wait() end local function clearAnims() for i, desc: Instance in pairs(workspace:GetDescendants()) do if desc:IsA("Bone") then desc.Transform = CFrame.identity elseif desc:IsA("Motor6D") then desc.Transform = CFrame.identity elseif desc:IsA("Animator") then task.defer(desc.StepAnimations, desc, 0) end end task.wait() end local function applyMotors(at: Instance) local name0 = if at:IsA("Keyframe") then "HumanoidRootPart" else at.Name local part0 = StarterCharacter:FindFirstChild(name0) local data = HIERARCHY[name0] if data and part0 and part0:IsA("BasePart") then for name1, motorName in data do local part1 = StarterCharacter:FindFirstChild(name1) if part1 and part1:IsA("BasePart") then local att: Attachment = part1:FindFirstChild(motorName .. "RigAttachment") local bone: Bone = MarioBase:FindFirstChild(motorName, true) local motor: Motor6D = part1:FindFirstChild(motorName) motor.Transform = att.WorldCFrame:ToObjectSpace(bone.TransformedWorldCFrame) local playerMotor = workspace.Player:FindFirstChild(motorName, true) local pose = at:FindFirstChild(name1) if playerMotor and playerMotor:IsA("Motor6D") then if motorName:find("Left") or motorName:find("Right") then playerMotor.Transform = motor.Transform.Rotation else playerMotor.Transform = motor.Transform end end updateAnim() if pose and pose:IsA("Pose") then if motorName:find("Left") or motorName:find("Right") then pose.CFrame = motor.Transform.Rotation else pose.CFrame = motor.Transform end applyMotors(pose) end end end end end local function remapKeyframe(keyframe: Keyframe): Keyframe clearAnims() for i, desc: Instance in pairs(keyframe:GetDescendants()) do if desc:IsA("Pose") then local bone: Instance? = MarioAnim:FindFirstChild(desc.Name, true) if bone and bone:IsA("Bone") then bone.Transform = desc.CFrame end end end for i, desc in MarioBase:GetDescendants() do if desc:IsA("Bone") then local anim = MarioAnim:FindFirstChild(desc.Name, true) if anim then local offset = desc.TransformedWorldCFrame:ToObjectSpace(anim.TransformedWorldCFrame) desc.Transform = offset end end end local newKeyframe = BASE_KEYFRAME:Clone() newKeyframe.Name = keyframe.Name newKeyframe.Time = keyframe.Time applyMotors(newKeyframe) return newKeyframe end local function remapKeyframeSequence(kfs: KeyframeSequence): KeyframeSequence local keyframes = kfs:GetKeyframes() clearAnims() local newKfs = kfs:Clone() newKfs:ClearAllChildren() for i, keyframe in keyframes do if keyframe:IsA("Keyframe") then local text = statusText:format(kfs.Name, i, #keyframes) statusHint.Text = text local newKeyframe = remapKeyframe(keyframe) newKeyframe.Parent = newKfs end end return newKfs end local animSaves = ServerStorage.AnimSaves:GetChildren() local animSavesR15 = ServerStorage.AnimSaves_R15 table.sort(animSaves, function(a, b) return a.Name < b.Name end) for i, animSave in animSaves do if animSave:IsA("KeyframeSequence") then local kfs = remapKeyframeSequence(animSave) kfs.Parent = animSavesR15 end end clearAnims() statusHint:Destroy()
1,311
littensy/ripple
littensy-ripple-c33bb8b/.lute/build.luau
local fs = require("@std/fs") local process = require("@lute/process") fs.createdirectory("build") process.run({ "rojo", "build", "--output=build/ripple.rbxm" }, { stdio = "inherit" })
52
littensy/ripple
littensy-ripple-c33bb8b/.lute/check.luau
local fs = require("@std/fs") local net = require("@lute/net") local process = require("@lute/process") process.run({ "rojo", "sourcemap", "--output=sourcemap.json" }, { stdio = "inherit" }) fs.writestringtofile( "roblox.d.luau", net.request("https://luau-lsp.pages.dev/globalTypes.None.d.luau", { method = "GET" }).body ) local analyze = process.run({ "luau-lsp", "analyze", "--sourcemap=sourcemap.json", "--ignore=**/node_modules/**", "--base-luaurc=.luaurc", "--definitions=roblox.d.luau", "packages", "tests", "benchmarks", }, { stdio = "inherit" }) fs.remove("roblox.d.luau") local selene = process.run({ "selene", "packages", "tests", "benchmarks", "storybook" }, { stdio = "inherit" }) local stylua = process.run( { "stylua", "--check", "packages", "tests", "benchmarks", "storybook" }, { stdio = "inherit" } ) local eslint = process.run({ "pnpm", "eslint", "packages" }, { stdio = "inherit" }) if not (analyze.ok and selene.ok and stylua.ok and eslint.ok) then process.exit(1) end
314
littensy/ripple
littensy-ripple-c33bb8b/benchmarks/bench.luau
local function bench(name: string, test: () -> ()) local start = os.clock() local iterations = 0 while os.clock() - start < 3 do iterations += 1 test() end local elapsed = os.clock() - start local micros = string.format("%.2f", elapsed / iterations * 1000 * 1000) print(`{name}: {micros} µs/iter`) end return bench
97
littensy/ripple
littensy-ripple-c33bb8b/benchmarks/otter/AnimationStepSignal.luau
--[[ Copyright (c) 2018-2023 Roblox Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] --!strict local boundCallbacks = {} return { Connect = function(_, callback: (number) -> ()) boundCallbacks[callback] = true return { Disconnect = function() boundCallbacks[callback] = nil end, } :: any end, Fire = function(_, dt: number) for callback, _ in boundCallbacks do callback(dt) end end, Clear = function(_) table.clear(boundCallbacks) end, }
341
littensy/ripple
littensy-ripple-c33bb8b/benchmarks/otter/assign.luau
--[[ MIT License Copyright (c) Roblox Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] --!strict -- Marker used to specify that the value is nothing, because nil cannot be -- stored in tables. local None = newproxy(true) local mt = getmetatable(None) mt.__tostring = function() return "Object.None" end --[[ Merges values from zero or more tables onto a target table. If a value is set to None, it will instead be removed from the table. This function is identical in functionality to JavaScript's Object.assign. ]] -- Luau TODO: no way to strongly type this accurately, it doesn't eliminate deleted keys of T, and Luau won't do intersections of type packs: <T, ...U>(T, ...: ...U): T & ...U return function<T, U, V, W>(target: T, source0: U?, source1: V?, source2: W?, ...): T & U & V & W if source0 ~= nil and typeof(source0 :: any) == "table" then for key, value in pairs(source0 :: any) do if value == None then (target :: any)[key] = nil else (target :: any)[key] = value end end end if source1 ~= nil and typeof(source1 :: any) == "table" then for key, value in pairs(source1 :: any) do if value == None then (target :: any)[key] = nil else (target :: any)[key] = value end end end if source2 ~= nil and typeof(source2 :: any) == "table" then for key, value in pairs(source2 :: any) do if value == None then (target :: any)[key] = nil else (target :: any)[key] = value end end end for index = 1, select("#", ...) do local rest = select(index, ...) if rest ~= nil and typeof(rest) == "table" then for key, value in pairs(rest) do if value == None then (target :: any)[key] = nil else (target :: any)[key] = value end end end end -- TODO? we can add & Object to this, if needed by real-world code, once CLI-49825 is fixed return (target :: any) :: T & U & V & W end
771
littensy/ripple
littensy-ripple-c33bb8b/benchmarks/otter/createGroupMotor.luau
--[[ Copyright (c) 2023 Roblox Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] --!strict local assign = require("./assign") local createSignal = require("./createSignal") local AnimationStepSignal = require("./AnimationStepSignal") local types = require("./types") type AnimationValue = types.AnimationValue type Goal<T> = types.Goal<T> type State = types.State type Motor<T, U> = types.Motor<T, U> type Unsubscribe = types.Unsubscribe type MotorCallback<T> = types.MotorCallback<T> type ValueGroup = { [string]: AnimationValue, } type GoalGroup = { [string]: Goal<any>, } type GroupMotorInternal = { __goals: GoalGroup, __states: { [string]: State, }, __allComplete: boolean, __onComplete: createSignal.Signal<ValueGroup>, __fireOnComplete: createSignal.FireSignal<ValueGroup>, __onStep: createSignal.Signal<ValueGroup>, __fireOnStep: createSignal.FireSignal<ValueGroup>, __running: boolean, __connection: RBXScriptConnection?, start: (self: GroupMotorInternal) -> (), stop: (self: GroupMotorInternal) -> (), step: (self: GroupMotorInternal, dt: number) -> (), setGoal: (self: GroupMotorInternal, goal: GoalGroup) -> (), onStep: (self: GroupMotorInternal, callback: MotorCallback<ValueGroup>) -> Unsubscribe, onComplete: (self: GroupMotorInternal, callback: MotorCallback<ValueGroup>) -> Unsubscribe, destroy: (self: GroupMotorInternal) -> (), } local GroupMotor = {} :: GroupMotorInternal (GroupMotor :: any).__index = GroupMotor export type GroupMotor = Motor<GoalGroup, ValueGroup> local function createGroupMotor(initialValues: ValueGroup): GroupMotor local states = {} for key, value in pairs(initialValues) do states[key] = { value = value, complete = true, } end local onComplete, fireOnComplete = createSignal() local onStep, fireOnStep = createSignal() local self = { __goals = {}, __states = states, __allComplete = true, __onComplete = onComplete, __fireOnComplete = fireOnComplete, __onStep = onStep, __fireOnStep = fireOnStep, __running = false, } setmetatable(self, GroupMotor) return self :: any end function GroupMotor:start() if self.__running then return end self.__connection = AnimationStepSignal:Connect(function(dt) self:step(dt) end) self.__running = true end function GroupMotor:stop() if self.__connection ~= nil then self.__connection:Disconnect() self.__running = false end end function GroupMotor:step(dt: number) if self.__allComplete then return end local allComplete = true local values = {} for key, state in pairs(self.__states) do if not state.complete then local goal = self.__goals[key] if goal ~= nil then local maybeNewState = goal.step(state, dt) if maybeNewState ~= nil then state = maybeNewState self.__states[key] = maybeNewState end else state.complete = true end if not state.complete then allComplete = false end end values[key] = state.value end local wasAllComplete = self.__allComplete self.__allComplete = allComplete self.__fireOnStep(values) -- Check self.__allComplete as the motor may have been restarted in the onStep callback -- even if allComplete is true. -- Check self.__running in case the motor was stopped by onStep if self.__allComplete and not wasAllComplete and self.__running then self:stop() self.__fireOnComplete(values) end end function GroupMotor:setGoal(goals: GoalGroup) self.__goals = assign({}, self.__goals, goals) for key in pairs(goals) do local state = self.__states[key] if state == nil then error(("Cannot set goal for the value %s because it doesn't exist"):format(tostring(key)), 2) end state.complete = false end self.__allComplete = false self:start() end function GroupMotor:onStep(callback: MotorCallback<ValueGroup>) local subscription = self.__onStep:subscribe(callback) return function() subscription:unsubscribe() end end function GroupMotor:onComplete(callback: MotorCallback<ValueGroup>) local subscription = self.__onComplete:subscribe(callback) return function() subscription:unsubscribe() end end function GroupMotor:destroy() self:stop() end return createGroupMotor
1,263
littensy/ripple
littensy-ripple-c33bb8b/benchmarks/otter/createSignal.luau
--[[ Copyright (c) 2023 Roblox Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] --!strict export type Callback<T> = (T) -> () export type Subscription = { unsubscribe: (self: Subscription) -> (), } export type Signal<T> = { subscribe: (self: Signal<T>, callback: Callback<T>) -> Subscription, } export type FireSignal<T> = (T) -> () type InternalSubscription<T> = { callback: Callback<T>, unsubscribed: boolean } local function createSignal<T>(): (Signal<T>, FireSignal<T>) local subscriptions: { [Callback<T>]: InternalSubscription<T> } = {} local suspendedSubscriptions = {} local firing = false local function subscribe(_self: Signal<T>, callback) local subscription = { callback = callback, unsubscribed = false, } -- If the callback is already registered, don't add to the -- suspendedConnection. Otherwise, this will disable the existing one. if firing and not subscriptions[callback] then suspendedSubscriptions[callback] = subscription else subscriptions[callback] = subscription end local function unsubscribe(_self: Subscription) subscription.unsubscribed = true subscriptions[callback] = nil suspendedSubscriptions[callback] = nil end return { unsubscribe = unsubscribe, } end local function fire(value: T) firing = true for callback, subscription in subscriptions do if not subscription.unsubscribed and not suspendedSubscriptions[callback] then callback(value) end end firing = false for callback, subscription in suspendedSubscriptions do subscriptions[callback] = subscription end table.clear(suspendedSubscriptions) end return { subscribe = subscribe, }, fire end return createSignal
618
littensy/ripple
littensy-ripple-c33bb8b/benchmarks/otter/createSingleMotor.luau
--[[ Copyright (c) 2018-2023 Roblox Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] --!strict local AnimationStepSignal = require("./AnimationStepSignal") local createSignal = require("./createSignal") local types = require("./types") type AnimationValue = types.AnimationValue type Goal<T> = types.Goal<T> type State = types.State type Motor<T, U> = types.Motor<T, U> type Unsubscribe = types.Unsubscribe type MotorCallback<T> = types.MotorCallback<T> type SingleMotorInternal = { __goal: Goal<any>, __state: State & any, __onComplete: createSignal.Signal<AnimationValue>, __fireOnComplete: createSignal.FireSignal<AnimationValue>, __onStep: createSignal.Signal<AnimationValue>, __fireOnStep: createSignal.FireSignal<AnimationValue>, __running: boolean, __connection: RBXScriptConnection?, start: (self: SingleMotorInternal) -> (), stop: (self: SingleMotorInternal) -> (), step: (self: SingleMotorInternal, dt: number) -> (), setGoal: (self: SingleMotorInternal, goal: Goal<any>) -> (), onStep: (self: SingleMotorInternal, callback: MotorCallback<AnimationValue>) -> Unsubscribe, onComplete: (self: SingleMotorInternal, callback: MotorCallback<AnimationValue>) -> Unsubscribe, destroy: (self: SingleMotorInternal) -> (), } local SingleMotor = {} :: SingleMotorInternal (SingleMotor :: any).__index = SingleMotor export type SingleMotor = Motor<Goal<any>, AnimationValue> local function createSingleMotor(initialValue: AnimationValue): SingleMotor local onComplete, fireOnComplete = createSignal() local onStep, fireOnStep = createSignal() local self = { __goal = nil, __state = { value = initialValue, complete = true, }, __onComplete = onComplete, __fireOnComplete = fireOnComplete, __onStep = onStep, __fireOnStep = fireOnStep, __running = false, } setmetatable(self, SingleMotor) return self :: any end function SingleMotor:start() if self.__running then return end self.__connection = AnimationStepSignal:Connect(function(dt) self:step(dt) end) self.__running = true end function SingleMotor:stop() if self.__connection ~= nil then self.__connection:Disconnect() end self.__running = false end function SingleMotor:step(dt: number) if self.__state.complete then return end if self.__goal == nil then return end local newState = self.__goal.step(self.__state, dt) if newState ~= nil then self.__state = newState end self.__fireOnStep(self.__state.value) if self.__state.complete and self.__running then self:stop() self.__fireOnComplete(self.__state.value) end end function SingleMotor:setGoal(goal) self.__goal = goal self.__state.complete = false self:start() end function SingleMotor:onStep(callback: MotorCallback<AnimationValue>) local subscription = self.__onStep:subscribe(callback) return function() subscription:unsubscribe() end end function SingleMotor:onComplete(callback: MotorCallback<AnimationValue>) local subscription = self.__onComplete:subscribe(callback) return function() subscription:unsubscribe() end end function SingleMotor:destroy() self:stop() end return createSingleMotor
979
littensy/ripple
littensy-ripple-c33bb8b/benchmarks/otter/ease.luau
--[[ Copyright (c) 2018-2023 Roblox Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] --!strict --[[ Ease functions for creating smooth animations. Provides different easing functions like linear, quadratic, cubic, quartic, quintic, and more. Inspired by Robert Penner's easing functions. Supports Roblox EasingStyle. ]] local types = require("./types") type State = types.State type Goal<T> = types.Goal<T> export type EasingStyle = Enum.EasingStyle | { number } export type EaseOptions = { -- Defaults to 1 duration: number?, -- Defaults to Enum.EasingStyle.Linear easingStyle: EasingStyle?, } type EaseState = { elapsed: number?, goal: number?, initialValue: number?, } local function linear(t: number, _s: EasingStyle): number return t end local function quad(t: number, _s: EasingStyle): number return t * t end local function cubic(t: number, _s: EasingStyle): number return t * t * t end local function quart(t: number, _s: EasingStyle): number return t * t * t * t end local function quint(t: number, _s: EasingStyle): number return t * t * t * t * t end local function exponential(t: number, _s: EasingStyle): number return t == 0 and 0 or math.pow(2, 10 * (t - 1)) end local function sine(t: number, _s: EasingStyle): number return 1 - math.cos((t * math.pi) / 2) end local function elastic(t: number, _s: EasingStyle): number return t == 0 and 0 or t == 1 and 1 or -math.pow(2, 10 * t - 10) * math.sin((t * 10 - 10.75) * ((2 * math.pi) / 3)) end local function back(t: number, _s: EasingStyle): number local c1 = 1.70158 local c3 = c1 + 1 return c3 * t * t * t - c1 * t * t end local function easeOutBounce(t: number): number local n1 = 7.5625 local d1 = 2.75 if t < 1 / d1 then return n1 * t * t elseif t < 2 / d1 then return n1 * (t - 1.5 / d1) * (t - 1.5 / d1) + 0.75 elseif t < 2.5 / d1 then return n1 * (t - 2.25 / d1) * (t - 2.25 / d1) + 0.9375 else return n1 * (t - 2.625 / d1) * (t - 2.625 / d1) + 0.984375 end end local function bounce(t: number, _s: EasingStyle): number return 1 - easeOutBounce(1 - t) end local function circular(t: number, _s: EasingStyle): number return -(math.sqrt(1 - t * t) - 1) end -- Function to evaluate cubic bezier x(t) or y(t) at time t local function evaluateBezier(t: number, p1: number, p2: number): number local oneMinusT = 1 - t local oneMinusT2 = oneMinusT * oneMinusT local t2 = t * t return 3 * oneMinusT2 * t * p1 + 3 * oneMinusT * t2 * p2 + t * t2 end local NUM_ITERATIONS = 10 local function cubicBezier(t: number, values: EasingStyle): number assert(typeof(values) == "table", "Expected values to be a table") assert(#values == 4, "Expected values to have 4 elements") local x1, y1, x2, y2 = table.unpack(values) assert(x1 >= 0 and x1 <= 1, "x1 must be between 0 and 1") assert(x2 >= 0 and x2 <= 1, "x2 must be between 0 and 1") -- Handle edge cases if t <= 0 then return 0 end if t >= 1 then return 1 end -- Binary search to find t value where x(t) = target local left = 0 local right = 1 local target = t local iterationCount = 0 local finalError for _ = 1, NUM_ITERATIONS do iterationCount += 1 local mid = (left + right) / 2 local x = evaluateBezier(mid, x1, x2) finalError = math.abs(x - target) if finalError < 0.0001 then -- Found close enough match local y = evaluateBezier(mid, y1, y2) return y elseif x < target then left = mid else right = mid end end -- Use final midpoint local finalT = (left + right) / 2 local y = evaluateBezier(finalT, y1, y2) return y end -- deviation: declare easing style table local Enum: typeof(Enum) = { EasingStyle = { Linear = "Linear", Quad = "Quad", Cubic = "Cubic", Quart = "Quart", Quint = "Quint", Exponential = "Exponential", Sine = "Sine", Back = "Back", Bounce = "Bounce", Elastic = "Elastic", Circular = "Circular", }, } :: any local easingFunctions = { [Enum.EasingStyle.Linear] = linear, [Enum.EasingStyle.Quad] = quad, [Enum.EasingStyle.Cubic] = cubic, [Enum.EasingStyle.Quart] = quart, [Enum.EasingStyle.Quint] = quint, [Enum.EasingStyle.Exponential] = exponential, [Enum.EasingStyle.Sine] = sine, [Enum.EasingStyle.Back] = back, [Enum.EasingStyle.Bounce] = bounce, [Enum.EasingStyle.Elastic] = elastic, [Enum.EasingStyle.Circular] = circular, } local function ease(goalPosition: number, inputOptions: EaseOptions?): Goal<EaseState> local duration = if inputOptions and inputOptions.duration then inputOptions.duration else 1 local easingStyle = if inputOptions and inputOptions.easingStyle then inputOptions.easingStyle else Enum.EasingStyle.Linear local easingFunction: (number, Enum.EasingStyle | { number }) -> number = if typeof(easingStyle) == "EnumItem" or typeof(easingStyle) == "string" then easingFunctions[easingStyle] else cubicBezier local function step(state: State & EaseState, dt: number): State & EaseState local p0 = if state.initialValue ~= nil then state.initialValue else state.value or 0 local elapsed = (state.elapsed or 0) + dt -- If the goalPosition changed, update initialValue if state.goal and goalPosition ~= state.goal :: number then p0 = state.value elapsed = 0 end local t = math.min(elapsed / duration, 1) local easedT = easingFunction(t, easingStyle) local p1 = p0 + (goalPosition - p0) * easedT local complete = elapsed >= duration or p0 == goalPosition if complete then p1 = goalPosition -- Set these for accuracy in the next animation p0 = goalPosition elapsed = 0 end return { initialValue = p0, goal = goalPosition, value = p1, elapsed = elapsed, complete = complete, } end return { step = step, } end return ease
2,037
littensy/ripple
littensy-ripple-c33bb8b/benchmarks/otter/types.luau
--[[ Copyright (c) 2018-2023 Roblox Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] --!strict export type MotorCallback<T> = (T) -> () export type Unsubscribe = () -> () -- Animation values need to be continuous and interpolatable; for now, that's -- probably just numbers, but one could imagine something more sophisticated export type AnimationValue = number type Empty = {} export type State = { value: AnimationValue, complete: boolean, } export type Goal<T = Empty> = { step: (state: State & T, dt: number) -> State & T, } export type Motor<T, U> = { start: (self: Motor<T, U>) -> (), stop: (self: Motor<T, U>) -> (), step: (self: Motor<T, U>, dt: number) -> (), setGoal: (self: Motor<T, U>, goal: T) -> (), onStep: (self: Motor<T, U>, callback: MotorCallback<U>) -> Unsubscribe, onComplete: (self: Motor<T, U>, callback: MotorCallback<U>) -> Unsubscribe, destroy: (self: Motor<T, U>) -> (), } return {}
467