Run it
Copy the script and paste it into your executor.
HttpService = :()
SCRIPT_VERSION =
VLib = (()
TweenService = :()
UserInputService = :()
Theme = {
Background = .(, , ),
Secondary = .(, , ),
Element = .(, , ),
ElementHover = .(, , ),
Off = .(, , ),
Stroke = .(, , ),
Text = .(, , ),
SubText = .(, , ),
Accent = .(, , ),
}
BUILDER_ICONS =
FONT_TITLE = Font.(, .FontWeight.Bold)
FONT_MAIN = Font.(, .FontWeight.Medium)
FONT_ICON = Font.(BUILDER_ICONS, .FontWeight.Regular)
FONT_ICON_BOLD = Font.(BUILDER_ICONS, .FontWeight.Bold)
TI = TweenInfo.(, .EasingStyle.Quad, .EasingDirection.Out)
TI_S = TweenInfo.(, .EasingStyle.Quart, .EasingDirection.Out)
STROKE_T =
(class, props, children)
inst = .(class)
k, v props
k ~= inst[k] = v
children
_, c children c.Parent = inst
props.Parent inst.Parent = props.Parent
inst
(parent, r)
(, { CornerRadius = .(, r ), Parent = parent })
(parent, color, trans, thick)
(, {
Color = color Theme.Stroke,
Transparency = trans ,
Thickness = thick ,
Parent = parent,
})
(parent, blur, trans)
ok, shadow = (()
(, {
BlurRadius = .(, blur ),
Transparency = trans ,
Parent = parent,
})
)
ok shadow
(obj, info, props)
t = TweenService:(obj, info TI, props)
t:()
t
(name, size, filled, color)
(, {
BackgroundTransparency = ,
Text = name ,
FontFace = filled FONT_ICON_BOLD FONT_ICON,
TextColor3 = color Theme.Text,
TextScaled = ,
Size = .(size , size ),
})
(frame, handle)
dragging, dragInput, startPos, startFramePos, dragEndConnection
handle.InputBegan:((inp)
inp.UserInputType == .UserInputType.MouseButton1 inp.UserInputType == .UserInputType.Touch
dragging =
startPos = inp.Position
startFramePos = frame.Position
dragEndConnection dragEndConnection:()
dragEndConnection = inp.Changed:(()
inp.UserInputState == .UserInputState.End
dragging =
dragEndConnection
dragEndConnection:()
dragEndConnection =
)
)
handle.InputChanged:((inp)
inp.UserInputType == .UserInputType.MouseMovement inp.UserInputType == .UserInputType.Touch
dragInput = inp
)
UserInputService.InputChanged:((inp)
inp == dragInput dragging
delta = inp.Position - startPos
frame.Position = .(
startFramePos.X.Scale, startFramePos.X.Offset + delta.X,
startFramePos.Y.Scale, startFramePos.Y.Offset + delta.Y)
)
()
gethui ()
ok, cg = (()
(cloneref (:())) :()
)
ok cg :()
Library = {}
ScreenGui = (, {
Name = ,
ZIndexBehavior = .ZIndexBehavior.Sibling,
ResetOnSpawn = ,
IgnoreGuiInset = ,
DisplayOrder = ,
})
(() .protect_gui .(ScreenGui) )
ScreenGui.Parent = ()
Library:(cfg)
cfg = cfg {}
cfg.Accent Theme.Accent = cfg.Accent
Window = { Tabs = {}, _current = }
BG = (, {
Name = ,
AnchorPoint = .(, ),
Position = .(, , , ),
Size = .(, ),
BackgroundColor3 = Theme.Background,
BackgroundTransparency = ,
BorderSizePixel = ,
Parent = ScreenGui,
})
(BG, )
(BG, Theme.Stroke, )
(BG, , )
TopBar = (, {
Name = ,
BackgroundColor3 = Theme.Secondary,
BackgroundTransparency = ,
Size = .(, , , ),
BorderSizePixel = ,
ZIndex = ,
Parent = BG,
})
(TopBar, Theme.Stroke, STROKE_T)
(TopBar, , )
(, {
Name = , Text = cfg.Title ,
FontFace = FONT_TITLE, TextColor3 = Theme.Text, TextSize = ,
TextXAlignment = .TextXAlignment.Left, TextWrapped = ,
BackgroundTransparency = , AnchorPoint = .(, ),
Position = .(, , , ), Size = .(, , , ),
Parent = TopBar,
})
(iconName, offsetX, hoverColor)
b = (, {
Text = , AutoButtonColor = , BackgroundColor3 = Theme.Element,
BackgroundTransparency = , AnchorPoint = .(, ),
Position = .(, offsetX, , ), Size = .(, ),
Parent = TopBar,
})
(b, )
ic = (iconName, , , Theme.SubText)
ic.AnchorPoint = .(, )
ic.Position = .(, , , )
ic.Parent = b
b.MouseEnter:(()
(b, TI, { BackgroundTransparency = })
(ic, TI, { TextColor3 = hoverColor Theme.Text })
)
b.MouseLeave:(()
(b, TI, { BackgroundTransparency = })
(ic, TI, { TextColor3 = Theme.SubText })
)
b
CloseBtn = (, -, .(, , ))
MinBtn = (, -, Theme.Text)
Body = (, {
Name = , BackgroundTransparency = ,
Position = .(, , , ), Size = .(, , , -),
Parent = BG,
})
TabList = (, {
Name = , BackgroundColor3 = Theme.Secondary, BackgroundTransparency = ,
BorderSizePixel = , Size = .(, , , ),
CanvasSize = .(), AutomaticCanvasSize = .AutomaticSize.Y,
ScrollBarThickness = , ScrollBarImageColor3 = Theme.Stroke, ScrollBarImageTransparency = ,
Parent = Body,
}, {
(, { Padding = .(, ), SortOrder = .SortOrder.LayoutOrder }),
(, { PaddingTop = .(, ), PaddingLeft = .(, ), PaddingRight = .(, ) }),
})
Content = (, {
Name = , BackgroundTransparency = ,
Position = .(, , , ), Size = .(, -, , ),
Parent = Body,
})
(, {
Name = , BackgroundColor3 = Theme.Stroke, BackgroundTransparency = STROKE_T,
BorderSizePixel = , Position = .(, , , ), Size = .(, , , ),
ZIndex = , Parent = Body,
})
(BG, TopBar)
CloseBtn.Activated:(()
(BG, TI, { GroupTransparency = , Size = .(BG.AbsoluteSize.X, ) })
.(); ScreenGui:()
)
minimized =
MinBtn.Activated:(()
minimized = minimized
minimized
Body.Visible =
(BG, TI_S, { Size = .(, ) })
(BG, TI_S, { Size = .(, ) })
.(); Body.Visible =
)
hidden =
UserInputService.InputBegan:((inp, gp)
gp
inp.KeyCode == (cfg.ToggleKey .KeyCode.RightShift)
hidden = hidden
BG.Visible = hidden
)
Window:(tcfg)
tcfg = tcfg {}
Tab = { _order = }
btn = (, {
Text = , AutoButtonColor = , BackgroundColor3 = Theme.Element,
BackgroundTransparency = , Size = .(, , , ),
Parent = TabList,
})
(btn, )
ic = (tcfg.Icon , , , Theme.SubText)
ic.AnchorPoint = .(, )
ic.Position = .(, , , )
ic.Parent = btn
nameLbl = (, {
BackgroundTransparency = , Text = tcfg.Name ,
FontFace = FONT_MAIN, TextColor3 = Theme.SubText, TextSize = ,
TextXAlignment = .TextXAlignment.Left, TextTruncate = .TextTruncate.AtEnd,
AnchorPoint = .(, ), Position = .(, , , ),
Size = .(, -, , ), Parent = btn,
})
pageWrap = (, {
Name = , BackgroundTransparency = , BorderSizePixel = ,
Size = .(, , , ), Visible = , GroupTransparency = ,
Parent = Content,
})
page = (, {
BackgroundTransparency = , BorderSizePixel = ,
Size = .(, , , ), CanvasSize = .(),
AutomaticCanvasSize = .AutomaticSize.Y, ScrollBarThickness = ,
ScrollBarImageColor3 = Theme.Stroke, ScrollBarImageTransparency = ,
Parent = pageWrap,
}, {
(, { Padding = .(, ), SortOrder = .SortOrder.LayoutOrder }),
(, {
PaddingTop = .(, ), PaddingBottom = .(, ),
PaddingLeft = .(, ), PaddingRight = .(, ),
}),
})
()
Window._current == Tab
_, t Window.Tabs
t ~= Tab t._wrap.Visible =
(t._btn, TI, { BackgroundTransparency = })
(t._icon, TI, { TextColor3 = Theme.SubText })
(t._name, TI, { TextColor3 = Theme.SubText })
Window._current = Tab
pageWrap.Visible =
pageWrap.GroupTransparency =
pageWrap.Position = .(, , , )
(pageWrap, TI_S, { GroupTransparency = , Position = .(, , , ) })
(btn, TI, { BackgroundTransparency = })
(ic, TI, { TextColor3 = Theme.Accent })
(nameLbl, TI, { TextColor3 = Theme.Text })
btn.MouseEnter:(()
pageWrap.Visible (btn, TI, { BackgroundTransparency = })
)
btn.MouseLeave:(()
pageWrap.Visible (btn, TI, { BackgroundTransparency = })
)
btn.Activated:()
Tab._btn, Tab._icon, Tab._name, Tab._page, Tab._wrap, Tab._select = btn, ic, nameLbl, page, pageWrap,
.(Window.Tabs, Tab)
#Window.Tabs == ()
(height)
Tab._order +=
row = (, {
BackgroundColor3 = Theme.Element, Size = .(, , , height ),
LayoutOrder = Tab._order, BorderSizePixel = , Parent = page,
})
(row, )
(row, Theme.Stroke, STROKE_T)
row
Tab:(text)
Tab._order +=
row = (, {
BackgroundTransparency = , Size = .(, , , ),
AutomaticSize = .AutomaticSize.Y, LayoutOrder = Tab._order,
BorderSizePixel = , Parent = page,
})
lbl = (, {
BackgroundTransparency = , Text = text ,
FontFace = FONT_MAIN, TextColor3 = Theme.SubText, TextSize = ,
TextXAlignment = .TextXAlignment.Left, TextWrapped = ,
AutomaticSize = .AutomaticSize.Y, Size = .(, -, , ),
Position = .(, , , ), Parent = row,
})
(, { PaddingTop = .(, ), PaddingBottom = .(, ), Parent = row })
{ Set = (_, t) lbl.Text = t , = row }
Tab:(bcfg)
bcfg = bcfg {}
Tab._order +=
btnEl = (, {
Text = , AutoButtonColor = , BackgroundColor3 = Theme.Element,
Size = .(, , , ), LayoutOrder = Tab._order, BorderSizePixel = , Parent = page,
})
(btnEl, ); (btnEl, Theme.Stroke, STROKE_T)
(, {
BackgroundTransparency = , Text = bcfg.Name ,
FontFace = FONT_MAIN, TextColor3 = Theme.Text, TextSize = ,
Size = .(, , , ), Parent = btnEl,
})
btnEl.MouseEnter:(() (btnEl, TI, { BackgroundColor3 = Theme.ElementHover }) )
btnEl.MouseLeave:(() (btnEl, TI, { BackgroundColor3 = Theme.Element }) )
btnEl.Activated:(()
(btnEl, TI, { BackgroundColor3 = Theme.Accent })
.(, ()
btnEl.Parent
(btnEl, TI, { BackgroundColor3 = Theme.Element })
)
bcfg.Callback .(bcfg.Callback)
)
{ = btnEl }
Tab:(tocfg)
tocfg = tocfg {}
state = tocfg.Default
row = ()
btnEl = (, { Text = , BackgroundTransparency = , Size = .(, , , ), Parent = row })
(, {
BackgroundTransparency = , Text = tocfg.Name ,
FontFace = FONT_MAIN, TextColor3 = Theme.Text, TextSize = ,
TextXAlignment = .TextXAlignment.Left, AnchorPoint = .(, ),
Position = .(, , , ), Size = .(, -, , ), Parent = btnEl,
})
track = (, {
BackgroundColor3 = state Theme.Accent Theme.Off,
AnchorPoint = .(, ), Position = .(, -, , ),
Size = .(, ), BorderSizePixel = , Parent = btnEl,
})
(track, )
knob = (, {
BackgroundColor3 = Theme.Text, AnchorPoint = .(, ),
Position = state .(, -, , ) .(, , , ),
Size = .(, ), BorderSizePixel = , Parent = track,
})
(knob, )
api = {}
api:(v)
state = v
(track, TI, { BackgroundColor3 = state Theme.Accent Theme.Off })
(knob, TI, { Position = state .(, -, , ) .(, , , ) })
tocfg.Callback .(tocfg.Callback, state)
api:() state
btnEl.Activated:(() api:( state) )
api.Instance = row
api
Tab:(txcfg)
txcfg = txcfg {}
row = ()
(, {
BackgroundTransparency = , Text = txcfg.Name ,
FontFace = FONT_MAIN, TextColor3 = Theme.Text, TextSize = ,
TextXAlignment = .TextXAlignment.Left, TextYAlignment = .TextYAlignment.Center,
TextWrapped = , AnchorPoint = .(, ),
Position = .(, , , ), Size = .(, -, , ), Parent = row,
})
boxWrap = (, {
BackgroundColor3 = Theme.Secondary, AnchorPoint = .(, ),
Position = .(, -, , ), Size = .(, , , ),
AutomaticSize = .AutomaticSize.X, ClipsDescendants = ,
BorderSizePixel = , Parent = row,
}, {
(, { PaddingLeft = .(, ), PaddingRight = .(, ) }),
})
(boxWrap, )
tbStroke = (boxWrap, Theme.Stroke, STROKE_T)
tb = (, {
BackgroundTransparency = , Text = txcfg.Default ,
PlaceholderText = txcfg.Placeholder , PlaceholderColor3 = Theme.SubText,
FontFace = FONT_MAIN, TextColor3 = Theme.Text, TextSize = ,
ClearTextOnFocus = , TextXAlignment = .TextXAlignment.Left,
AutomaticSize = .AutomaticSize.X, Size = .(, , , ), Parent = boxWrap,
}, {
(, {
MinSize = .(txcfg.MinWidth , ),
MaxSize = .(txcfg.MaxWidth , .huge),
}),
})
tb.Focused:(() (tbStroke, TI, { Color = Theme.Accent, Transparency = }) )
tb.FocusLost:(()
(tbStroke, TI, { Color = Theme.Stroke, Transparency = STROKE_T })
txcfg.Callback .(txcfg.Callback, tb.Text)
)
{
Set = (_, t) tb.Text = t ,
Get = () tb.Text ,
= row,
}
Tab:(dcfg)
dcfg = dcfg {}
options = dcfg.Options {}
multi = dcfg.Multi
selected = {}
dcfg.Default
(dcfg.Default) ==
_, d dcfg.Default selected[d] =
selected[dcfg.Default] =
row = ()
row.ClipsDescendants =
header = (, { Text = , BackgroundTransparency = , Size = .(, , , ), Parent = row })
(, {
BackgroundTransparency = , Text = dcfg.Name ,
FontFace = FONT_MAIN, TextColor3 = Theme.Text, TextSize = ,
TextXAlignment = .TextXAlignment.Left, AnchorPoint = .(, ),
Position = .(, , , ), Size = .(, , , ), Parent = header,
})
valLbl = (, {
BackgroundTransparency = , Text = ,
FontFace = FONT_MAIN, TextColor3 = Theme.SubText, TextSize = ,
TextXAlignment = .TextXAlignment.Right, TextTruncate = .TextTruncate.AtEnd,
AnchorPoint = .(, ), Position = .(, -, , ),
Size = .(, -, , ), Parent = header,
})
chev = (, , , Theme.SubText)
chev.AnchorPoint = .(, )
chev.Position = .(, -, , )
chev.Parent = header
list = (, {
BackgroundTransparency = , Position = .(, , , ),
Size = .(, , , ), AutomaticSize = .AutomaticSize.Y,
Visible = , Parent = row,
}, {
(, { Padding = .(, ), SortOrder = .SortOrder.LayoutOrder }),
(, { PaddingLeft = .(,), PaddingRight = .(,), PaddingBottom = .(,) }),
})
()
picked = {}
_, o options selected[o] .(picked, o)
valLbl.Text = #picked == .(picked, )
api = {}
optionBtns = {}
()
_, b optionBtns b.btn:()
.(optionBtns)
i, opt options
ob = (, {
Text = , AutoButtonColor = , BackgroundColor3 = Theme.Secondary,
Size = .(, , , ), LayoutOrder = i, BorderSizePixel = , Parent = list,
})
(ob, )
txt = (, {
BackgroundTransparency = , Text = opt, FontFace = FONT_MAIN,
TextColor3 = selected[opt] Theme.Accent Theme.SubText, TextSize = ,
TextXAlignment = .TextXAlignment.Left, Position = .(, , , ),
Size = .(, -, , ), Parent = ob,
})
check = (, , , Theme.Accent)
check.AnchorPoint = .(, )
check.Position = .(, -, , )
check.Visible = selected[opt] ==
check.Parent = ob
ob.MouseEnter:(() (ob, TI, { BackgroundColor3 = Theme.ElementHover }) )
ob.MouseLeave:(() (ob, TI, { BackgroundColor3 = Theme.Secondary }) )
ob.Activated:(()
multi
selected[opt] = selected[opt]
.(selected); selected[opt] =
_, b optionBtns
on = selected[b.opt] ==
b.check.Visible = on
(b.txt, TI, { TextColor3 = on Theme.Accent Theme.SubText })
()
dcfg.Callback
multi
out = {}
_, o options selected[o] .(out, o)
.(dcfg.Callback, out)
.(dcfg.Callback, opt)
multi
.()
api.()
)
.(optionBtns, { btn = ob, opt = opt, txt = txt, check = check })
()
()
n = #options
n ==
+ (n * ) + ((n - ) * ) +
open =
api.(force)
force ~= open = force open = open
open list.Visible =
(row, TI_S, { Size = .(, , , open () ) })
(chev, TI, { Rotation = open })
open .(, () open list.Visible = )
header.Activated:(() api.() )
api:(newOpts)
options = newOpts options
()
open api.()
api:(val)
.(selected)
(val) == _, x val selected[x] =
selected[val] =
()
api:()
out = {}
_, o options selected[o] .(out, o)
multi out out[]
api.Instance = row
()
api
Tab
Window.Instance = BG
Window
Library
)()
() ==
previousUnload = ().MAS_CodeInterpreter_Unload
(previousUnload) ==
(previousUnload)
containers = {
:().LocalPlayer:(),
(gethui) == () ,
:(),
}
_, container (containers)
container
_, gui (container:())
gui:()
ours =
_, descendant (gui:())
descendant:()
descendant.Text:()
ours =
ours
gui:()
unloaded =
focusCleanup
trackedConnections = {}
(connection)
trackedConnections[#trackedConnections + ] = connection
connection
MAS_UNIVERSE_ID =
MAS_ROOT_PLACE_ID =
IS_MAS = .GameId == MAS_UNIVERSE_ID .PlaceId == MAS_ROOT_PLACE_ID
SETTINGS_FILE =
DEFAULT_SETTINGS = {
renderDistance = ,
maxRendered = ,
showLabels = ,
showWires = ,
showSequencerWires = ,
showClassId = ,
wireAnimation = ,
wireWidth = ,
labelScale = ,
labelBackgroundTransparency = ,
graphShowWires = ,
graphAnimateBackground = ,
graphRememberLayout = ,
graphBackgroundTransparency = ,
graphLayout = ,
}
settings = {}
key, value (DEFAULT_SETTINGS)
settings[key] = value
settingsStatus
settingsLoadNote =
(value, minimum, maximum, fallback)
value = (value)
value value ~= value
fallback
.(maximum, .(minimum, value))
(value, fallback)
(value) ==
value
fallback
()
(isfile) ~= (readfile) ~=
settingsLoadNote =
existsOk, exists = (isfile, SETTINGS_FILE)
existsOk exists
settingsLoadNote = .. SETTINGS_FILE ..
readOk, raw = (readfile, SETTINGS_FILE)
readOk (raw) ~= raw ==
settingsLoadNote = .. SETTINGS_FILE ..
decodeOk, data = (()
HttpService:(raw)
)
decodeOk (data) ~=
settingsLoadNote =
settings.renderDistance = (data.renderDistance, , , DEFAULT_SETTINGS.renderDistance)
settings.maxRendered = .((data.maxRendered, , , DEFAULT_SETTINGS.maxRendered))
settings.showLabels = (data.showLabels, DEFAULT_SETTINGS.showLabels)
settings.showWires = (data.showWires, DEFAULT_SETTINGS.showWires)
settings.showSequencerWires = (data.showSequencerWires, DEFAULT_SETTINGS.showSequencerWires)
settings.showClassId = (data.showClassId, DEFAULT_SETTINGS.showClassId)
settings.wireAnimation = (data.wireAnimation, DEFAULT_SETTINGS.wireAnimation)
settings.wireWidth = (data.wireWidth, , , DEFAULT_SETTINGS.wireWidth)
settings.labelScale = (data.labelScale, , , DEFAULT_SETTINGS.labelScale)
settings.labelBackgroundTransparency = (
data.labelBackgroundTransparency, , , DEFAULT_SETTINGS.labelBackgroundTransparency)
settings.graphShowWires = (data.graphShowWires, DEFAULT_SETTINGS.graphShowWires)
settings.graphAnimateBackground = (
data.graphAnimateBackground, DEFAULT_SETTINGS.graphAnimateBackground)
settings.graphRememberLayout = (
data.graphRememberLayout, DEFAULT_SETTINGS.graphRememberLayout)
settings.graphBackgroundTransparency = (
data.graphBackgroundTransparency, , , DEFAULT_SETTINGS.graphBackgroundTransparency)
settings.graphLayout = (data.graphLayout) == data.graphLayout
settingsLoadNote = .. SETTINGS_FILE ..
(note)
(writefile) ~=
settingsStatus
settingsStatus:((note ) .. )
,
ok, writeError = (()
(SETTINGS_FILE, HttpService:(settings))
)
settingsStatus
ok
settingsStatus:((note ) .. .. SETTINGS_FILE .. )
settingsStatus:( .. (writeError))
ok, writeError
()
(label, builder)
label
label.Text =
label.TextScaled =
parts = {}
canvas = .()
canvas.Size = .(, )
canvas.BackgroundTransparency =
canvas.ZIndex =
canvas.Parent = label
color = label.TextColor3
(sizeX, sizeY, offsetX, offsetY, rotation)
part = .()
part.Size = .(sizeX, sizeY)
part.AnchorPoint = .(, )
part.Position = .(, offsetX, , offsetY)
part.Rotation = rotation
part.BackgroundColor3 = color
part.BorderSizePixel =
part.ZIndex =
part.Parent = canvas
parts[#parts + ] = part
part
(bar)
label:():(()
_, part (parts)
part.BackgroundColor3 = label.TextColor3
)
(label)
(label, (bar)
(, , -, )
(, , , )
(, , , -)
(, , , )
(, , , -)
(, , , )
(, , , )
)
(label)
(label, (bar)
(, , -, )
(, , , )
(, , , -)
)
(label)
(label, (bar)
(, , -, -)
(, , , )
(, , , )
)
(label)
(label, (bar)
(, , , -)
(, , -, , -)
(, , , , )
(, , , )
)
Window = VLib:({
Title = .. SCRIPT_VERSION,
ToggleKey = .KeyCode.RightShift,
Accent = .(, , ),
})
VisualsTab, StatsTab, UpdateTab, SettingsTab
unloadInterpreter
ModelTab
IS_MAS
VisualsTab = Window:({Name = , Icon = })
StatsTab = Window:({Name = , Icon = })
ModelTab = Window:({Name = , Icon = })
ValidateTab = Window:({Name = , Icon = })
SettingsTab = Window:({Name = , Icon = })
UpdateTab = Window:({Name = , Icon = })
(StatsTab StatsTab._icon)
(ModelTab ModelTab._icon)
(UpdateTab UpdateTab._icon)
ModelTab = Window:({Name = , Icon = })
(ModelTab ModelTab._icon)
statsRows = {}
(inst)
name = inst.Name
name ==
name ==
name ==
name ==
name ==
name ==
name:(, #) ==
name:(, #) ==
inst:()
parent = inst.Parent
parent ~= parent.Name ==
current = inst.Parent
current current ~=
currentName = current.Name
currentName ==
currentName:(, #) ==
currentName:(, #) ==
current = current.Parent
(root)
target = root
ok, descendants = (target.GetDescendants, target)
ok
{}
parts = {}
_, inst (descendants)
inst:() (inst)
parts[#parts + ] = inst
parts
decodedInsertedCache = ({}, {__mode = })
partInsertedCache = ({}, {__mode = })
(part)
inserted = partInsertedCache[part]
inserted inserted.Parent == part inserted.Name ==
inserted
inserted = part:()
partInsertedCache[part] = inserted
inserted
dataVersion =
(part)
part:()
inserted = (part)
inserted inserted:()
raw = inserted.Value
cached = decodedInsertedCache[inserted]
cached cached.raw == raw
cached.ok
cached.data
ok, data = (()
HttpService:(raw)
)
dataVersion +=
decodedInsertedCache[inserted] = {raw = raw, ok = ok, data = data, version = dataVersion}
ok
data
GATE_OPERATORS = { [] = , [] = , [] = , [] = , [] = }
OPCODE_NAMES = {
[] = , [] = , [] = , [] = ,
[] = , [] = , [] = , [] = ,
[] = , [] = , [] = , [] = ,
[] = , [] = ,
}
parseCache = ({}, {__mode = })
(data)
(data) ~=
(data)
opcode = (data[])
opcode ==
.. (data[] ) .. .. (data[] )
opcode ==
.. (data[] )
opcode ==
.. (data[] )
opcode ==
.. (data[] )
opcode ==
.. (data[] )
opcode ==
()
:((data[] ), (data[] ), (data[] ),
(data[] ), (data[] ), (data[] ),
(data[] ), (data[] ))
opcode ==
.. (data[] )
opcode ==
.. (data[] ) ..
opcode ==
.. (data[] ) .. .. (data[] )
opcode ==
steps = {}
(data[]) ==
index, step (data[])
(step) ==
steps[#steps + ] = (step[] ) .. .. (step[] )
steps[#steps + ] = (step)
.. (data[] #steps) .. .. .(steps, ) ..
opcode ==
()
:((data[] ), (data[] ), (data[] ))
opcode ==
.. (data[] ) .. .. (data[] ) .. .. (data[] ) ..
opcode ==
buttons = (data[]) == data[] {}
names = {}
_, button (buttons)
(button) ==
label = (button.t ):(, )
names[#names + ] = label .. (button.sI ~= ( .. (button.sI)) )
.. (#names > .(names, ) )
opcode ==
mode = (data[])
operator = GATE_OPERATORS[mode]
()
:((data[] ), operator, (data[] ),
(data[] ), (data[] ))
.. (data[])
(data)
(data) ~=
(data)
cached = parseCache[data]
cached
cached
result = (data)
parseCache[data] = result
result
(text)
(text):(, ):(, ):(, ):(, )
(text)
pieces = {}
cursor =
operators = {, , , , , , , , , , , , , , , , , , }
(value, color)
pieces[#pieces + ] = .. color .. .. (value) ..
cursor <= #text
remainder = text:(cursor)
whitespace = remainder:()
whitespace
pieces[#pieces + ] = (whitespace)
cursor = cursor + #whitespace
character = text:(cursor, cursor)
character == character ==
quote = character
endCursor = cursor +
endCursor <= #text
current = text:(endCursor, endCursor)
current ==
endCursor = .(endCursor + , #text + )
current == quote
endCursor = endCursor +
endCursor = endCursor +
(text:(cursor, endCursor - ), )
cursor = endCursor
word = remainder:()
number = remainder:()
remainder:()
word
following = text:(cursor + #word):()
word == word ==
(word, )
following == text:(cursor + #word):()
(word, )
pieces[#pieces + ] = (word)
cursor = cursor + #word
number
(number, )
cursor = cursor + #number
matchedOperator
_, operator (operators)
text:(cursor, cursor + #operator - ) == operator
matchedOperator = operator
matchedOperator
(matchedOperator, )
cursor = cursor + #matchedOperator
pieces[#pieces + ] = (character)
cursor = cursor +
.(pieces)
(text)
text = (text)
stepLabel, stepRest = text:()
stepLabel
.. (stepLabel) ..
.. (stepRest)
key, value = text:()
key
.. (key) ..
.. .. (value)
(text)
(commandText, width)
lines = {}
logicalLine (commandText .. ):()
logicalLine = logicalLine:(, ):(, )
logicalLine ==
lines[#lines + ] =
first =
current =
word logicalLine:()
candidate
current ==
candidate = word
candidate = current .. .. word
limit = first width (width - )
#candidate > limit current ~=
lines[#lines + ] = (first ) .. current
first =
current = word
current = candidate
lines[#lines + ] = (first ) .. current
lines
graphDetailCache = ({}, {__mode = })
(data)
(data) == (data[]) ==
operator = GATE_OPERATORS[(data[]) ]
text = ():(
(data[] ), operator, (data[] ),
(data[] ), (data[] ))
(text)
(data) ~= (data[]) ~= (data[]) ~=
detail = (data):(, , )
(detail)
text = (data[]:(, ))
wrapped = (text, )
colored = {}
_, line (wrapped)
colored[#colored + ] = (line)
.(colored, ), #wrapped
(data)
(data) ~=
(data)
cached = graphDetailCache[data]
cached
cached.text, cached.lines
text, lines = (data)
graphDetailCache[data] = {text = text, lines = lines}
text, lines
EMPTY_IDS = {}
decodedClassIdCache = ({}, {__mode = })
classIdsCache = ({}, {__mode = })
outputSignalIdsCache = ({}, {__mode = })
e it again.
-- Decode once per attribute value and share the result.
local function decodeClassId(part)
local raw = part:GetAttribute("ClassId")
if raw == nil then
return nil
end
local cached = decodedClassIdCache[part]
if cached and cached.raw == raw then
return cached.decoded
end
local decoded = raw
if type(raw) == "string" then
local ok, value = pcall(function()
return HttpService:JSONDecode(raw)
end)
if ok then
decoded = value
end
end
decodedClassIdCache[part] = {raw = raw, decoded = decoded}
return decoded
end
local function countClassIds(part)
local classId = decodeClassId(part)
if classId == nil then
return 0
end
if type(classId) == "table" then
local count = #classId
if count > 0 then
return count
end
for _ in pairs(classId) do
count = count + 1
end
return count
end
return 1
end
local function getClassIds(part)
local raw = part:GetAttribute("ClassId")
if raw == nil then
return EMPTY_IDS
end
-- Several readers ask for the same ids during one refresh (ports, wires,
-- graph, validation). Build the list once per attribute value.
local cached = classIdsCache[part]
if cached and cached.raw == raw then
return cached.ids
end
local classId = decodeClassId(part)
if classId == nil then
classIdsCache[part] = {raw = raw, ids = EMPTY_IDS}
return EMPTY_IDS
end
local ids = {}
if type(classId) == "table" then
for _, id in pairs(classId) do
ids[#ids + 1] = tostring(id)
end
else
ids[1] = tostring(classId)
end
classIdsCache[part] = {raw = raw, ids = ids}
return ids
end
local function countSignalIds(value)
if type(value) == "table" then
local count = 0
for _, item in pairs(value) do
count += countSignalIds(item)
end
return count
elseif type(value) == "number" or (type(value) == "string" and value:match("^%d+$")) then
return 1
end
return 0
end
local function getPortCounts(part, data)
local opcode = type(data) == "table" and tonumber(data[1])
local classIdCount = countClassIds(part)
if opcode == 1 then
return 1, 1
elseif opcode == 5 or opcode == 6 or opcode == 8 then
return 0, 1
elseif opcode == 7 then
return 0, 1
elseif opcode == 101 then
return classIdCount, 0
elseif opcode == 102 or opcode == 104 then
return classIdCount, 1
elseif opcode == 103 then
local steps = type(data[2]) == "table" and #data[2] or tonumber(data[3]) or 0
return classIdCount, steps
elseif opcode == 105 then
return classIdCount, 2
elseif opcode == 106 or opcode == 107 then
local count = 0
for index = 2, #data do
count += countSignalIds(data[index])
end
return 0, count
elseif opcode == 108 then
return classIdCount, 2
end
return 0, 0
end
local function getOutputSignalIds(data)
if type(data) ~= "table" then
return EMPTY_IDS
end
-- The decoded payload is immutable and cached, so its extracted ids stay
-- valid until the Inserted value changes and a new table replaces it.
local cached = outputSignalIdsCache[data]
if cached then
return cached
end
local opcode = tonumber(data[1])
local ids = {}
local function add(id)
if id ~= nil then
ids[#ids + 1] = tostring(id)
end
end
if opcode == 1 then
add(data[3])
elseif opcode == 5 or opcode == 6 or opcode == 8 then
add(data[2])
elseif opcode == 7 then
add(data[3])
elseif opcode == 102 then
add(data[3])
elseif opcode == 103 and type(data[2]) == "table" then
for _, step in ipairs(data[2]) do
if type(step) == "table" then
add(step[2])
end
end
elseif opcode == 104 then
add(data[2])
elseif opcode == 105 then
add(data[2])
add(data[3])
elseif opcode == 106 or opcode == 107 then
-- GUI-style blocks can expose one or more signal IDs anywhere in their payload.
local function addPayload(value)
if type(value) == "table" then
for _, item in pairs(value) do
addPayload(item)
end
elseif type(value) == "number" or (type(value) == "string" and value:match("^%d+$")) then
add(value)
end
end
for index = 2, #data do
addPayload(data[index])
end
elseif opcode == 108 then
add(data[6])
add(data[7])
end
outputSignalIdsCache[data] = ids
return ids
end
local function findMatchingInputs(parts, dataByPart, sequencerWiresEnabled, buildTargets)
local sourcesBySignal = {}
for _, part in ipairs(parts) do
local data = dataByPart and dataByPart[part] or getData(part)
for _, signalId in ipairs(getOutputSignalIds(data)) do
local sources = sourcesBySignal[signalId]
if not sources then
sources = {}
sourcesBySignal[signalId] = sources
end
sources[#sources + 1] = part
end
end
local matches = {}
-- Wire creation needs the same input targets the port pass already reads.
-- Build that map here so createAnimatedLinks can skip a second full scan.
local targetsBySignal = {}
for _, part in ipairs(parts) do
local partMatches
local data = dataByPart and dataByPart[part] or getData(part)
local opcode = type(data) == "table" and tonumber(data[1])
if opcode ~= 106 and opcode ~= 107 then
local seenInputs = {}
for _, signalId in ipairs(getClassIds(part)) do
if not seenInputs[signalId] then
seenInputs[signalId] = true
local sources = sourcesBySignal[signalId]
if not partMatches then
partMatches = {}
end
partMatches[#partMatches + 1] = {
signalId = signalId,
source = sources and sources[1] or nil,
}
if buildTargets ~= false and data and (opcode ~= 103 or sequencerWiresEnabled) then
local targets = targetsBySignal[signalId]
if not targets then
targets = {}
targetsBySignal[signalId] = targets
end
targets[#targets + 1] = part
end
end
end
end
if partMatches then
matches[part] = partMatches
end
end
return matches, targetsBySignal
end
local function getClassIdText(part)
local classId = part:GetAttribute("ClassId")
if classId == nil then
return nil
end
return "ClassId=" .. tostring(classId)
end
local function buildLabelDescription(part, data)
local description = parse(data)
if settings.showClassId then
local classIdText = getClassIdText(part)
if classIdText then
description = description .. "\n" .. classIdText
end
end
return description
end
local COLORS = {
[1] = Color3.fromRGB(170, 75, 75),
[5] = Color3.fromRGB(170, 75, 75),
[6] = Color3.fromRGB(170, 75, 75),
[7] = Color3.fromRGB(210, 130, 55),
[8] = Color3.fromRGB(170, 75, 75),
[101] = Color3.fromRGB(45, 145, 85),
[102] = Color3.fromRGB(55, 115, 205),
[103] = Color3.fromRGB(145, 90, 190),
[104] = Color3.new(1, 0.6, 0),
[105] = Color3.new(0.8, 0, 1),
[108] = Color3.fromRGB(225, 185, 55)
}
local function createGui(part, titleText, description, color)
local existing = part:FindFirstChild("LogicBlockGui")
if existing then
existing:Destroy()
end
local labelScale = settings.labelScale
local billboard = Instance.new("BillboardGui")
billboard.Name = "LogicBlockGui"
billboard.Adornee = part
billboard.Size = UDim2.new(4 * labelScale, 0, labelScale, 0)
billboard.StudsOffset = Vector3.new(0, 2 * labelScale, 0)
billboard.AlwaysOnTop = true
local frame = Instance.new("Frame")
frame.Size = UDim2.new(1, 0, 1, 0)
frame.BackgroundColor3 = color or COLORS[1]
frame.BackgroundTransparency = settings.labelBackgroundTransparency
frame.Parent = billboard
local title = Instance.new("TextLabel")
title.Size = UDim2.new(1, 0, 0.5, 0)
title.BackgroundTransparency = 1
title.TextColor3 = Color3.fromRGB(15, 15, 15)
title.TextScaled = true
title.Font = Enum.Font.Code
title.Text = titleText
title.Parent = frame
local detail = Instance.new("TextLabel")
detail.Size = UDim2.new(1, 0, 0.5, 0)
detail.Position = UDim2.new(0, 0, 0.5, 0)
detail.BackgroundTransparency = 1
detail.TextColor3 = Color3.fromRGB(15, 15, 15)
detail.TextScaled = true
detail.Font = Enum.Font.Code
detail.Text = description
detail.Parent = frame
billboard.Parent = part
return {billboard = billboard, frame = frame, title = title, detail = detail}
end
local function clearConnectors(parts)
local oldWires = workspace:FindFirstChild("MAS_VisualWires")
if oldWires then
oldWires:Destroy()
end
for _, part in ipairs(parts) do
for _, child in ipairs(part:GetChildren()) do
local name = child.Name
if name:sub(1, #"WireConnector_") == "WireConnector_" or name:sub(1, #"MAS_WireAttachment") == "MAS_WireAttachment" then
child:Destroy()
end
end
end
end
local connectorParts = setmetatable({}, {__mode = "k"})
local connectorPartSet = setmetatable({}, {__mode = "k"})
local function trackConnectorPart(part)
if not connectorPartSet[part] then
connectorPartSet[part] = true
connectorParts[#connectorParts + 1] = part
end
end
local function clearWireConnectors()
clearConnectors(connectorParts)
table.clear(connectorParts)
table.clear(connectorPartSet)
end
local function createAnimatedLinks(parts, sequencerWiresEnabled, dataByPart, targetsBySignal)
local folder = Instance.new("Folder")
folder.Name = "MAS_VisualWires"
folder.Parent = workspace
dataByPart = dataByPart or {}
local INPUT_PREFIX = "WireConnector_In_"
local PORT_PREFIX = "WireConnector_"
-- Index ports once: findPort used to rescan a block's children for every
-- wire, which is O(wires x children) on a fully wired build.
local portsByPart = {}
for _, part in ipairs(parts) do
local inputs, outputs = {}, {}
for _, child in ipairs(part:GetChildren()) do
if child:IsA("BasePart") then
local name = child.Name
local isInput = name:sub(1, #INPUT_PREFIX) == INPUT_PREFIX
if isInput or name:sub(1, #PORT_PREFIX) == PORT_PREFIX then
local signalId = child:GetAttribute("SignalId")
if signalId ~= nil then
local map = isInput and inputs or outputs
local key = tostring(signalId)
if map[key] == nil then
map[key] = child
end
end
end
end
end
portsByPart[part] = {inputs = inputs, outputs = outputs}
end
if not targetsBySignal then
targetsBySignal = {}
for _, target in ipairs(parts) do
local targetData = dataByPart[target] or getData(target)
dataByPart[target] = targetData
local targetOpcode = type(targetData) == "table" and tonumber(targetData[1])
if targetData and targetOpcode ~= 106 and targetOpcode ~= 107
and (targetOpcode ~= 103 or sequencerWiresEnabled) then
for _, inputId in ipairs(getClassIds(target)) do
local targets = targetsBySignal[inputId]
if not targets then
targets = {}
targetsBySignal[inputId] = targets
end
targets[#targets + 1] = target
end
end
end
end
local linkIndex = 0
local links = {}
for _, source in ipairs(parts) do
local sourceData = dataByPart[source] or getData(source)
local sourceOpcode = type(sourceData) == "table" and tonumber(sourceData[1])
if sourceData and (sourceOpcode ~= 103 or sequencerWiresEnabled) then
-- Some payloads repeat a signal id (for example a two-output block
-- with both fields set to the same id). Overlapping beams look like
-- one wire but cost two, so build each source/target pair once.
local seenOutputs = {}
local sourcePorts = portsByPart[source]
for _, outputId in ipairs(getOutputSignalIds(sourceData)) do
if not seenOutputs[outputId] then
seenOutputs[outputId] = true
local seenTargets = {}
local sourcePort = sourcePorts and sourcePorts.outputs[outputId]
for _, target in ipairs(targetsBySignal[outputId] or EMPTY_IDS) do
if target ~= source and not seenTargets[target] then
seenTargets[target] = true
linkIndex += 1
local targetPorts = portsByPart[target]
local targetPort = targetPorts and targetPorts.inputs[outputId]
local sourceAttachment = Instance.new("Attachment")
sourceAttachment.Name = "MAS_WireAttachment_Out_" .. linkIndex
sourceAttachment.Position = Vector3.zero
trackConnectorPart(source)
sourceAttachment.Parent = sourcePort or source
local targetAttachment = Instance.new("Attachment")
targetAttachment.Name = "MAS_WireAttachment_In_" .. linkIndex
targetAttachment.Position = Vector3.zero
trackConnectorPart(target)
targetAttachment.Parent = targetPort or target
local beam = Instance.new("Beam")
beam.Name = "SignalWire_" .. linkIndex
beam.Attachment0 = sourceAttachment
beam.Attachment1 = targetAttachment
beam.Width0 = settings.wireWidth
beam.Width1 = settings.wireWidth
beam.FaceCamera = true
beam.LightEmission = 1
beam.Color = ColorSequence.new(Color3.fromRGB(0, 255, 255))
beam.Parent = folder
-- Static beams still show connectivity. Skipping the
-- marker and its 25 Hz update loop is the cheap mode.
if settings.wireAnimation then
local marker = Instance.new("Part")
marker.Name = "MovingArrow_" .. linkIndex
marker.Shape = Enum.PartType.Ball
marker.Size = Vector3.new(0.3, 0.3, 0.3)
marker.Color = Color3.fromRGB(0, 255, 255)
marker.Material = Enum.Material.Neon
marker.Transparency = 0
marker.Anchored = true
marker.CanCollide = false
marker.CanQuery = false
marker.CanTouch = false
marker.Position = sourceAttachment.WorldPosition
marker.Parent = folder
local billboard = Instance.new("BillboardGui")
billboard.Size = UDim2.fromOffset(56, 56)
billboard.AlwaysOnTop = true
billboard.Adornee = marker
billboard.Parent = marker
local arrow = Instance.new("TextLabel")
arrow.Size = UDim2.fromScale(1, 1)
arrow.BackgroundTransparency = 1
arrow.Text = "➤"
arrow.TextColor3 = Color3.fromRGB(0, 255, 255)
arrow.TextStrokeColor3 = Color3.new(0, 0, 0)
arrow.TextStrokeTransparency = 0
arrow.TextScaled = true
arrow.Font = Enum.Font.Code
arrow.Parent = billboard
links[#links + 1] = {
beam = beam,
marker = marker,
arrow = arrow,
sourceAttachment = sourceAttachment,
targetAttachment = targetAttachment,
startTime = os.clock(),
}
end
end
end
end
end
end
end
if #links > 0 then
local cyan = Color3.fromRGB(0, 255, 255)
local green = Color3.fromRGB(80, 255, 120)
local cycle = 1.5
-- One shared update loop for every wire instead of two threads per link.
-- Marker positions read the attachments live, so moving a part needs no rebuild.
task.spawn(function()
local colorTick = 0
while #links > 0 do
local now = os.clock()
colorTick += 1
local updateColors = colorTick % 3 == 0
-- Compact dead links in place. Removing each one with
-- table.remove from the end was O(n^2) when a whole wire folder
-- disappeared between frames.
local writeIndex = 1
for index = 1, #links do
local link = links[index]
if link.beam.Parent and link.marker.Parent and link.arrow.Parent
and link.sourceAttachment.Parent and link.targetAttachment.Parent then
local elapsed = now - link.startTime
link.marker.Position = link.sourceAttachment.WorldPosition:Lerp(
link.targetAttachment.WorldPosition, (elapsed % cycle) / cycle)
if updateColors then
local phase = (math.sin(elapsed * math.pi / cycle - math.pi / 2) + 1) / 2
local color = cyan:Lerp(green, phase)
link.beam.Color = ColorSequence.new(color)
link.marker.Color = color
link.arrow.TextColor3 = color
end
links[writeIndex] = link
writeIndex += 1
end
end
for index = writeIndex, #links do
links[index] = nil
end
-- 25 Hz is visually identical for a slow travelling-dot effect and
-- leaves more frame time to the rest of the build.
task.wait(0.04)
end
end)
end
return linkIndex
end
-- Inputs and outputs used to sit exactly on the block centre, so every port of
-- a block rendered as one overlapping blob. Keep a tight two-row cluster in the
-- middle of the block instead: outputs on one row, inputs on the other.
local function portCFrame(part, side, index, count)
local spacing = 0.42
local lateral = (index - (count + 1) / 2) * spacing
return part.CFrame * CFrame.new(side * 0.24, 0, lateral)
end
local function createConnectors(parts, sequencerWiresEnabled, dataByPart)
local matchingInputs, targetsBySignal = findMatchingInputs(parts, dataByPart, sequencerWiresEnabled)
for _, part in ipairs(parts) do
local data = dataByPart[part] or getData(part)
if data then
local inputCount, outputCount = getPortCounts(part, data)
local isSequencer = tonumber(data[1]) == 103
if isSequencer and not sequencerWiresEnabled then
inputCount, outputCount = 0, 0
end
if inputCount > 0 or outputCount > 0 then
trackConnectorPart(part)
end
local outputSignalIds = getOutputSignalIds(data)
for index = 1, outputCount do
local output = Instance.new("Part")
local opcode = tonumber(data[1])
if opcode == 103 then
output.Name = "WireConnector_Step_" .. index
elseif opcode == 105 or opcode == 108 then
output.Name = "WireConnector_" .. (index == 1 and "True" or "False")
else
output.Name = "WireConnector_Out_" .. index
end
output.Size = Vector3.new(0.2, 0.2, 0.2)
output.Color = Color3.fromRGB(50, 200, 50)
output.Material = Enum.Material.Neon
output.Anchored = true
output.CanCollide = false
output.CanQuery = false
output.CFrame = portCFrame(part, 1, index, outputCount)
if outputSignalIds[index] ~= nil then
output:SetAttribute("SignalId", tostring(outputSignalIds[index]))
end
output.Parent = part
end
local partInputs = matchingInputs[part] or EMPTY_IDS
for index = 1, inputCount do
local match = partInputs[index]
local input = Instance.new("Part")
input.Name = "WireConnector_In_" .. index
input.Shape = Enum.PartType.Ball
input.Size = Vector3.new(0.4, 0.4, 0.4)
input.Color = Color3.fromRGB(0, 255, 255)
input.Material = Enum.Material.Neon
input.Anchored = true
input.CanCollide = false
input.CanQuery = false
input.CFrame = portCFrame(part, -1, index, inputCount)
if match then
input:SetAttribute("SignalId", match.signalId)
end
input.Parent = part
end
end
end
return createAnimatedLinks(parts, sequencerWiresEnabled, dataByPart, targetsBySignal)
end
local commandSignalIdsCache = setmetatable({}, {__mode = "k"})
local function getCommandSignalIds(data)
if type(data) ~= "table" then
return EMPTY_IDS
end
local cached = commandSignalIdsCache[data]
if cached then
return cached
end
local ids = {}
if tonumber(data[1]) ~= 101 or type(data[2]) ~= "string" then
commandSignalIdsCache[data] = ids
return ids
end
for commandText in data[2]:gmatch("[^;]+") do
local command, arguments = commandText:match("^%s*(%S+)%s+(.+)%s*$")
command = command and command:lower()
if command == "signal" then
local signalId = arguments:match("^(%d+)")
if signalId then
ids[#ids + 1] = signalId
end
elseif command == "signalas" then
local signalId = arguments:match("^%S+%s+(%d+)")
if signalId then
ids[#ids + 1] = signalId
end
end
end
commandSignalIdsCache[data] = ids
return ids
end
local graphGui
-- Kept between rebuilds so Refresh (and reopening the graph) lands on the same
-- window rect and camera instead of snapping back to the default view.
-- A normal open restores the saved layout when Remember graph layout is on;
-- otherwise it starts centered at the default size.
local graphPendingState
-- The live window parts and a forward declaration so the Refresh button can
-- rebuild from module scope (and so executors can call it directly).
local graphCurrent
local refreshLogicGraph
-- Rebuild a saved graph rect inside the current viewport. The setting stores
-- plain numbers, not UDim2 objects, because the JSON encoder cannot serialize
-- Roblox datatypes. Width/height are absolute pixels; the saved position keeps
-- its scale/offset pair, then gets clamped so a smaller viewport cannot strand
-- the window off-screen.
local function savedGraphLayout()
local saved = settings.graphLayout
if type(saved) ~= "table" then
return nil
end
local rawWidth, rawHeight = tonumber(saved.width), tonumber(saved.height)
if not rawWidth or not rawHeight or rawWidth < 1 or rawHeight < 1 then
return nil
end
local camera = workspace.CurrentCamera
local viewportSize = camera and camera.ViewportSize or Vector2.new(1280, 720)
local width = math.clamp(rawWidth, 460, math.max(460, viewportSize.X - 24))
local height = math.clamp(rawHeight, 300, math.max(300, viewportSize.Y - 24))
local xScale = clampSettingNumber(saved.positionXScale, 0, 1, 0.5)
local yScale = clampSettingNumber(saved.positionYScale, 0, 1, 0.5)
local centerX = xScale * viewportSize.X + clampSettingNumber(saved.positionXOffset, -1000000, 1000000, 0)
local centerY = yScale * viewportSize.Y + clampSettingNumber(saved.positionYOffset, -1000000, 1000000, 0)
centerX = math.clamp(centerX, width / 2, math.max(width / 2, viewportSize.X - width / 2))
centerY = math.clamp(centerY, height / 2, math.max(height / 2, viewportSize.Y - height / 2))
return {
size = UDim2.fromOffset(width, height),
position = UDim2.fromOffset(centerX, centerY),
contentPosition = UDim2.fromOffset(
clampSettingNumber(saved.contentX, -1000000, 1000000, 40),
clampSettingNumber(saved.contentY, -1000000, 1000000, 40)),
scale = clampSettingNumber(saved.scale, 0.08, 8, 1),
}
end
local function openLogicGraph()
local Players = game:GetService("Players")
local UserInputService = game:GetService("UserInputService")
local player = Players.LocalPlayer
local playerGui = player and player:FindFirstChildOfClass("PlayerGui")
if not playerGui then
return
end
if graphGui then
graphGui:Destroy()
end
local graphNodes = {}
local parts = findAllBasePartsRecursive()
for _, part in ipairs(parts) do
local data = getData(part)
if data then
-- getOutputSignalIds is cached and shared: copy before the graph adds
-- event/command ids that only it knows about.
local outputSignalIds = table.clone(getOutputSignalIds(data))
for _, signalId in ipairs(getCommandSignalIds(data)) do
outputSignalIds[#outputSignalIds + 1] = signalId
end
local opcode = tonumber(data[1])
-- Events and GUI bricks emit signals through payload fields the
-- shared extractor does not know about, so add them for the graph.
if opcode == 3 or opcode == 4 then
if data[2] ~= nil then
outputSignalIds[#outputSignalIds + 1] = tostring(data[2])
end
elseif opcode == 200 and type(data[3]) == "table" then
for _, button in ipairs(data[3]) do
if type(button) == "table" and button.sI ~= nil then
outputSignalIds[#outputSignalIds + 1] = tostring(button.sI)
end
end
end
-- A GUI brick only belongs in the graph when one of its buttons
-- actually sends a signal; plain surfaces and signs are skipped.
local includeNode = opcode ~= nil
if opcode == 200 then
includeNode = false
if type(data[3]) == "table" then
for _, button in ipairs(data[3]) do
if type(button) == "table" and button.sI ~= nil then
includeNode = true
break
end
end
end
end
-- Every decoded block becomes a node, so the type filter lists all
-- block kinds instead of only the ones that happen to be wired up.
if includeNode then
graphNodes[#graphNodes + 1] = {
part = part,
data = data,
outputSignalIds = outputSignalIds,
}
end
end
end
local targetsBySignal = {}
for index, node in ipairs(graphNodes) do
local opcode = tonumber(node.data[1])
if opcode ~= 106 and opcode ~= 107 then
local seenInputs = {}
for _, signalId in ipairs(getClassIds(node.part)) do
if not seenInputs[signalId] then
seenInputs[signalId] = true
local targets = targetsBySignal[signalId]
if not targets then
targets = {}
targetsBySignal[signalId] = targets
end
targets[#targets + 1] = index
end
end
end
end
local adjacency, edgeSet = {}, {}
for index, node in ipairs(graphNodes) do
adjacency[index] = {}
edgeSet[index] = {}
local signalIds = node.outputSignalIds
local seenSignals = {}
for _, signalId in ipairs(signalIds) do
if not seenSignals[signalId] then
seenSignals[signalId] = true
for _, targetIndex in ipairs(targetsBySignal[signalId] or EMPTY_IDS) do
if not edgeSet[index][targetIndex] then
edgeSet[index][targetIndex] = true
adjacency[index][#adjacency[index] + 1] = targetIndex
end
end
end
end
end
-- Tarjan's algorithm groups mutually connected nodes so cycles can be placed in circles.
local nextIndex, stack, onStack = 0, {}, {}
local visitIndex, lowLink, components = {}, {}, {}
local function strongConnect(nodeIndex)
nextIndex += 1
visitIndex[nodeIndex], lowLink[nodeIndex] = nextIndex, nextIndex
stack[#stack + 1] = nodeIndex
onStack[nodeIndex] = true
for _, targetIndex in ipairs(adjacency[nodeIndex]) do
if not visitIndex[targetIndex] then
strongConnect(targetIndex)
lowLink[nodeIndex] = math.min(lowLink[nodeIndex], lowLink[targetIndex])
elseif onStack[targetIndex] then
lowLink[nodeIndex] = math.min(lowLink[nodeIndex], visitIndex[targetIndex])
end
end
if lowLink[nodeIndex] == visitIndex[nodeIndex] then
local component = {}
repeat
local member = table.remove(stack)
onStack[member] = nil
component[#component + 1] = member
until member == nodeIndex
components[#components + 1] = component
end
end
for index = 1, #graphNodes do
if not visitIndex[index] then
strongConnect(index)
end
end
local componentOf, componentEdges, indegree, rank = {}, {}, {}, {}
for componentIndex, component in ipairs(components) do
componentEdges[componentIndex] = {}
indegree[componentIndex] = 0
rank[componentIndex] = 0
for _, nodeIndex in ipairs(component) do
componentOf[nodeIndex] = componentIndex
end
end
for sourceIndex, targets in ipairs(adjacency) do
local sourceComponent = componentOf[sourceIndex]
for _, targetIndex in ipairs(targets) do
local targetComponent = componentOf[targetIndex]
if sourceComponent ~= targetComponent and not componentEdges[sourceComponent][targetComponent] then
componentEdges[sourceComponent][targetComponent] = true
indegree[targetComponent] += 1
end
end
end
local queue = {}
local parentComponent, childComponents = {}, {}
for index = 1, #components do
childComponents[index] = {}
if indegree[index] == 0 then
queue[#queue + 1] = index
end
end
local queueIndex = 1
while queueIndex <= #queue do
local sourceComponent = queue[queueIndex]
queueIndex += 1
for targetComponent in pairs(componentEdges[sourceComponent]) do
rank[targetComponent] = math.max(rank[targetComponent], rank[sourceComponent] + 1)
if not parentComponent[targetComponent] then
parentComponent[targetComponent] = sourceComponent
childComponents[sourceComponent][#childComponents[sourceComponent] + 1] = targetComponent
end
indegree[targetComponent] -= 1
if indegree[targetComponent] == 0 then
queue[#queue + 1] = targetComponent
end
end
end
local positions = {}
local nodeWidth, nodeHeight = 260, 100
local componentRadius, componentHeight, componentWidth = {}, {}, {}
local depth, rowHeights = {}, {}
local branchGap, rootGap, rowGap = 110, 150, 110
local function measureComponent(componentIndex, level)
depth[componentIndex] = level
local count = #components[componentIndex]
local radius = count > 1 and math.max(135, count * 46) or 0
componentRadius[componentIndex] = radius
componentHeight[componentIndex] = count > 1 and radius * 2 + nodeHeight or nodeHeight
componentWidth[componentIndex] = count > 1 and radius * 2 + nodeWidth or nodeWidth
rowHeights[level] = math.max(rowHeights[level] or 0, componentHeight[componentIndex])
for _, childIndex in ipairs(childComponents[componentIndex]) do
measureComponent(childIndex, level + 1)
end
end
local roots = {}
for index = 1, #components do
if not parentComponent[index] then
roots[#roots + 1] = index
measureComponent(index, 0)
end
end
local subtreeWidths = {}
local function measureTree(componentIndex)
local children = childComponents[componentIndex]
local childrenWidth = 0
for _, childIndex in ipairs(children) do
childrenWidth += measureTree(childIndex) + branchGap
end
if #children > 0 then
childrenWidth -= branchGap
end
subtreeWidths[componentIndex] = math.max(componentWidth[componentIndex], childrenWidth)
return subtreeWidths[componentIndex]
end
local maxDepth, rowY = 0, {}
for _, rootIndex in ipairs(roots) do
measureTree(rootIndex)
end
for _, level in pairs(depth) do
maxDepth = math.max(maxDepth, level)
end
local graphHeight, cursorY = 300, 90
for level = 0, maxDepth do
rowY[level] = cursorY
cursorY += (rowHeights[level] or nodeHeight) + rowGap
end
graphHeight = math.max(graphHeight, cursorY + 40)
local function placeTree(componentIndex, leftX)
local span = subtreeWidths[componentIndex]
local centerX = leftX + span / 2
local centerY = rowY[depth[componentIndex]] + rowHeights[depth[componentIndex]] / 2
local component = components[componentIndex]
local radius = componentRadius[componentIndex]
for memberIndex, nodeIndex in ipairs(component) do
local angle = #component > 1 and ((memberIndex - 1) / #component) * math.pi * 2 - math.pi / 2 or 0
positions[nodeIndex] = {
x = centerX + math.cos(angle) * radius,
y = centerY + math.sin(angle) * radius,
}
end
local children = childComponents[componentIndex]
local childrenWidth = 0
for _, childIndex in ipairs(children) do
childrenWidth += subtreeWidths[childIndex] + branchGap
end
if #children > 0 then
childrenWidth -= branchGap
end
local childX = centerX - childrenWidth / 2
for _, childIndex in ipairs(children) do
placeTree(childIndex, childX)
childX += subtreeWidths[childIndex] + branchGap
end
end
local totalRootWidth = 0
for _, rootIndex in ipairs(roots) do
totalRootWidth += subtreeWidths[rootIndex] + rootGap
end
if #roots > 0 then
totalRootWidth -= rootGap
end
local graphWidth = math.max(300, totalRootWidth + 300)
local rootX = 150
for _, rootIndex in ipairs(roots) do
placeTree(rootIndex, rootX)
rootX += subtreeWidths[rootIndex] + rootGap
end
local screen = Instance.new("ScreenGui")
screen.Name = "MAS_LogicGraph"
screen.ResetOnSpawn = false
screen.DisplayOrder = 20
screen.Parent = playerGui
graphGui = screen
local background = Instance.new("Frame")
background.Name = "GraphWindow"
background.AnchorPoint = Vector2.new(0.5, 0.5)
-- A Refresh passes its live rect through graphPendingState; a normal open
-- prefers the saved rect so window size/pan/zoom survive executor sessions.
local layout = graphPendingState
graphPendingState = nil
if not layout and settings.graphRememberLayout then
layout = savedGraphLayout()
end
background.Position = (layout and layout.position) or UDim2.fromScale(0.5, 0.5)
background.Size = (layout and layout.size) or UDim2.new(0.9, 0, 0.85, 0)
background.BackgroundColor3 = Color3.fromRGB(18, 22, 32)
background.BackgroundTransparency = settings.graphBackgroundTransparency
background.BorderSizePixel = 0
background.Parent = screen
local header = Instance.new("Frame")
header.Size = UDim2.new(1, 0, 0, 44)
header.BackgroundColor3 = Color3.fromRGB(30, 36, 50)
header.Active = true
header.Parent = background
local title = Instance.new("TextLabel")
title.Size = UDim2.new(1, -426, 1, 0)
title.Position = UDim2.fromOffset(12, 0)
title.BackgroundTransparency = 1
title.TextColor3 = Color3.new(1, 1, 1)
title.TextXAlignment = Enum.TextXAlignment.Left
title.TextTruncate = Enum.TextTruncate.AtEnd
title.Font = Enum.Font.Code
title.TextSize = 18
title.Text = ("Logic graph • %d nodes • scroll to zoom, drag to pan, corner to resize"):format(#graphNodes)
title.Parent = header
local baseTitle = title.Text
-- Windows caption-style close: flat until hovered, then the red bar with
-- a white X, filling the header height.
local close = Instance.new("TextButton")
close.Size = UDim2.fromOffset(46, 44)
close.Position = UDim2.new(1, -46, 0, 0)
close.BackgroundColor3 = Color3.fromRGB(232, 17, 35)
close.BackgroundTransparency = 1
close.BorderSizePixel = 0
close.AutoButtonColor = false
close.Text = ""
close.Parent = header
-- Draw the X with two bars: the glyph is far too small at any text size.
local closeBars = {}
for _, rotation in ipairs({45, -45}) do
local bar = Instance.new("Frame")
bar.Size = UDim2.fromOffset(26, 2)
bar.AnchorPoint = Vector2.new(0.5, 0.5)
bar.Position = UDim2.fromScale(0.5, 0.5)
bar.Rotation = rotation
bar.BackgroundColor3 = Color3.fromRGB(235, 238, 245)
bar.BorderSizePixel = 0
bar.Parent = close
closeBars[#closeBars + 1] = bar
end
local function tintClose(color)
for _, bar in ipairs(closeBars) do
bar.BackgroundColor3 = color
end
end
close.MouseEnter:Connect(function()
close.BackgroundTransparency = 0
tintClose(Color3.new(1, 1, 1))
end)
close.MouseLeave:Connect(function()
close.BackgroundTransparency = 1
tintClose(Color3.fromRGB(235, 238, 245))
end)
close.Activated:Connect(function()
screen:Destroy()
end)
-- Chrome-style refresh as a matching caption button, left of Close.
local refresh = Instance.new("TextButton")
refresh.Size = UDim2.fromOffset(42, 44)
refresh.Position = UDim2.new(1, -88, 0, 0)
refresh.BackgroundColor3 = Color3.new(1, 1, 1)
refresh.BackgroundTransparency = 1
refresh.BorderSizePixel = 0
refresh.Text = ""
refresh.AutoButtonColor = false
refresh.Parent = header
local refreshIcon = Instance.new("ImageLabel")
refreshIcon.Size = UDim2.fromOffset(19, 19)
refreshIcon.Position = UDim2.fromScale(0.5, 0.5)
refreshIcon.AnchorPoint = Vector2.new(0.5, 0.5)
refreshIcon.BackgroundTransparency = 1
refreshIcon.Image = "rbxassetid://10734933222"
refreshIcon.ImageColor3 = Color3.fromRGB(225, 233, 250)
refreshIcon.Parent = refresh
refresh.MouseEnter:Connect(function()
refresh.BackgroundTransparency = 0.9
refreshIcon.ImageColor3 = Color3.new(1, 1, 1)
end)
refresh.MouseLeave:Connect(function()
refresh.BackgroundTransparency = 1
refreshIcon.ImageColor3 = Color3.fromRGB(225, 233, 250)
end)
-- Node filters: block type plus a live "contains" text filter.
local kindNames = {}
local kindCounts = {}
local graphNodeEntries = {}
local graphWireFrames = {}
local graphFiltering = false
-- Global setting and an active search filter both decide wire visibility;
-- keeping this in one place makes the Settings toggle work on an open graph.
local function updateGraphWireVisibility()
for _, wire in ipairs(graphWireFrames) do
wire.Visible = settings.graphShowWires and not graphFiltering
end
end
local selectedKinds = {}
local applyGraphFilter
local syncTypeButton
local typeMenu, typeCatcher
local function closeTypeMenu()
if typeCatcher then
typeCatcher:Destroy()
typeCatcher = nil
end
if typeMenu then
typeMenu:Destroy()
typeMenu = nil
end
end
local searchHolder = Instance.new("Frame")
searchHolder.Size = UDim2.fromOffset(190, 28)
searchHolder.Position = UDim2.new(1, -286, 0.5, -14)
searchHolder.BackgroundColor3 = Color3.fromRGB(22, 27, 38)
searchHolder.BorderSizePixel = 0
searchHolder.ZIndex = 2
searchHolder.Parent = header
local searchCorner = Instance.new("UICorner")
searchCorner.CornerRadius = UDim.new(0, 6)
searchCorner.Parent = searchHolder
local searchStroke = Instance.new("UIStroke")
searchStroke.Color = Color3.fromRGB(70, 82, 105)
searchStroke.Thickness = 1
searchStroke.Transparency = 0.1
searchStroke.Parent = searchHolder
local searchBox = Instance.new("TextBox")
searchBox.Name = "NodeSearch"
searchBox.Size = UDim2.new(1, -46, 1, 0)
searchBox.Position = UDim2.fromOffset(10, 0)
searchBox.BackgroundTransparency = 1
searchBox.Text = ""
searchBox.PlaceholderText = "Search…"
searchBox.PlaceholderColor3 = Color3.fromRGB(118, 130, 152)
searchBox.TextColor3 = Color3.fromRGB(228, 235, 248)
searchBox.TextSize = 14
searchBox.Font = Enum.Font.Gotham
searchBox.TextXAlignment = Enum.TextXAlignment.Left
searchBox.ClearTextOnFocus = false
searchBox.ZIndex = 3
searchBox.Parent = searchHolder
-- The syntax help lives behind a [?] button, so the placeholder stays short
-- and the box can never overflow into the refresh button.
local helpPopup, helpCatcher
local function closeHelp()
if helpCatcher then
helpCatcher:Destroy()
helpCatcher = nil
end
if helpPopup then
helpPopup:Destroy()
helpPopup = nil
end
end
local helpButton = Instance.new("TextButton")
helpButton.Name = "SearchHelp"
helpButton.Size = UDim2.fromOffset(18, 18)
helpButton.Position = UDim2.new(1, -22, 0.5, -9)
helpButton.BackgroundColor3 = Color3.fromRGB(46, 60, 84)
helpButton.BorderSizePixel = 0
helpButton.Text = "?"
helpButton.TextColor3 = Color3.fromRGB(200, 215, 240)
helpButton.Font = Enum.Font.GothamBold
helpButton.TextSize = 12
helpButton.AutoButtonColor = false
helpButton.ZIndex = 3
helpButton.Parent = searchHolder
local helpCorner = Instance.new("UICorner")
helpCorner.CornerRadius = UDim.new(1, 0)
helpCorner.Parent = helpButton
helpButton.MouseEnter:Connect(function()
helpButton.BackgroundColor3 = Color3.fromRGB(60, 80, 112)
end)
helpButton.MouseLeave:Connect(function()
helpButton.BackgroundColor3 = Color3.fromRGB(46, 60, 84)
end)
local function openHelp()
closeHelp()
helpCatcher = Instance.new("TextButton")
helpCatcher.Name = "SearchHelpCatcher"
helpCatcher.Size = UDim2.fromScale(1, 1)
helpCatcher.BackgroundTransparency = 1
helpCatcher.Text = ""
helpCatcher.AutoButtonColor = false
helpCatcher.ZIndex = 58
helpCatcher.Parent = screen
helpCatcher.Activated:Connect(closeHelp)
helpPopup = Instance.new("Frame")
helpPopup.Name = "SearchHelpPopup"
helpPopup.AnchorPoint = Vector2.new(1, 0)
helpPopup.Position = UDim2.new(1, -16, 0, 58)
helpPopup.Size = UDim2.fromOffset(340, 142)
helpPopup.BackgroundColor3 = Color3.fromRGB(24, 29, 41)
helpPopup.BorderSizePixel = 0
helpPopup.ZIndex = 60
helpPopup.Parent = background
local popupCorner = Instance.new("UICorner")
popupCorner.CornerRadius = UDim.new(0, 8)
popupCorner.Parent = helpPopup
local popupStroke = Instance.new("UIStroke")
popupStroke.Color = Color3.fromRGB(70, 82, 105)
popupStroke.Thickness = 1
popupStroke.Transparency = 0.15
popupStroke.Parent = helpPopup
local titleLabel = Instance.new("TextLabel")
titleLabel.Size = UDim2.new(1, -24, 0, 18)
titleLabel.Position = UDim2.fromOffset(12, 10)
titleLabel.BackgroundTransparency = 1
titleLabel.Text = "Search help"
titleLabel.TextColor3 = Color3.fromRGB(235, 240, 250)
titleLabel.Font = Enum.Font.GothamBold
titleLabel.TextSize = 13
titleLabel.TextXAlignment = Enum.TextXAlignment.Left
titleLabel.ZIndex = 61
titleLabel.Parent = helpPopup
local body = Instance.new("TextLabel")
body.Size = UDim2.new(1, -24, 1, -38)
body.Position = UDim2.fromOffset(12, 30)
body.BackgroundTransparency = 1
body.Text = table.concat({
'<font color="#68DDF5">text</font> matches a block kind and its payload.',
'<font color="#68DDF5">signal:9201,9203</font> blocks that send or receive those ids.',
'<font color="#68DDF5">signal:9201 luck</font> ids plus payload text.',
'<font color="#68DDF5">All types</font> tick several kinds; All types clears.',
}, "\n\n")
body.TextColor3 = Color3.fromRGB(198, 208, 226)
body.Font = Enum.Font.Gotham
body.TextSize = 12
body.TextXAlignment = Enum.TextXAlignment.Left
body.TextYAlignment = Enum.TextYAlignment.Top
body.TextWrapped = true
body.RichText = true
body.ZIndex = 61
body.Parent = helpPopup
end
helpButton.Activated:Connect(function()
if helpPopup then
closeHelp()
else
openHelp()
end
end)
-- Block-type filter with a small menu; "All types" clears it.
local typeButton = Instance.new("TextButton")
typeButton.Name = "TypeFilter"
typeButton.Size = UDim2.fromOffset(116, 28)
typeButton.Position = UDim2.new(1, -410, 0.5, -14)
typeButton.BackgroundColor3 = Color3.fromRGB(22, 27, 38)
typeButton.BorderSizePixel = 0
typeButton.Text = "All types"
typeButton.TextColor3 = Color3.fromRGB(200, 210, 230)
typeButton.Font = Enum.Font.Gotham
typeButton.TextSize = 14
typeButton.TextTruncate = Enum.TextTruncate.AtEnd
typeButton.AutoButtonColor = false
typeButton.ZIndex = 2
typeButton.Parent = header
local typeCorner = Instance.new("UICorner")
typeCorner.CornerRadius = UDim.new(0, 6)
typeCorner.Parent = typeButton
local typeStroke = Instance.new("UIStroke")
typeStroke.Color = Color3.fromRGB(70, 82, 105)
typeStroke.Thickness = 1
typeStroke.Transparency = 0.1
typeStroke.Parent = typeButton
syncTypeButton = function()
local selected, onlyKind = 0, nil
for kind in pairs(selectedKinds) do
selected = selected + 1
onlyKind = kind
end
if selected == 0 then
typeButton.Text = "All types"
typeButton.TextColor3 = Color3.fromRGB(200, 210, 230)
elseif selected == 1 then
typeButton.Text = #onlyKind > 14 and (onlyKind:sub(1, 13) .. "…") or onlyKind
typeButton.TextColor3 = Color3.new(1, 1, 1)
else
typeButton.Text = ("%d types"):format(selected)
typeButton.TextColor3 = Color3.new(1, 1, 1)
end
end
local function openTypeMenu()
closeTypeMenu()
local rows = #kindNames + 1
local menuHeight = math.min(rows, 10) * 30 + 8
local catcher = Instance.new("TextButton")
catcher.Name = "TypeMenuCatcher"
catcher.Size = UDim2.fromScale(1, 1)
catcher.BackgroundTransparency = 1
catcher.Text = ""
catcher.ZIndex = 38
catcher.AutoButtonColor = false
catcher.Parent = screen
catcher.Activated:Connect(closeTypeMenu)
typeCatcher = catcher
local menu = Instance.new("ScrollingFrame")
menu.Name = "TypeFilterMenu"
menu.Position = UDim2.new(1, -410, 0, 40)
menu.Size = UDim2.fromOffset(198, menuHeight)
menu.BackgroundColor3 = Color3.fromRGB(16, 20, 29)
menu.BackgroundTransparency = 0.02
menu.BorderSizePixel = 0
menu.ScrollBarThickness = 5
menu.ScrollBarImageColor3 = Color3.fromRGB(90, 105, 130)
menu.CanvasSize = UDim2.fromOffset(0, rows * 30 + 8)
menu.ZIndex = 39
menu.Parent = header
typeMenu = menu
local menuCorner = Instance.new("UICorner")
menuCorner.CornerRadius = UDim.new(0, 6)
menuCorner.Parent = menu
local menuStroke = Instance.new("UIStroke")
menuStroke.Color = Color3.fromRGB(70, 82, 105)
menuStroke.Thickness = 1
menuStroke.Transparency = 0.05
menuStroke.Parent = menu
local padding = Instance.new("UIPadding")
padding.PaddingLeft = UDim.new(0, 4)
padding.PaddingRight = UDim.new(0, 4)
padding.PaddingTop = UDim.new(0, 4)
padding.Parent = menu
local rowGroup = Instance.new("Frame")
rowGroup.Name = "TypeRows"
rowGroup.Size = UDim2.fromScale(1, 1)
rowGroup.BackgroundTransparency = 1
rowGroup.Parent = menu
local function refreshRows()
for _, child in ipairs(rowGroup:GetChildren()) do
child:Destroy()
end
local anySelected = next(selectedKinds) ~= nil
local function addRow(rowIndex, label, kind)
local ticked = kind == nil and not anySelected or (kind ~= nil and selectedKinds[kind] == true)
local baseColor = ticked and Color3.fromRGB(46, 60, 84) or Color3.fromRGB(24, 29, 40)
local row = Instance.new("TextButton")
row.Size = UDim2.new(1, -8, 0, 28)
row.Position = UDim2.fromOffset(0, (rowIndex - 1) * 30)
row.BackgroundColor3 = baseColor
row.BorderSizePixel = 0
row.Text = ""
row.AutoButtonColor = false
row.ZIndex = 40
row.Parent = rowGroup
local box = Instance.new("Frame")
box.Size = UDim2.fromOffset(14, 14)
box.Position = UDim2.fromOffset(6, 7)
box.BackgroundColor3 = ticked and Color3.fromRGB(82, 146, 255) or Color3.fromRGB(15, 19, 27)
box.BorderSizePixel = 0
box.ZIndex = 41
box.Parent = row
local boxCorner = Instance.new("UICorner")
boxCorner.CornerRadius = UDim.new(0, 3)
boxCorner.Parent = box
local boxStroke = Instance.new("UIStroke")
boxStroke.Color = ticked and Color3.fromRGB(150, 190, 255) or Color3.fromRGB(92, 106, 132)
boxStroke.Thickness = 1
boxStroke.Parent = box
if ticked then
local shortBar = Instance.new("Frame")
shortBar.Size = UDim2.fromOffset(5, 2)
shortBar.AnchorPoint = Vector2.new(0.5, 0.5)
shortBar.Position = UDim2.fromScale(0.34, 0.6)
shortBar.Rotation = 45
shortBar.BackgroundColor3 = Color3.new(1, 1, 1)
shortBar.BorderSizePixel = 0
shortBar.ZIndex = 42
shortBar.Parent = box
local longBar = Instance.new("Frame")
longBar.Size = UDim2.fromOffset(8, 2)
longBar.AnchorPoint = Vector2.new(0.5, 0.5)
longBar.Position = UDim2.fromScale(0.62, 0.46)
longBar.Rotation = -45
longBar.BackgroundColor3 = Color3.new(1, 1, 1)
longBar.BorderSizePixel = 0
longBar.ZIndex = 42
longBar.Parent = box
end
local text = Instance.new("TextLabel")
text.Size = UDim2.new(1, -30, 1, 0)
text.Position = UDim2.fromOffset(26, 0)
text.BackgroundTransparency = 1
text.Text = label
text.TextXAlignment = Enum.TextXAlignment.Left
text.TextColor3 = ticked and Color3.new(1, 1, 1) or Color3.fromRGB(215, 224, 240)
text.Font = Enum.Font.Gotham
text.TextSize = 14
text.TextTruncate = Enum.TextTruncate.AtEnd
text.ZIndex = 41
text.Parent = row
row.MouseEnter:Connect(function()
row.BackgroundColor3 = Color3.fromRGB(42, 52, 72)
end)
row.MouseLeave:Connect(function()
row.BackgroundColor3 = baseColor
end)
row.Activated:Connect(function()
if kind == nil then
selectedKinds = {}
elseif selectedKinds[kind] then
selectedKinds[kind] = nil
else
selectedKinds[kind] = true
end
syncTypeButton()
refreshRows()
if applyGraphFilter then
applyGraphFilter()
end
end)
end
addRow(1, ("All types (%d)"):format(#graphNodeEntries), nil)
for optionIndex, kind in ipairs(kindNames) do
addRow(optionIndex + 1, ("%s (%d)"):format(kind, kindCounts[kind] or 0), kind)
end
end
refreshRows()
end
typeButton.Activated:Connect(function()
if typeMenu then
closeTypeMenu()
else
openTypeMenu()
end
end)
if type(masInterpreter) == "table" then
masInterpreter.openGraphFilters = openTypeMenu
end
typeButton.MouseEnter:Connect(function()
typeButton.BackgroundColor3 = Color3.fromRGB(34, 41, 56)
end)
typeButton.MouseLeave:Connect(function()
typeButton.BackgroundColor3 = Color3.fromRGB(22, 27, 38)
end)
local viewport = Instance.new("Frame")
viewport.Position = UDim2.fromOffset(0, 44)
viewport.Size = UDim2.new(1, 0, 1, -44)
viewport.BackgroundColor3 = Color3.fromRGB(18, 22, 32)
local canvasTint = Instance.new("UIGradient")
canvasTint.Rotation = 90
canvasTint.Color = ColorSequence.new(Color3.fromRGB(27, 33, 47), Color3.fromRGB(12, 15, 22))
canvasTint.Parent = viewport
viewport.ClipsDescendants = true
viewport.Active = true
viewport.Parent = background
local resizeGrip = Instance.new("TextButton")
resizeGrip.Name = "ResizeGrip"
resizeGrip.Size = UDim2.fromOffset(26, 26)
resizeGrip.AnchorPoint = Vector2.new(1, 1)
resizeGrip.Position = UDim2.new(1, -2, 1, -2)
resizeGrip.BackgroundColor3 = Color3.fromRGB(70, 85, 115)
resizeGrip.BackgroundTransparency = 0.15
resizeGrip.Text = "◢"
resizeGrip.TextColor3 = Color3.new(1, 1, 1)
resizeGrip.TextSize = 18
resizeGrip.Font = Enum.Font.Code
resizeGrip.ZIndex = 30
resizeGrip.Parent = background
local gripStroke = Instance.new("UIStroke")
gripStroke.Color = Color3.fromRGB(225, 235, 255)
gripStroke.Transparency = 0.55
gripStroke.Thickness = 1
gripStroke.Parent = resizeGrip
resizeGrip.MouseEnter:Connect(function()
resizeGrip.BackgroundColor3 = Color3.fromRGB(95, 115, 155)
end)
resizeGrip.MouseLeave:Connect(function()
resizeGrip.BackgroundColor3 = Color3.fromRGB(70, 85, 115)
end)
local content = Instance.new("Frame")
content.Name = "GraphContent"
content.Size = UDim2.fromOffset(graphWidth, graphHeight)
content.Position = (layout and layout.contentPosition) or UDim2.fromOffset(40, 40)
content.BackgroundTransparency = 1
content.Parent = viewport
local scale = Instance.new("UIScale")
scale.Scale = (layout and layout.scale) or 1
scale.Parent = content
graphCurrent = {
background = background,
content = content,
scale = scale,
updateWireVisibility = updateGraphWireVisibility,
}
-- Constellation backdrop: a few drifting dots linked to close neighbours,
-- drawn behind the canvas so the graph is not a flat dark rectangle.
local constellation = Instance.new("Frame")
constellation.Name = "Constellation"
constellation.Size = UDim2.fromScale(1, 1)
constellation.BackgroundTransparency = 1
-- Global ZIndexBehaviour: 0 would sit under the opaque window background.
constellation.ZIndex = 1
constellation.Parent = viewport
local GRID_COLUMNS = 10
local GRID_ROWS = 4
local DOT_COUNT = GRID_COLUMNS * GRID_ROWS
local MAX_LINKS = 40
local constellationDots = {}
local constellationLines = {}
local constellationRandom = Random.new()
for index = 1, DOT_COUNT do
local dot = Instance.new("Frame")
local dotSize = index % 6 == 0 and 4 or 3
dot.Size = UDim2.fromOffset(dotSize, dotSize)
dot.AnchorPoint = Vector2.new(0.5, 0.5)
dot.BackgroundColor3 = Color3.fromRGB(150, 172, 205)
dot.BackgroundTransparency = 0.3 + constellationRandom:NextNumber() * 0.3
dot.BorderSizePixel = 0
dot.ZIndex = 1
dot.Parent = constellation
local angle = constellationRandom:NextNumber(0, math.pi * 2)
local speed = 0.0016 + constellationRandom:NextNumber() * 0.0026
local column = (index - 1) % GRID_COLUMNS
local row = math.floor((index - 1) / GRID_COLUMNS)
constellationDots[index] = {
frame = dot,
x = (column + 0.15 + constellationRandom:NextNumber() * 0.7) / GRID_COLUMNS,
y = (row + 0.15 + constellationRandom:NextNumber() * 0.7) / GRID_ROWS,
vx = math.cos(angle) * speed,
vy = math.sin(angle) * speed,
}
end
local function constellationLine(index)
local line = constellationLines[index]
if not line then
line = Instance.new("Frame")
line.AnchorPoint = Vector2.new(0, 0.5)
line.BorderSizePixel = 0
line.BackgroundColor3 = Color3.fromRGB(140, 165, 205)
line.ZIndex = 1
line.Parent = constellation
constellationLines[index] = line
end
return line
end
local constellationClock = 0
local constellationConnection = game:GetService("RunService").Heartbeat:Connect(function()
local now = os.clock()
if not settings.graphAnimateBackground then
constellationClock = now
return
end
local step = now - constellationClock
if step < 0.05 then
return
end
constellationClock = now
local size = viewport.AbsoluteSize
if size.X < 2 or size.Y < 2 then
return
end
step = math.min(step, 0.25)
local aspect = size.X / size.Y
for _, dot in ipairs(constellationDots) do
dot.x = dot.x + dot.vx * step
dot.y = dot.y + dot.vy * step
if dot.x < 0 then
dot.x, dot.vx = 0, -dot.vx
elseif dot.x > 1 then
dot.x, dot.vx = 1, -dot.vx
end
if dot.y < 0 then
dot.y, dot.vy = 0, -dot.vy
elseif dot.y > 1 then
dot.y, dot.vy = 1, -dot.vy
end
dot.frame.Position = UDim2.fromScale(dot.x, dot.y)
end
local used = 0
local linked = {}
for first = 1, DOT_COUNT do
local a = constellationDots[first]
local nearest, nearestDistance = nil, math.huge
for other = 1, DOT_COUNT do
if other ~= first then
local b = constellationDots[other]
local dx = (a.x - b.x) * aspect
local dy = a.y - b.y
local distance = math.sqrt(dx * dx + dy * dy)
if distance < nearestDistance then
nearest, nearestDistance = other, distance
end
end
end
local candidates = {
{ index = nearest, distance = nearestDistance },
}
for _, candidate in ipairs(candidates) do
local second = candidate.index
if second and second > first and used < MAX_LINKS then
local key = first * 1000 + second
if not linked[key] then
linked[key] = true
used = used + 1
local b = constellationDots[second]
local x1, y1 = a.x * size.X, a.y * size.Y
local x2, y2 = b.x * size.X, b.y * size.Y
local length = math.sqrt((x2 - x1) ^ 2 + (y2 - y1) ^ 2)
local line = constellationLine(used)
line.Visible = length >= 1
line.Position = UDim2.fromOffset(x1, y1)
line.Size = UDim2.fromOffset(math.max(length, 1), 1)
line.Rotation = math.deg(math.atan2(y2 - y1, x2 - x1))
line.BackgroundTransparency = 0.7 + 0.18 * math.min(candidate.distance, 1)
end
end
end
end
for index = used + 1, #constellationLines do
constellationLines[index].Visible = false
end
end)
-- Rebuild from the current workspace state without losing the window rect
-- or the current pan/zoom, since a build keeps changing while it is open.
refresh.Activated:Connect(function()
refreshLogicGraph()
end)
local function addSegment(x1, y1, x2, y2, thickness)
local dx, dy = x2 - x1, y2 - y1
local length = math.sqrt(dx * dx + dy * dy)
if length < 1 then
return
end
local line = Instance.new("Frame")
line.BorderSizePixel = 0
line.BackgroundColor3 = Color3.fromRGB(65, 205, 220)
line.AnchorPoint = Vector2.new(0.5, 0.5)
line.Position = UDim2.fromOffset((x1 + x2) / 2, (y1 + y2) / 2)
line.Size = UDim2.fromOffset(length, thickness or 3)
line.Rotation = math.deg(math.atan2(dy, dx))
line.Visible = settings.graphShowWires
line.Parent = content
graphWireFrames[#graphWireFrames + 1] = line
end
for sourceIndex, targets in ipairs(adjacency) do
local sourcePosition = positions[sourceIndex]
for _, targetIndex in ipairs(targets) do
local targetPosition = positions[targetIndex]
if sourceIndex == targetIndex then
local radius = 48
local previousX, previousY
for step = 0, 12 do
local angle = (step / 12) * math.pi * 2
local x = sourcePosition.x + math.cos(angle) * radius
local y = sourcePosition.y - 42 + math.sin(angle) * radius
if previousX then
addSegment(previousX, previousY, x, y, 3)
end
previousX, previousY = x, y
end
else
local dx = targetPosition.x - sourcePosition.x
local dy = targetPosition.y - sourcePosition.y
local length = math.sqrt(dx * dx + dy * dy)
if length > 0 then
local ux, uy = dx / length, dy / length
local startX = sourcePosition.x + ux * (nodeWidth / 2)
local startY = sourcePosition.y + uy * (nodeHeight / 2)
local endX = targetPosition.x - ux * (nodeWidth / 2)
local endY = targetPosition.y - uy * (nodeHeight / 2)
addSegment(startX, startY, endX, endY, 3)
local arrowLength, arrowWidth = 13, 7
addSegment(endX, endY, endX - ux * arrowLength - uy * arrowWidth,
endY - uy * arrowLength + ux * arrowWidth, 3)
addSegment(endX, endY, endX - ux * arrowLength + uy * arrowWidth,
endY - uy * arrowLength - ux * arrowWidth, 3)
end
end
end
end
-- One shared card for the (i) buttons: it lists the signals a node listens
-- to and the signals it sends, without cluttering every node.
local signalCard = Instance.new("Frame")
signalCard.Name = "SignalCard"
signalCard.Size = UDim2.fromOffset(210, 64)
signalCard.BackgroundColor3 = Color3.fromRGB(16, 21, 31)
signalCard.BackgroundTransparency = 0.02
signalCard.BorderSizePixel = 0
signalCard.Visible = false
signalCard.ZIndex = 45
-- Parented to the screen, not the canvas: the card must not shrink with the
-- graph zoom, and it never gets clipped by the viewport.
signalCard.Parent = screen
local cardCorner = Instance.new("UICorner")
cardCorner.CornerRadius = UDim.new(0, 6)
cardCorner.Parent = signalCard
local cardStroke = Instance.new("UIStroke")
cardStroke.Color = Color3.fromRGB(65, 205, 220)
cardStroke.Thickness = 1
cardStroke.Transparency = 0.35
cardStroke.Parent = signalCard
local cardTitle = Instance.new("TextLabel")
cardTitle.Size = UDim2.new(1, -20, 0, 18)
cardTitle.Position = UDim2.fromOffset(10, 6)
cardTitle.BackgroundTransparency = 1
cardTitle.Font = Enum.Font.Code
cardTitle.TextSize = 13
cardTitle.TextColor3 = Color3.fromRGB(120, 225, 240)
cardTitle.TextXAlignment = Enum.TextXAlignment.Left
-- Child ZIndex must sit above the card frame (45), otherwise the labels
-- render behind their own background and the card looks empty.
cardTitle.ZIndex = 46
cardTitle.Parent = signalCard
local cardBody = Instance.new("TextLabel")
cardBody.Position = UDim2.fromOffset(10, 24)
cardBody.BackgroundTransparency = 1
cardBody.Font = Enum.Font.Code
cardBody.TextSize = 11
cardBody.TextColor3 = Color3.fromRGB(190, 214, 230)
cardBody.TextXAlignment = Enum.TextXAlignment.Left
cardBody.TextYAlignment = Enum.TextYAlignment.Top
cardBody.TextWrapped = true
cardBody.ZIndex = 46
cardBody.Parent = signalCard
local function showSignalCard(node, frame)
local inputs = {}
for _, id in ipairs(getClassIds(node.part)) do
inputs[#inputs + 1] = tostring(id)
end
local outputs = {}
for _, id in ipairs(node.outputSignalIds) do
outputs[#outputs + 1] = tostring(id)
end
local inText = #inputs > 0 and table.concat(inputs, ", ") or "none"
local outText = #outputs > 0 and table.concat(outputs, ", ") or "none"
cardTitle.Text = node.part.Name
cardBody.Text = "In " .. inText .. "\nOut " .. outText
local lineCount = math.ceil(#inText / 30) + math.ceil(#outText / 30)
local cardHeight = 34 + math.max(2, lineCount) * 14
signalCard.Size = UDim2.fromOffset(210, cardHeight)
cardBody.Size = UDim2.new(1, -20, 0, cardHeight - 30)
local bounds = background.AbsolutePosition
local limitX = bounds.X + background.AbsoluteSize.X - 218
local limitY = bounds.Y + background.AbsoluteSize.Y - cardHeight - 8
local left = frame.AbsolutePosition.X + frame.AbsoluteSize.X + 8
local top = frame.AbsolutePosition.Y
if left > limitX then
left = frame.AbsolutePosition.X - 218
end
-- The graph can be queried before its first layout pass, when the
-- window still reports a zero size; keep the clamp range valid.
left = math.clamp(left, bounds.X + 8, math.max(bounds.X + 8, limitX))
top = math.clamp(top, bounds.Y + 50, math.max(bounds.Y + 50, limitY))
signalCard.Position = UDim2.fromOffset(left, top)
signalCard.Visible = true
end
local function teleportToNode(node)
local character = player.Character
local root = character and character:FindFirstChild("HumanoidRootPart")
if not root or not node.part then
return
end
root.CFrame = node.part.CFrame * CFrame.new(0, 3, 5)
end
local signalCardNode
-- Only a click on the empty canvas closes the card; node clicks leave it
-- alone so the (i) button can toggle it without a race.
content.InputBegan:Connect(function(input)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
signalCard.Visible = false
end
end)
for index, node in ipairs(graphNodes) do
local nodeFrame = Instance.new("Frame")
nodeFrame.AnchorPoint = Vector2.new(0.5, 0.5)
nodeFrame.Position = UDim2.fromOffset(positions[index].x, positions[index].y)
nodeFrame.Size = UDim2.fromOffset(nodeWidth, nodeHeight)
nodeFrame.BackgroundColor3 = COLORS[tonumber(node.data[1])] or Color3.fromRGB(55, 65, 85)
nodeFrame.BackgroundTransparency = 0.04
nodeFrame.BorderSizePixel = 0
nodeFrame.ZIndex = 2
nodeFrame.Parent = content
local outline = Instance.new("UIStroke")
outline.Color = Color3.fromRGB(225, 235, 255)
outline.Transparency = 0.15
outline.Thickness = 2
outline.Parent = nodeFrame
local opcode = tonumber(node.data[1])
local nameLabel = Instance.new("TextLabel")
nameLabel.Size = UDim2.new(1, -10, 0, 24)
nameLabel.Position = UDim2.fromOffset(5, 2)
nameLabel.BackgroundTransparency = 1
nameLabel.TextColor3 = Color3.new(1, 1, 1)
nameLabel.TextTransparency = 0
nameLabel.TextTruncate = Enum.TextTruncate.AtEnd
nameLabel.TextStrokeColor3 = Color3.new(0, 0, 0)
nameLabel.TextStrokeTransparency = 0
nameLabel.Font = Enum.Font.Code
nameLabel.TextSize = 18
nameLabel.Text = opcode == 101 and "CommandExecutor" or node.part.Name
-- The node frame is ZIndex 2, so a default-ZIndex label would render
-- behind the frame's background and appear as a faint ghost.
nameLabel.ZIndex = 3
nameLabel.Parent = nodeFrame
-- Quick actions in the top-right corner: (i) lists the node signal ids
-- and TP drops the character next to the block in the world.
local function makeNodeButton(text, offsetX, textSize)
local button = Instance.new("TextButton")
button.Size = UDim2.fromOffset(16, 16)
button.Position = UDim2.new(1, offsetX, 0, 5)
button.BackgroundColor3 = Color3.fromRGB(26, 33, 46)
button.BackgroundTransparency = 0.15
button.BorderSizePixel = 0
button.Text = text
button.TextColor3 = Color3.fromRGB(206, 220, 240)
button.Font = Enum.Font.GothamBold
button.TextSize = textSize
button.AutoButtonColor = false
button.ZIndex = 4
button.Parent = nodeFrame
local corner = Instance.new("UICorner")
corner.CornerRadius = UDim.new(0, 4)
corner.Parent = button
local stroke = Instance.new("UIStroke")
stroke.Color = Color3.fromRGB(120, 150, 190)
stroke.Thickness = 1
stroke.Transparency = 0.5
stroke.Parent = button
button.MouseEnter:Connect(function()
button.BackgroundColor3 = Color3.fromRGB(48, 62, 88)
end)
button.MouseLeave:Connect(function()
button.BackgroundColor3 = Color3.fromRGB(26, 33, 46)
end)
return button
end
local infoButton = makeNodeButton("i", -40, 11)
infoButton.Name = "NodeInfo"
infoButton.Activated:Connect(function()
if signalCard.Visible and signalCardNode == nodeFrame then
signalCard.Visible = false
else
signalCardNode = nodeFrame
showSignalCard(node, nodeFrame)
end
end)
local teleportButton = makeNodeButton("TP", -21, 8)
teleportButton.Name = "NodeTeleport"
teleportButton.Activated:Connect(function()
teleportToNode(node)
end)
-- Any block that feeds at least one signal gets a details button, not
-- just prompts and sequencers.
local hasOutput = type(node.outputSignalIds) == "table" and #node.outputSignalIds > 0
local hasDropdown = opcode == 7 or opcode == 103 or hasOutput
local compactToggle = hasDropdown and opcode ~= 7 and opcode ~= 103
-- Every block type gets its own dark "code" box so the payload reads
-- consistently instead of only command/logic nodes having one.
local detailBackground = Instance.new("Frame")
detailBackground.Name = opcode == 101 and "CommandCodeBackground" or "LogicDetailBackground"
detailBackground.Position = UDim2.fromOffset(5, 25)
detailBackground.Size = UDim2.new(1, -10, 1, -30)
detailBackground.BackgroundColor3 = Color3.fromRGB(5, 13, 11)
detailBackground.BackgroundTransparency = 0.02
detailBackground.BorderSizePixel = 0
detailBackground.ZIndex = 2
detailBackground.Parent = nodeFrame
local detail = Instance.new("TextLabel")
detail.Size = UDim2.new(1, -10, 1, -32)
detail.Position = UDim2.fromOffset(5, 28)
detail.BackgroundTransparency = 1
detail.ZIndex = 3
detail.TextColor3 = Color3.new(1, 1, 1)
detail.TextWrapped = true
detail.TextTruncate = Enum.TextTruncate.AtEnd
detail.TextStrokeColor3 = Color3.new(0, 0, 0)
detail.TextStrokeTransparency = 0
detail.Font = Enum.Font.Code
detail.TextSize = 13
detail.RichText = true
local detailText, detailLineCount = formatGraphDetail(node.data)
detail.Text = detailText
if opcode == 101 then
-- Commands read as code: start at the left margin so wrapped lines
-- stack under each other instead of being centred line by line.
detail.Position = UDim2.fromOffset(10, 28)
detail.Size = UDim2.new(1, -20, 1, -34)
detail.TextXAlignment = Enum.TextXAlignment.Left
end
detail.Parent = nodeFrame
-- Long commands get a chevron that grows the node to show every line.
local expandButton
if opcode == 101 and (detailLineCount or 0) > 5 then
expandButton = makeNodeButton("▼", -59, 10)
expandButton.Name = "NodeExpand"
local expanded = false
expandButton.Activated:Connect(function()
expanded = not expanded
local height = 100
if expanded then
height = math.clamp(36 + (detailLineCount or 1) * 16, 100, 520)
end
nodeFrame.Size = UDim2.fromOffset(nodeWidth, height)
nodeFrame.ZIndex = expanded and 40 or 2
detailBackground.Size = UDim2.new(1, -10, 1, -30)
detail.Size = UDim2.new(1, -20, 1, -34)
detail.TextTruncate = expanded and Enum.TextTruncate.None
or Enum.TextTruncate.AtEnd
expandButton.Text = expanded and "▲" or "▼"
end)
end
if hasDropdown then
local toggle = Instance.new("TextButton")
toggle.Name = "DetailsDropdown"
if compactToggle then
-- Blocks that already print their payload keep it visible; the
-- button shrinks to a corner chevron that opens the full list.
detail.Size = UDim2.new(1, -46, 1, -32)
detail.Position = UDim2.fromOffset(23, 28)
toggle.Size = UDim2.fromOffset(18, 18)
toggle.AnchorPoint = Vector2.new(1, 1)
toggle.Position = UDim2.new(1, -5, 1, -5)
toggle.TextSize = 12
toggle.Text = "▼"
else
detail.Visible = false
toggle.Size = UDim2.new(1, -10, 0, 28)
toggle.Position = UDim2.fromOffset(5, 58)
toggle.TextSize = 14
toggle.Text = "Show details ▼"
end
toggle.BackgroundColor3 = Color3.fromRGB(20, 24, 34)
toggle.BackgroundTransparency = compactToggle and 0.1 or 0
toggle.BorderSizePixel = 0
toggle.TextColor3 = Color3.fromRGB(225, 235, 255)
toggle.Font = Enum.Font.Code
toggle.ZIndex = 4
toggle.Parent = nodeFrame
local items = {}
if opcode == 103 then
local steps = type(node.data[2]) == "table" and node.data[2] or {}
for stepIndex, step in ipairs(steps) do
if type(step) == "table" then
items[#items + 1] = ("Step %d • %ss → signal %s")
:format(stepIndex, tostring(step[1] or 0), tostring(step[2] or 0))
else
items[#items + 1] = ("Step %d • %s"):format(stepIndex, tostring(step))
end
end
if #items == 0 then
items[1] = "No sequence steps"
end
elseif opcode == 7 then
local labels = {"Prompt class", "Fire signal", "Action text", "Object text",
"Max distance", "Hold duration", "Cooldown", "Key"}
for fieldIndex, label in ipairs(labels) do
items[#items + 1] = label .. ": " .. tostring(node.data[fieldIndex + 1] or "—")
end
elseif opcode == 200 then
local buttons = type(node.data[3]) == "table" and node.data[3] or {}
for buttonIndex, button in ipairs(buttons) do
if type(button) == "table" then
local label = tostring(button.t or ("Button " .. buttonIndex)):gsub("[\r\n]+", " ")
items[#items + 1] = ("Button %d • %s"):format(buttonIndex, label)
items[#items + 1] = ("Signal • %s"):format(button.sI ~= nil and tostring(button.sI) or "none")
end
end
if #items == 0 then
items[1] = "No GUI buttons"
end
items[#items + 1] = ("Outputs: %d"):format(#node.outputSignalIds)
else
-- Generic blocks: show the payload fields plus how many signals
-- this block emits, so the button is informative on its own.
if opcode == 101 and type(node.data[2]) == "string" then
local commandIndex = 0
for segment in node.data[2]:gmatch("[^;/]+") do
local command = segment:gsub("^%s+", ""):gsub("%s+$", "")
if command ~= "" then
commandIndex = commandIndex + 1
items[#items + 1] = ("Command %d • %s"):format(commandIndex, command)
end
end
if #items == 0 then
items[1] = "No commands"
end
else
local parsed = tostring(parse(node.data))
local _, rest = parsed:match("^(.-):%s*(.*)$")
for chunk in tostring(rest or parsed):gmatch("%S+") do
local key, value = chunk:match("^(.-)=(.*)$")
if key then
items[#items + 1] = key .. ": " .. value
else
items[#items + 1] = "Value: " .. chunk
end
end
end
items[#items + 1] = ("Outputs: %d"):format(#node.outputSignalIds)
end
local dropdown = Instance.new("ScrollingFrame")
dropdown.Name = "DetailsList"
dropdown.Position = UDim2.fromOffset(positions[index].x - nodeWidth / 2, positions[index].y + 50)
dropdown.Size = UDim2.fromOffset(nodeWidth, 132)
dropdown.BackgroundColor3 = Color3.fromRGB(12, 14, 20)
dropdown.BackgroundTransparency = 0.02
dropdown.BorderSizePixel = 1
dropdown.BorderColor3 = Color3.fromRGB(85, 100, 125)
dropdown.ScrollBarThickness = 6
dropdown.CanvasSize = UDim2.fromOffset(0, #items * 25 + 8)
dropdown.Visible = false
dropdown.ZIndex = 20
dropdown.Parent = content
for itemIndex, itemText in ipairs(items) do
local item = Instance.new("TextLabel")
item.Size = UDim2.new(1, -12, 0, 24)
item.Position = UDim2.fromOffset(6, (itemIndex - 1) * 25 + 4)
item.BackgroundColor3 = Color3.fromRGB(22, 26, 36)
item.BackgroundTransparency = 0.12
item.TextColor3 = Color3.fromRGB(225, 232, 245)
item.TextXAlignment = Enum.TextXAlignment.Left
item.TextTruncate = Enum.TextTruncate.AtEnd
item.Font = Enum.Font.Code
item.TextSize = 13
item.RichText = true
item.Text = highlightDetailLine(itemText)
item.ZIndex = 21
item.Parent = dropdown
end
toggle.Activated:Connect(function()
dropdown.Visible = not dropdown.Visible
if compactToggle then
toggle.Text = dropdown.Visible and "▲" or "▼"
else
toggle.Text = dropdown.Visible and "Hide details ▲" or "Show details ▼"
end
end)
end
-- Search runs on plain text: detail.Text is rich text, so a query like
-- ";r" would otherwise never match a command broken up by <font> tags.
-- Signals on either side of the block: what it emits and the ClassIds
-- it listens to. "signal:..." in the search box matches this set.
local signals = {}
for _, id in ipairs(node.outputSignalIds) do
signals[tostring(id)] = true
end
for _, id in ipairs(getClassIds(node.part)) do
signals[tostring(id)] = true
end
graphNodeEntries[#graphNodeEntries + 1] = {
frame = nodeFrame,
kind = nameLabel.Text,
text = (nameLabel.Text .. " " .. tostring(parse(node.data))):lower(),
signals = signals,
}
end
local seenKind = {}
for _, entry in ipairs(graphNodeEntries) do
kindCounts[entry.kind] = (kindCounts[entry.kind] or 0) + 1
if not seenKind[entry.kind] then
seenKind[entry.kind] = true
kindNames[#kindNames + 1] = entry.kind
end
end
table.sort(kindNames)
applyGraphFilter = function()
local query = searchBox.Text:lower():gsub("^%s+", ""):gsub("%s+$", "")
-- Optional "signal:a,b,c" prefix: keep only nodes that emit or listen to
-- one of those signal ids, then match the rest as plain text.
local signalIds = nil
local textQuery = query
local prefix, idList, rest = query:match("^(signal%s*:%s*)([%d%s,;]+)(.*)$")
if prefix and idList:match("%d") then
signalIds = {}
for id in idList:gmatch("%d+") do
signalIds[id] = true
end
textQuery = rest:gsub("^%s+", "")
end
local filterCount = 0
for _ in pairs(selectedKinds) do
filterCount = filterCount + 1
end
local matches = 0
for _, entry in ipairs(graphNodeEntries) do
local kindOk = filterCount == 0 or selectedKinds[entry.kind] == true
local signalOk = true
if signalIds then
signalOk = false
for id in pairs(signalIds) do
if entry.signals[id] then
signalOk = true
break
end
end
end
local textOk = textQuery == "" or string.find(entry.text, textQuery, 1, true) ~= nil
local visible = kindOk and signalOk and textOk
entry.frame.Visible = visible
if visible then
matches = matches + 1
end
end
graphFiltering = filterCount > 0 or query ~= ""
updateGraphWireVisibility()
title.Text = graphFiltering
and ("Logic graph • %d/%d shown"):format(matches, #graphNodeEntries)
or baseTitle
end
searchBox:GetPropertyChangedSignal("Text"):Connect(applyGraphFilter)
searchBox.FocusLost:Connect(applyGraphFilter)
if type(masInterpreter) == "table" then
masInterpreter.setGraphFilter = function(kind, text)
selectedKinds = {}
if type(kind) == "table" then
for _, value in ipairs(kind) do
if type(value) == "string" then
selectedKinds[value] = true
end
end
elseif type(kind) == "string" then
selectedKinds[kind] = true
end
syncTypeButton()
searchBox.Text = text or ""
applyGraphFilter()
end
masInterpreter.openSearchHelp = openHelp
-- Testing hook: open the signal card for a node index (1-based).
masInterpreter.showNodeSignals = function(index)
local node = graphNodes[index or 1]
local entry = graphNodeEntries[index or 1]
if node and entry then
signalCardNode = entry.frame
showSignalCard(node, entry.frame)
end
end
end
local dragging, dragStart, contentStart = false, nil, nil
local movingWindow, resizingWindow = false, false
local windowDragStart, windowStartCenter, resizeStart, resizeStartSize
header.InputBegan:Connect(function(input)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
local mouse = input.Position
local closeTopLeft, closeSize = close.AbsolutePosition, close.AbsoluteSize
local onClose = mouse.X >= closeTopLeft.X and mouse.X <= closeTopLeft.X + closeSize.X
and mouse.Y >= closeTopLeft.Y and mouse.Y <= closeTopLeft.Y + closeSize.Y
local refreshTopLeft, refreshSize = refresh.AbsolutePosition, refresh.AbsoluteSize
local onRefresh = mouse.X >= refreshTopLeft.X and mouse.X <= refreshTopLeft.X + refreshSize.X
and mouse.Y >= refreshTopLeft.Y and mouse.Y <= refreshTopLeft.Y + refreshSize.Y
local searchTopLeft, searchSize = searchHolder.AbsolutePosition, searchHolder.AbsoluteSize
local onSearch = mouse.X >= searchTopLeft.X and mouse.X <= searchTopLeft.X + searchSize.X
and mouse.Y >= searchTopLeft.Y and mouse.Y <= searchTopLeft.Y + searchSize.Y
local typeTopLeft, typeSize = typeButton.AbsolutePosition, typeButton.AbsoluteSize
local onType = mouse.X >= typeTopLeft.X and mouse.X <= typeTopLeft.X + typeSize.X
and mouse.Y >= typeTopLeft.Y and mouse.Y <= typeTopLeft.Y + typeSize.Y
if not onClose and not onRefresh and not onSearch and not onType then
movingWindow = true
windowDragStart = input.Position
windowStartCenter = background.AbsolutePosition + background.AbsoluteSize / 2
end
end
end)
resizeGrip.InputBegan:Connect(function(input)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
resizingWindow = true
resizeStart = input.Position
resizeStartSize = background.AbsoluteSize
end
end)
local inputBeganConnection = UserInputService.InputBegan:Connect(function(input)
if input.UserInputType == Enum.UserInputType.MouseButton1
and not movingWindow and not resizingWindow then
local mouse = UserInputService:GetMouseLocation()
local topLeft, size = viewport.AbsolutePosition, viewport.AbsoluteSize
if mouse.X >= topLeft.X and mouse.X <= topLeft.X + size.X
and mouse.Y >= topLeft.Y and mouse.Y <= topLeft.Y + size.Y then
dragging = true
dragStart = input.Position
contentStart = content.Position
end
end
end)
local inputChangedConnection = UserInputService.InputChanged:Connect(function(input)
if input.UserInputType == Enum.UserInputType.MouseMovement and movingWindow then
local delta = input.Position - windowDragStart
local camera = workspace.CurrentCamera
local viewportSize = camera and camera.ViewportSize or Vector2.new(1200, 800)
local size = background.AbsoluteSize
local targetX = math.clamp(windowStartCenter.X + delta.X, size.X / 2,
math.max(size.X / 2, viewportSize.X - size.X / 2))
local targetY = math.clamp(windowStartCenter.Y + delta.Y, size.Y / 2,
math.max(size.Y / 2, viewportSize.Y - size.Y / 2))
local currentCenter = background.AbsolutePosition + size / 2
background.Position = background.Position
+ UDim2.fromOffset(targetX - currentCenter.X, targetY - currentCenter.Y)
elseif input.UserInputType == Enum.UserInputType.MouseMovement and resizingWindow then
local delta = input.Position - resizeStart
local camera = workspace.CurrentCamera
local viewportSize = camera and camera.ViewportSize or Vector2.new(1200, 800)
local width = math.clamp(resizeStartSize.X + delta.X, 460, math.max(460, viewportSize.X - 24))
local height = math.clamp(resizeStartSize.Y + delta.Y, 300, math.max(300, viewportSize.Y - 24))
-- Keep the window's top-left corner anchored while the bottom-right
-- grip moves. Measuring before/after avoids the ScreenGui inset offset.
local before = background.AbsolutePosition
background.Size = UDim2.fromOffset(width, height)
local after = background.AbsolutePosition
background.Position = background.Position + UDim2.fromOffset(before.X - after.X, before.Y - after.Y)
elseif dragging and input.UserInputType == Enum.UserInputType.MouseMovement then
local delta = input.Position - dragStart
content.Position = UDim2.fromOffset(contentStart.X.Offset + delta.X, contentStart.Y.Offset + delta.Y)
elseif input.UserInputType == Enum.UserInputType.MouseWheel then
local mouse = UserInputService:GetMouseLocation()
local topLeft, size = viewport.AbsolutePosition, viewport.AbsoluteSize
if mouse.X >= topLeft.X and mouse.X <= topLeft.X + size.X
and mouse.Y >= topLeft.Y and mouse.Y <= topLeft.Y + size.Y then
local oldScale = scale.Scale
local newScale = math.clamp(oldScale * (input.Position.Z > 0 and 1.15 or 1 / 1.15), 0.08, 8)
local cursorX, cursorY = mouse.X - topLeft.X, mouse.Y - topLeft.Y
local offsetX, offsetY = content.Position.X.Offset, content.Position.Y.Offset
content.Position = UDim2.fromOffset(cursorX - (cursorX - offsetX) * newScale / oldScale,
cursorY - (cursorY - offsetY) * newScale / oldScale)
scale.Scale = newScale
end
end
end)
local inputEndedConnection = UserInputService.InputEnded:Connect(function(input)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
dragging = false
movingWindow = false
resizingWindow = false
end
end)
screen.Destroying:Connect(function()
inputBeganConnection:Disconnect()
inputChangedConnection:Disconnect()
inputEndedConnection:Disconnect()
constellationConnection:Disconnect()
-- A Refresh already carries its live rect in graphPendingState; skip the
-- write in that path so refresh does not hammer the settings file.
if settings.graphRememberLayout and not graphPendingState then
local size = background.AbsoluteSize
if size.X >= 1 and size.Y >= 1 then
settings.graphLayout = {
width = math.floor(size.X),
height = math.floor(size.Y),
positionXScale = background.Position.X.Scale,
positionXOffset = background.Position.X.Offset,
positionYScale = background.Position.Y.Scale,
positionYOffset = background.Position.Y.Offset,
contentX = content.Position.X.Offset,
contentY = content.Position.Y.Offset,
scale = scale.Scale,
}
saveSettings("Graph layout saved")
end
end
if graphGui == screen then
graphGui = nil
graphCurrent = nil
end
end)
end
-- Rebuild the graph in place: keep the rect and camera, re-read the workspace.
function refreshLogicGraph()
if not graphGui or not graphCurrent then
openLogicGraph()
return
end
graphPendingState = {
size = graphCurrent.background.Size,
position = graphCurrent.background.Position,
contentPosition = graphCurrent.content.Position,
scale = graphCurrent.scale.Scale,
}
openLogicGraph()
end
if IS_MAS then
VisualsTab:CreateButton({Name = "Open logic graph", Callback = openLogicGraph})
end
local maxRenderDistance = settings.renderDistance
local maxRendered = settings.maxRendered
local function getRenderOrigin()
local camera = workspace.CurrentCamera
if camera then
return camera.CFrame.Position
end
local players = game:GetService("Players")
local player = players.LocalPlayer
local root = player and player.Character and player.Character:FindFirstChild("HumanoidRootPart")
return root and root.Position or nil
end
-- Max-heap of the nearest candidates. Keeping only maxRendered entries turns
-- the old full sort (O(n log n)) into O(n log maxRendered), which matters when
-- thousands of blocks are within the render distance.
local function siftNearestHeap(heap, index, size)
local item = heap[index]
while true do
local child = index * 2
if child > size then
break
end
if child < size and heap[child].distanceSquared < heap[child + 1].distanceSquared then
child += 1
end
if item.distanceSquared >= heap[child].distanceSquared then
break
end
heap[index] = heap[child]
index = child
end
heap[index] = item
end
local function offerNearest(heap, size, limit, part, distanceSquared)
if size < limit then
size += 1
-- Only the entries that make the heap need a table. Reusing one
-- candidate table per scan would alias every heap slot, so clone here
-- and mutate the root in place for replacements below.
heap[size] = {part = part, distanceSquared = distanceSquared}
local index = size
while index > 1 do
local parent = math.floor(index / 2)
if heap[parent].distanceSquared >= heap[index].distanceSquared then
break
end
heap[parent], heap[index] = heap[index], heap[parent]
index = parent
end
elseif distanceSquared < heap[1].distanceSquared then
heap[1].part = part
heap[1].distanceSquared = distanceSquared
siftNearestHeap(heap, 1, size)
end
return size
end
local renderableParts = {}
local function getRenderableParts(allParts, dataByPart)
local origin = getRenderOrigin()
local maxDistanceSquared = maxRenderDistance * maxRenderDistance
local limit = math.floor(maxRendered)
if limit <= 0 then
return {}
end
local heap = {}
local size = 0
for _, part in ipairs(allParts) do
if dataByPart[part] then
local distanceSquared = 0
if origin then
-- Squared distance straight from the components. Avoid the
-- temporary Vector3 subtraction per candidate: on a large build
-- that is thousands of short-lived vectors per refresh.
local position = part.Position
local deltaX = position.X - origin.X
local deltaY = position.Y - origin.Y
local deltaZ = position.Z - origin.Z
distanceSquared = deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ
end
if distanceSquared <= maxDistanceSquared then
size = offerNearest(heap, size, limit, part, distanceSquared)
end
end
end
if size > 1 then
table.sort(heap, function(a, b)
return a.distanceSquared < b.distanceSquared
end)
end
local rendered = renderableParts
table.clear(rendered)
for index = 1, size do
rendered[index] = heap[index].part
end
return rendered
end
local lastStats = {logicBlocks = 0, renderedBlocks = 0, wireCount = 0, byType = {}, dataVersion = -1}
local wiresEnabled = settings.showWires
local guisEnabled = settings.showLabels
local sequencerWiresEnabled = settings.showSequencerWires
local visualsFrozen = false
local function updateStats()
if not StatsTab then
return
end
local values = {
{"Logic blocks found", lastStats.logicBlocks},
{"Blocks rendered", lastStats.renderedBlocks},
{"Wire links", lastStats.wireCount},
}
-- Labels are created once and updated in place: destroying and recreating
-- them on every refresh made the stats panel flicker during a build.
local breakdown = {}
for key, count in pairs(lastStats.byType or {}) do
breakdown[#breakdown + 1] = {key, count}
end
table.sort(breakdown, function(a, b)
if a[2] == b[2] then
return a[1] < b[1]
end
return a[2] > b[2]
end)
for index = 1, math.min(#breakdown, 8) do
values[#values + 1] = {" " .. breakdown[index][1], breakdown[index][2]}
end
for index, value in ipairs(values) do
local text = value[1] .. ": " .. tostring(value[2])
local row = statsRows[index]
if row then
row:Set(text)
else
statsRows[index] = StatsTab:CreateLabel(text)
end
end
for index = #values + 1, #statsRows do
statsRows[index]:Set("")
end
end
local cachedParts = nil
local partsDirty = true
local refreshDataByPart = setmetatable({}, {__mode = "k"})
local visualCache = setmetatable({}, {__mode = "k"})
local visualGeneration = 0
local lastWireSignature = nil
local lastWireCount = 0
local lastMassBuildAt = 0
local function getParts()
-- DescendantRemoving marks partsDirty, so the cached list is trusted until
-- a part is added or removed. The old fallback checked IsDescendantOf for
-- every block on every refresh just to catch that same case.
if partsDirty or not cachedParts then
cachedParts = findAllBasePartsRecursive()
partsDirty = false
end
return cachedParts
end
local wirePieceCache = setmetatable({}, {__mode = "k"})
local wirePieces = {}
-- Stable id per instance: when a render slot swaps to a different block with
-- identical data, the signature must change or the old connectors stay behind.
local wirePartIds = setmetatable({}, {__mode = "k"})
local nextWirePartId = 0
local function wirePartId(part)
local id = wirePartIds[part]
if not id then
nextWirePartId += 1
id = nextWirePartId
wirePartIds[part] = id
end
return id
end
local function wireSignature(parts, dataByPart, sequencerEnabled)
local pieces = wirePieces
table.clear(pieces)
for _, part in ipairs(parts) do
local data = dataByPart[part]
if data then
local inserted = getInserted(part)
local insertedCache = inserted and decodedInsertedCache[inserted]
local version = insertedCache and insertedCache.version or 0
local classId = part:GetAttribute("ClassId")
local name = part.Name
local cached = wirePieceCache[part]
local piece
if cached and cached.version == version and cached.classId == classId and cached.name == name then
piece = cached.piece
else
piece = wirePartId(part) .. ":" .. name .. ":" .. tostring(data[1]) .. ":"
.. table.concat(getClassIds(part), ",") .. ":"
.. table.concat(getOutputSignalIds(data), ",")
wirePieceCache[part] = {
version = version,
classId = classId,
name = name,
piece = piece,
}
end
pieces[#pieces + 1] = piece
end
end
table.sort(pieces)
return (sequencerEnabled and "1" or "0") .. table.concat(pieces, ";")
end
local function setVisuals(wiresEnabled, guisEnabled, sequencerWiresEnabled)
local allParts = getParts()
visualGeneration += 1
local generation = visualGeneration
local dataByPart = refreshDataByPart
table.clear(dataByPart)
local logicCount = 0
for _, part in ipairs(allParts) do
local data = getData(part)
if data then
dataByPart[part] = data
logicCount += 1
end
end
local parts = getRenderableParts(allParts, dataByPart)
-- Billboards update individually: editing one block updates only that
-- label, and a refresh where nothing changed costs almost nothing. Each
-- live entry is stamped with the refresh generation so cleanup does not
-- need a second per-refresh set.
-- If something else keeps deleting every billboard, rebuilding all of them
-- on every event turns into a freeze. Allow at most one mass rebuild per
-- 1.5s and let the next refresh recover the rest.
local missing = 0
if guisEnabled then
for _, part in ipairs(parts) do
local entry = visualCache[part]
if not entry or not entry.gui or not entry.gui.billboard or not entry.gui.billboard.Parent then
missing += 1
end
end
end
local allowMassBuild = missing < 40 or (os.clock() - lastMassBuildAt) > 1.5
if missing >= 40 and allowMassBuild then
-- Only stamp the throttle when a mass rebuild is actually allowed.
-- Stamping on every check would keep pushing the window forward and
-- leave every billboard deleted forever.
lastMassBuildAt = os.clock()
end
if guisEnabled then
for _, part in ipairs(parts) do
local data = dataByPart[part]
local inserted = getInserted(part)
local insertedCache = inserted and decodedInsertedCache[inserted]
-- A version number replaces the raw payload, so the per-refresh
-- signature does not copy a block's whole JSON string.
-- Keep the three signature fields separate: concatenating a fresh
-- string for every rendered block on every refresh was pure garbage.
local partName = part.Name
local classId = part:GetAttribute("ClassId")
local version = insertedCache and insertedCache.version or 0
local entry = visualCache[part]
if entry then
entry.generation = generation
end
local opcode = type(data) == "table" and tonumber(data[1]) or nil
local color = COLORS[opcode] or Color3.new(1, 1, 1)
if not entry or not entry.gui or not entry.gui.billboard or not entry.gui.billboard.Parent then
if allowMassBuild then
local description = buildLabelDescription(part, data)
local gui = createGui(part, part.Name, description, color)
visualCache[part] = {
partName = partName,
version = version,
classId = classId,
gui = gui,
generation = generation,
}
end
elseif entry.partName ~= partName or entry.version ~= version or entry.classId ~= classId then
-- Text-only change: update the existing labels instead of
-- destroying and recreating a billboard for every block.
local description = buildLabelDescription(part, data)
local gui = entry.gui
if gui.title.Text ~= part.Name then
gui.title.Text = part.Name
end
if gui.detail.Text ~= description then
gui.detail.Text = description
end
gui.frame.BackgroundColor3 = color
entry.partName = partName
entry.version = version
entry.classId = classId
end
end
end
for part, entry in pairs(visualCache) do
if not guisEnabled or entry.generation ~= generation then
if entry.gui and entry.gui.billboard and entry.gui.billboard.Parent then
entry.gui.billboard:Destroy()
end
visualCache[part] = nil
end
end
local wireCount = 0
if wiresEnabled then
local signature = wireSignature(parts, dataByPart, sequencerWiresEnabled)
if signature ~= lastWireSignature then
clearWireConnectors()
wireCount = createConnectors(parts, sequencerWiresEnabled, dataByPart)
lastWireSignature = signature
lastWireCount = wireCount
else
wireCount = lastWireCount
end
elseif lastWireSignature ~= nil then
clearWireConnectors()
lastWireSignature = nil
lastWireCount = 0
end
if lastStats.logicBlocks ~= logicCount or lastStats.renderedBlocks ~= #parts
or lastStats.wireCount ~= wireCount or lastStats.dataVersion ~= dataVersion then
-- Breakdown by opcode: tells you at a glance whether a build is mostly
-- arithmetic, compares or I/O before you start hunting for perf. The
-- decoded version catches an opcode swap that leaves the totals equal.
local byType = {}
for _, data in pairs(dataByPart) do
local opcode = type(data) == "table" and tonumber(data[1]) or nil
local key = opcode and (OPCODE_NAMES[opcode] or ("Opcode " .. opcode)) or "Unknown"
byType[key] = (byType[key] or 0) + 1
end
lastStats = {
logicBlocks = logicCount,
renderedBlocks = #parts,
wireCount = wireCount,
byType = byType,
dataVersion = dataVersion,
}
updateStats()
end
end
local function refreshLabelAppearance()
local scale = settings.labelScale
local transparency = settings.labelBackgroundTransparency
for part, entry in pairs(visualCache) do
local gui = entry.gui
local billboard = gui and gui.billboard
if billboard and billboard.Parent then
billboard.Size = UDim2.new(4 * scale, 0, scale, 0)
billboard.StudsOffset = Vector3.new(0, 2 * scale, 0)
gui.frame.BackgroundTransparency = transparency
-- ClassId visibility is part of the detail text, so rebuild only
-- that string; the payload parser itself is still cached.
local data = getData(part)
if data then
local description = buildLabelDescription(part, data)
if gui.detail.Text ~= description then
gui.detail.Text = description
end
end
end
end
end
masInterpreter = {}
masInterpreter.toggle = setVisuals
if IS_MAS then
VisualsTab:CreateToggle({
Name = "Wire connectors",
Default = wiresEnabled,
Callback = function(enabled)
wiresEnabled = enabled
settings.showWires = enabled
setVisuals(wiresEnabled, guisEnabled, sequencerWiresEnabled)
saveSettings(enabled and "Wire connectors shown" or "Wire connectors hidden")
end,
})
VisualsTab:CreateToggle({
Name = "Logic block labels",
Default = guisEnabled,
Callback = function(enabled)
guisEnabled = enabled
settings.showLabels = enabled
setVisuals(wiresEnabled, guisEnabled, sequencerWiresEnabled)
saveSettings(enabled and "Logic labels shown" or "Logic labels hidden")
end,
})
VisualsTab:CreateToggle({
Name = "Sequencer wires",
Default = sequencerWiresEnabled,
Callback = function(enabled)
sequencerWiresEnabled = enabled
settings.showSequencerWires = enabled
setVisuals(wiresEnabled, guisEnabled, sequencerWiresEnabled)
saveSettings(enabled and "Sequencer wires shown" or "Sequencer wires hidden")
end,
})
local renderDistanceInput = VisualsTab:CreateTextbox({
Name = "Max render distance (studs)",
Default = tostring(maxRenderDistance),
Placeholder = "500",
})
local maxRenderedInput = VisualsTab:CreateTextbox({
Name = "Max rendered logic blocks",
Default = tostring(maxRendered),
Placeholder = "200",
})
VisualsTab:CreateToggle({
Name = "Freeze visuals (stop auto rebuilds)",
Default = visualsFrozen,
Callback = function(enabled)
visualsFrozen = enabled
if not enabled then
partsDirty = true
scheduleVisualRefresh()
end
end,
})
VisualsTab:CreateButton({Name = "Rescan workspace now", Callback = function()
partsDirty = true
-- Force a wire rebuild too; the signature cache cannot see wires that were
-- deleted externally or by another script.
lastWireSignature = nil
setVisuals(wiresEnabled, guisEnabled, sequencerWiresEnabled)
end})
-- ==========================================================================
-- Settings tab. Controls here change live visuals immediately and persist to a
-- small JSON file, so a new executor session starts with the same preferences.
-- ==========================================================================
SettingsTab:CreateLabel("Changes save automatically to " .. SETTINGS_FILE .. ".")
settingsStatus = SettingsTab:CreateLabel(settingsLoadNote)
SettingsTab:CreateLabel("Label appearance")
local labelScaleInput = SettingsTab:CreateTextbox({
Name = "Label scale (0.5 - 2)",
Default = tostring(settings.labelScale),
Placeholder = "1",
})
local labelTransparencyInput = SettingsTab:CreateTextbox({
Name = "Label background transparency (0 - 1)",
Default = tostring(settings.labelBackgroundTransparency),
Placeholder = "0.5",
})
SettingsTab:CreateButton({Name = "Apply label appearance", Callback = function()
settings.labelScale = clampSettingNumber(labelScaleInput:Get(), 0.5, 2, settings.labelScale)
settings.labelBackgroundTransparency = clampSettingNumber(
labelTransparencyInput:Get(), 0, 1, settings.labelBackgroundTransparency)
labelScaleInput:Set(tostring(settings.labelScale))
labelTransparencyInput:Set(tostring(settings.labelBackgroundTransparency))
refreshLabelAppearance()
saveSettings("Label appearance applied")
end})
SettingsTab:CreateToggle({
Name = "Show ClassId on labels",
Default = settings.showClassId,
Callback = function(enabled)
settings.showClassId = enabled
refreshLabelAppearance()
saveSettings(enabled and "ClassId shown" or "ClassId hidden")
end,
})
SettingsTab:CreateLabel("Wires")
SettingsTab:CreateToggle({
Name = "Animate wire dots (turn off on low-end devices)",
Default = settings.wireAnimation,
Callback = function(enabled)
settings.wireAnimation = enabled
lastWireSignature = nil
setVisuals(wiresEnabled, guisEnabled, sequencerWiresEnabled)
saveSettings(enabled and "Wire animation enabled" or "Wire animation disabled")
end,
})
local wireWidthInput = SettingsTab:CreateTextbox({
Name = "Wire thickness (0.01 - 0.5)",
Default = tostring(settings.wireWidth),
Placeholder = "0.08",
})
SettingsTab:CreateButton({Name = "Apply wire thickness", Callback = function()
settings.wireWidth = clampSettingNumber(wireWidthInput:Get(), 0.01, 0.5, settings.wireWidth)
wireWidthInput:Set(tostring(settings.wireWidth))
lastWireSignature = nil
setVisuals(wiresEnabled, guisEnabled, sequencerWiresEnabled)
saveSettings("Wire thickness applied")
end})
SettingsTab:CreateLabel("Logic graph")
SettingsTab:CreateToggle({
Name = "Show connection wires",
Default = settings.graphShowWires,
Callback = function(enabled)
settings.graphShowWires = enabled
if graphCurrent and graphCurrent.updateWireVisibility then
graphCurrent.updateWireVisibility()
end
saveSettings(enabled and "Graph wires shown" or "Graph wires hidden")
end,
})
SettingsTab:CreateToggle({
Name = "Animate graph backdrop",
Default = settings.graphAnimateBackground,
Callback = function(enabled)
settings.graphAnimateBackground = enabled
saveSettings(enabled and "Graph backdrop animated" or "Graph backdrop paused")
end,
})
local graphTransparencyInput = SettingsTab:CreateTextbox({
Name = "Background transparency (0 - 0.85)",
Default = tostring(settings.graphBackgroundTransparency),
Placeholder = "0",
})
SettingsTab:CreateButton({Name = "Apply graph transparency", Callback = function()
settings.graphBackgroundTransparency = clampSettingNumber(
graphTransparencyInput:Get(), 0, 0.85, settings.graphBackgroundTransparency)
graphTransparencyInput:Set(tostring(settings.graphBackgroundTransparency))
if graphCurrent and graphCurrent.background then
graphCurrent.background.BackgroundTransparency = settings.graphBackgroundTransparency
end
saveSettings("Graph transparency applied")
end})
SettingsTab:CreateToggle({
Name = "Remember graph layout",
Default = settings.graphRememberLayout,
Callback = function(enabled)
settings.graphRememberLayout = enabled
saveSettings(enabled and "Graph layout will be remembered" or "Graph layout will not be saved")
end,
})
SettingsTab:CreateButton({Name = "Reset graph layout", Callback = function()
settings.graphLayout = nil
graphPendingState = nil
if graphCurrent then
graphCurrent.background.Size = UDim2.new(0.9, 0, 0.85, 0)
graphCurrent.background.Position = UDim2.fromScale(0.5, 0.5)
graphCurrent.content.Position = UDim2.fromOffset(40, 40)
graphCurrent.scale.Scale = 1
end
saveSettings("Graph layout reset")
end})
SettingsTab:CreateLabel("Performance presets")
local function applyPerformancePreset(distance, limit, name)
maxRenderDistance = distance
maxRendered = limit
settings.renderDistance = distance
settings.maxRendered = limit
renderDistanceInput:Set(tostring(distance))
maxRenderedInput:Set(tostring(limit))
setVisuals(wiresEnabled, guisEnabled, sequencerWiresEnabled)
saveSettings(name .. " preset applied")
end
SettingsTab:CreateButton({Name = "Low: 250 studs / 80 blocks", Callback = function()
applyPerformancePreset(250, 80, "Low")
end})
SettingsTab:CreateButton({Name = "Balanced: 500 studs / 200 blocks", Callback = function()
applyPerformancePreset(500, 200, "Balanced")
end})
SettingsTab:CreateButton({Name = "High: 1,000 studs / 500 blocks", Callback = function()
applyPerformancePreset(1000, 500, "High")
end})
SettingsTab:CreateButton({Name = "Save settings now", Callback = function()
saveSettings("Settings saved")
end})
-- Static checks over the current build. Nothing here needs the server: every
-- signal id lives in the client-side attributes, so a full pass is instant.
local validationRows = {}
local validationIssues = {}
local validationFocus = 0
local validationStatus = ValidateTab:CreateLabel("Run validation to list problems in the current build.")
-- The default Roblox camera scripts rewrite CurrentCamera.CFrame every frame,
-- so a one-shot assignment is undone immediately. Switching to Scriptable for
-- the duration of the fly-over is what makes the move actually visible.
local focusToken = 0
local focusMarkerToken = 0
local focusMarkers = {}
local focusRestoreType = Enum.CameraType.Custom
local function clearFocusMarkers(token)
-- A timer left over from an earlier focus must not clear a newer highlight.
if token and token ~= focusMarkerToken then
return
end
for _, instance in ipairs(focusMarkers) do
if instance and instance.Parent then
instance:Destroy()
end
end
table.clear(focusMarkers)
end
local function markPart(part, text)
focusMarkerToken = focusMarkerToken + 1
local markerToken = focusMarkerToken
clearFocusMarkers()
-- Keep the mark until the next focus (or a minute), not eight seconds: the
-- old timer used to wipe a fresh highlight the moment it fired.
task.delay(60, function()
clearFocusMarkers(markerToken)
end)
local highlight = Instance.new("Highlight")
highlight.Name = "MASFocusHighlight"
highlight.Adornee = part
highlight.FillColor = Color3.fromRGB(255, 145, 30)
highlight.FillTransparency = 0.45
highlight.OutlineColor = Color3.fromRGB(255, 235, 150)
highlight.OutlineTransparency = 0
highlight.DepthMode = Enum.HighlightDepthMode.AlwaysOnTop
highlight.Parent = part
focusMarkers[#focusMarkers + 1] = highlight
-- Highlight alone is easy to miss on a small block, so the block also gets
-- a selection outline and a floating caption naming the problem.
local box = Instance.new("SelectionBox")
box.Name = "MASFocusBox"
box.Adornee = part
box.LineThickness = 0.08
box.SurfaceTransparency = 0.92
box.Color3 = Color3.fromRGB(255, 205, 90)
box.Parent = part
focusMarkers[#focusMarkers + 1] = box
local billboard = Instance.new("BillboardGui")
billboard.Name = "MASFocusLabel"
billboard.Adornee = part
billboard.Size = UDim2.fromOffset(260, 34)
billboard.StudsOffset = Vector3.new(0, math.max(2.5, part.Size.Y * 0.6 + 1.5), 0)
billboard.AlwaysOnTop = true
billboard.MaxDistance = 400
billboard.Parent = part
local label = Instance.new("TextLabel")
label.Size = UDim2.fromScale(1, 1)
label.BackgroundColor3 = Color3.fromRGB(14, 14, 18)
label.BackgroundTransparency = 0.1
label.BorderSizePixel = 0
label.Text = text
label.TextColor3 = Color3.fromRGB(255, 214, 130)
label.TextSize = 14
label.Font = Enum.Font.GothamMedium
label.TextWrapped = true
label.Parent = billboard
local padding = Instance.new("UICorner")
padding.CornerRadius = UDim.new(0, 6)
padding.Parent = label
focusMarkers[#focusMarkers + 1] = billboard
end
focusCleanup = function()
focusToken = focusToken + 1
clearFocusMarkers()
local camera = workspace.CurrentCamera
if camera and camera.CameraType == Enum.CameraType.Scriptable then
camera.CameraType = focusRestoreType
end
end
local function focusPart(part, text)
local camera = workspace.CurrentCamera
if not (camera and part and part:IsDescendantOf(workspace)) then
return false, "that block is gone - run validation again"
end
focusToken = focusToken + 1
local token = focusToken
-- Never capture Scriptable as the type to restore to: a second click during
-- a fly-over would otherwise "restore" the camera into a permanent lock.
if camera.CameraType ~= Enum.CameraType.Scriptable then
focusRestoreType = camera.CameraType
end
local startCFrame = camera.CFrame
local targetCFrame = CFrame.lookAt(part.Position + Vector3.new(9, 9, 9), part.Position)
camera.CameraType = Enum.CameraType.Scriptable
local elapsed = 0
local connection
connection = game:GetService("RunService").RenderStepped:Connect(function(delta)
if token ~= focusToken then
connection:Disconnect()
return
end
elapsed = elapsed + delta
local alpha = math.min(elapsed / 0.35, 1)
alpha = alpha * alpha * (3 - 2 * alpha)
camera.CFrame = startCFrame:Lerp(targetCFrame, alpha)
if alpha >= 1 then
connection:Disconnect()
end
end)
-- Hold the view until the player actually looks away or walks off, with a
-- hard cap so a stuck character or idle session cannot leave the camera
-- locked. A short ignore window keeps a twitchy mouse from cancelling it.
local holdElapsed = 0
local holdConnection
holdConnection = game:GetService("RunService").RenderStepped:Connect(function(delta)
if token ~= focusToken then
holdConnection:Disconnect()
return
end
holdElapsed = holdElapsed + delta
if holdElapsed < 1.2 then
return
end
local mouseDelta = game:GetService("UserInputService"):GetMouseDelta()
local movedMouse = math.abs(mouseDelta.X) + math.abs(mouseDelta.Y) > 4
local walking = false
if type(game:GetService("UserInputService").IsKeyDown) == "function" then
local keys = game:GetService("UserInputService")
walking = keys:IsKeyDown(Enum.KeyCode.W) or keys:IsKeyDown(Enum.KeyCode.A)
or keys:IsKeyDown(Enum.KeyCode.S) or keys:IsKeyDown(Enum.KeyCode.D)
or keys:IsKeyDown(Enum.KeyCode.Space)
end
if movedMouse or walking or holdElapsed > 15 then
holdConnection:Disconnect()
if token == focusToken and camera.CameraType == Enum.CameraType.Scriptable then
camera.CameraType = focusRestoreType
if not camera.CameraSubject then
local character = PlayersService.LocalPlayer and PlayersService.LocalPlayer.Character
local humanoid = character and character:FindFirstChildOfClass("Humanoid")
if humanoid then
camera.CameraSubject = humanoid
end
end
end
end
end)
-- A marker failure must never leave the camera locked in Scriptable.
pcall(markPart, part, text or ("ISSUE - " .. part.Name))
return true
end
local function runValidation()
local parts = getParts()
local dataByPart = {}
for _, part in ipairs(parts) do
dataByPart[part] = getData(part)
end
local matches = findMatchingInputs(parts, dataByPart, nil, false)
local issues = {}
local unconnected = 0
for _, part in ipairs(parts) do
local wanted = select(1, getPortCounts(part, dataByPart[part]))
if wanted > 0 then
local connected = 0
for _, match in ipairs(matches[part] or EMPTY_IDS) do
if match.source then
connected = connected + 1
end
end
if connected < wanted then
unconnected = unconnected + 1
issues[#issues + 1] = {
part = part,
text = string.format("%s - %d/%d inputs connected", part.Name, connected, wanted),
}
end
end
end
local owners = {}
for _, part in ipairs(parts) do
-- A block can name the same output twice (for example both fields of a
-- two-output block). It is still one emitter, not a duplicate signal.
local seenIds = {}
for _, id in ipairs(getOutputSignalIds(dataByPart[part])) do
if not seenIds[id] then
seenIds[id] = true
owners[id] = owners[id] or {}
table.insert(owners[id], part)
end
end
end
local duplicateSignals = 0
local duplicateIds = {}
for id, list in pairs(owners) do
if #list > 1 then
duplicateSignals = duplicateSignals + 1
duplicateIds[#duplicateIds + 1] = id
end
end
-- pairs() over the owner map is unordered; sort so Focus next issue walks
-- duplicate signals in a stable, repeatable order.
table.sort(duplicateIds, function(a, b)
local numberA, numberB = tonumber(a), tonumber(b)
if numberA and numberB then
return numberA < numberB
elseif numberA then
return true
elseif numberB then
return false
end
return tostring(a) < tostring(b)
end)
for _, id in ipairs(duplicateIds) do
local list = owners[id]
issues[#issues + 1] = {
part = list[2],
text = string.format("signal %s emitted by %d blocks", id, #list),
}
end
validationIssues = issues
validationFocus = 0
local summary = string.format("%d blocks - %d unconnected-input blocks - %d duplicated signals",
#parts, unconnected, duplicateSignals)
validationStatus:Set(#issues == 0 and (summary .. " - no issues") or (summary .. " - press Focus next issue"))
local rows = {summary}
for index = 1, math.min(#issues, 12) do
rows[#rows + 1] = issues[index].text
end
if #issues > 12 then
rows[#rows + 1] = string.format("... %d more", #issues - 12)
end
for index, text in ipairs(rows) do
local row = validationRows[index]
if row then
row:Set(text)
else
validationRows[index] = ValidateTab:CreateLabel(text)
end
end
for index = #rows + 1, #validationRows do
validationRows[index]:Set("")
end
end
ValidateTab:CreateButton({
Name = "Run validation",
Callback = function()
local ok, err = pcall(runValidation)
if not ok then
validationStatus:Set("Validation failed: " .. tostring(err))
end
end,
})
ValidateTab:CreateButton({
Name = "Focus next issue",
Callback = function()
local ok, err = pcall(function()
if #validationIssues == 0 then
runValidation()
end
if #validationIssues == 0 then
validationStatus:Set("No issues to focus - the build passed both checks.")
return
end
validationFocus = validationFocus % #validationIssues + 1
local issue = validationIssues[validationFocus]
local focused, focusError = focusPart(issue.part, issue.text)
if focused then
validationStatus:Set(string.format("Issue %d/%d: %s", validationFocus, #validationIssues, issue.text))
else
validationStatus:Set(string.format("Issue %d/%d: %s (%s)", validationFocus, #validationIssues, issue.text, tostring(focusError)))
end
end)
if not ok then
validationStatus:Set("Focus failed: " .. tostring(err))
end
end,
})
StatsTab:CreateButton({Name = "Refresh stats", Callback = function()
-- Re-scan first: redrawing lastStats alone did nothing after a frozen or
-- missed refresh, which made the button look broken.
partsDirty = true
setVisuals(wiresEnabled, guisEnabled, sequencerWiresEnabled)
updateStats()
end})
VisualsTab:CreateButton({Name = "Apply render limits", Callback = function()
local distance = tonumber(renderDistanceInput:Get())
local count = tonumber(maxRenderedInput:Get())
if distance then
maxRenderDistance = clampSettingNumber(distance, 0, 1000000, maxRenderDistance)
end
if count then
maxRendered = math.floor(clampSettingNumber(count, 0, 1000000, maxRendered))
end
renderDistanceInput:Set(tostring(maxRenderDistance))
maxRenderedInput:Set(tostring(maxRendered))
settings.renderDistance = maxRenderDistance
settings.maxRendered = maxRendered
setVisuals(wiresEnabled, guisEnabled, sequencerWiresEnabled)
saveSettings("Render limits applied")
end})
VisualsTab:CreateButton({Name = "Destroy GUI", Callback = function()
if unloadInterpreter then
unloadInterpreter()
end
end})
end
if IS_MAS then
setVisuals(wiresEnabled, guisEnabled, sequencerWiresEnabled)
end
local refreshQueued = false
local lastRefreshAt = 0
local refreshSuppressed = false
local function scheduleVisualRefresh()
if not IS_MAS or unloaded or refreshQueued or refreshSuppressed or visualsFrozen then
return
end
-- Coalesce bursts and cap the refresh rate so a build tool that rewrites
-- data every drag frame can never saturate a frame with visual work.
local delay = 0.2
local since = os.clock() - lastRefreshAt
if since < 0.4 then
delay = math.max(delay, 0.4 - since)
end
refreshQueued = true
task.delay(delay, function()
refreshQueued = false
if unloaded then
return
end
lastRefreshAt = os.clock()
setVisuals(wiresEnabled, guisEnabled, sequencerWiresEnabled)
end)
end
-- Visual watchers and the initial block count are MaS-only. In an
-- arbitrary game the workspace can stream thousands of parts, and every
-- part here would add three signals that are never disconnected: the
-- client hitches on execute and can die outright. Outside MaS this
-- build only needs the Export tab, so none of this runs.
if IS_MAS then
local watchedParts = setmetatable({}, {__mode = "k"})
local watchedInsertedValues = setmetatable({}, {__mode = "k"})
local function watchInsertedValue(inserted)
if isGeneratedVisual(inserted) or watchedInsertedValues[inserted] then
return
end
watchedInsertedValues[inserted] = true
track(inserted.Changed:Connect(scheduleVisualRefresh))
end
local function watchPart(part)
if isGeneratedVisual(part) or watchedParts[part] then
return
end
watchedParts[part] = true
track(part:GetAttributeChangedSignal("ClassId"):Connect(scheduleVisualRefresh))
-- Renaming a block changes its label title, so refresh once per rename.
track(part:GetPropertyChangedSignal("Name"):Connect(scheduleVisualRefresh))
-- Moving a part does not need a rebuild: billboards are adorned to it and
-- wire attachments/beams follow it automatically. Watching CFrame here used
-- to trigger a full rebuild on every drag frame, which froze the game.
local inserted = getInserted(part)
if inserted and inserted:IsA("StringValue") then
watchInsertedValue(inserted)
end
end
-- getParts already holds every base part, so reuse that traversal instead
-- of walking the whole workspace again just to attach watchers. watchPart
-- also subscribes to that part's Inserted value, which covers the old
-- Inserted branch for parts that are not blocks yet.
local initialParts = getParts()
for _, part in ipairs(initialParts) do
watchPart(part)
end
track(workspace.DescendantAdded:Connect(function(instance)
if isGeneratedVisual(instance) then
return
end
if instance:IsA("BasePart") then
watchPart(instance)
partsDirty = true
if getData(instance) or instance:GetAttribute("ClassId") ~= nil then
scheduleVisualRefresh()
end
elseif instance.Name == "Inserted" and instance:IsA("StringValue")
and instance.Parent and instance.Parent:IsA("BasePart") then
watchInsertedValue(instance)
scheduleVisualRefresh()
end
end))
track(workspace.DescendantRemoving:Connect(function(instance)
if isGeneratedVisual(instance) then
return
end
if instance:IsA("BasePart") then
-- getParts can reuse its cache until the next refresh instead of
-- checking IsDescendantOf for every block; the removal already
-- tells us the list changed.
partsDirty = true
if getData(instance) or instance:GetAttribute("ClassId") ~= nil then
scheduleVisualRefresh()
end
elseif instance.Name == "Inserted" and instance:IsA("StringValue") then
scheduleVisualRefresh()
end
end))
-- The initial setVisuals call above already counted every block; walking
-- the whole workspace a second time just for this print doubled startup.
print("MAS: displayed " .. lastStats.logicBlocks .. " logic blocks")
print("MAS: wire connectors created: " .. lastStats.wireCount)
end
-- ==========================================================================
-- Model export / import: saves the workspace build to a local JSON file and
-- rebuilds it through the game's own build remotes (no game save/load used).
-- ==========================================================================
local function setupModelTab()
local PlayersService = game:GetService("Players")
local MODEL_FOLDER = "MAS_Models"
local MODEL_FORMAT = "MAS_MODEL_V1"
local function modelEnum(enumType, name, default)
if type(name) ~= "string" then
return default
end
local ok, value = pcall(function()
return enumType[name]
end)
if ok and value then
return value
end
return default
end
local function modelEncodeCFrame(cf)
local x, y, z, r00, r01, r02, r10, r11, r12, r20, r21, r22 = cf:GetComponents()
return {x, y, z, r00, r01, r02, r10, r11, r12, r20, r21, r22}
end
local function modelDecodeCFrame(data)
if type(data) ~= "table" or #data < 12 then
return CFrame.new()
end
return CFrame.new(data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11], data[12])
end
local function modelEncodeColor(color)
return {math.round(color.R * 255), math.round(color.G * 255), math.round(color.B * 255)}
end
local function modelDecodeColor(data, fallback)
if type(data) == "table" and #data >= 3 then
return Color3.fromRGB(data[1], data[2], data[3])
end
return fallback or Color3.new(1, 1, 1)
end
local function modelEncodeVector(vector)
return {vector.X, vector.Y, vector.Z}
end
local function modelDecodeVector(data, fallback)
if type(data) == "table" and #data >= 3 then
return Vector3.new(data[1], data[2], data[3])
end
return fallback or Vector3.new(1, 1, 1)
end
local function modelSafeName(name)
local text = tostring(name or ""):gsub("[^%w%-_ ]", "_"):gsub("%s+", "_")
if text == "" then
text = "build_" .. tostring(game.PlaceId)
end
return text:sub(1, 60)
end
local cachedSyncRemote
local function modelSyncRemote()
-- Imports invoke this remote hundreds of times; resolving the tool chain on
-- every call was a measurable slice of the import time.
local cached = cachedSyncRemote
if cached and cached.Parent then
return cached
end
cachedSyncRemote = nil
local lp = PlayersService.LocalPlayer
if not lp then
return nil
end
local tool = lp.Character and lp.Character:FindFirstChild("Building Tools")
if not tool then
local backpack = lp:FindFirstChild("Backpack")
tool = backpack and backpack:FindFirstChild("Building Tools")
end
local api = tool and tool:FindFirstChild("SyncAPI")
cachedSyncRemote = api and api:FindFirstChild("ServerEndpoint") or nil
return cachedSyncRemote
end
local BUILD_TOOL_NAME = "Building Tools"
-- Import goes through the server build remotes, so a server-sided "Building
-- Tools" tool has to exist. It is equipped on demand (exactly one copy) and the
-- caller waits for SyncAPI to replicate before giving up.
local function modelEnsureBuildTool(timeout)
local lp = PlayersService.LocalPlayer
if not lp then
return nil, "no local player"
end
local character = lp.Character
local equipped = character and character:FindFirstChild(BUILD_TOOL_NAME)
if equipped then
if modelSyncRemote() then
return equipped
end
-- The tool can replicate before its SyncAPI remote does. Wait for it
-- instead of failing an import just because the tool was already held.
local equippedDeadline = os.clock() + (timeout or 3)
repeat
if modelSyncRemote() then
return equipped
end
task.wait(0.1)
Shows the Wire connections collected from the workspace [MIGHT LAG ON HUGE PROJECTS] Export / Importing external maps Logic Graph for better visibility Script validations