Dataset Viewer
Auto-converted to Parquet Duplicate
repo
stringclasses
371 values
file_path
stringlengths
29
241
code
stringlengths
100
736k
tokens
int64
20
266k
imezx/Surround
imezx-Surround-dde33fc/src/init.luau
--!optimize 2 --!native local Surround = {} local RunService = game:GetService("RunService") local ReplicatedStorage = game:GetService("ReplicatedStorage") local scheduler = require(ReplicatedStorage:WaitForChild("scheduler")) local begin_profiler, end_profiler = scheduler.profiler.Begin, scheduler.profiler.End local Player: Player = game:GetService("Players").LocalPlayer type Object = { root: BasePart, sound: Sound, baseVolume: number, max_distance: number, } local default_max_distance: number = 15 local throttle: number = 1 / 24 local last_throttle: number = 0 local objects: { Object } = {} local queued: { Object } = {} Surround.addObject = function(_object: BasePart, sound: Sound, baseVolume: number?, max_distance: number?) if not _object or not sound then return end local object: BasePart = _object if _object:IsA("Model") and _object.PrimaryPart then object = _object.PrimaryPart end if not object:IsA("BasePart") then return end table.insert(objects, { root = object, sound = sound, baseVolume = baseVolume or sound.Volume, max_distance = max_distance or default_max_distance, }) end Surround.removeObject = function(_object: BasePart, sound: Sound) if not _object or not sound then return end local object: BasePart = _object if _object:IsA("Model") and _object.PrimaryPart then object = _object.PrimaryPart end for idx: number, obj: Object in objects do if obj.root == object and obj.sound == sound then table.remove(objects, idx) return end end end RunService.PreRender:Connect(function(dt: number) if last_throttle <= throttle then last_throttle += dt return end last_throttle = 0 local characterRoot: BasePart? = Player.Character and Player.Character.PrimaryPart if not characterRoot then return end begin_profiler("Surround.simulate") local characterPos: Vector3 = characterRoot.Position if next(queued) then local sounds: { [Sound]: number } = {} for _, object: Object in queued do local pos: Vector3 = object.root.Position local distance: number = (pos - characterPos).Magnitude local volume: number = math.clamp(object.baseVolume * (1 - distance / object.max_distance), 0, object.baseVolume) local highest_volume: number = sounds[object.sound] or -1 if volume <= highest_volume then continue end sounds[object.sound] = volume end table.clear(queued) for sound: Sound, volume: number in sounds do sound.Volume = volume end else for idx: number, object: Object in objects do if not object.root or not object.sound or not object.root.Parent then objects[idx] = nil continue end if not object.root:IsDescendantOf(workspace) then continue end table.insert(queued, object) end end end_profiler("Surround.simulate") end) return Surround :: typeof(Surround)
729
imezx/MultiRaycast
imezx-MultiRaycast-c45dd4d/src/init.luau
--@EternityDev --!strict --!native --!optimize 2 local Raycast = {} Raycast.__index = Raycast local RunService = game:GetService("RunService") local Signal = require(script.Signal) local PreSimulation = RunService.PreSimulation local sampleActor = script:WaitForChild("Actor") function Raycast.new(header: string, directory: Instance, raycastParam: RaycastParams?, actors: number?) if not header then header = tostring(math.random(99, 1999)) end if not raycastParam then raycastParam = RaycastParams.new() end local meta = setmetatable({}, Raycast) meta.filter = raycastParam meta.origin = Vector3.new() meta.direction = Vector3.new() meta.state = "inactive" meta.inputs = {} meta.outputs = {} meta.connections = {} meta.task = {} meta._actors = {} meta.Signal = Signal(`Signal-{header}`) if not directory:FindFirstChild(`Actors-{header}`) then Instance.new("Folder", directory).Name = `Actors-{header}` end for idx=1,actors or 4 do local actor = sampleActor:Clone() meta.inputs[idx] = actor.Input meta.outputs[idx] = actor.Output.Event if RunService:IsClient() then actor.Client.Enabled = true actor.Server.Enabled = false else actor.Client.Enabled = false actor.Server.Enabled = true end table.insert(meta._actors, actor) actor.Parent = directory:FindFirstChild(`Actors-{header}`) end meta:_bind() return meta end function Raycast:updateFilter(raycastParam: RaycastParams) if not raycastParam then return end self.filter = raycastParam end function Raycast:setOrigin(origin: Vector3) if not origin then return end self.origin = origin end function Raycast:setDirection(direction: Vector3) if not direction then return end self.direction = direction end function Raycast:_unbind() for _, c in self.connections do c:Disconnect() end table.clear(self.connections) end function Raycast:_bind() for idx, output: RBXScriptSignal in self.outputs do self.connections[idx] = output:Connect(function(...) self.Signal:Fire(...) end) end end function Raycast:run(forceRun: boolean?) if not forceRun then if self.state == "active" then return end end self.state = "active" local newTask newTask = task.spawn(function() while PreSimulation:Wait() do for _, input: BindableEvent in self.inputs do input:Fire(self.origin, self.direction, self.filter) end end end) table.insert(self.task, newTask) end function Raycast:stop() if self.state == "inactive" then return end for _, t in self.task do task.cancel(t) end table.clear(self.task) self.state = "inactive" end function Raycast:destroy() self:stop() self:_unbind() self.Signal:Destroy() for _, actor in self._actors do actor.Parent:Destroy() break end table.clear(self) setmetatable(self, nil) end return Raycast :: typeof(Raycast)
710
imezx/TaskChain
imezx-TaskChain-83b1c84/src/Types.luau
--!strict --!optimize 2 local promise = require(script.Parent.Parent.promise) local janitor = require(script.Parent.Parent.janitor) export type Promise<T...> = promise.TypedPromise<T...> export type Janitor = janitor.Janitor export type task = { type: "call" | "wait" | "promise" | "andThen" | "catch" | "finally" | "track", payload: any, } export type status = "Pending" | "Running" | "Resolved" | "Rejected" | "Destroyed" export type TaskChain = { call: (self: TaskChain, func: (...any) -> ...any, ...any) -> TaskChain, wait: (self: TaskChain, duration: number) -> TaskChain, promise: (self: TaskChain, promise: Promise) -> TaskChain, andThen: (self: TaskChain, onSuccess: ((...any) -> ...any)?, onFailure: ((any) -> any)?) -> TaskChain, track: <T>(self: TaskChain, item: T, cleanupMethod: string | boolean | nil) -> TaskChain, catch: (self: TaskChain, errorHandler: (err: any) -> any) -> TaskChain, finally: (self: TaskChain, handler: () -> ()) -> TaskChain, destroy: (self: TaskChain) -> (), remove: (self: TaskChain) -> (), await: (self: TaskChain) -> any?, fork: (self: TaskChain) -> TaskChain, _tasks: { task }, _janitor: Janitor, _promise: Promise, _status: status, _isProcessing: boolean, } return { promise = promise, janitor = janitor, }
374
imezx/TaskChain
imezx-TaskChain-83b1c84/src/init.luau
--!optimize 2 local TaskChain = {} TaskChain.__index = TaskChain local types = require(script.Types) --] local function _processNextTask(self: types.TaskChain) if self._status == "Destroyed" or not self._isProcessing then return end if #self._tasks == 0 then self._isProcessing = false return end local taskDescriptor = table.remove(self._tasks, 1) self._promise = self._promise:andThen(function(...) if self._status == "Destroyed" then return types.promise .new(function(_, _, onCancel) onCancel(function() return end) end) :cancel() end local results = { ... } local taskType = taskDescriptor.type local payload = taskDescriptor.payload if taskType == "call" then return payload.func(table.unpack(results), table.unpack(payload.args)) elseif taskType == "wait" then local waitPromise = types.promise.delay(payload.duration) self._janitor:Add(waitPromise, "cancel") return waitPromise:andThen(function() return table.unpack(results) end) elseif taskType == "promise" then self._janitor:Add(payload.promise, "cancel") return payload.promise elseif taskType == "andThen" then local p = types.promise.resolve(table.unpack(results)) return p:andThen(payload.onSuccess, payload.onFailure) elseif taskType == "track" then self._janitor:Add(payload.item, payload.cleanupMethod) return table.unpack(results) elseif taskType == "catch" or taskType == "finally" then return table.unpack(results) end end) _processNextTask(self) end --] function TaskChain.new(): types.TaskChain local self = setmetatable({ _tasks = {}, _janitor = types.janitor.new(), _status = "Pending", _isProcessing = false, }, TaskChain) self._promise = types.promise.resolve() self._janitor:Add(self._promise, "cancel") return self end --] function TaskChain:call(func: (...any) -> ...any, ...): types.TaskChain table.insert(self._tasks, { type = "call", payload = { func = func, args = { ... } }, }) if not self._isProcessing then self._isProcessing = true self._status = "Running" _processNextTask(self) end return self end --] function TaskChain:wait(duration: number?): types.TaskChain table.insert(self._tasks, { type = "wait", payload = { duration = (duration or 0.016666) }, }) if not self._isProcessing then self._isProcessing = true self._status = "Running" _processNextTask(self) end return self end --] function TaskChain:promise(promise: types.Promise): types.TaskChain table.insert(self._tasks, { type = "promise", payload = { promise = promise }, }) if not self._isProcessing then self._isProcessing = true self._status = "Running" _processNextTask(self) end return self end --] function TaskChain:andThen(onSuccess, onFailure): types.TaskChain table.insert(self._tasks, { type = "andThen", payload = { onSuccess = onSuccess, onFailure = onFailure }, }) if not self._isProcessing then self._isProcessing = true self._status = "Running" _processNextTask(self) end return self end --] function TaskChain:track(item, cleanupMethod: string): types.TaskChain table.insert(self._tasks, { type = "track", payload = { item = item, cleanupMethod = cleanupMethod }, }) if not self._isProcessing then self._isProcessing = true self._status = "Running" _processNextTask(self) end return self end --] function TaskChain:catch(errorHandler): types.TaskChain self._promise = self._promise:catch(errorHandler) self._promise:catch(function() if self._status ~= "Destroyed" then self._status = "Rejected" end end) return self end --] function TaskChain:finally(handler): types.TaskChain self._promise = self._promise:finally(handler) self._promise:andThen(function() if self._status == "Running" then self._status = "Resolved" end end) return self end --] function TaskChain:await(): any? local value = select(2, self._promise:await()) self:destroy() return value end --] function TaskChain:fork(): types.TaskChain local newChain = TaskChain.new() newChain._promise = self._promise return newChain end --] function TaskChain:destroy() if self._status == "Destroyed" then return end self._status = "Destroyed" self._isProcessing = false self._tasks = {} self._janitor:Destroy() table.clear(self) setmetatable(self, nil) end TaskChain.remove = TaskChain.destroy return table.freeze(TaskChain)
1,143
imezx/Scheduler
imezx-Scheduler-43e0719/src/client/init.luau
--!optimize 2 local client = {} local ContextActionService = game:GetService("ContextActionService") local CollectionService = game:GetService("CollectionService") local localPlayer = game:GetService("Players").LocalPlayer local vide = require("../vide") local Profiler = require("./profiler") local client_performance = require("@self/performance") local remotes = require("@self/remotes/Remotes") local spawn_app = require("./ui/spawn_app") local home_app = require("./ui/home") local unbind_performance_socket = remotes.fromEvent("scheduler.unbind_performance_socket") local profiler_state = remotes.fromEvent("scheduler.profiler_state") local server_frame_value = vide.source({}) local version: string, rootScope, root_performance, home_app_ui Profiler.store("server_frame_value", server_frame_value) local function onStateChanged(instance: Instance?) if instance and instance ~= localPlayer then return end if localPlayer:HasTag("__allowedScheduler__") then script.Parent.profiler:SetAttribute("__state__", true) else script.Parent.profiler:SetAttribute("__state__", false) end end client.assign_ver = function(ver: string) version = ver end client.init = function() if script:HasTag("__init__") then return end script:AddTag("__init__") CollectionService:GetInstanceAddedSignal("__allowedScheduler__"):Connect(onStateChanged) CollectionService:GetInstanceRemovedSignal("__allowedScheduler__"):Connect(onStateChanged) task.defer(onStateChanged) end client.toggle_widget = function(_, state: Enum.UserInputState) if state and state ~= Enum.UserInputState.End then return end -- cleanup if root_performance then root_performance() root_performance = nil end if not localPlayer:HasTag("__allowedScheduler__") or rootScope then home_app_ui = nil profiler_state:FireServer(false) unbind_performance_socket:FireServer() Profiler.reset() Profiler.Pause() if rootScope then rootScope() rootScope = nil end spawn_app.unmount_all() return end if home_app_ui then return end root_performance = client_performance.run(Profiler) profiler_state:FireServer(true) Profiler.reset() Profiler.Resume() rootScope = vide.root(function() -- Server Scheduler home_app_ui = home_app({ env = "Server", Profiler = Profiler, profiler_state = profiler_state, ProfilerState = Profiler.get_stored("server_frame_value"), Runtime = Profiler.get_stored("server_runtime"), version = version, onClose = function() if home_app_ui then home_app_ui.Enabled = false end end, onDestroy = function() home_app_ui = nil profiler_state:FireServer(false) unbind_performance_socket:FireServer() Profiler.reset() Profiler.Pause() if not rootScope then return end rootScope() rootScope = nil spawn_app.unmount_all() end, }) home_app_ui.Parent = game.Players.LocalPlayer:WaitForChild("PlayerGui", 9e9) end) end client.bind_to = function(key_bind: Enum.KeyCode) if not client then warn(`please use .client() first.`) return end ContextActionService:UnbindAction("Toggle Scheduler Widget") ContextActionService:BindAction("Toggle Scheduler Widget", client.toggle_widget, false, key_bind or Enum.KeyCode.F3) end return client :: typeof(client)
784
imezx/Scheduler
imezx-Scheduler-43e0719/src/client/performance.luau
--!optimize 2 local Players = game:GetService("Players") local RunService = game:GetService("RunService") local Stats = game:GetService("Stats") local vide = require("../../vide") local remotes = require("./remotes/Remotes") local get_performance_socket = remotes.fromFunction("scheduler.get_performance_socket") local communicate_frame_time = remotes.fromEvent("scheduler.communicate_frame_time") local server_frame_time = remotes.fromEvent("scheduler.server_frame_time") local communicate_run_time = remotes.fromEvent("scheduler.communicate_run_time") local root, source, cleanup = vide.root, vide.source, vide.cleanup local open_connections: { [Player | string]: RBXScriptConnection } = {} local Buffer = remotes.buffer local localUser: Player = Players.LocalPlayer local average_heartbeat: number = 0 local average_frames: number = 0 local render_gpu_frame_time: number = 0 local render_cpu_frame_time: number = 0 local counter: number = 0 local acccumulate: number = 0 local UPDATE_EVERY: number = 1 local scope_value = source("") local store = source({}) local localSocketId = source("") local memory_usage = source({} :: { number }) local heartbeat_time = source({} :: { number }) local frames_time = source({} :: { number }) local render_gpu_time = source({} :: { number }) local render_cpu_time = source({} :: { number }) local function performance(Profiler) cleanup(function() for host: Player | string, socket: RBXScriptConnection in open_connections do socket:Disconnect() end table.clear(open_connections) end) local function obtain_store_data(host: Player | string) local data = host and get_performance_socket:Invoke(3, { to = host, id = 0 }, nil) if not data or not data.socket then return end localSocketId(data.socket) local memory = source(0) local heartbeat_time = source(0) local frames_time = source(0) local render_gpu_time = source(0) local render_cpu_time = source(0) store()[host] = { memory = memory, heartbeat_time = heartbeat_time, frames_time = frames_time, render_gpu_time = render_gpu_time, render_cpu_time = render_cpu_time, } store(store()) local socket: RBXScriptConnection socket = communicate_frame_time.OnClientEvent:Connect(function(_host: Player | string, packet: buffer) if _host ~= host or type(packet) ~= "buffer" then return end -- socket:Disconnect() local packet_heartbeat_time: number, packet_frames_time: number, packet_render_gpu_time: number, packet_render_cpu_time: number, packet_memory: number = buffer.readf64(packet, 0), buffer.readf64(packet, 8), buffer.readf64(packet, 16), buffer.readf64(packet, 24), buffer.readf64(packet, 32) heartbeat_time(packet_heartbeat_time) frames_time(packet_frames_time) render_gpu_time(packet_render_gpu_time) render_cpu_time(packet_render_cpu_time) memory(packet_memory) Profiler.socket_assign(host, { memory = packet_memory, heartbeat_time = packet_heartbeat_time, frames_time = packet_frames_time, render_cpu_time = packet_render_cpu_time, render_gpu_time = packet_render_gpu_time, }) end) open_connections[host] = socket if host == localUser then communicate_run_time.OnClientEvent:Connect(function(packet: buffer) if type(packet) ~= "buffer" then return end local parsed_runTime: string = buffer.tostring(packet) scope_value(parsed_runTime) local scope_value = Profiler.get_stored("server_runtime") if not scope_value then Profiler.store("server_runtime", scope_value) end end) end end obtain_store_data("server") for _, player: Player in Players:GetPlayers() do obtain_store_data(player) end cleanup(Players.PlayerAdded:Connect(obtain_store_data)) cleanup(Players.PlayerRemoving:Connect(function(Player: Player) if open_connections[Player] then open_connections[Player]:Disconnect() open_connections[Player] = nil end end)) cleanup(RunService.Heartbeat:Connect(function() for host: Player | string, socket: RBXScriptConnection in open_connections do if socket and socket.Connected then continue end store()[host] = nil store(store()) end end)) local server_frame_value = Profiler.get_stored("server_frame_value") cleanup(RunService.Heartbeat:Connect(function(dt: number) counter += 1 acccumulate += dt average_heartbeat += Stats.HeartbeatTime average_frames += Stats.FrameTime render_gpu_frame_time += Stats.RenderGPUFrameTime render_cpu_frame_time += Stats.RenderCPUFrameTime if acccumulate > UPDATE_EVERY then if next(open_connections) then local b: buffer = buffer.create(40) local data_memory: number, data_heartbeat_time: number, data_frames_time: number, data_render_cpu_frame_time: number, data_render_gpu_frame_time: number = Stats:GetTotalMemoryUsageMb() * 1e3 * 1e3, average_heartbeat / counter, average_frames / counter, render_cpu_frame_time / counter, render_gpu_frame_time / counter buffer.writef64(b, 0, data_heartbeat_time) buffer.writef64(b, 8, data_frames_time) buffer.writef64(b, 16, data_render_gpu_frame_time) buffer.writef64(b, 24, data_render_cpu_frame_time) buffer.writef64(b, 32, data_memory) memory_usage()[localUser] = data_memory heartbeat_time()[localUser] = data_heartbeat_time frames_time()[localUser] = data_frames_time render_gpu_time()[localUser] = data_render_cpu_frame_time render_cpu_time()[localUser] = data_render_gpu_frame_time communicate_frame_time:FireServer(localSocketId(), b) Profiler.socket_assign(localUser, { memory = data_memory, heartbeat_time = data_heartbeat_time, frames_time = data_frames_time, render_cpu_time = data_render_cpu_frame_time, render_gpu_time = data_render_gpu_frame_time, }) end average_heartbeat = 0 average_frames = 0 render_gpu_frame_time = 0 render_cpu_frame_time = 0 acccumulate -= UPDATE_EVERY counter = 0 end end)) cleanup(server_frame_time.OnClientEvent:Connect(function(packet: buffer) if type(packet) ~= "buffer" then return end local raw_exported_server_frames = Buffer.read(packet) if not raw_exported_server_frames then return end server_frame_value(Profiler.merge(raw_exported_server_frames, false)) end)) end return { run = function(Profiler) return root(function() performance(Profiler) end) end, }
1,609
imezx/Scheduler
imezx-Scheduler-43e0719/src/client/remotes/Function.luau
--!optimize 2 --!strict --@EternityDev local Function = {} Function.__index = Function local RunService = game:GetService("RunService") function Function.new(remote: RemoteFunction) local meta = setmetatable({ remote = remote, }, Function) remote.Destroying:Once(function() if not meta then return end Function.Remove(meta) end) return meta end function Function:Invoke(expireTime: number, ...: any): (...any?) if not RunService:IsClient() then return error("Cannot execute InvokeServer on the server.", 2) end if not expireTime then return end local timer, session local obj = { ... } local thread: thread = coroutine.running() timer = task.delay(expireTime or 3, function() task.cancel(session) task.spawn(thread, nil) end) session = task.spawn(function() local obj = self.remote:InvokeServer(table.unpack(obj)) task.cancel(timer) task.spawn(thread, obj) end) return coroutine.yield() end function Function:Remove() setmetatable(self, nil) end function Function:Destroy() self.remote:Destroy() end return Function
254
imezx/Scheduler
imezx-Scheduler-43e0719/src/client/remotes/Remotes.luau
--!optimize 2 --!strict --@EternityDev --Client local Remotes = {} if not script.Parent.Parent.Parent:FindFirstChild("Remotes") then Instance.new("Folder", script.Parent.Parent.Parent).Name = "Remotes" end local RemotesDir = script.Parent.Parent.Parent:WaitForChild("Remotes") local Function = require("./Function") function Remotes.fromEvent(remoteName: string): RemoteEvent if not RemotesDir:FindFirstChild(`Remote_{remoteName}`) then error(`Oops, cant find remote-event for "{remoteName}", make sure you have defined it on server-side.`) end return RemotesDir[`Remote_{remoteName}`] end function Remotes.fromFunction(remoteName: string) if not RemotesDir:FindFirstChild(`Remote_{remoteName}`) then error(`Oops, cant find remote-function for "{remoteName}", make sure you have defined it on server-side.`) end return Function.new(RemotesDir[`Remote_{remoteName}`]) end Remotes.buffer = require("../../util/bufferencoder") return Remotes
237
imezx/Scheduler
imezx-Scheduler-43e0719/src/init.luau
--!optimize 2 --!strict local scheduler = {} local profiler = require("@self/profiler") local client = nil scheduler.profiler = profiler scheduler.server = function() local server = require("@self/server") return server end scheduler.client = function() if client then return client end client = require("@self/client") client.assign_ver("0.1.4") return client end return scheduler :: typeof(scheduler)
96
imezx/Scheduler
imezx-Scheduler-43e0719/src/profiler/init.luau
--!optimize 2 --!native local Profiler = {} Profiler.isRunning = false local IsServer: boolean = game:GetService("RunService"):IsServer() local vide = require("../vide") local convert_scale = require("./util/convert_scale") local Signal = require("./util/limesignal") local socket_changed_signal = Signal.Signal.new() local lastUpdated: number, profiler_state: boolean = os.clock(), IsServer type socket_array_map = { memory: number, heartbeat_time: number, frames_time: number, render_gpu_time: number, render_cpu_time: number, } type socket_transcript_type_inner = { id: number, host: string, memory: string, cpu: string, frames: string, gpu: string, cpuRender: string, } type socket_transcript_type = { socket_transcript_type_inner } type TimerInfo = { name: string, startTime: number, deductedTime: number, } local activeTimers: { [thread]: { TimerInfo } } = {} local frameSystems: { { Name: string, Duration: number, Color: Color3 } } = {} local colorCache: { [string]: Color3 } = {} local sockets: { [Player | string]: socket_array_map } = {} local stores: { [string]: any } = {} local timerPool: { TimerInfo } = {} local function allocTimer(name: string, startTime: number): TimerInfo local t = table.remove(timerPool) if t then t.name = name t.startTime = startTime t.deductedTime = 0 return t end return { name = name, startTime = startTime, deductedTime = 0, } end local function freeTimer(t: TimerInfo) table.insert(timerPool, t) end local state: (any) -> { any } = vide.source({}) local function generateColor(str: string): Color3 if colorCache[str] then return colorCache[str] end local hash: number = 0 for i: number = 1, #str do local char: number = string.byte(str, i) hash = (bit32.lshift(hash, 5) - hash) + char hash = bit32.band(hash, hash) -- Convert to 32bit integer end local hue: number = (hash % 360) / 360 local color: Color3 = Color3.fromHSV(hue, 0.8, 0.95) colorCache[str] = color return color end Profiler.reset = function() Profiler.isRunning = false table.clear(activeTimers) table.clear(frameSystems) Profiler.isRunning = true end -- Sockets Profiler.all_sockets = function(): { [Player | string]: socket_array_map? } return sockets end Profiler.socket_assign = function(host: Player | string, new_map: socket_array_map) sockets[host] = new_map socket_changed_signal:fire() end Profiler.getSocket = function(host: Player | string): socket_array_map? return sockets[host] end -- { id = 1, host = "server", memory = "0.00GB", cpu = "0.0us", gpu = "0.0us", cpuRender = "0.00ms" }, Profiler.sockets_transcript = function(): socket_transcript_type local idx: number, transcript: socket_transcript_type = 1, {} for host: Player | string, map: socket_array_map in sockets do local frame_time: number = 1 / (map.frames_time or 1) if frame_time ~= frame_time or frame_time == math.huge then frame_time = 0 end table.insert(transcript, { id = idx, host = type(host) == "string" and host or (host :: Player).Name, memory = convert_scale("B", map.memory), cpu = convert_scale("s", map.heartbeat_time or 0), frames = string.format("%.2f", frame_time), gpu = convert_scale("s", map.render_gpu_time or 0), cpuRender = convert_scale("s", map.render_cpu_time or 0), }) idx += 1 end table.sort(transcript, function(a: socket_transcript_type_inner, b: socket_transcript_type_inner): boolean return a.id ~= 1 and true or a.host < b.host end) return transcript end Profiler.onSocketChanged = socket_changed_signal -- Profilers Profiler.RunTime = function(): number local runTime: number = 0 for _, frame: { Name: string, Duration: number, Color: Color3 } in frameSystems do runTime += frame.Duration end return runTime end Profiler.merge = function(map_value: { { Name: string, Duration: number, Color: Color3 } }?, update_state: boolean?) map_value = map_value or frameSystems local merged: { [string]: { Name: string, Duration: number, Count: number, Color: Color3 } } = {} for _, frameData: { Name: string, Duration: number, Color: Color3 } in map_value :: any do if not merged[frameData.Name] then merged[frameData.Name] = { Name = frameData.Name, Duration = frameData.Duration, Count = 1, Color = frameData.Color, } else local system = merged[frameData.Name] system.Duration += frameData.Duration system.Count += 1 end end local sorted = {} for _, system in merged do system.Duration /= system.Count table.insert(sorted, system) end table.sort(sorted, function(a, b) return a.Name < b.Name end) if update_state == nil or update_state then state(sorted) end table.clear(frameSystems) return sorted end Profiler.Begin = function(name: string) if not Profiler.isRunning or not profiler_state then return end local startTime = os.clock() local currentThread: thread = coroutine.running() local threadStack = activeTimers[currentThread] if not threadStack then threadStack = {} activeTimers[currentThread] = threadStack end table.insert(threadStack, allocTimer(name, startTime)) -- overhead compensation local endTime = os.clock() local overhead = endTime - startTime if #threadStack > 1 then threadStack[#threadStack - 1].deductedTime += overhead end end Profiler.End = function(name: string) if not Profiler.isRunning or not profiler_state then return end local endStart: number = os.clock() local currentThread: thread = coroutine.running() local threadTimers: { TimerInfo } = activeTimers[currentThread] if not threadTimers then return end local lastIndex = #threadTimers if lastIndex > 0 and threadTimers[lastIndex].name == name then local timer = threadTimers[lastIndex] table.remove(threadTimers, lastIndex) local duration: number = endStart - timer.startTime - timer.deductedTime if duration < 0 then duration = 0 end table.insert(frameSystems, { Name = name, Duration = duration, Color = generateColor(name), }) freeTimer(timer) else for i: number = lastIndex - 1, 1, -1 do local timer: TimerInfo = threadTimers[i] if timer.name == name then table.remove(threadTimers, i) local duration: number = endStart - timer.startTime - timer.deductedTime if duration < 0 then duration = 0 end table.insert(frameSystems, { Name = name, Duration = duration, Color = generateColor(name), }) freeTimer(timer) break end end end local endFinish = os.clock() local overhead = endFinish - endStart if #threadTimers > 0 then threadTimers[#threadTimers].deductedTime += overhead end if #threadTimers == 0 then activeTimers[currentThread] = nil end if endStart - lastUpdated >= 1 then lastUpdated = endStart Profiler.merge(nil, true) end end Profiler.Pause = function() Profiler.isRunning = false end Profiler.Resume = function() Profiler.isRunning = true end Profiler.dump_state = function() return state end Profiler.dump_frames = function(): { { Name: string, Duration: number, Color: Color3 } } return frameSystems end -- Misc Profiler.store = function(key: string, value: any) stores[key] = value end Profiler.get_stored = function(key: string): any? return stores[key] end if not IsServer then script:GetAttributeChangedSignal("__state__"):Connect(function() profiler_state = script:GetAttribute("__state__") end) profiler_state = script:GetAttribute("__state__") end return Profiler :: typeof(Profiler)
1,987
imezx/Scheduler
imezx-Scheduler-43e0719/src/server/init.luau
--!optimize 2 local server = {} local HttpService = game:GetService("HttpService") local RunService = game:GetService("RunService") local Stats = game:GetService("Stats") local CollectionService = game:GetService("CollectionService") local convert_units = require("./util/convert_units") local remotes = require("@self/remotes/Remotes") local Buffer = remotes.buffer local get_performance_socket = remotes.fromFunction("scheduler.get_performance_socket") local unbind_performance_socket = remotes.fromEvent("scheduler.unbind_performance_socket") local communicate_frame_time = remotes.fromEvent("scheduler.communicate_frame_time") local server_frame_time = remotes.fromEvent("scheduler.server_frame_time") local communicate_run_time = remotes.fromEvent("scheduler.communicate_run_time") local profiler_state = remotes.fromEvent("scheduler.profiler_state") local SEND_EVERY: number = 1 server.allowed = function(): { Player } return CollectionService:GetTagged("__allowedScheduler__") end server.allow = function(player: Player) player:AddTag("__allowedScheduler__") end server.disallow = function(player: Player) player:RemoveTag("__allowedScheduler__") end server.init = function(Profiler) if script:HasTag("__init__") then return end script:AddTag("__init__") local active_sockets = {} local _queue = {} get_performance_socket.remote.OnServerInvoke = function(sender: Player) local socket_id: string = HttpService:GenerateGUID(false):gsub("-", "") active_sockets[sender] = socket_id return { socket = socket_id, } end unbind_performance_socket.OnServerEvent:Connect(function(sender: Player) active_sockets[sender] = nil end) communicate_frame_time.OnServerEvent:Connect(function(sender: Player, socketId: string, packet: buffer) if type(socketId) ~= "string" or type(packet) ~= "buffer" or buffer.len(packet) ~= 40 or not active_sockets[sender] or active_sockets[sender] ~= socketId then return end _queue[sender] = packet end) profiler_state.OnServerEvent:Connect(function(sender: Player, state: boolean) if not active_sockets[sender] or not sender:HasTag("__allowedScheduler__") or type(state) ~= "boolean" then return end Profiler.reset() if state == true then Profiler.Resume() else Profiler.Pause() end end) local average_heartbeat: number = 0 local average_frames: number = 0 local render_gpu_frame_time: number = 0 local render_cpu_frame_time: number = 0 local counter: number = 0 local acccumulate: number = 0 RunService.Heartbeat:Connect(function(dt: number) counter += 1 acccumulate += dt average_heartbeat += Stats.HeartbeatTime average_frames += dt render_gpu_frame_time += Stats.RenderGPUFrameTime render_cpu_frame_time += Stats.RenderCPUFrameTime if acccumulate > SEND_EVERY and Profiler.isRunning then if next(active_sockets) then local runTime: string = convert_units("s", Profiler.RunTime()) local exported_scheduler: { { Name: string, Duration: number, Color: Color3 } } = Profiler.dump_frames() local b: buffer = buffer.create(40) buffer.writef64(b, 0, average_heartbeat / counter) buffer.writef64(b, 8, average_frames / counter) buffer.writef64(b, 16, render_gpu_frame_time / counter) buffer.writef64(b, 24, render_cpu_frame_time / counter) buffer.writef64(b, 32, Stats:GetTotalMemoryUsageMb() * 1e3 * 1e3) for socket: Player in active_sockets do if not socket or not socket.Parent then active_sockets[socket] = nil continue end communicate_frame_time:FireClient(socket, "server", b) server_frame_time:FireClient(socket, Buffer.write(exported_scheduler)) communicate_run_time:FireClient(socket, buffer.fromstring(runTime)) end end if next(_queue) then for host: Player, packet: buffer in _queue do if not host or not host.Parent or buffer.len(packet) ~= 40 then _queue[host] = nil continue end for socket: Player in active_sockets do if not socket or not socket.Parent then active_sockets[socket] = nil continue end if socket == host then continue end communicate_frame_time:FireClient(socket, host, packet) end _queue[host] = nil end end average_heartbeat = 0 average_frames = 0 render_gpu_frame_time = 0 render_cpu_frame_time = 0 acccumulate -= SEND_EVERY counter = 0 end end) end return server :: typeof(server)
1,141
imezx/Scheduler
imezx-Scheduler-43e0719/src/server/remotes/Function.luau
--!optimize 2 --!strict --@EternityDev local Function = {} Function.__index = Function local RunService = game:GetService("RunService") function Function.new(remote: RemoteFunction) local meta = setmetatable({ remote = remote, }, Function) remote.Destroying:Once(function() if not meta then return end Function.Remove(meta) end) return meta end function Function:Invoke(expireTime: number, player: Player, ...: any): ...any? if not RunService:IsServer() then return error("Cannot execute InvokeClient on the Client.", 2) end if not expireTime then return end local timer, session local obj = { ... } local thread: thread = coroutine.running() timer = task.delay(expireTime or 3, function() task.cancel(session) task.spawn(thread, nil) end) session = task.spawn(function() if not player or not player.Parent then task.cancel(timer) task.spawn(thread, nil) return end local response = self.remote:InvokeClient(player, table.unpack(obj)) task.cancel(timer) task.spawn(thread, response) end) return coroutine.yield() end function Function:Remove() setmetatable(self, nil) end function Function:Destroy() self.remote:Destroy() end return Function
296
imezx/Scheduler
imezx-Scheduler-43e0719/src/server/remotes/Remotes.luau
--!optimize 2 --!strict --@EternityDev --Server local Remotes = {} if not script.Parent.Parent.Parent:FindFirstChild("Remotes") then Instance.new("Folder", script.Parent.Parent.Parent).Name = "Remotes" end local RemotesDir = script.Parent.Parent.Parent:WaitForChild("Remotes") local Function = require("./Function") function Remotes.fromEvent(remoteName: string): RemoteEvent if not RemotesDir:FindFirstChild(`Remote_{remoteName}`) then Instance.new("RemoteEvent", RemotesDir).Name = `Remote_{remoteName}` end return RemotesDir[`Remote_{remoteName}`] end function Remotes.fromFunction(remoteName: string) if not RemotesDir:FindFirstChild(`Remote_{remoteName}`) then Instance.new("RemoteFunction", RemotesDir).Name = `Remote_{remoteName}` end return Function.new(RemotesDir[`Remote_{remoteName}`]) end Remotes.buffer = require("../../util/bufferencoder") return Remotes
227
imezx/Scheduler
imezx-Scheduler-43e0719/src/ui/home.luau
--!optimize 2 local pebble = require("../../pebble") local vide = require("../../vide") local spawn_app = require("./spawn_app") local scheduler_app = require("./scheduler") local performance_app = require("./performance") type HomeProps = { env: string, Profiler: any, profiler_state: RemoteEvent, version: string, onClose: () -> (), onDestroy: () -> (), } local create = vide.create local source = vide.source local values = vide.values local cleanup = vide.cleanup local env_apps = source({ { env = "Server", Position = UDim2.fromScale(0.25, 0.5), menus = source({ scheduler = scheduler_app, }), }, { env = "Client", Position = UDim2.fromScale(0.5, 0.5), menus = source({ scheduler = scheduler_app, performance = performance_app, }), }, }) local home_app_ui, performance_app_ui, server_app_ui, client_app_ui return function(props: HomeProps) home_app_ui = pebble.widget({ title = "Home", subtitle = `v{props.version}`, min_size = Vector2.new(230, 200), bind_to_close = props.onClose, pebble.container({ create("UIListLayout")({ Padding = UDim.new(0, 2), VerticalFlex = Enum.UIFlexAlignment.SpaceEvenly, HorizontalFlex = Enum.UIFlexAlignment.Fill, }), create("ScrollingFrame")({ -- Size = UDim2.fromScale(1, 1), CanvasSize = UDim2.new(), AutomaticCanvasSize = Enum.AutomaticSize.Y, BackgroundTransparency = 1, ScrollBarThickness = 6, HorizontalScrollBarInset = Enum.ScrollBarInset.Always, create("UIFlexItem")({ FlexMode = Enum.UIFlexMode.Fill, }), pebble.padding({ x = UDim.new(0, 1), right = UDim.new(0, 8), }), create("UIListLayout")({ FillDirection = Enum.FillDirection.Horizontal, HorizontalFlex = Enum.UIFlexAlignment.Fill, Padding = UDim.new(0, 8), Wraps = true, }), values(env_apps, function(value, key) return pebble.pane({ name = "", size = UDim2.fromOffset(200, 0), automaticsize = Enum.AutomaticSize.Y, create("UIListLayout")({ Padding = UDim.new(0, 8), }), pebble.typography({ text = value.env, wrapped = true, }), values(value.menus, function(app_constructor, i) local menu: string = i() return pebble.button({ size = UDim2.new(1, 0, 0, 30), text = menu, activated = function() if menu == "scheduler" then if value.env == "Client" and client_app_ui then pcall(client_app_ui) client_app_ui = nil elseif server_app_ui then pcall(server_app_ui) server_app_ui = nil end local newApp = spawn_app.spawn_app(app_constructor, { env = value.env, Position = value.Position, ProfilerState = value.env == "Server" and props.Profiler.get_stored( "server_frame_value" ) or props.Profiler.dump_state(), Runtime = value.env == "Server" and props.Profiler.get_stored("server_runtime"), Pause = function() if value.env == "Server" then props.profiler_state:FireServer(false) else props.Profiler.Pause() end end, Resume = function() if value.env == "Server" then props.profiler_state:FireServer(true) else props.Profiler.Resume() end end, onClose = function() if value.env == "Client" and client_app_ui then pcall(client_app_ui) client_app_ui = nil elseif server_app_ui then pcall(server_app_ui) server_app_ui = nil end if not client_app_ui and not server_app_ui and not performance_app_ui and not home_app_ui then spawn_app.unmount_all() props.onDestroy() end end, }) if value.env == "Client" then client_app_ui = newApp else server_app_ui = newApp end elseif menu == "performance" then if performance_app_ui then pcall(performance_app_ui) performance_app_ui = nil end performance_app_ui = spawn_app.spawn_app(app_constructor, { performanceData = props.Profiler.sockets_transcript(), IsVisible = true, onClose = function() if performance_app_ui then pcall(performance_app_ui) performance_app_ui = nil end if not client_app_ui and not server_app_ui and not performance_app_ui and not home_app_ui then spawn_app.unmount_all() props.onDestroy() end end, }) end end, }) end), }) end), }), }), }) cleanup(home_app_ui) return home_app_ui end
1,244
imezx/Scheduler
imezx-Scheduler-43e0719/src/ui/performance.luau
--!optimize 2 local vide = require("../../vide") local pebble = require("../../pebble") local Profiler = require("../profiler") local create = vide.create local source = vide.source local values = vide.values local cleanup = vide.cleanup local function parse(data) local columnDefinitions = { { key = "host", displayName = "Host" }, { key = "memory", displayName = "Memory Usage" }, { key = "cpu", displayName = "CPU" }, { key = "frames", displayName = "FPS" }, { key = "gpu", displayName = "GPU" }, { key = "cpuRender", displayName = "CPU Render" }, } local resultTable = {} local columnMap = {} for i, def in columnDefinitions do resultTable[i] = { def.displayName } columnMap[def.key] = i end for _, record in data do for _, def in columnDefinitions do local key: string = def.key local value = record[key] local columnIndex: number = columnMap[key] if columnIndex and value ~= nil then table.insert(resultTable[columnIndex], value) end end end return resultTable end return function(props) local performanceData = source(parse(props.performanceData)) Profiler.onSocketChanged:disconnectAll() cleanup(Profiler.onSocketChanged:connect(function() local parse = parse(Profiler.sockets_transcript()) performanceData(parse) end)) return pebble.widget({ title = "Performance", min_size = Vector2.new(450, 250), size = Vector2.new(550, 250), bind_to_close = props.onClose, pebble.container({ Size = UDim2.fromScale(1, 1), create("UIFlexItem")({ FlexMode = Enum.UIFlexMode.Fill, }), pebble.tablesheet({ size = UDim2.fromScale(1, 1), column_sizes = source({ 100, 80, 100, 200 }), read_value = function(column, row) local value = performanceData()[column][row] return value and value or "" end, on_click = function() end, on_click2 = function() end, columns = performanceData, }), }), }) end
516
imezx/Scheduler
imezx-Scheduler-43e0719/src/ui/scheduler.luau
--!optimize 2 local vide = require("../../vide") local pebble = require("../../pebble") local stack_bar = require("./stack_bar") local convert_scale = require("../util/convert_scale") type SchedulerProps = { env: string, Position: UDim2, ProfilerState: () -> { any }, Runtime: string?, Pause: () -> (), Resume: () -> (), onClose: () -> (), } local create = vide.create local source = vide.source local derive = vide.derive local indexes = vide.indexes local action = vide.action local cleanup = vide.cleanup local effect = vide.effect local function changed(property: string, fn: (...any) -> ()) return action(function(instance) local cn = instance:GetPropertyChangedSignal(property):Connect(function() fn(instance[property]) end) cleanup(function() cn:Disconnect() end) end) end local sort_by_options = { "Name", "Frame Time", } return function(props: SchedulerProps) local selected: (number?) -> number = source(0) local sort_by: (number?) -> number = source(2) -- Derived state for total runtime local totalRuntime: () -> number = derive(function() local total: number = 0 for _, system in props.ProfilerState() do total += system.Duration end return total end) local function assign_frame(value_accessor, index) local gui_state = source(Enum.GuiState.Idle) local _frame: Frame local b = create("ImageButton")({ Name = function() return value_accessor().Name end, Size = UDim2.new(1, 0, 0, 32), LayoutOrder = function() return 1e9 - value_accessor().Duration * 1e8 end, BackgroundColor3 = function() return if gui_state() == Enum.GuiState.Press then pebble.theme.bg[-1]() elseif gui_state() == Enum.GuiState.Hover then pebble.theme.bg[6]() else pebble.theme.bg[3]() end, Visible = true, changed("GuiState", gui_state), MouseButton2Click = function() props.Pause() end, create("Folder")({ (function() _frame = create("Frame")({ Position = UDim2.new(0, 0, 1, 4), AnchorPoint = Vector2.new(0, 1), Size = function() return UDim2.new(value_accessor().Duration / totalRuntime(), 0, 0, 1) end, BackgroundColor3 = pebble.theme.fg_on_bg_high[0], }) return _frame end)(), effect(function() if not _frame then return end _frame.Size = UDim2.new(value_accessor().Duration / totalRuntime(), 0, 0, 1) end), }), create("UIStroke")({ Color = pebble.theme.bg[-3], }), create("UICorner")({ CornerRadius = UDim.new(0, 4), }), create("UIListLayout")({ FillDirection = Enum.FillDirection.Horizontal, VerticalAlignment = Enum.VerticalAlignment.Center, HorizontalFlex = Enum.UIFlexAlignment.SpaceEvenly, Padding = UDim.new(0, 8), }), pebble.padding({ x = UDim.new(0, 8), }), create("Frame")({ Size = UDim2.fromOffset(16, 16), AnchorPoint = Vector2.new(0.5, 0.5), BackgroundColor3 = function() return value_accessor().Color end, create("UICorner")({ CornerRadius = UDim.new(1, 0), }), }), pebble.typography({ automaticsize = Enum.AutomaticSize.None, text = function() return value_accessor().Name end, truncate = Enum.TextTruncate.SplitWord, xalignment = Enum.TextXAlignment.Left, disabled = false, create("UIFlexItem")({ FlexMode = Enum.UIFlexMode.Fill, GrowRatio = 1, ShrinkRatio = 1, }), }), pebble.typography({ automaticsize = Enum.AutomaticSize.XY, text = function() return convert_scale("s", value_accessor().Duration) end, xalignment = Enum.TextXAlignment.Right, disabled = true, }), }) cleanup(b) return b end return pebble.widget({ title = "Scheduler", subtitle = `host: {props.env}`, min_size = Vector2.new(200, 300), bind_to_close = props.onClose, create("Frame")({ Name = "Elements", Size = UDim2.fromScale(1, 1), AutomaticSize = Enum.AutomaticSize.Y, BackgroundTransparency = 1, create("UIListLayout")({ VerticalAlignment = Enum.VerticalAlignment.Bottom, FillDirection = Enum.FillDirection.Vertical, VerticalFlex = Enum.UIFlexAlignment.SpaceBetween, Padding = UDim.new(0, 8), }), create("Frame")({ Size = UDim2.fromScale(1, 0), AutomaticSize = Enum.AutomaticSize.Y, BackgroundTransparency = 1, pebble.pane({ name = "Overview", size = UDim2.fromScale(1, 0), create("UIListLayout")({ FillDirection = Enum.FillDirection.Vertical, }), pebble.typography({ text = props.Runtime and function() return `Runtime: {props.Runtime}` end or function() local time: number = totalRuntime() return `Run time: {convert_scale("s", time)}` end, }), stack_bar({ values = props.ProfilerState, selected = selected, }), pebble.row({ justifycontent = Enum.UIFlexAlignment.Fill, pebble.button({ text = "Pause all", activated = props.Pause, }), pebble.button({ text = "Resume all", activated = props.Resume, }), }), }), }), pebble.select({ size = UDim2.new(1, 0, 0, 30), options = sort_by_options, selected = sort_by, update_selected = function(new: number) sort_by(new) end, }), create("ScrollingFrame")({ Name = "Systems", Size = UDim2.fromScale(1, 0), CanvasSize = UDim2.new(), AutomaticCanvasSize = Enum.AutomaticSize.Y, BackgroundTransparency = 1, ScrollBarThickness = 6, VerticalScrollBarInset = Enum.ScrollBarInset.Always, ScrollBarImageColor3 = pebble.theme.fg_on_bg_low[3], create("UIFlexItem")({ FlexMode = Enum.UIFlexMode.Fill, }), create("UIListLayout")({ FillDirection = Enum.FillDirection.Vertical, Padding = UDim.new(0, 8), SortOrder = function() return if sort_by() == 1 then Enum.SortOrder.Name else Enum.SortOrder.LayoutOrder end, }), pebble.padding({ y = UDim.new(0, 1), x = UDim.new(0, 1), }), indexes(props.ProfilerState, assign_frame), }), }), }) end
1,742
imezx/Scheduler
imezx-Scheduler-43e0719/src/ui/spawn_app.luau
-- by jabby --!strict --!optimize 2 local Players = game:GetService("Players") local vide = require("../../vide") local destroy_fn: { [() -> ()]: boolean } = {} local function unmount_all() for destroy in destroy_fn do destroy() end table.clear(destroy_fn) end local function spawn_app<T>(app, props: T): () -> () return vide.root(function(destroy) local destroy = function() destroy_fn[destroy] = nil pcall(destroy) end local application = app(props) application.Parent = Players.LocalPlayer.PlayerGui vide.cleanup(application) destroy_fn[destroy] = true return destroy end) end return { unmount_all = unmount_all, spawn_app = spawn_app, }
179
imezx/Scheduler
imezx-Scheduler-43e0719/src/ui/stack_bar.luau
--!optimize 2 local vide = require("../../vide") local create = vide.create local indexes = vide.indexes local derive = vide.derive type stack_bar = { values: () -> { { Name: string, Color: Color3, Size: UDim2, Duration: number } }, selected: (index: number) -> (), } return function(props: stack_bar) local total: () -> number = derive(function() local total: number = 0 for _, value in props.values() do total += value.Duration end return total end) return create("Frame")({ Name = "Graph", Size = UDim2.new(1, 0, 0, 32), indexes(props.values, function(value, index) return create("Frame")({ Size = function() local duration = value().Duration local totalDuration = total() if totalDuration == 0 then return UDim2.fromScale(0, 1) end return UDim2.fromScale(duration / totalDuration, 1) end, BackgroundColor3 = function() return value().Color end, MouseEnter = function() props.selected(index) end, }) end), create("UIListLayout")({ FillDirection = Enum.FillDirection.Horizontal, }), }) end
299
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/Enums.luau
--!optimize 2 --[[ ## made by anexpia •…• ## assigns values to specific bytes so that they can be encoded this is mainly for sending values that cannot be encoded from server to client like newproxy() objects, or other unique values like tables that you want to be the same everytime they're sent in a remote. you probably don't need to use this most of the time, but the option exists and its helpful when its actually needed ]] local RS = game:GetService("RunService") local Settings = require(script.Parent.Settings) local SyncingEnabled = Settings.serverclientsyncing local IsSyncOrigin = if SyncingEnabled then RS:IsServer() else true local nametovalue: {[string]: any} = {} local bytetovalue: {[number]: any} = { [2] = true, [3] = false, [102] = "", [103] = 0, [104] = 1, [105] = -1, [106] = math.huge, [107] = -math.huge, [108] = 0 / 0, } local valuetobyte: {[any]: number} = { [true] = 2, [false] = 3, [""] = 102, [0] = 103, [1] = 104, [-1] = 105, [math.huge] = 106, [-math.huge] = 107, -- no nan since nan will error if in table } local freebytes local currentposition = 0 local function sanitizename(name) if type(name) ~= "string" then error(`expected name to be a string, got {typeof(name)}`, 0) end if name == "" then error("name should not be an empty string", 0) end return string.gsub(name, "[^%w_]", "_") -- turn everything that isnt %w and _ into _ end -- Removes the value associated with 'name' from byte registry. local function removename(name: string) name = sanitizename(name) local value = nametovalue[name] if value then local oldbyte = valuetobyte[value] valuetobyte[value] = nil if bytetovalue[oldbyte] == value then bytetovalue[oldbyte] = nil end if IsSyncOrigin then table.insert(freebytes, oldbyte) nametovalue[name] = nil -- not done on client because this is called whenever the attribute is changed, and current value is needed if SyncingEnabled then script:SetAttribute(name, nil) end end end end if not IsSyncOrigin then local function attributechanged(name, byte) removename(name) byte = byte or script:GetAttribute(name) if byte then local value = nametovalue[name] if not value then value = newproxy() nametovalue[name] = value end valuetobyte[value] = byte bytetovalue[byte] = value else nametovalue[name] = nil end end script.AttributeChanged:Connect(attributechanged) for name, value in script:GetAttributes() do attributechanged(name, value) end else freebytes = {} end return { bytetovalue = bytetovalue, nametovalue = nametovalue, valuetobyte = valuetobyte, --[[ Assigns 2 bytes to the name and returns the value that is encoded as the byte. Registered names are synced from server to client. ]] register = function(name: string, predefined: any?): any name = sanitizename(name) if valuetobyte[predefined] then error(`cannot define {name} with the value {predefined} as the value is already defined`, 0) end if nametovalue[name] then if predefined then local oldvalue = nametovalue[name] local byte = valuetobyte[oldvalue] nametovalue[name] = predefined if byte then valuetobyte[oldvalue] = nil valuetobyte[predefined] = byte bytetovalue[byte] = predefined end end return nametovalue[name] end local v = predefined or newproxy() if IsSyncOrigin then local byte = table.remove(freebytes) if not byte then byte = currentposition - 1 currentposition = byte end nametovalue[name] = v valuetobyte[v] = byte bytetovalue[byte] = v if SyncingEnabled then script:SetAttribute(name, byte) end else nametovalue[name] = v end return v end, remove = removename, }
1,131
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/Miscellaneous/floatencoder.luau
--!native --!optimize 2 --!strict -- read float16 number from buffer local function readf16(buff: buffer, cursor: number): number local n: number = buffer.readu16(buff, cursor) local mantissa: number, exponent: number, sign: number = bit32.extract(n, 0, 10), bit32.extract(n, 10, 5), bit32.extract(n, 15, 1) if mantissa == 0b0000000000 then if exponent == 0b00000 then return 0 elseif exponent == 0b11111 then return if sign == 1 then -math.huge else math.huge end elseif exponent == 0b11111 then return 0/0 end local value: number = ((mantissa / 1024) + 1) * 2 ^ (exponent - 15) if sign == 1 then return -value end return value end -- write number as float16 into buffer local function writef16(buff: buffer, cursor: number, value: number): () if value == 0 then buffer.writeu16(buff, cursor, 0) elseif value >= 65520 then buffer.writeu16(buff, cursor, 0b0_11111_0000000000) elseif value <= -65520 then buffer.writeu16(buff, cursor, 0b1_11111_0000000000) elseif value ~= value then buffer.writeu16(buff, cursor, 0b0_11111_0000000001) else local sign: number = 0 if value < 0 then sign = 1 value = -value end local mantissa: number, exponent: number = math.frexp(value) if exponent < -14 then -- safeguard against tiny exponents like -20 buffer.writeu16(buff, cursor, 0) return end buffer.writeu16(buff, cursor, bit32.bor((mantissa * 2048 - 1023.5), (exponent + 14) * 2^10, (sign) * 2^15)) end end return { writef16 = writef16; readf16 = readf16; }
503
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/Miscellaneous/init.luau
--!native --!optimize 2 -- quaternion stuff from https://devforum.roblox.com/t/introducing-luau-buffer-type-beta/2724894/105?u=anexpia -- modified a bit to be more performant when encoding local Types = require(script.Parent.Types) local floatencoder = require(script.floatencoder) local FP_EPSILON = 1e-6 local I16_PRECISION = 32767 -- int16 range { -32,786, 32,767 } local BUFF_CFRAME_SIZE = (3*4) + (1 + 3*2) -- i.e. 3x f32, 1x u8 and 3x i16 local cframe_ToAxisAngle = CFrame.identity.ToAxisAngle local function getNormalisedQuaternion(cframe: CFrame) local axis_shadowed, angle = cframe_ToAxisAngle(cframe) local ha = angle / 2 local axis: vector = if vector.magnitude(axis_shadowed) > FP_EPSILON then vector.normalize(axis_shadowed) else (Vector3.xAxis :: any) axis *= math.sin(ha) local w = math.cos(ha) local length = math.sqrt(vector.dot(axis, axis) + w*w) if length < FP_EPSILON then return 0, 0, 0, 1 end axis /= length return axis.x, axis.y, axis.z, w / length end local function compressQuaternion(cframe) local qx, qy, qz, qw = getNormalisedQuaternion(cframe) local index = -1 local value = -math.huge local sign for i = 1, 4, 1 do local val = select(i, qx, qy, qz, qw) local abs = math.abs(val) if abs > value then index = i value = abs sign = val end end sign = sign >= 0 and 1 or -1 local v0, v1, v2 if index == 1 then v0 = math.floor(qy * sign * I16_PRECISION + 0.5) v1 = math.floor(qz * sign * I16_PRECISION + 0.5) v2 = math.floor(qw * sign * I16_PRECISION + 0.5) elseif index == 2 then v0 = math.floor(qx * sign * I16_PRECISION + 0.5) v1 = math.floor(qz * sign * I16_PRECISION + 0.5) v2 = math.floor(qw * sign * I16_PRECISION + 0.5) elseif index == 3 then v0 = math.floor(qx * sign * I16_PRECISION + 0.5) v1 = math.floor(qy * sign * I16_PRECISION + 0.5) v2 = math.floor(qw * sign * I16_PRECISION + 0.5) elseif index == 4 then v0 = math.floor(qx * sign * I16_PRECISION + 0.5) v1 = math.floor(qy * sign * I16_PRECISION + 0.5) v2 = math.floor(qz * sign * I16_PRECISION + 0.5) end return index, v0, v1, v2 end local function decompressQuaternion(index, v0, v1, v2) v0 /= I16_PRECISION v1 /= I16_PRECISION v2 /= I16_PRECISION local d = math.sqrt(1 - (v0*v0 + v1*v1 + v2*v2)) if index == 1 then return d, v0, v1, v2 elseif index == 2 then return v0, d, v1, v2 elseif index == 3 then return v0, v1, d, v2 end return v0, v1, v2, d end local function write(buf: buffer, offset: number, input: CFrame) local pos = input.Position buffer.writef32(buf, offset, pos.X) buffer.writef32(buf, offset + 4, pos.Y) buffer.writef32(buf, offset + 8, pos.Z) local qi, q0, q1, q2 = compressQuaternion(input) buffer.writeu8(buf, offset + 12, qi) buffer.writei16(buf, offset + 13, q0) buffer.writei16(buf, offset + 15, q1) buffer.writei16(buf, offset + 17, q2) end local function read(buf: buffer, byte: number, offset: number, info: Types.ReadSettings): (CFrame, number) local x = buffer.readf32(buf, offset) local y = buffer.readf32(buf, offset + 4) local z = buffer.readf32(buf, offset + 8) if info.sanitize_nanandinf then if (x / x) ~= 1 then x = 0 end if (y / y) ~= 1 then y = 0 end if (z / z) ~= 1 then z = 0 end end local qi = buffer.readu8(buf, offset + 12) local q0 = buffer.readi16(buf, offset + 13) local q1 = buffer.readi16(buf, offset + 15) local q2 = buffer.readi16(buf, offset + 17) local qx, qy, qz, qw = decompressQuaternion(qi, q0, q1, q2) return CFrame.new(x, y, z, qx, qy, qz, qw), offset + BUFF_CFRAME_SIZE end return { readCFrame = read, writeCFrame = write, cframesize = BUFF_CFRAME_SIZE, writef16 = floatencoder.writef16; readf16 = floatencoder.readf16; }
1,298
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/RbxEnumEncoder.luau
--!optimize 2 --[[ ## made by anexpia •…• ## ]] local RS = game:GetService("RunService") local Settings = require(script.Parent.Settings) local SyncingEnabled = Settings.serverclientsyncing local enumitem_to_type = {} local enumitem_to_value = {} local exposed = { enumitem_to_type = enumitem_to_type; enumitem_to_value = enumitem_to_value; compact = {}, full = {}, } for _, enum in Enum:GetEnums() do local n = tostring(enum) enumitem_to_type[enum] = n for _, enumitem in enum:GetEnumItems() do enumitem_to_type[enumitem] = n enumitem_to_value[enumitem] = enumitem.Value end end do -- encode enums as <19> <u8 length> <string> -- encode enumitems as <20> <u8 length> <string> <u16 value> local full = exposed.full local nametoenum = {} for _, v in Enum:GetEnums() do nametoenum[tostring(v)] = v end -- this is to avoid erroring due to version mismatch when decoding local enum_FromValue = (Enum.Material :: any).FromValue @native function full.encodeEnum(buf: buffer, offset: number, enum: Enum): number local name = enumitem_to_type[enum] local length = #name buffer.writeu8(buf, offset, length); offset += 1 buffer.writestring(buf, offset, name) return offset + length end @native function full.encodeEnumItem(buf: buffer, offset: number, enumitem: EnumItem): number offset = full.encodeEnum(buf, offset, enumitem :: any) buffer.writeu16(buf, offset, enumitem_to_value[enumitem]) return offset + 2 end @native function full.decodeEnum(buf: buffer, byte: number, cursor: number): (Enum, number, boolean?) local length = buffer.readu8(buf, cursor); cursor += 1 local name = buffer.readstring(buf, cursor, length) return nametoenum[name], cursor + length, true end @native function full.decodeEnumItem(buf: buffer, byte: number, cursor: number): (EnumItem, number, boolean?) local enum, newcursor = full.decodeEnum(buf, byte, cursor) local value = buffer.readu16(buf, newcursor) return enum and enum_FromValue(enum, value), newcursor + 2, true end end do -- encode enums as <19> <u16 index> -- encode enumitems as <20> <u16 index> -- syncing table between client & server is necessary to avoid issues due to version mismatch local enumarray: { Enum } = {} local enumitemarray: { EnumItem } = {} local valuelookup: { [any]: number } = {} local compact = exposed.compact local IsSyncOrigin = if SyncingEnabled then RS:IsServer() else true if IsSyncOrigin then local tosend1, tosend2 if SyncingEnabled then tosend1, tosend2 = {}, {} local request: RemoteFunction = script:FindFirstChild("request") if request == nil then request = Instance.new("RemoteFunction") request.Name = "request" request.Parent = script end request.OnServerInvoke = function(player, v) return tosend1, tosend2 end end do -- using tostring on index because the enum/enumitem may not exist -- which will lead to gaps getting created when syncing local enum_i, enumitem_i = 0, 0 for _, k in Enum:GetEnums() do enum_i += 1 enumarray[enum_i] = k valuelookup[k] = enum_i if tosend1 then tosend1[tostring(enum_i)] = k end for _, v in k:GetEnumItems() do enumitem_i += 1 enumitemarray[enumitem_i] = v valuelookup[v] = enumitem_i if tosend2 then tosend2[tostring(enumitem_i)] = v end end end end else task.spawn(function() local request = script:WaitForChild("request") local function addtoarray(toarray, fromdict) for k, v in fromdict do k = tonumber(k) toarray[k] = v valuelookup[v] = k end end while true do local success, r1, r2 = pcall(request.InvokeServer, request) if success and r1 and r2 then addtoarray(enumarray, r1) addtoarray(enumitemarray, r2) break else task.wait(3) end end end) end @native function compact.encodeEnum(buf: buffer, offset: number, value: Enum): number local position = valuelookup[value] buffer.writeu16(buf, offset, position or 0) return offset + 2 end compact.encodeEnumItem = (compact.encodeEnum :: any) :: (buf: buffer, offset: number, value: EnumItem) -> number @native function compact.decodeEnum(buf: buffer, byte: number, cursor: number): (Enum, number) local position = buffer.readu16(buf, cursor) return enumarray[position], cursor + 2 end @native function compact.decodeEnumItem(buf: buffer, byte: number, cursor: number): (EnumItem, number) local position = buffer.readu16(buf, cursor) return enumitemarray[position], cursor + 2 end end function exposed.getBehaviorFromSetting(operationsettings): (typeof(exposed.full), "full" | "compact") local value = operationsettings.rbxenum_behavior or Settings.rbxenum_behavior local enumbehavior = exposed[value] if enumbehavior == nil then error(`{value} is an invalid value for rbx_enumbehavior, options are 'full' / 'compact'`, 0) end return enumbehavior, value end return exposed
1,388
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/Read.luau
--!native --!optimize 2 --!nolint LocalShadow --[[ ## made by anexpia •…• ## ]] local Encoder = script.Parent local Datatypes = require(Encoder.ReadDatatypes) local RbxEnumEncoder = require(Encoder.RbxEnumEncoder) local Settings = require(Encoder.Settings) local Types = require(Encoder.Types) type ReadSettings = Types.ReadSettings local defaultwritingtable = {} --[[ Decodes the buffer created by encoder.write() <em>param</em> - buff : the buffer to decode <em>param</em> - readstart : reading starts from the offset given. <em>param</em> - readsettings : { . <strong>allowdeduplication: boolean</strong> -- if the buffer was written with deduplication enabled . <strong>references: {any}</strong> -- table of values that couldn't be encoded which is returned by encoder.write() . <strong>shiftseed: number</strong> -- the type bytes of values are unshuffled using the seed. . <strong>rbxenum_behavior: "full" | "compact"</strong> -- override for the default setting. . <strong>sanitize_nanandinf: boolean</strong> -- override for the default setting. } ]] return function(buff: buffer, readstart: number?, readsettings: ReadSettings?): { [any]: any } local readsettings: ReadSettings = readsettings or Settings local shiftseed = readsettings.shiftseed local dedupenabled = readsettings.allowdeduplication local cursor = readstart or 0 local isdoingdeduplication_old = false do local firstbyte = buffer.readu8(buff, cursor) if shiftseed then math.randomseed(shiftseed) firstbyte = (firstbyte - math.random(1, 127)) % 128 math.randomseed(shiftseed) end if firstbyte == 101 then return {} elseif firstbyte > 1 then error(`expected '0', '1', or '101' for first byte, got {firstbyte}`) end isdoingdeduplication_old = firstbyte == 0 if isdoingdeduplication_old then dedupenabled = false end end local enumbehavior = RbxEnumEncoder.getBehaviorFromSetting(readsettings) local sanitize_nanandinf = readsettings.sanitize_nanandinf if sanitize_nanandinf == nil then sanitize_nanandinf = Settings.sanitize_nanandinf end Datatypes.adjustforsettings(enumbehavior, sanitize_nanandinf) local deduplicationindex = 0 local deduplicationtable = if dedupenabled then {} else nil local currenttable = {} local maintable = currenttable local writingtable = defaultwritingtable local formedtables = {currenttable} local formedcount = 0 local lastwasdictkey = false local dictkey = nil local currentindex = 0 local info: Types.decodeinfo = { sanitize_nanandinf = sanitize_nanandinf, references = readsettings.references, deduplicationtable = deduplicationtable, tables = formedtables, } while cursor <= (buffer.len(buff) - 1) do local byte = buffer.readu8(buff, cursor) cursor += 1 local isdictkey = byte > 127 if isdictkey then byte = (255 - byte) end if shiftseed then byte = (byte - math.random(1, 127)) % 128 end local value: any, canbededuplicated: boolean? local func = Datatypes[byte] if func then value, cursor, canbededuplicated = func(buff, byte, cursor, info) elseif byte == 1 then formedcount += 1 if currentindex > 0 then table.move(writingtable, 1, currentindex, 1, currenttable) currentindex = 0 end currenttable = formedtables[formedcount] if currenttable == nil then currenttable = {} formedtables[formedcount] = currenttable end lastwasdictkey = false dictkey = nil continue elseif byte == 0 then if isdoingdeduplication_old then isdoingdeduplication_old = false currenttable = {} deduplicationtable = currenttable info.deduplicationtable = deduplicationtable continue else if shiftseed then math.randomseed(os.time()) end if currentindex > 0 then table.move(writingtable, 1, currentindex, 1, currenttable) end table.clear(writingtable) return maintable end elseif byte == 101 then value = {} elseif byte ~= 4 then -- not nil error(`{byte} is not a type byte`) end if dedupenabled and canbededuplicated then deduplicationindex += 1 deduplicationtable[deduplicationindex] = value end if lastwasdictkey then lastwasdictkey = false if dictkey ~= nil then currenttable[dictkey] = value dictkey = nil end elseif isdictkey then dictkey = value lastwasdictkey = true else currentindex += 1 writingtable[currentindex] = value end end if shiftseed then math.randomseed(os.time()) end error("buffer is not terminated with '0' byte", 0) end
1,240
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/BrickColor.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local Settings = require(Module.Settings) local Types = require(Module.Types) type datatypedecodinginfo = Types.datatypedecodinginfo local brickcolorbyte = 30 return { [brickcolorbyte] = @native function(buff: buffer, byte: number, cursor: number): (BrickColor, number) return BrickColor.new(buffer.readu16(buff, cursor)), cursor + 2 end; } :: datatypedecodinginfo
127
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/CFrame.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local Settings = require(Module.Settings) local Types = require(Module.Types) local Miscellaneous = require(Module.Miscellaneous) type datatypedecodinginfo = Types.datatypedecodinginfo local cframebyte = 17 return { [cframebyte] = Miscellaneous.readCFrame } :: datatypedecodinginfo
97
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/Color3.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local Settings = require(Module.Settings) local Types = require(Module.Types) local Miscellaneous = require(Module.Miscellaneous) local color3always6bytes = Settings.color3always6bytes local readf16 = Miscellaneous.readf16 type datatypedecodinginfo = Types.datatypedecodinginfo local u8colorbyte = 23 local f16colorbyte = 24 local writebytesign return { [u8colorbyte] = @native function(buff: buffer, byte: number, cursor: number): (Color3, number) local r, g, b = buffer.readu8(buff, cursor), buffer.readu8(buff, cursor + 1), buffer.readu8(buff, cursor + 2) return Color3.fromRGB(r, g, b), cursor + 3 end; [f16colorbyte] = @native function(buff: buffer, byte: number, cursor: number): (Color3, number) local r, g, b = readf16(buff, cursor), readf16(buff, cursor + 2), readf16(buff, cursor + 4) return Color3.new(r, g, b), cursor + 6 end; } :: datatypedecodinginfo
290
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/ColorSequence.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local Settings = require(Module.Settings) local Types = require(Module.Types) type datatypedecodinginfo = Types.datatypedecodinginfo local colorbyte = 25 local uI16_max = (2 ^ 16) - 1 return { [colorbyte] = @native function(buff: buffer, byte: number, cursor: number): (ColorSequence, number) local length = buffer.readu8(buff, cursor); cursor += 1 local tbl = table.create(length) for i = 1, length do local time = math.clamp(buffer.readu16(buff, cursor) / uI16_max, 0, 1) local r, g, b = buffer.readu8(buff, cursor + 2), buffer.readu8(buff, cursor + 3), buffer.readu8(buff, cursor + 4); cursor += 5 tbl[i] = ColorSequenceKeypoint.new(time, Color3.fromRGB(r, g, b)) end return ColorSequence.new(tbl), cursor end; } :: datatypedecodinginfo
266
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/ContentAndFont.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local Settings = require(Module.Settings) local Types = require(Module.Types) type datatypedecodinginfo = Types.datatypedecodinginfo local contentbyte = 33 local fontbyte = 34 local writebytesign local FromValue = (Enum.FontWeight :: any).FromValue -- localizing it to silence errors 😭 return { [contentbyte] = @native function(buff: buffer, byte: number, cursor: number): (Content, number) local length = buffer.readu8(buff, cursor); cursor += 1 if length == 0 then return Content.none, cursor elseif length == 1 then local num = buffer.readf64(buff, cursor) return Content.fromAssetId(num), cursor + 8 else length -= 1 local uri = buffer.readstring(buff, cursor, length) return Content.fromUri(uri), cursor + length end end; [fontbyte] = @native function(buff: buffer, byte: number, cursor: number): (Font, number) local length = buffer.readu8(buff, cursor); cursor += 1 if length == 0 then local num = buffer.readf64(buff, cursor); cursor += 8 local weightv, stylev = buffer.readu16(buff, cursor), buffer.readu8(buff, cursor + 2) return Font.fromId(num, FromValue(Enum.FontWeight, weightv), FromValue(Enum.FontStyle, stylev)), cursor + 3 else length -= 1 local familyname = buffer.readstring(buff, cursor, length); cursor += length if familyname == "" then familyname = "Arimo" end local weightv, stylev = buffer.readu16(buff, cursor), buffer.readu8(buff, cursor + 2) -- not using FromName because familyname can be empty return Font.new(`rbxasset://fonts/families/{familyname}.json`, FromValue(Enum.FontWeight, weightv), FromValue(Enum.FontStyle, stylev)), cursor + 3 end end; } :: datatypedecodinginfo
494
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/DateTime.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local Types = require(Module.Types) type datatypedecodinginfo = Types.datatypedecodinginfo local datetimebyte = 35 return { [datetimebyte] = @native function(buff: buffer, byte: number, cursor: number): (DateTime, number) local unixmillis = buffer.readf64(buff, cursor) return DateTime.fromUnixTimestampMillis(unixmillis), cursor + 8 end; } :: datatypedecodinginfo
129
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/NumberRange.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local Settings = require(Module.Settings) local Types = require(Module.Types) type datatypedecodinginfo = Types.datatypedecodinginfo local numberbyte = 21 local writebytesign return { [numberbyte] = @native function(buff: buffer, byte: number, cursor: number): (NumberRange, number) local min = buffer.readf32(buff, cursor) local max = buffer.readf32(buff, cursor + 4) return NumberRange.new(min, max), cursor + 8 end; } :: datatypedecodinginfo
152
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/NumberSequence.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local Settings = require(Module.Settings) local Types = require(Module.Types) local Miscellaneous = require(Module.Miscellaneous) type datatypedecodinginfo = Types.datatypedecodinginfo local readf16 = Miscellaneous.readf16 local numberbyte = 22 local writebytesign local uI16_max = (2 ^ 16) - 1 return { [numberbyte] = @native function(buff: buffer, byte: number, cursor: number): (NumberSequence, number) local length = buffer.readu8(buff, cursor); cursor += 1 local tbl = table.create(length) for i = 1, length do local time = math.clamp(buffer.readu16(buff, cursor) / uI16_max, 0, 1) local value = buffer.readf32(buff, cursor + 2) local envelope = readf16(buff, cursor + 6); cursor += 8 tbl[i] = NumberSequenceKeypoint.new(time, value, envelope) end return NumberSequence.new(tbl), cursor end; } :: datatypedecodinginfo
271
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/PhysicalProperties.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local Settings = require(Module.Settings) local Types = require(Module.Types) type datatypedecodinginfo = Types.datatypedecodinginfo local physpropsbyte = 29 local writebytesign return { [physpropsbyte] = @native function(buff: buffer, byte: number, cursor: number): (PhysicalProperties, number) local Density = buffer.readf32(buff, cursor) local Friction = buffer.readf32(buff, cursor + 4) local Elasticity = buffer.readf32(buff, cursor + 8) local FrictionWeight = buffer.readf32(buff, cursor + 12) local ElasticityWeight = buffer.readf32(buff, cursor + 16) return PhysicalProperties.new(Density, Friction, Elasticity, FrictionWeight, ElasticityWeight), cursor + 20 end; } :: datatypedecodinginfo
220
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/Ray.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local Settings = require(Module.Settings) local Types = require(Module.Types) type datatypedecodinginfo = Types.datatypedecodinginfo local raybyte = 18 local writebytesign return { [raybyte] = @native function(buff: buffer, byte: number, cursor: number, info: Types.decodeinfo): (Ray, number) local ox = buffer.readf32(buff, cursor); cursor += 4 local oy = buffer.readf32(buff, cursor); cursor += 4 local oz = buffer.readf32(buff, cursor); cursor += 4 local dx = buffer.readf32(buff, cursor); cursor += 4 local dy = buffer.readf32(buff, cursor); cursor += 4 local dz = buffer.readf32(buff, cursor); cursor += 4 if info.sanitize_nanandinf then if (ox / ox) ~= 1 then ox = 0 end if (oy / oy) ~= 1 then oy = 0 end if (oz / oz) ~= 1 then oz = 0 end if (dx / dx) ~= 1 then dx = 0 end if (dy / dy) ~= 1 then dy = 0 end if (dz / dz) ~= 1 then dz = 0 end end return Ray.new(Vector3.new(ox, oy, oz), Vector3.new(dx, dy, dz)), cursor end; } :: datatypedecodinginfo
357
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/Rect.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local Settings = require(Module.Settings) local Types = require(Module.Types) type datatypedecodinginfo = Types.datatypedecodinginfo local rectbyte = 28 local writebytesign return { [rectbyte] = @native function(buff: buffer, byte: number, cursor: number): (Rect, number) local xmin = buffer.readf32(buff, cursor) local ymin = buffer.readf32(buff, cursor + 4) local xmax = buffer.readf32(buff, cursor + 8) local ymax = buffer.readf32(buff, cursor + 12) return Rect.new(xmin, ymin, xmax, ymax), cursor + 16 end; } :: datatypedecodinginfo
185
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/UDim.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local Settings = require(Module.Settings) local Types = require(Module.Types) type datatypedecodinginfo = Types.datatypedecodinginfo local udimbyte = 26 local writebytesign return { [udimbyte] = @native function(buff: buffer, byte: number, cursor: number): (UDim, number) local scale = buffer.readf32(buff, cursor) local offset = buffer.readi32(buff, cursor + 4) return UDim.new(scale, offset), cursor + 8 end; } :: datatypedecodinginfo
154
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/UDim2.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local Settings = require(Module.Settings) local Types = require(Module.Types) type datatypedecodinginfo = Types.datatypedecodinginfo local udim2byte = 27 local writebytesign return { [udim2byte] = @native function(buff: buffer, byte: number, cursor: number): (UDim2, number) local xscale = buffer.readf32(buff, cursor) local xoffset = buffer.readi32(buff, cursor + 4) local yscale = buffer.readf32(buff, cursor + 8) local yoffset = buffer.readi32(buff, cursor + 12) return UDim2.new(xscale, xoffset, yscale, yoffset), cursor + 16 end; } :: datatypedecodinginfo
201
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/Vector2.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local Settings = require(Module.Settings) local Types = require(Module.Types) type datatypedecodinginfo = Types.datatypedecodinginfo local vectorbyte = 16 local vectorint16byte = 32 local writebytesign return { [vectorbyte] = @native function(buff: buffer, byte: number, cursor: number, info: Types.decodeinfo): (Vector2, number) local x = buffer.readf32(buff, cursor) local y = buffer.readf32(buff, cursor + 4) if info.sanitize_nanandinf then if (x / x) ~= 1 then x = 0 end if (y / y) ~= 1 then y = 0 end end return Vector2.new(x, y), cursor + 8 end; [vectorint16byte] = @native function(buff: buffer, byte: number, cursor: number): (Vector2int16, number) local x = buffer.readi16(buff, cursor) local y = buffer.readi16(buff, cursor + 2) return Vector2int16.new(x, y), cursor + 4 end; } :: datatypedecodinginfo
291
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/Vector3.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local Settings = require(Module.Settings) local Types = require(Module.Types) type datatypedecodinginfo = Types.datatypedecodinginfo local vectorbyte = 15 local vectorint16byte = 31 local writebytesign return { [vectorbyte] = @native function(buff: buffer, byte: number, cursor: number, info: Types.decodeinfo): (vector, number, boolean?) local x = buffer.readf32(buff, cursor) local y = buffer.readf32(buff, cursor + 4) local z = buffer.readf32(buff, cursor + 8) -- need to check if deduplication is possible as if nan exists, the vector -- cannot be deduplicated during writing process, thus would cause value positions to get shifted local candeduplicate = x == x and y == y and z == z if info.sanitize_nanandinf then if (x / x) ~= 1 then x = 0 end if (y / y) ~= 1 then y = 0 end if (z / z) ~= 1 then z = 0 end end return vector.create(x, y, z), cursor + 12, candeduplicate end; [vectorint16byte] = @native function(buff: buffer, byte: number, cursor: number): (Vector3int16, number) local x = buffer.readi16(buff, cursor) local y = buffer.readi16(buff, cursor + 2) local z = buffer.readi16(buff, cursor + 4) return Vector3int16.new(x, y, z), cursor + 6 end; } :: datatypedecodinginfo
402
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/buffer.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local Settings = require(Module.Settings) local Types = require(Module.Types) type datatypedecodinginfo = Types.datatypedecodinginfo local bufferu8byte = 12 local bufferu16byte = 13 local bufferu32byte = 14 @native local function readbuffer(buff: buffer, byte: number, cursor: number, info: Types.decodeinfo): (buffer, number) local length if byte == bufferu8byte then length = buffer.readu8(buff, cursor); cursor += 1 elseif byte == bufferu16byte then length = buffer.readu16(buff, cursor); cursor += 2 else length = buffer.readu32(buff, cursor); cursor += 4 end local value = buffer.create(length) buffer.copy(value, 0, buff, cursor, length) return value, cursor + length end return { [bufferu8byte] = readbuffer; [bufferu16byte] = readbuffer; [bufferu32byte] = readbuffer; } :: datatypedecodinginfo
262
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/init.luau
--[[ ## made by anexpia •…• ## originally this also had write functions for each datatype but i found that it was slower than having if conditions so now it only contains read functions and thats it ]] local bytetofunction = {} local bytetodatatype = {} for _, t in script:GetChildren() do local name = t.Name if t.Name == "template" then continue end for num, func in require(t) do if bytetodatatype[num] then warn(`The modules {name} and {bytetodatatype[num]} are using the same byte {num}`) continue end bytetofunction[num] = func bytetodatatype[num] = name end end table.clear(bytetodatatype) bytetodatatype = nil :: any local enumbyte = 19 local enumitembyte = 20 -- math.huge -math.huge nan local f106, f107, f108 = bytetofunction[106], bytetofunction[107], bytetofunction[108] local f103 = bytetofunction[103] -- returns 0 function bytetofunction.adjustforsettings(enumbehavior, sanitize_nanandinf: boolean?) bytetofunction[enumbyte] = enumbehavior.decodeEnum bytetofunction[enumitembyte] = enumbehavior.decodeEnumItem if sanitize_nanandinf then for i = 106, 108 do bytetofunction[i] = f103 end else bytetofunction[106], bytetofunction[107], bytetofunction[108] = f106, f107, f108 end end return bytetofunction
389
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/number.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local Settings = require(Module.Settings) local Types = require(Module.Types) local Enums = require(Module.Enums) type datatypedecodinginfo = Types.datatypedecodinginfo local u8numbyte = 5 local n_u8numbyte = 8 local u16numbyte = 6 local n_u16numbyte = 9 local u32numbyte = 7 local n_u32numbyte = 10 local floatnumbyte = 11 local t = { [u8numbyte] = @native function(buff: buffer, byte: number, cursor: number): (number, number, boolean?) return buffer.readu8(buff, cursor), cursor + 1 end; [n_u8numbyte] = @native function(buff: buffer, byte: number, cursor: number): (number, number, boolean?) return -buffer.readu8(buff, cursor), cursor + 1 end; [u16numbyte] = @native function(buff: buffer, byte: number, cursor: number): (number, number, boolean?) return buffer.readu16(buff, cursor), cursor + 2, true end; [n_u16numbyte] = @native function(buff: buffer, byte: number, cursor: number): (number, number, boolean?) return -buffer.readu16(buff, cursor), cursor + 2, true end; [u32numbyte] = @native function(buff: buffer, byte: number, cursor: number): (number, number, boolean?) return buffer.readu32(buff, cursor), cursor + 4, true end; [n_u32numbyte] = @native function(buff: buffer, byte: number, cursor: number): (number, number, boolean?) return -buffer.readu32(buff, cursor), cursor + 4, true end; [floatnumbyte] = @native function(buff: buffer, byte: number, cursor: number): (number, number, boolean?) return buffer.readf64(buff, cursor), cursor + 8, true end } return t
476
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/string.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local Settings = require(Module.Settings) local Types = require(Module.Types) type datatypedecodinginfo = Types.datatypedecodinginfo local stringu8byte = 54 local stringu16byte = 55 local stringu32byte = 56 local writebytesign return { [stringu8byte] = @native function(buff: buffer, byte: number, cursor: number): (string, number, boolean?) local length = buffer.readu8(buff, cursor); cursor += 1 return buffer.readstring(buff, cursor, length), cursor + length, true end; [stringu16byte] = @native function(buff: buffer, byte: number, cursor: number): (string, number, boolean?) local length = buffer.readu16(buff, cursor); cursor += 2 return buffer.readstring(buff, cursor, length), cursor + length, true end; [stringu32byte] = @native function(buff: buffer, byte: number, cursor: number): (string, number, boolean?) local length = buffer.readu32(buff, cursor); cursor += 4 return buffer.readstring(buff, cursor, length), cursor + length, true end; } :: datatypedecodinginfo
296
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/table_and_deduplicate.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local ByteToValue = require(Module.Enums).bytetovalue local Types = require(Module.Types) type datatypedecodinginfo = Types.datatypedecodinginfo local tblu8byte = 51 local tblu16byte = 52 local tblu32byte = 53 local dedupu8byte = 57 local dedupu16byte = 58 local dedupu32byte = 59 local referenceu8byte = 60 local referenceu16byte = 61 local referenceu32byte = 62 local customvaluebyte = 99 @native local function readtable(buff: buffer, byte: number, cursor: number, info: Types.decodeinfo) local index if byte == tblu8byte then index = buffer.readu8(buff, cursor); cursor += 1 elseif byte == tblu16byte then index = buffer.readu16(buff, cursor); cursor += 2 else index = buffer.readu32(buff, cursor); cursor += 4 end local formedtables = info.tables local f = formedtables[index] if f then return f, cursor else local value = {} formedtables[index] = value return value, cursor end end @native local function readdeduplicate(buff: buffer, byte: number, cursor: number, info: Types.decodeinfo) local index if byte == dedupu8byte then index = buffer.readu8(buff, cursor); cursor += 1 elseif byte == dedupu16byte then index = buffer.readu16(buff, cursor); cursor += 2 else index = buffer.readu32(buff, cursor); cursor += 4 end return info.deduplicationtable[index], cursor end @native local function readreference(buff: buffer, byte: number, cursor: number, info: Types.decodeinfo) local index if byte == referenceu8byte then index = buffer.readu8(buff, cursor); cursor += 1 elseif byte == referenceu16byte then index = buffer.readu16(buff, cursor); cursor += 2 else index = buffer.readu32(buff, cursor); cursor += 4 end local references = info.references if references then return references[index], cursor else error('Missing references table when decoding buffer that contains value references.') end end local t = { [tblu8byte] = readtable; [tblu16byte] = readtable; [tblu32byte] = readtable; [dedupu8byte] = readdeduplicate; [dedupu16byte] = readdeduplicate; [dedupu32byte] = readdeduplicate; [referenceu8byte] = readreference; [referenceu16byte] = readreference; [referenceu32byte] = readreference; [customvaluebyte] = @native function(buff: buffer, byte: number, cursor: number) return ByteToValue[-buffer.readu8(buff, cursor)], cursor + 1 end, } :: datatypedecodinginfo -- doing those here so theres no cost for indexing ByteToValue for byte, v in ByteToValue do if byte > 0 then -- this runs somehow faster with native .... ok i guess t[byte] = @native function(buff, byte, cursor) return v, cursor end end end return t
792
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/template.luau
--!nolint LocalUnused --!nolint ImportUnused --!optimize 2 local Module = script.Parent.Parent local Settings = require(Module.Settings) local Types = require(Module.Types) type datatypedecodinginfo = Types.datatypedecodinginfo local templatebyte = -1 local writebytesign return { [templatebyte] = @native function(buff: buffer, byte: number, cursor: number): (any, number, boolean?) error('Byte read function should be changed for the template.', 0) end; } :: datatypedecodinginfo
128
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/Settings.luau
local Encoder = script.Parent -- explanation for each of the settings exists in the main module local t = { color3always6bytes = false; rbxenum_behavior = "full" :: "full" | "compact"; serverclientsyncing = false; sanitize_nanandinf = false; } for att, value in Encoder:GetAttributes() do if t[att] ~= nil then if type(value) == type(t[att]) then t[att] = value else warn(`[BUFFERENCODER] {typeof(value)} is not a valid type for the setting {att}`) end end end return t
141
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/Types.luau
type anyTable = { [any]: any } export type encodeinfo = { valuepositionlookup: anyTable; settings: WriteSettings, scanlist: { anyTable }, referencelist: { any }, allocatedsize: number; } export type decodeinfo = { sanitize_nanandinf: boolean?, references: { any }?; deduplicationtable: { any }; tables: { anyTable }; } export type WriteSettings = { allowdeduplication: boolean?, allowreferences: boolean?, shiftseed: number?, rbxenum_behavior: "full" | "compact" | nil, color3always6bytes: boolean?, } export type ReadSettings = { allowdeduplication: boolean?, references: { any }?, shiftseed: number?, rbxenum_behavior: "full" | "compact" | nil, sanitize_nanandinf: boolean?, } export type datatypedecodinginfo = { [number]: (buff: buffer, byte: number, cursor: number, info: decodeinfo) -> (any, number, boolean?), } return 0
239
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/Write.luau
--!native --!optimize 2 --!nolint LocalShadow --[[ ## made by anexpia •…• ## ]] -- [[ byte tags, if negative then its a dict key ]] -- 0 -> at end: terminate, at start: deduplication table -- 1 -> stop and start new table -- 2 -> boolean: true -- 3 -> boolean: false -- 4 -> nil -- 5 to 11 -> number -- 12 to 14 -> buffer -- 15 -> v3 (3 f32) -- 16 -> v2 (2 f32) -- 17 -> cframe -- 18 -> ray (6 f32) -- 19 -> enum < polymorphic - depends on setting 'rbxenum_behavior' > -- 20 -> enumitem < polymorphic - depends on setting 'rbxenum_behavior' > -- 21 -> numberrange (2 f32) -- 22 -> numbersequence -- 23 -> color3 (u8) -- 24 -> color3 (f16) -- 25 -> colorsequence -- 26 -> udim (1 int32 1 f32) -- 27 -> udim2 (2 int32 2 f32) -- 28 -> rect (4 f32) -- 29 -> physicalproperties (really long) -- 30 -> brickcolor (int16) -- 31 -> vector3int16 (3 i16) -- 32 -> vector2int16 (2 i16) -- 33 -> content (depends) -- 34 -> font (depends) -- 35 -> datetime (f64) -- 51 -> table position (u8) -- 52 -> table position (u16) -- 53 -> table position (u32) -- 54 -> u8 length string -- 55 -> u16 length string -- 56 -> u32 length string -- 57 -> value deduplicate (u8) -- 58 -> value deduplicate (u16) -- 59 -> value deduplicate (u32) -- 60 -> reference (u8) -- 61 -- reference (u16) -- 62 -- reference (u32) -- 99 -> 2 byte custom value || <99> <-index> -- 101 -> empty table -- 102 -> empty string -- 103 -> 0 -- 104 -> 1 -- 105 -> -1 -- 106 -> math.huge -- 107 -> -math.huge -- 108 -> nan local uI16_max = (2 ^ 16) - 1 local Enums = require(script.Parent.Enums) local Miscellaneous = require(script.Parent.Miscellaneous) local RbxEnumEncoder = require(script.Parent.RbxEnumEncoder) local Settings = require(script.Parent.Settings) local Types = require(script.Parent.Types) type encodeinfo = Types.encodeinfo type WriteSettings = Types.WriteSettings local valuetobyte = Enums.valuetobyte local writef16 = Miscellaneous.writef16 local writeCFrame = Miscellaneous.writeCFrame local CFrameSize = Miscellaneous.cframesize -- shift the byte associated with a value/datatype by the number given local tryshift = function(v: number, shiftseed: number?): number if shiftseed then return (v + math.random(1, 127)) % 128 else return v end end -- write the byte associated with a given value or datatype local function writebytesign(buff: buffer, cursor: number, value: number, isdict: boolean?, shiftseed: number?) if shiftseed then value = (value + math.random(1, 127)) % 128 end if isdict then value = 255 - value end buffer.writeu8(buff, cursor, value) end -- expand the size of the writingbuffer local function expandbuffertosize(buff: buffer, newsize: number, info: encodeinfo): buffer if newsize > info.allocatedsize then newsize //= 1/1.375 info.allocatedsize = newsize local newbuff = buffer.create(newsize) buffer.copy(newbuff, 0, buff) return newbuff end return buff end -- write every value into the buffer local function write( buff: buffer, cursor: number, info: encodeinfo ): (buffer, number) local writesettings = info.settings local shiftseed: number?, dedupallowed = writesettings.shiftseed, writesettings.allowdeduplication local color3always6bytes = writesettings.color3always6bytes if color3always6bytes == nil then color3always6bytes = Settings.color3always6bytes end local enumbehavior, enumbehaviortype = RbxEnumEncoder.getBehaviorFromSetting(writesettings) local fullrbxenum: boolean = enumbehaviortype == 'full' local scancount: number = 1 local deduplicatedcount: number = 0 local referencecount: number = 0 local valuepositionlookup = info.valuepositionlookup local scanlist = info.scanlist local referencelist = info.referencelist for _, tbl in scanlist do buff = expandbuffertosize(buff, cursor + 1, info) writebytesign(buff, cursor, 1, nil, shiftseed); cursor += 1 local arraywritelength: number = rawlen(tbl) local isdoingdict: boolean = arraywritelength == 0 local iternum: number = if isdoingdict then 2 else 1 local lastkey: number = 0 for k, v in next, tbl do if (not isdoingdict) then local diff: number = (k - lastkey) - 1 if diff > 0 then buff = expandbuffertosize(buff, cursor + diff, info) if shiftseed then for i = 0, diff - 1 do buffer.writeu8(buff, cursor + i, (4 + math.random(1, 127)) % 128) end else buffer.fill(buff, cursor, 4, diff) end cursor += diff end lastkey = k end for i = 1, iternum do local isdict: boolean = isdoingdict and i == 1 local value: any = if isdict then k else v local valuebyte: number? = valuetobyte[value] if valuebyte then if valuebyte <= 0 then buff = expandbuffertosize(buff, cursor + 2, info) writebytesign(buff, cursor, 99, isdict, shiftseed) buffer.writeu8(buff, cursor + 1, -valuebyte); cursor += 2 else buff = expandbuffertosize(buff, cursor + 1, info) writebytesign(buff, cursor, valuebyte, isdict, shiftseed); cursor += 1 end continue end local t: string = typeof(value) local candeduplicate: boolean = dedupallowed and (t == 'string' or t == 'Vector3' or t == 'number' or (fullrbxenum and (t == 'EnumItem' or t == 'Enum'))) if candeduplicate then if value ~= value then -- nan shouldnt be deduplicated, whether in a vector or as a number if t == 'number' then buff = expandbuffertosize(buff, cursor + 1, info) writebytesign(buff, cursor, 108, isdict, shiftseed); cursor += 1 else local value: Vector3 = value -- vector in this case buff = expandbuffertosize(buff, cursor + 13, info) writebytesign(buff, cursor, 15, isdict, shiftseed); cursor += 1 buffer.writef32(buff, cursor, value.X); cursor += 4 buffer.writef32(buff, cursor, value.Y); cursor += 4 buffer.writef32(buff, cursor, value.Z); cursor += 4 end continue end if t == 'number' then local value: number = value -- numbers below 256 that arent float values shouldnt be deduplicated local abs = math.abs(value) if not (abs > 0xFF or abs % 1 ~= 0) then -- encoding here to avoid rechecking later buff = expandbuffertosize(buff, cursor + 5, info) writebytesign(buff, cursor, if value < 0 then 8 else 5, isdict, shiftseed) buffer.writeu8(buff, cursor + 1, abs); cursor += 2 continue end end local added: number? = valuepositionlookup[value] if added then if added <= 0xFF then -- u8 buff = expandbuffertosize(buff, cursor + 2, info) writebytesign(buff, cursor, 57, isdict, shiftseed) buffer.writeu8(buff, cursor + 1, added); cursor += 2 elseif added <= 0xFFFF then -- u16 buff = expandbuffertosize(buff, cursor + 3, info) writebytesign(buff, cursor, 58, isdict, shiftseed) buffer.writeu16(buff, cursor + 1, added); cursor += 3 else -- u32 buff = expandbuffertosize(buff, cursor + 5, info) writebytesign(buff, cursor, 59, isdict, shiftseed) buffer.writeu32(buff, cursor + 1, added); cursor += 5 end continue else deduplicatedcount += 1 valuepositionlookup[value] = deduplicatedcount end end if t == "nil" then buff = expandbuffertosize(buff, cursor + 1, info) writebytesign(buff, cursor, 4, isdict, shiftseed); cursor += 1 elseif t == "number" then local value: number = value if value ~= value then buff = expandbuffertosize(buff, cursor + 1, info) writebytesign(buff, cursor, 108, isdict, shiftseed); cursor += 1 else local abs = math.abs(value) if (value % 1) ~= 0 or abs > 0xFFFFFFFF then -- float64 buff = expandbuffertosize(buff, cursor + 9, info) writebytesign(buff, cursor, 11, isdict, shiftseed) buffer.writef64(buff, cursor + 1, value); cursor += 9 else local offset = if value < 0 then 3 else 0 if abs <= 0xFF then -- uint8 buff = expandbuffertosize(buff, cursor + 2, info) writebytesign(buff, cursor, 5 + offset, isdict, shiftseed) buffer.writeu8(buff, cursor + 1, abs); cursor += 2 elseif abs <= 0xFFFF then -- uint16 buff = expandbuffertosize(buff, cursor + 3, info) writebytesign(buff, cursor, 6 + offset, isdict, shiftseed) buffer.writeu16(buff, cursor + 1, abs); cursor += 3 else buff = expandbuffertosize(buff, cursor + 5, info) writebytesign(buff, cursor, 7 + offset, isdict, shiftseed) buffer.writeu32(buff, cursor + 1, abs); cursor += 5 end end end elseif t == "string" then local value: string = value local len: number = #value if len <= 0xFF then -- not zero-terminated since no benefit in making it zero-terminated buff = expandbuffertosize(buff, cursor + len + 2, info) writebytesign(buff, cursor, 54, isdict, shiftseed) buffer.writeu8(buff, cursor + 1, len); cursor += 2 elseif len <= 0xFFFF then buff = expandbuffertosize(buff, cursor + len + 3, info) writebytesign(buff, cursor, 55, isdict, shiftseed) buffer.writeu16(buff, cursor + 1, len); cursor += 3 else buff = expandbuffertosize(buff, cursor + len + 5, info) writebytesign(buff, cursor, 56, isdict, shiftseed) buffer.writeu32(buff, cursor + 1, len); cursor += 5 end buffer.writestring(buff, cursor, value); cursor += len elseif t == "table" then local value: {[any]: any} = value local scanpos: number? = valuepositionlookup[value] if (not scanpos) and (next(value) ~= nil) then scanpos = scancount + 1 scancount = scanpos :: any valuepositionlookup[value] = scanpos scanlist[scanpos] = value end if scanpos then if scanpos <= 0xFF then buff = expandbuffertosize(buff, cursor + 2, info) writebytesign(buff, cursor, 51, isdict, shiftseed) buffer.writeu8(buff, cursor + 1, scanpos); cursor += 2 elseif scanpos <= 0xFFFF then buff = expandbuffertosize(buff, cursor + 3, info) writebytesign(buff, cursor, 52, isdict, shiftseed) buffer.writeu16(buff, cursor + 1, scanpos); cursor += 3 else buff = expandbuffertosize(buff, cursor + 5, info) writebytesign(buff, cursor, 53, isdict, shiftseed) buffer.writeu32(buff, cursor + 1, scanpos); cursor += 5 end else buff = expandbuffertosize(buff, cursor + 1, info) writebytesign(buff, cursor, 101, isdict, shiftseed); cursor += 1 end elseif t == "buffer" then local value: buffer = value local length: number = buffer.len(value) if length <= 0xFF then buff = expandbuffertosize(buff, cursor + 2 + length, info) writebytesign(buff, cursor, 12, isdict, shiftseed) buffer.writeu8(buff, cursor + 1, length) cursor += 2 elseif length <= 0xFFFF then buff = expandbuffertosize(buff, cursor + 3 + length, info) writebytesign(buff, cursor, 13, isdict, shiftseed) buffer.writeu16(buff, cursor + 1, length) cursor += 3 else buff = expandbuffertosize(buff, cursor + 5 + length, info) writebytesign(buff, cursor, 14, isdict, shiftseed) buffer.writeu32(buff, cursor + 1, length) cursor += 5 end buffer.copy(buff, cursor, value) cursor += length elseif t == "Vector3" then local value: Vector3 = value buff = expandbuffertosize(buff, cursor + 13, info) writebytesign(buff, cursor, 15, isdict, shiftseed); cursor += 1 buffer.writef32(buff, cursor, value.X); cursor += 4 buffer.writef32(buff, cursor, value.Y); cursor += 4 buffer.writef32(buff, cursor, value.Z); cursor += 4 elseif t == "Vector2" then local value: Vector2 = value buff = expandbuffertosize(buff, cursor + 9, info) writebytesign(buff, cursor, 16, isdict, shiftseed); cursor += 1 buffer.writef32(buff, cursor, value.X); cursor += 4 buffer.writef32(buff, cursor, value.Y); cursor += 4 elseif t == "CFrame" then local value: CFrame = value buff = expandbuffertosize(buff, cursor + CFrameSize + 1, info) writebytesign(buff, cursor, 17, isdict, shiftseed); cursor += 1 writeCFrame(buff, cursor, value); cursor += CFrameSize elseif t == "Ray" then local value: Ray = value buff = expandbuffertosize(buff, cursor + 25, info) writebytesign(buff, cursor, 18, isdict, shiftseed); cursor += 1 local pos: Vector3, dir: Vector3 = value.Origin, value.Direction buffer.writef32(buff, cursor, pos.X); cursor += 4 buffer.writef32(buff, cursor, pos.Y); cursor += 4 buffer.writef32(buff, cursor, pos.Z); cursor += 4 buffer.writef32(buff, cursor, dir.X); cursor += 4 buffer.writef32(buff, cursor, dir.Y); cursor += 4 buffer.writef32(buff, cursor, dir.Z); cursor += 4 elseif t == "Enum" then local value: Enum = value local size: number = 3 -- <u8> 19 | <u16> position if fullrbxenum then size = 2 + #RbxEnumEncoder.enumitem_to_type[value] -- <u8> byte | <u8> length | string end buff = expandbuffertosize(buff, cursor + size, info) writebytesign(buff, cursor, 19, isdict, shiftseed) cursor = enumbehavior.encodeEnum(buff, cursor + 1, value) elseif t == "EnumItem" then local value: EnumItem = value local size: number = 3 -- <u8> 20 | <u16> position if fullrbxenum then size = 4 + #RbxEnumEncoder.enumitem_to_type[value] -- <u8> 20 | <u8> length | string | <u16> value end buff = expandbuffertosize(buff, cursor + size, info) writebytesign(buff, cursor, 20, isdict, shiftseed) cursor = enumbehavior.encodeEnumItem(buff, cursor + 1, value) elseif t == "NumberRange" then local value: NumberRange = value buff = expandbuffertosize(buff, cursor + 9, info) writebytesign(buff, cursor, 21, isdict, shiftseed); cursor += 1 buffer.writef32(buff, cursor, value.Min); cursor += 4 buffer.writef32(buff, cursor, value.Max); cursor += 4 elseif t == "NumberSequence" then local value: NumberSequence = value local keypoints: {NumberSequenceKeypoint} = value.Keypoints buff = expandbuffertosize(buff, cursor + 2 + #keypoints * 8, info) writebytesign(buff, cursor, 22, isdict, shiftseed); buffer.writeu8(buff, cursor + 1, #keypoints); cursor += 2 for _, k in keypoints do buffer.writeu16(buff, cursor, math.round(k.Time * uI16_max)) buffer.writef32(buff, cursor + 2, k.Value) writef16(buff, cursor + 6, k.Envelope); cursor += 8 end elseif t == "Color3" then local value: Color3 = value local r: number, g: number, b: number = value.R, value.G, value.B if color3always6bytes or (math.max(r, g, b) > 1 or math.min(r, g, b) < 0) then buff = expandbuffertosize(buff, cursor + 7, info) -- one or more of values is out of 1 byte limit, so this encodes as 2 bytes each writebytesign(buff, cursor, 24, isdict, shiftseed) writef16(buff, cursor + 1, r) writef16(buff, cursor + 3, g) writef16(buff, cursor + 5, b) cursor += 7 else buff = expandbuffertosize(buff, cursor + 4, info) writebytesign(buff, cursor, 23, isdict, shiftseed) buffer.writeu8(buff, cursor + 1, math.round(r * 255)) buffer.writeu8(buff, cursor + 2, math.round(g * 255)) buffer.writeu8(buff, cursor + 3, math.round(b * 255)) cursor += 4 end elseif t == "ColorSequence" then local value: ColorSequence = value local keypoints: {ColorSequenceKeypoint} = value.Keypoints buff = expandbuffertosize(buff, cursor + 2 + #keypoints * 5, info) writebytesign(buff, cursor, 25, isdict, shiftseed) buffer.writeu8(buff, cursor + 1, #keypoints); cursor += 2 for _, k in keypoints do local color = k.Value -- colors in colorsequences are always limited to 0-1 buffer.writeu16(buff, cursor, math.round(k.Time * uI16_max)) buffer.writeu8(buff, cursor + 2, math.round(color.R * 255)) buffer.writeu8(buff, cursor + 3, math.round(color.G * 255)) buffer.writeu8(buff, cursor + 4, math.round(color.B * 255)) cursor += 5 end elseif t == "UDim" then local value: UDim = value buff = expandbuffertosize(buff, cursor + 9, info) writebytesign(buff, cursor, 26, isdict, shiftseed) buffer.writef32(buff, cursor + 1, value.Scale) buffer.writei32(buff, cursor + 5, value.Offset) cursor += 9 elseif t == "UDim2" then local value: UDim2 = value buff = expandbuffertosize(buff, cursor + 17, info) local x: UDim, y: UDim = value.X, value.Y writebytesign(buff, cursor, 27, isdict, shiftseed) buffer.writef32(buff, cursor + 1, x.Scale) buffer.writei32(buff, cursor + 5, x.Offset) buffer.writef32(buff, cursor + 9, y.Scale) buffer.writei32(buff, cursor + 13, y.Offset) cursor += 17 elseif t == "Rect" then local value: Rect = value buff = expandbuffertosize(buff, cursor + 17, info) local min: Vector2, max: Vector2 = value.Min, value.Max writebytesign(buff, cursor, 28, isdict, shiftseed) buffer.writef32(buff, cursor + 1, min.X) buffer.writef32(buff, cursor + 5, min.Y) buffer.writef32(buff, cursor + 9, max.X) buffer.writef32(buff, cursor + 13, max.Y) cursor += 17 elseif t == "PhysicalProperties" then local value: PhysicalProperties = value buff = expandbuffertosize(buff, cursor + 21, info) writebytesign(buff, cursor, 29, isdict, shiftseed) buffer.writef32(buff, cursor + 1, value.Density) buffer.writef32(buff, cursor + 5, value.Friction) buffer.writef32(buff, cursor + 9, value.Elasticity) buffer.writef32(buff, cursor + 13, value.FrictionWeight) buffer.writef32(buff, cursor + 17, value.ElasticityWeight) cursor += 21 elseif t == "BrickColor" then local value: BrickColor = value buff = expandbuffertosize(buff, cursor + 3, info) writebytesign(buff, cursor, 30, isdict, shiftseed) buffer.writeu16(buff, cursor + 1, value.Number) cursor += 3 elseif t == "Vector3int16" then local value: Vector3int16 = value buff = expandbuffertosize(buff, cursor + 7, info) writebytesign(buff, cursor, 31, isdict, shiftseed) buffer.writei16(buff, cursor + 1, value.X) buffer.writei16(buff, cursor + 3, value.Y) buffer.writei16(buff, cursor + 5, value.Z) cursor += 7 elseif t == "Vector2int16" then local value: Vector2int16 = value buff = expandbuffertosize(buff, cursor + 5, info) writebytesign(buff, cursor, 32, isdict, shiftseed) buffer.writei16(buff, cursor + 1, value.X) buffer.writei16(buff, cursor + 3, value.Y) cursor += 5 elseif t == "Content" then local value: Content = value if value.SourceType == Enum.ContentSourceType.Uri then local uri: string = value.Uri :: string local num: string? = string.match(uri, "%d+$") if num then buff = expandbuffertosize(buff, cursor + 10, info) writebytesign(buff, cursor, 33, isdict, shiftseed) buffer.writeu8(buff, cursor + 1, 1) buffer.writef64(buff, cursor + 2, tonumber(num) :: number) cursor += 10 else -- im going to make a guess and say that the content links are NOT going past 254 bytes in length 😨 local len: number = #uri if len > 254 then error("content uri length cannot be more than 254 bytes.", 0) end buff = expandbuffertosize(buff, cursor + 2 + len, info) writebytesign(buff, cursor, 33, isdict, shiftseed) buffer.writeu8(buff, cursor + 1, len + 1); cursor += 2 buffer.writestring(buff, cursor , uri) cursor += len end continue else buff = expandbuffertosize(buff, cursor + 2, info) writebytesign(buff, cursor, 33, isdict, shiftseed) buffer.writeu8(buff, cursor + 1, 0); cursor += 2 end elseif t == "Font" then local value: Font = value local family: string = value.Family local num: string? = string.match(family, "%d+$") if num then buff = expandbuffertosize(buff, cursor + 13, info) writebytesign(buff, cursor, 34, isdict, shiftseed) buffer.writeu8(buff, cursor + 1, 0) buffer.writef64(buff, cursor + 2, tonumber(num) :: number) cursor += 10 else local familyname: string = string.match(family, "/(%w+).json$") or "" local length: number = #familyname -- same here if length > 254 then error("font name length cannot be more than 254 bytes.", 0) end buff = expandbuffertosize(buff, cursor + 5 + length, info) writebytesign(buff, cursor, 34, isdict, shiftseed) buffer.writeu8(buff, cursor + 1, length + 1); cursor += 2 buffer.writestring(buff, cursor, familyname) cursor += length end buffer.writeu16(buff, cursor, RbxEnumEncoder.enumitem_to_value[value.Weight]) buffer.writeu8(buff, cursor + 2, RbxEnumEncoder.enumitem_to_value[value.Style]); cursor += 3 elseif t == "DateTime" then local value: DateTime = value buff = expandbuffertosize(buff, cursor + 9, info) writebytesign(buff, cursor, 35, isdict, shiftseed) buffer.writef64(buff, cursor + 1, value.UnixTimestampMillis); cursor += 9 else if referencelist then local referenceposition: number = valuepositionlookup[value] if not referenceposition then referenceposition = referencecount + 1 referencecount = referenceposition :: any valuepositionlookup[value] = referenceposition referencelist[referenceposition] = value end if referenceposition <= 0xFF then buff = expandbuffertosize(buff, cursor + 2, info) writebytesign(buff, cursor, 60, isdict, shiftseed) buffer.writeu8(buff, cursor + 1, referenceposition); cursor += 2 elseif referenceposition <= 0xFFFF then buff = expandbuffertosize(buff, cursor + 3, info) writebytesign(buff, cursor, 61, isdict, shiftseed) buffer.writeu16(buff, cursor + 1, referenceposition); cursor += 3 else buff = expandbuffertosize(buff, cursor + 5, info) writebytesign(buff, cursor, 62, isdict, shiftseed) buffer.writeu32(buff, cursor + 1, referenceposition); cursor += 5 end elseif isdict then break else buff = expandbuffertosize(buff, cursor + 1, info) writebytesign(buff, cursor, 4, isdict, shiftseed); cursor += 1 end end end if k == arraywritelength then iternum = 2; isdoingdict = true end end end return buff, cursor end local writingbuffer = buffer.create(256) local writingbuffersize = 256 type BenchmarkerProfiler = { Begin: (name: string) -> nil; End: () -> nil; } --[[ returns the table given encoded as a buffer, and the size of buffer <em>param</em> - value : the table to encode <em>param</em> - writeoffset : writing starts from the offset given. <em>param</em> - writesettings : { . <strong>allowdeduplication: boolean</strong> -- attempt to deduplicate repeated values if enabled to reduce buffer size . <strong>allowreferences: boolean</strong> -- if enabled, return a table containing the values it couldn't encode alongside the buffer. . <strong>shiftseed: number</strong> -- the type bytes of values are shuffled using the seed. . <strong>rbxenum_behavior: "full" | "compact"</strong> -- override for the default setting. . <strong>color3always6bytes: boolean</strong> -- override for the default setting. } ]] return function( value: { [any]: any }, writeoffset: number?, writesettings: WriteSettings?, Profiler: BenchmarkerProfiler? ): (buffer, { any }?) if type(value) == "table" then local writesettings: WriteSettings = writesettings or (Settings :: any) local shiftseed = writesettings.shiftseed if shiftseed then math.randomseed(shiftseed) end local referencelist = if writesettings.allowreferences then {} else nil if next(value) == nil then local b = buffer.create(1) buffer.writeu8(b, 0, tryshift(101, shiftseed)) if shiftseed then math.randomseed(os.time()) end return b, referencelist end local cursor: number = writeoffset or 0 local info: encodeinfo = { valuepositionlookup = {[value] = 1}, scanlist = {value}, referencelist = referencelist, settings = writesettings, allocatedsize = writingbuffersize; } local buff = writingbuffer if Profiler then Profiler.Begin("Write") end buff, cursor = write(buff, cursor, info) buff = expandbuffertosize(buff, cursor + 1, info) writebytesign(buff, cursor, 0, nil, shiftseed) if Profiler then Profiler.End() Profiler.Begin("Finish") end writingbuffer = buff writingbuffersize = info.allocatedsize local truncatedbuffer = buffer.create(cursor + 2) buffer.copy(truncatedbuffer, 0, buff, 0, cursor + 1) if shiftseed then math.randomseed(os.time()) end if Profiler then Profiler.End() end return truncatedbuffer, referencelist else error(`Expected a table to be encoded into a buffer, got {typeof(value)}`, 0) end end
7,360
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/bufferencoder/init.luau
--[[ ## made by anexpia •…• ## v---v---v---v---v---v currently supported types v---v---v---v---v---v [x] -> datatype has deduplication deduplication means that if the value exists in more than one table, it will be encoded only once this reduces buffer size and time it takes to encode the value luau types > string [x] > number [x] > boolean > nil > table > buffer > vector [x] roblox types > Enum [x]? only if rbxenum_behavior is 'full' > EnumItem [x]? only if rbxenum_behavior is 'full' > BrickColor > Color3 > ColorSequence > NumberSequence > NumberRange > CFrame > Ray > Vector3int16 > Vector2 > Vector2int16 > Rect > UDim > UDim2 > PhysicalProperties > Content > Font > DateTime can also encode custom values into 2 bytes > this is done by using enums.register(name, value) > value is optional, itll give you a newproxy() if you dont give it a value > max 255 values v---v---v---v---v---v---v---v settings v---v---v---v---v---v---v---v > color3always6bytes: boolean >> default false this toggles if color3 components are always saved as float16 numbers > rbxenum_behavior: string ( 'full' | 'compact' ) >> default 'compact' this has 2 behaviors currently. > "full" encodes the enums as <19> <u8 length> <string> enumitems are <20> <u8 length> <string> <u16 value> this should be used for data saving as this guarantees the enumitems stay the same as long as roblox doesn't do anything weird * encoded values are deduplicated if allowed, so if the same enum & enumitem are encoded multiple times it will not cost the same to encode it each time > "compact" *default behavior* this should ONLY BE USED for sending the enums & enumitems in temporary sessions!!! (like in remotes) the order of the enum & enumitem table is not guaranteed to be consistent between every session thus you will definitely encounter bugs if you use this for saving data * no deduplication since there's no benefit, as this saves both enums and enumitems as 3 bytes, > serverclientsyncing: boolean determines whether to sync enumitems and custom values between client and server > sanitize_nanandinf: boolean determines whether to turn NaN and math.huge into 0 when reading buffer content this only sanitizes them for Numbers, Vectors, Rays, and CFrames ]] return { read = require(script.Read); write = require(script.Write); enums = require(script.Enums) }
681
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/convert_scale.luau
--!optimize 2 -- jabby_util local function convert_scale(unit: string, value: number): string local s = math.sign(value) value = math.abs(value) local prefixes = { [4] = "T", [3] = "G", [2] = "M", [1] = "k", [0] = "", [-1] = "m", [-2] = "μ", [-3] = "n", [-4] = "p", } local order = 0 while value >= 1000 do order += 1 value /= 1000 end while value ~= 0 and value < 1 do order -= 1 value *= 1000 end local format = "%.01f" if value >= 100 then format = "%.01f" value = math.floor(value) elseif value >= 10 then format = "%.01f" value = math.floor(value * 1e1) / 1e1 elseif value >= 1 then format = "%.02f" value = math.floor(value * 1e2) / 1e2 end return string.format(format, value * s) .. prefixes[math.clamp(order, -4, 4)] .. unit end return convert_scale
305
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/convert_units.luau
--!optimize 2 -- jabby_util local function convert_units(unit: string, value: number): string local s = math.sign(value) value = math.abs(value) local prefixes = { [4] = "T", [3] = "G", [2] = "M", [1] = "k", [0] = " ", [-1] = "m", [-2] = "u", [-3] = "n", [-4] = "p", } local order = 0 while value >= 1000 do order += 1 value /= 1000 end while value ~= 0 and value < 1 do order -= 1 value *= 1000 end if value >= 100 then value = math.floor(value) elseif value >= 10 then value = math.floor(value * 1e1) / 1e1 elseif value >= 1 then value = math.floor(value * 1e2) / 1e2 end return value * s .. prefixes[order] .. unit end return convert_units
264
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/limesignal/init.luau
--!optimize 2 --!strict --!native --$Packages local ThreadPool = require("@self/threadpool") --$Types export type Connection<T...> = { disconnect: (self: Connection<T...>) -> (), reconnect: (self: Connection<T...>) -> (), connected: boolean, } export type Event<T...> = { connect: (self: Event<T...>, fn: (T...) -> ()) -> Connection<T...>, connectOnce: (self: Event<T...>, fn: (T...) -> ()) -> Connection<T...>, disconnectAll: (self: Event<T...>) -> (), wait: (self: Event<T...>) -> T..., from: (emitter: (event: Event<T...>, T...) -> ()) -> Event<T...>, } export type Bindable<T...> = { new: () -> Bindable<T...>, wrap: (signal: RBXScriptSignal<T...>) -> Bindable<T...>, fire: (self: Bindable<T...>, T...) -> (), Destroy: (self: Bindable<T...>) -> (), -- why PascalCase? because it does call Destroy method on RBXScriptConnection if it exists RBXScriptConnection: RBXScriptConnection?, event: Event<T...>, } export type Signal<T...> = { new: () -> Signal<T...>, wrap: (signal: RBXScriptSignal<T...>) -> Signal<T...>, connect: (self: Signal<T...>, fn: (T...) -> ()) -> Connection<T...>, connectOnce: (self: Signal<T...>, fn: (T...) -> ()) -> Connection<T...>, disconnectAll: (self: Signal<T...>) -> (), wait: (self: Signal<T...>) -> T..., fire: (self: Signal<T...>, T...) -> (), Destroy: (self: Signal<T...>) -> (), RBXScriptConnection: RBXScriptConnection?, } local Connection = {} :: Connection<...any> (Connection :: any).__index = Connection local function disconnect(self) if not self.connected then return end self.connected = false local next = (self :: any)._next local prev = (self :: any)._prev if next then next._prev = prev end if prev then prev._next = next end local signal = (self :: any)._signal if signal._head == self then signal._head = next end end Connection.disconnect = disconnect -- i know this is annoying but this is only for micro optimization function reconnect(self) if self.connected then return end self.connected = true local signal = (self :: any)._signal local head = signal._head if head then head._prev = self end signal._head = self; (self :: any)._next = head; (self :: any)._prev = false end Connection.reconnect = reconnect --$Lime local Bindable = {} :: Bindable<...any> (Bindable :: any).__index = Bindable local Event = {} :: Event<...any> (Event :: any).__index = Event local Signal = {} :: Signal<...any> (Signal :: any).__index = Signal local rbxConnect, rbxDisconnect do local bindable = Instance.new("BindableEvent") rbxConnect = bindable.Event.Connect rbxDisconnect = bindable.Event:Connect(function() end).Disconnect bindable:Destroy() end local function connect<T...>(self, fn) local head = (self :: any)._head local cn = setmetatable({ connected = true, _signal = self, _fn = fn, _next = head, _prev = false, }, Connection) if head then head._prev = cn end (self :: any)._head = cn :: any return cn :: any end Signal.connect = connect Event.connect = connect :: any local function once<T...>(self, fn) local cn cn = connect(self, function(...: any) disconnect(cn) fn(...) end) return cn end Signal.connectOnce = once Event.connectOnce = once :: any local function wait<T...>(self): T... local thread = coroutine.running() local cn cn = connect(self, function(...) disconnect(cn) task.spawn(thread, ...) end) return coroutine.yield() end Signal.wait = wait Event.wait = wait :: any local function fire<T...>(self, ...) local event = (self :: any).event or self local cn = event._head while cn do -- local thread -- if #freeThreads > 0 then -- thread = freeThreads[#freeThreads] -- freeThreads[#freeThreads] = nil -- else -- thread = coroutine.create(yielder) -- coroutine.resume(thread) -- end -- task.spawn(thread, cn._fn, thread, ...) -- now we spawn in shared threadpool! ThreadPool.spawn(cn._fn, ...) cn = cn._next end end Signal.fire = fire Bindable.fire = fire :: any local function disconnectAll<T...>(self) local cn = (self :: any)._head while cn do disconnect(cn) cn = cn._next end end Event.disconnectAll = disconnectAll Signal.disconnectAll = disconnectAll local function Destroy<T...>(self) disconnectAll((self :: any).event or self) local cn = self.RBXScriptConnection if cn then rbxDisconnect(cn) self.RBXScriptConnection = nil :: any end end Signal.Destroy = Destroy Bindable.Destroy = Destroy :: any function Event.from(emitter) return setmetatable({ _emitter = emitter, _head = false }, Event) :: any end function Bindable.new() local event = setmetatable({ _head = false }, Event) return setmetatable({ event = event }, Bindable) :: any end function Bindable.wrap(signal) local wrapper = Bindable.new() wrapper.RBXScriptConnection = rbxConnect(signal, function(...) fire(wrapper :: any, ...) end) return wrapper end function Signal.new() return setmetatable({ _head = false }, Signal) :: any end function Signal.wrap(signal) local wrapper = Signal.new() wrapper.RBXScriptConnection = rbxConnect(signal, function(...) fire(wrapper, ...) end) return wrapper end local function createEmitter(): <T...>(event: Event<T...>, T...) -> () local function emitter(event, ...) if not event._emitter or event._emitter ~= emitter then error("Emitted an invalid event") end fire(event, ...) end return emitter :: any end return { Signal = Signal, Event = Event, Bindable = Bindable, createEmitter = createEmitter, }
1,490
imezx/Scheduler
imezx-Scheduler-43e0719/src/util/limesignal/threadpool.luau
-- source credit to https://github.com/lukadev-0/util.luau/blob/main/packages/threadpool/init.luau local threadpool = {} local freeThreads: { thread } = {} local function run<T...>(f: (T...) -> (), thread: thread, ...) f(...) table.insert(freeThreads, thread) end local function yielder() while true do run(coroutine.yield()) end end --[=[ Executes the given function in a separate thread, threads are pooled and reused. 별도의 스레드에서 지정된 함수를 실행하며 스레드는 풀링되어 재사용됩니다. ```lua ThreadPool.spawn(function() task.wait(2) print("Hello Caveful Games!") end) ``` ]=] function threadpool.spawn<T...>(f: (T...) -> (), ...: T...) local thread if #freeThreads > 0 then thread = freeThreads[#freeThreads] freeThreads[#freeThreads] = nil else thread = coroutine.create(yielder) coroutine.resume(thread) end task.spawn(thread, f, thread, ...) end return threadpool
263
imezx/Gradien
imezx-Gradien-eaf9c89/src/Debug.luau
--!optimize 2 local Types = require("./Types") local GradClip = require("./GradClip") local Anomaly = require("./Util/Anomaly") type Tensor = Types.Tensor local Debug = {} function Debug.checkTensor(t: Tensor, name: string?): boolean if Anomaly.hasBadValues(t) then warn(`Gradien.Debug: tensor '{name or "?"}' has NaN/Inf/invalid values`) return false end return true end function Debug.checkGradients(params: { Tensor }, label: string?): (boolean, number?) for i, p in params do local g = p._grad if g and Anomaly.hasBadValues(g) then warn(`Gradien.Debug: bad gradient in param {i} ({label or ""})`) return false, i end end return true, nil end function Debug.wrapOptimizer( opt, params: { Tensor }, cfgs: { maxGradNorm: number?, clipValue: number?, warnOnNaN: boolean?, label: string? }? ) local cfg = cfgs or {} local maxGradNorm = cfg.maxGradNorm local clipValue = cfg.clipValue local warnOnNaN = cfg.warnOnNaN if type(warnOnNaN) ~= "boolean" then warnOnNaN = true end local label = cfg.label or "wrapped optimizer" local wrapped = {} function wrapped:zeroGrad() opt:zeroGrad() end function wrapped:step() if maxGradNorm then GradClip.clipNorm(params, maxGradNorm) end if clipValue then GradClip.clipValue(params, clipValue) end if warnOnNaN then Debug.checkGradients(params, label) end opt:step() end return wrapped end function Debug.checkModel(model, label: string?) local params = model:parameters() Debug.checkGradients(params, label) for i, p in params do Debug.checkTensor(p, `{label or "model"}.param{i}`) end end return Debug
449
imezx/Gradien
imezx-Gradien-eaf9c89/src/GradClip.luau
--!native --!optimize 2 local GC = {} function GC.clipValue(params, clip) task.desynchronize() for _, p in params do if p._grad then for i = 1, #p._grad._storage do p._grad._storage[i] = math.clamp(p._grad._storage[i], -clip, clip) end end end task.synchronize() end function GC.clipNorm(params, maxNorm) task.desynchronize() local total = 0 for _, p in params do if p._grad then for i = 1, #p._grad._storage do total += p._grad._storage[i] ^ 2 end end end total = math.sqrt(total) if total > maxNorm then local scale = maxNorm / (total + 1e-9) for _, p in params do if p._grad then for i = 1, #p._grad._storage do p._grad._storage[i] *= scale end end end end task.synchronize() end return GC
253
imezx/Gradien
imezx-Gradien-eaf9c89/src/Initializer.luau
--!native --!optimize 2 local Types = require("./Types") local Initializer = {} local function _randn(): number local u1 = math.random() local u2 = math.random() if u1 <= 1e-7 then u1 = 1e-7 end return math.sqrt(-2 * math.log(u1)) * math.cos(2 * math.pi * u2) end function Initializer.xavierUniform(W: Types.Tensor) task.desynchronize() local fanIn = W._shape[2] local fanOut = W._shape[1] local bound = math.sqrt(6 / (fanIn + fanOut)) for i = 1, #W._storage do W._storage[i] = (math.random() * 2 - 1) * bound end task.synchronize() end function Initializer.kaimingUniform(W: Types.Tensor) task.desynchronize() local fanIn = W._shape[2] local bound = math.sqrt(6 / fanIn) for i = 1, #W._storage do W._storage[i] = (math.random() * 2 - 1) * bound end task.synchronize() end function Initializer.heUniform(W: Types.Tensor) Initializer.kaimingUniform(W) end -- N(0, 2 / fanIn) function Initializer.heNormal(W: Types.Tensor) task.desynchronize() local fanIn = W._shape[2] local std = math.sqrt(2 / fanIn) for i = 1, #W._storage do W._storage[i] = _randn() * std end task.synchronize() end -- U(-sqrt(3 / fanIn), sqrt(3 / fanIn)) function Initializer.lecunUniform(W: Types.Tensor) task.desynchronize() local fanIn = W._shape[2] local bound = math.sqrt(3 / fanIn) for i = 1, #W._storage do W._storage[i] = (math.random() * 2 - 1) * bound end task.synchronize() end -- N(0, 1 / fanIn) function Initializer.lecunNormal(W: Types.Tensor) task.desynchronize() local fanIn = W._shape[2] local std = math.sqrt(1 / fanIn) for i = 1, #W._storage do W._storage[i] = _randn() * std end task.synchronize() end function Initializer.zeros(B: Types.Tensor) task.desynchronize() for i = 1, #B._storage do B._storage[i] = 0 end task.synchronize() end return Initializer
585
imezx/Gradien
imezx-Gradien-eaf9c89/src/Metrics.luau
--!native --!optimize 2 local Types = require("./Types") local M = {} function M.accuracy(logits: Types.Tensor, targets: Types.Tensor): number task.desynchronize() local C, B = logits._shape[1], logits._shape[2] local correct = 0 for j = 1, B do local best = -1 / 0 local arg = 1 for i = 1, C do local v = logits._storage[(i - 1) * B + j] if v > best then best = v arg = i end end if arg == targets[j] then correct += 1 end end task.synchronize() return correct / B end function M.topk(logits: Types.Tensor, targets: Types.Tensor, k: number): number task.desynchronize() local C, B = logits._shape[1], logits._shape[2] local hit = 0 for j = 1, B do local arr = {} for i = 1, C do arr[i] = logits._storage[(i - 1) * B + j] end table.sort(arr, function(a, b) return a > b end) local thresh = arr[math.min(k, C)] local t = targets[j] local ok = false for i = 1, C do if logits._storage[(i - 1) * B + j] >= thresh and i == t then ok = true end end if ok then hit += 1 end end task.synchronize() return hit / B end function M.mse(pred: Types.Tensor, target: Types.Tensor): number task.desynchronize() local s = 0 for i = 1, #pred._storage do local d = pred._storage[i] - target._storage[i] s += d * d end task.synchronize() return s / pred._shape[#pred._shape] end function M.prf1(pred: Types.Tensor, target: Types.Tensor, C: number): (number, number, number) task.desynchronize() local yhat: { number }, B: number if type(pred) == "table" and pred._storage ~= nil then local Cx, Bb = pred._shape[1], pred._shape[2] B = Bb yhat = table.create(B, 1) for j = 1, B do local best, arg = -1 / 0, 1 for i = 1, Cx do local v = pred._storage[(i - 1) * B + j] if v > best then best, arg = v, i end end yhat[j] = arg end else yhat = pred B = #yhat end local tpC: { number }, fpC: { number }, fnC: { number } = {}, {}, {} for c = 1, C do tpC[c] = 0 fpC[c] = 0 fnC[c] = 0 end for j = 1, B do local p, t = yhat[j], target[j] if p and t and p >= 1 and p <= C and t >= 1 and t <= C then if p == t then tpC[p] += 1 else fpC[p] += 1 fnC[t] += 1 end end end local sumP, sumR, sumF = 0, 0, 0 for c = 1, C do local pc = tpC[c] / (tpC[c] + fpC[c] + 1e-9) local rc = tpC[c] / (tpC[c] + fnC[c] + 1e-9) local fc = 2 * pc * rc / (pc + rc + 1e-9) sumP += pc sumR += rc sumF += fc end task.synchronize() return sumP / C, sumR / C, sumF / C end function M.confusion(pred: Types.Tensor, target: Types.Tensor, C: number): { { number } } task.desynchronize() local yhat: { number }, B: number if type(pred) == "table" and pred._storage ~= nil then local Cx, Bb = pred._shape[1], pred._shape[2] B = Bb yhat = table.create(B, 1) for j = 1, B do local best, arg = -1 / 0, 1 for i = 1, Cx do local v = pred._storage[(i - 1) * B + j] if v > best then best, arg = v, i end end yhat[j] = arg end else yhat = pred B = #yhat end local mat: { { number } } = {} for i = 1, C do mat[i] = table.create(C, 0) for j = 1, C do mat[i][j] = 0 end end for j = 1, B do local t, p = target[j], yhat[j] if t >= 1 and t <= C and p >= 1 and p <= C then mat[t][p] += 1 end end task.synchronize() return mat end return M
1,276
imezx/Gradien
imezx-Gradien-eaf9c89/src/State.luau
--!native --!optimize 2 local Types = require("./Types") local Util = require("./Util") local State = {} local assert = Util.Assert local function mapParamsToIndices(params: { Types.Tensor }): { [Types.Tensor]: string } local map = {} for i, p in params do map[p] = `{i}` end return map end --@param params { Types.Tensor } --@return Snapshot function State.dump(params: { Types.Tensor }): Types.Snapshot task.desynchronize() local n = #params local out: Types.Snapshot = table.create(n) for i = 1, n do local t = params[i] assert(t and t._storage and t._shape, `State.dump: expected Tensor at params[{i}]`) local shp = table.clone(t._shape) local dat = table.create(#t._storage, 0) for k = 1, #t._storage do dat[k] = t._storage[k] end out[i] = { shape = shp, dtype = t._dtype or "f32", data = dat } end task.synchronize() return out end function State.load(params: { Types.Tensor }, snap: Types.Snapshot): boolean if snap == nil then return false end task.desynchronize() local changed = false if #params ~= #snap then warn(`Gradien: Model parameter count mismatch (Model: {#params}, Snapshot: {#snap})`) end for i = 1, math.min(#params, #snap) do local t = params[i] local s = snap[i] local data = s and (s.data or s.values) if t and data then if #t._storage ~= #data then warn(`Gradien: Layer {i} size mismatch (Model: {#t._storage}, Snapshot: {#data})`) end local n = math.min(#t._storage, #data) for k = 1, n do t._storage[k] = data[k] :: number end changed = true end end task.synchronize() return changed end function State.dumpModel(model: Types.Module): Types.Snapshot return State.dump(model:parameters()) end function State.loadModel(model: Types.Module, snap: Types.Snapshot): boolean return State.load(model:parameters(), snap) end -- Serializes optimizer state by converting Tensor Keys -> Index Strings function State.dumpOptimizer(optim: Types.Optimizer, modelParams: { Types.Tensor }): Types.OptimizerState? if optim and type(optim.getState) == "function" then local rawState = optim:getState() if not rawState then return nil end local serialized = table.clone(rawState) local paramMap = mapParamsToIndices(modelParams) for k, v in rawState do if type(v) == "table" then local isTensorMap = false local newTable = {} for tk, tv in v do if type(tk) == "table" and tk._storage then isTensorMap = true local idx = paramMap[tk] if idx then newTable[idx] = tv end else newTable[tk] = tv end end if isTensorMap then serialized[k] = newTable end end end return serialized end return nil end function State.loadOptimizer(optim: Types.Optimizer, snap: Types.OptimizerState?, modelParams: { Types.Tensor }): () if not snap then return end if optim and type(optim.setState) == "function" then local restored = table.clone(snap) for k, v in snap do if type(v) == "table" then local reconstructed = {} local wasParamMap = false for idxStr, val in v do local idx = tonumber(idxStr) if idx and modelParams[idx] then wasParamMap = true reconstructed[modelParams[idx]] = val else reconstructed[idxStr] = val end end if wasParamMap then restored[k] = reconstructed end end end optim:setState(restored) end end function State.dumpTrainer(trainer: Types.Trainer): Types.TrainerSnapshot local params = trainer.model:parameters() return { model = State.dumpModel(trainer.model), optimizer = State.dumpOptimizer(trainer.optimizer, params), step = trainer.step or nil, epoch = trainer.epoch or nil, bestMetric = trainer.bestMetric, } end function State.loadTrainer(trainer: Types.Trainer, snap: Types.TrainerSnapshot) if not snap then error("State.loadTrainer: no snapshot provided") end State.loadModel(trainer.model, snap.model) if snap.optimizer then local params = trainer.model:parameters() State.loadOptimizer(trainer.optimizer, snap.optimizer, params) end trainer.step = snap.step or trainer.step or 0 trainer.epoch = snap.epoch or trainer.epoch or 0 trainer.bestMetric = snap.bestMetric end function State.toBuffer(snap: Types.Snapshot): buffer return Util.Buffer.write(snap) end function State.fromBuffer(b: buffer): Types.Snapshot? return Util.Buffer.read(b) end return State
1,205
imezx/Gradien
imezx-Gradien-eaf9c89/src/Tensor.luau
--!native --!optimize 2 local Tensor = {} local Util = require("./Util") local Types = require("./Types") local Tape -- lazy-load local TensorMethods = {} local function attachMethods(t) for name, fn in TensorMethods do t[name] = fn end end export type Tensor = Types.Tensor local sizeFromShape = Util.sizeFromShape local assert = Util.Assert local sqrt = math.sqrt local log = math.log local cos = math.cos local sin = math.sin local floor = math.floor local pi = math.pi local random = math.random local function computeStrides(shape: { number }): { number } task.desynchronize() local rank = #shape local strides = table.create(rank) local acc: number = 1 for i = rank, 1, -1 do strides[i] = acc acc *= shape[i] end task.synchronize() return strides end local function newTensor( storage: { number }, shape: { number }, dtype: Types.DType?, requiresGrad: boolean?, sizeOverride: number? ): Tensor local shapeClone = table.clone(shape) local strides = computeStrides(shapeClone) local t: Types.Tensor = { _storage = storage, _shape = shapeClone, _dtype = dtype or "f64", _requiresGrad = requiresGrad == true, _size = sizeOverride or #storage, _strides = strides, _parents = nil, _backprop = nil, _grad = nil, } attachMethods(t :: any) return t :: any end local function ensureSize(t: Types.Tensor): number local size = t._size if not size then size = #t._storage t._size = size end return size end local function is_contiguous(self: Tensor): boolean if not self._strides then return true end local computed = computeStrides(self._shape) for i = 1, #self._strides do if self._strides[i] ~= computed[i] then return false end end return true end local function contiguous(self: Tensor): Tensor if is_contiguous(self) then return self end local size = ensureSize(self) local out = newTensor(self._storage, self._shape, self._dtype, self._requiresGrad, size) return out end local function ensureStrides(t: Types.Tensor): { number } local strides = t._strides if not strides then strides = computeStrides(t._shape) t._strides = strides end return strides end function Tensor.zeros(shape: { number }, dtype: Types.DType?, requiresGrad: boolean?): Tensor dtype = dtype or "f64" local n = sizeFromShape(shape) return newTensor(table.create(n, 0), shape, dtype, requiresGrad, n) end function Tensor.ones(shape: { number }, dtype: Types.DType?, requiresGrad: boolean?): Tensor dtype = dtype or "f64" local n = sizeFromShape(shape) return newTensor(table.create(n, 1), shape, dtype, requiresGrad, n) end function Tensor.empty(shape: { number }, dtype: Types.DType?, requiresGrad: boolean?): Tensor dtype = dtype or "f64" local n = sizeFromShape(shape) return newTensor(table.create(n), shape, dtype, requiresGrad, n) end function Tensor.fromArray(data: { number }, shape: { number }, dtype: Types.DType?, requiresGrad: boolean?): Tensor local n = sizeFromShape(shape) assert(#data == n, ("Tensor.fromArray: got %d elements, expected %d"):format(#data, n)) dtype = dtype or "f64" return newTensor(table.clone(data), shape, dtype, requiresGrad, n) end function Tensor.randn(shape: { number }, dtype: Types.DType?, requiresGrad: boolean?): Tensor dtype = dtype or "f64" local n = sizeFromShape(shape) local storage = table.create(n) task.desynchronize() for i = 1, n, 2 do local u1 = random() local u2 = random() local radius = sqrt(-2 * log(u1)) local theta = 2 * pi * u2 local z0 = radius * cos(theta) local z1 = radius * sin(theta) storage[i] = z0 if i + 1 <= n then storage[i + 1] = z1 end end task.synchronize() return newTensor(storage, shape, dtype, requiresGrad, n) end local function reshape(self: Tensor, newShape: { number }): Tensor local size = ensureSize(self) assert(sizeFromShape(newShape) == size, "reshape: element count mismatch") local out = newTensor(self._storage, newShape, self._dtype, self._requiresGrad, size) if not self._requiresGrad then return out end if not Tape then Tape = require("./autograd/Tape") :: any end return Tape.makeNode(out, { self }, function(gy: Types.Tensor) if self._requiresGrad then self._grad = self._grad or Tensor.zeros(self._shape, self._dtype, false) task.desynchronize() local gs, ys = (self._grad :: Types.Tensor)._storage, gy._storage for i = 1, #ys do gs[i] += ys[i] end task.synchronize() end end) end local function expand(self: Tensor, newShape: { number }): Tensor local rank = #self._shape local newRank = #newShape assert(newRank >= rank, "expand: new rank must be >= old rank") local expansionStrides = table.create(newRank, 0) local oldShapeExpanded = table.create(newRank, 1) local oldStrides = ensureStrides(self) local oldStridesExpanded = table.create(newRank, 0) for i = 1, rank do oldShapeExpanded[newRank - rank + i] = self._shape[i] oldStridesExpanded[newRank - rank + i] = oldStrides[i] end for i = 1, newRank do if oldShapeExpanded[i] == 1 and newShape[i] > 1 then expansionStrides[i] = 0 elseif oldShapeExpanded[i] == newShape[i] then expansionStrides[i] = oldStridesExpanded[i] else error("expand: incompatible shapes") end end local outSize = sizeFromShape(newShape) local outStorage = table.create(outSize) task.desynchronize() local src = self._storage local coord = table.create(newRank, 0) for flatOut = 1, outSize do local srcOffset = 0 for d = 1, newRank do srcOffset += coord[d] * expansionStrides[d] end outStorage[flatOut] = src[srcOffset + 1] for d = newRank, 1, -1 do local val = coord[d] + 1 if val < newShape[d] then coord[d] = val break end coord[d] = 0 end end task.synchronize() local out = newTensor(outStorage, newShape, self._dtype, self._requiresGrad, outSize) if not self._requiresGrad then return out end if not Tape then Tape = require("./autograd/Tape") :: any end local dtype = self._dtype local shapeCopy = table.clone(self._shape) return Tape.makeNode(out, { self }, function(gy: Types.Tensor) if not self._requiresGrad then return end self._grad = self._grad or Tensor.zeros(shapeCopy, dtype, false) task.desynchronize() local gs = (self._grad :: Types.Tensor)._storage local gys = gy._storage local coordBack = table.create(newRank, 0) for flatOut = 1, outSize do local srcOffset = 0 for d = 1, newRank do srcOffset += coordBack[d] * expansionStrides[d] end gs[srcOffset + 1] += gys[flatOut] for d = newRank, 1, -1 do local val = coordBack[d] + 1 if val < newShape[d] then coordBack[d] = val break end coordBack[d] = 0 end end task.synchronize() end) end local function slice(self: Tensor, dim: number, startIdx: number, endIdx: number?, step: number?): Tensor local shape = self._shape local rank = #shape assert(dim >= 1 and dim <= rank, "slice: dim out of range") local sizeDim = shape[dim] local s = startIdx local e = endIdx or sizeDim local st = step or 1 assert(st > 0, "slice: step must be > 0") assert(s >= 1 and s <= sizeDim, "slice: startIdx out of bounds") assert(e >= 1 and e <= sizeDim, "slice: endIdx out of bounds") assert(e >= s, "slice: endIdx must be >= startIdx") local length = floor((e - s) / st) + 1 local outShape = table.clone(shape) outShape[dim] = length local outSize = sizeFromShape(outShape) local inStrides = ensureStrides(self) local outStorage = table.create(outSize) local indexMap = self._requiresGrad and table.create(outSize) or nil task.desynchronize() local coord = table.create(rank, 1) local srcStorage = self._storage for flatOut = 1, outSize do local posDim = s + (coord[dim] - 1) * st local flatIn0 = 0 for d = 1, rank do local cd = coord[d] if d == dim then cd = posDim end flatIn0 += (cd - 1) * inStrides[d] end local storageIndex = flatIn0 + 1 outStorage[flatOut] = srcStorage[storageIndex] if indexMap then indexMap[flatOut] = storageIndex end for d = rank, 1, -1 do local val = coord[d] + 1 if val <= outShape[d] then coord[d] = val break end coord[d] = 1 end end task.synchronize() local out = newTensor(outStorage, outShape, self._dtype, self._requiresGrad, outSize) if not self._requiresGrad then return out end if not Tape then Tape = require("./autograd/Tape") :: any end local shapeCopy = table.clone(shape) local mapCopy = indexMap local dtype = self._dtype return Tape.makeNode(out, { self }, function(gy: Types.Tensor) if not self._requiresGrad then return end self._grad = self._grad or Tensor.zeros(shapeCopy, dtype, false) task.desynchronize() local gsrc = (self._grad :: Types.Tensor)._storage local gys = gy._storage if mapCopy then for i = 1, #gys do local dest = mapCopy[i] if dest then gsrc[dest] += gys[i] end end end task.synchronize() end) end local function transpose(self: Tensor, dim1: number?, dim2: number?): Tensor local shape = self._shape local rank = #shape local d1 = dim1 local d2 = dim2 if d1 == nil and d2 == nil then assert(rank == 2, "transpose: default dims only valid for rank-2 tensors") d1, d2 = 1, 2 else assert(d1 ~= nil and d2 ~= nil, "transpose: both dim1 and dim2 must be provided") end assert(d1 >= 1 and d1 <= rank, "transpose: dim1 out of range") assert(d2 >= 1 and d2 <= rank, "transpose: dim2 out of range") assert(d1 ~= d2, "transpose: dim1 and dim2 must be different") local perm = table.create(rank) for i = 1, rank do perm[i] = i end perm[d1], perm[d2] = perm[d2], perm[d1] local outShape = table.create(rank) for i = 1, rank do outShape[i] = shape[perm[i]] end local size = ensureSize(self) local outSize = size local outStrides = computeStrides(outShape) local dst = table.create(outSize) local indexMap = self._requiresGrad and table.create(outSize) or nil task.desynchronize() local coordIn = table.create(rank, 1) for flatIn = 1, size do local flatOut0 = 0 for outDim = 1, rank do local inDim = perm[outDim] local c = coordIn[inDim] flatOut0 += (c - 1) * outStrides[outDim] end local outIndex = flatOut0 + 1 dst[outIndex] = self._storage[flatIn] if indexMap then indexMap[outIndex] = flatIn end for d = rank, 1, -1 do local val = coordIn[d] + 1 if val <= shape[d] then coordIn[d] = val break end coordIn[d] = 1 end end task.synchronize() local out = newTensor(dst, outShape, self._dtype, self._requiresGrad, outSize) if not self._requiresGrad then return out end if not Tape then Tape = require("./autograd/Tape") :: any end local shapeCopy = table.clone(shape) local mapCopy = indexMap local dtype = self._dtype return Tape.makeNode(out, { self }, function(gy: Types.Tensor) if not self._requiresGrad then return end self._grad = self._grad or Tensor.zeros(shapeCopy, dtype, false) task.desynchronize() local gsrc = (self._grad :: Types.Tensor)._storage local gys = gy._storage if mapCopy then for i = 1, #gys do local srcIdx = mapCopy[i] if srcIdx then gsrc[srcIdx] += gys[i] end end end task.synchronize() end) end local function narrow(self: Tensor, dim: number, startIdx: number, length: number): Tensor assert(length >= 1, "narrow: length must be >= 1") local endIdx = startIdx + length - 1 return slice(self, dim, startIdx, endIdx, 1) end local function sum(self: Tensor, dim: number?): Tensor if dim then error("Tensor.sum with dim not implemented yet") end local s = 0 local storage = self._storage task.desynchronize() for i = 1, #storage do s += storage[i] end task.synchronize() local out = newTensor({ s }, { 1 }, self._dtype, self._requiresGrad, 1) if not self._requiresGrad then return out end if not Tape then Tape = require("./autograd/Tape") :: any end return Tape.makeNode(out, { self }, function(gy: Types.Tensor) if self._requiresGrad then self._grad = self._grad or Tensor.zeros(self._shape, self._dtype, false) local g = gy._storage[1] task.desynchronize() local gs = (self._grad :: Types.Tensor)._storage for i = 1, #gs do gs[i] += g end task.synchronize() end end) end local function detach(self: Tensor): Tensor return newTensor(self._storage, self._shape, self._dtype, false, ensureSize(self)) end local function noGrad(self: Tensor): () self._requiresGrad = false self._grad = nil end local function backward(self: Tensor, grad: Tensor?) if not self._requiresGrad then error("Tensor does not require grad") end if not Tape then Tape = require("./autograd/Tape") :: any end if not grad then if self._size == 1 then grad = Tensor.ones(self._shape, self._dtype, false) else error("backward: grad must be provided for non-scalar tensors") end end Tape.backwardFrom(self, grad) end TensorMethods.reshape = reshape Tensor.reshape = reshape TensorMethods.expand = expand Tensor.expand = expand TensorMethods.is_contiguous = is_contiguous Tensor.is_contiguous = is_contiguous TensorMethods.contiguous = contiguous Tensor.contiguous = contiguous TensorMethods.slice = slice Tensor.slice = slice TensorMethods.transpose = transpose Tensor.transpose = transpose TensorMethods.narrow = narrow Tensor.narrow = narrow TensorMethods.sum = sum Tensor.sum = sum TensorMethods.detach = detach Tensor.detach = detach TensorMethods.noGrad = noGrad Tensor.noGrad = noGrad TensorMethods.backward = backward Tensor.backward = backward return Tensor
3,943
imezx/Gradien
imezx-Gradien-eaf9c89/src/Trainer.luau
--!native --!optimize 2 local Tape = require("./autograd/Tape") local Types = require("./Types") local Losses = require("./nn/Losses") local Metrics = require("./Metrics") local Util = require("./Util") local Trainer = {} Trainer.__index = Trainer local assert = Util.Assert local function asArrayCallbacks(raw: Types.Callbacks?, default: { Types.CallbackFn }?): { Types.CallbackFn } if type(raw) ~= "table" then return default or {} end if not next(raw) then return raw :: { Types.CallbackFn } end local tbl = raw :: Types.CallbackTable local out: { Types.CallbackFn } = {} if tbl.onStep then local fn = tbl.onStep table.insert(out, function(event: Types.TrainerEvent, ctx: Types.CallbackContext) if event == "step_end" then fn(ctx) end end) end if tbl.onEpochEnd then local fn = tbl.onEpochEnd table.insert(out, function(event: Types.TrainerEvent, ctx: Types.CallbackContext) if event == "epoch_end" then fn(ctx) end end) end if tbl.onBest then local fn = tbl.onBest table.insert(out, function(event: Types.TrainerEvent, ctx: Types.CallbackContext) if event == "best" then fn(ctx) end end) end return out end local function fireCallbacks(callbacks: { Types.CallbackFn }, event: Types.TrainerEvent, ctx: Types.CallbackContext) for _, cb in callbacks do cb(event, ctx) end end local function runSimple(cfg: Types.SimpleConfig): () task.desynchronize() local model = cfg.model local opt = cfg.optimizer(model:parameters()) local lossFn = cfg.loss local loader = cfg.loader local metricFn = cfg.metric local steps = cfg.steps or 100 local reportEvery = cfg.reportEvery or 10 local onMetric = cfg.onMetric local callbacks = asArrayCallbacks(cfg.callbacks, nil) local bestMetric: number? = nil for step = 1, steps do opt:zeroGrad() local X, Y = loader() local out = model:forward(X) local lossValue, grad = lossFn(out, Y) Tape.backwardFrom(out, grad) opt:step() local metricValue: number? = nil if metricFn and (step % reportEvery == 0) then local m = metricFn(out, Y) metricValue = m if onMetric then onMetric(m) end if bestMetric == nil or m > bestMetric then bestMetric = m if #callbacks > 0 then fireCallbacks(callbacks, "best", { epoch = 1, step = step, loss = lossValue, metric = m, model = model, optimizer = opt, }) end end end if #callbacks > 0 then fireCallbacks(callbacks, "step_end", { epoch = 1, step = step, loss = lossValue, metric = metricValue, model = model, optimizer = opt, }) end end task.synchronize() end --@param cfg { model: Module, optimizerFactory: (({ Tensor }) -> Optimizer)?, optimizer: Optimizer?, loss: LossFn, metric: ((Tensor, Tensor) -> number)?, reportEvery: number?, callbacks: Callbacks? } --@return Trainer function Trainer.new(cfg: Types.TrainerConfig) local model = cfg.model local params = model:parameters() local opt: Types.Optimizer if cfg.optimizerFactory then opt = cfg.optimizerFactory(params) else assert(cfg.optimizer, "Trainer.new: provide optimizerFactory OR optimizer instance") opt = cfg.optimizer :: Types.Optimizer end local self = setmetatable({ model = model, optimizer = opt, loss = cfg.loss, metric = cfg.metric, reportEvery = cfg.reportEvery or 10, lrScheduler = cfg.lrScheduler, callbacks = asArrayCallbacks(cfg.callbacks, {}), bestMetric = nil, step = 0, epoch = 1, }, Trainer) return self end --@param makeLoader () -> () -> (Tensor?, Tensor?) --@param opts { epochs: number?, stepsPerEpoch: number?, onMetric: ((number, number, number) -> ())? } function Trainer:fit(makeLoader: () -> () -> (Types.Tensor?, Types.Tensor?), opts: Types.FitOptions?) local fitOpts = (opts or {}) :: Types.FitOptions local epochs = fitOpts.epochs or self.epoch or 1 local stepsPerEpoch = fitOpts.stepsPerEpoch local onMetric = fitOpts.onMetric for epoch = 1, epochs do self.epoch = epoch local loader = makeLoader() local lastLoss: number? = nil local lastMetric: number? = nil local stepsThisEpoch = 0 while true do local X, Y = loader() if not X then break end self.step += 1 stepsThisEpoch += 1 self.optimizer:zeroGrad() local out = self.model:forward(X) local lossValue, grad = self.loss(out, Y) Tape.backwardFrom(out, grad) self.optimizer:step() if self.lrScheduler then local newLr = self.lrScheduler(self.step) if type(newLr) == "number" then if type(self.optimizer.setLr) == "function" then self.optimizer:setLr(newLr) elseif type(self.optimizer.setLR) == "function" then self.optimizer:setLR(newLr) end end end lastLoss = lossValue local metricValue: number? = nil if self.metric and self.reportEvery > 0 and (self.step % self.reportEvery == 0) then local m = self.metric(out, Y) metricValue = m lastMetric = m if onMetric then onMetric(epoch, self.step, m) end if self.bestMetric == nil or m > (self.bestMetric :: number) then self.bestMetric = m fireCallbacks(self.callbacks, "best", { epoch = epoch, step = self.step, loss = lossValue, metric = m, model = self.model, optimizer = self.optimizer, }) end end fireCallbacks(self.callbacks, "step_end", { epoch = epoch, step = self.step, loss = lossValue, metric = metricValue, model = self.model, optimizer = self.optimizer, }) if stepsPerEpoch and stepsThisEpoch >= stepsPerEpoch then break end end fireCallbacks(self.callbacks, "epoch_end", { epoch = epoch, step = self.step, loss = lastLoss, metric = lastMetric, model = self.model, optimizer = self.optimizer, }) end end --@param cfg Types.TrainerConfig --@param opts { smoothing: number?, loss: Types.LossFn?, metric: ((Types.Tensor, any) -> number)? }? function Trainer.newClassification( cfg: Types.TrainerConfig, opts: { smoothing: number?, loss: Types.LossFn?, metric: ((Types.Tensor, any) -> number)?, }? ) local cfgOpts = (opts or {}) :: { smoothing: number?, loss: Types.LossFn?, metric: ((Types.Tensor, any) -> number)?, } local smoothing = cfgOpts.smoothing local lossFn = cfgOpts.loss or cfg.loss if not lossFn then lossFn = function(logits, target) return Losses.cross_entropy_backward(logits, target, smoothing) end end local metricFn = cfgOpts.metric or cfg.metric if not metricFn then metricFn = function(logits, target) return Metrics.accuracy(logits, target) end end return Trainer.new({ model = cfg.model, optimizerFactory = cfg.optimizerFactory, optimizer = cfg.optimizer, loss = lossFn, metric = metricFn, reportEvery = cfg.reportEvery, lrScheduler = cfg.lrScheduler, callbacks = cfg.callbacks, }) end function Trainer:run(loader: () -> (Types.Tensor?, Types.Tensor?), opts: Types.FitOptions?) local function makeLoader() return loader end self:fit(makeLoader, opts) end setmetatable(Trainer, { __call = function(_, cfg: Types.SimpleConfig) return runSimple(cfg) end, }) return Trainer
1,961
imezx/Gradien
imezx-Gradien-eaf9c89/src/Types.luau
--!strict export type DType = "f64" | "f32" | "i32" | "u8" export type Shape = { number } export type Storage = { number } export type Tensor = { _storage: Storage, _shape: Shape, _dtype: DType, _requiresGrad: boolean, _size: number, _strides: { number }?, _parents: { Tensor }?, _backprop: ((grad: Tensor) -> ())?, _grad: Tensor?, } export type Module<TIn = Tensor, TOut = Tensor> = { forward: (self: Module<TIn, TOut>, x: TIn) -> TOut, parameters: (self: Module<TIn, TOut>) -> { Tensor }, } export type OptimizerState = { lr: number, b1: number, b2: number, eps: number, t: number, m: { [Tensor]: { [number]: number } }, v: { [Tensor]: { [number]: number } }, } export type Optimizer = { step: (self: Optimizer) -> (), zeroGrad: (self: Optimizer) -> (), getState: (self: Optimizer) -> OptimizerState?, setState: (self: Optimizer, state: OptimizerState?) -> (), } export type LossFn = (pred: Tensor, target: Tensor) -> (number, Tensor) export type Dataset = { size: (self: Dataset) -> number, at: (self: Dataset, i: number) -> (Tensor, Tensor), batch: (self: Dataset, indices: { number }) -> (Tensor, Tensor), slice: (self: Dataset, i: number, j: number) -> (Tensor, Tensor), } export type BatchIter = () -> ({ number }, { number }) | nil export type Snapshot = { SnapshotTensor } export type TrainerSnapshot = { model: Snapshot, optimizer: OptimizerState?, step: number?, epoch: number?, bestMetric: number?, } export type SnapshotTensor = { shape: { number }, dtype: DType, data: { number }, } export type TrainerEvent = "step_end" | "epoch_end" | "best" export type CallbackContext = { epoch: number, step: number?, loss: number?, metric: number?, model: Module, optimizer: Optimizer, } export type CallbackFn = (TrainerEvent, CallbackContext) -> () export type CallbackTable = { onStep: ((CallbackContext) -> ())?, onEpochEnd: ((CallbackContext) -> ())?, onBest: ((CallbackContext) -> ())?, } export type Callbacks = { CallbackFn } | CallbackTable export type SimpleConfig = { model: Module, optimizer: (params: { Tensor }) -> Optimizer, loss: LossFn, loader: () -> (Tensor, Tensor), metric: ((Tensor, Tensor) -> number)?, steps: number?, reportEvery: number?, onMetric: ((number) -> ())?, callbacks: Callbacks?, } export type TrainerConfig = { model: Module, optimizerFactory: (({ Tensor }) -> Optimizer)?, optimizer: Optimizer?, loss: LossFn, metric: ((Tensor, Tensor) -> number)?, reportEvery: number?, lrScheduler: ((number) -> number)?, callbacks: Callbacks?, } export type FitOptions = { epochs: number?, stepsPerEpoch: number?, onMetric: ((number, number, number) -> ())?, -- (epoch, step, metric) } export type Trainer = { step: number, epoch: number, model: Module, optimizer: Optimizer, loss: LossFn, metric: ((Tensor, Tensor) -> number)?, lrScheduler: ((number) -> number)?, reportEvery: number?, callbacks: { CallbackFn }, bestMetric: number?, } export type Sample = { name: string, total: number, self: number, count: number, avg: number, selfAvg: number, min: number, max: number, last: number, percent: number, } export type Stat = { name: string, total: number, selfTime: number, count: number, min: number, max: number, last: number, } export type Marker = { name: string, start: number, child: number, } export type Callable = (...any) -> ...any return nil
946
imezx/Gradien
imezx-Gradien-eaf9c89/src/Util/Anomaly.luau
--!native --!optimize 2 local Types = require("../Types") local Anomaly = {} function Anomaly.hasBadValues(t: Types.Tensor) for i = 1, #t._storage do local v = t._storage[i] if v ~= v or v == math.huge or v == -math.huge then return true end end return false end function Anomaly.hasNaN(t: Types.Tensor) for i = 1, #t._storage do local v = t._storage[i] if v ~= v then return true end end return false end function Anomaly.hasInf(t: Types.Tensor) for i = 1, #t._storage do local v = t._storage[i] if v == math.huge or v == -math.huge then return true end end return false end return Anomaly
205
imezx/Gradien
imezx-Gradien-eaf9c89/src/Util/Assert.luau
--!optimize 2 --@Eternity_Devs return function<T>(condition: T, errorMessage: string, level: number?): T if not (condition :: any) then error(errorMessage, level or 2) end return condition end
58
End of preview. Expand in Data Studio

Luau Stack HQ

Luau Stack HQ is a highly curated & deduplicated Luau source code from github repository with linter (stylua), it contains ~36.72M tokens (28024 unique files & 378 unique repo). It is built strictly for the training stages, providing a pristine density of type-safe, functional architecture without the noise of standard web scrapes.

# Licensing

The source code contained within this dataset belongs to their respective original authors. All data was sourced from public GitHub repositories under open-source licenses, with forks explicitly excluded. Please respect the original repository licenses when utilizing this dataset for commercial model training.

Downloads last month
7