local function G(G,f,v)if G:IsA("\066\097\115\101\080\097\114\116")then table.insert(f,G)else if G:IsA("\077\111\100\101\108")then table.insert(v,G)end local e=G:GetDescendants()for G,e in ipairs(e)do if e:IsA("\066\097\115\101\080\097\114\116")then table.insert(f,e)elseif e:IsA("\077\111\100\101\108")then table.insert(v,e)end end end end function Selection.Add(f,v)local e=GetCore()local z={}for G,f in pairs(f)do if f.Parent and not Selection.ItemIndex[f]then table.insert(z,f)end end local j=Selection.Items local r={}local b={}for f,v in pairs(z)do Selection.ItemIndex[v]=true CreateSelectionBoxes(v)local e=Maid.new()Selection.Maid[v]=e e.RemovalListener=v.AncestryChanged:Connect(function(G,f)if f==nil then Selection.Remove({v})end end)G(v,r,b)local z=not v:IsA("\066\097\115\101\080\097\114\116")or nil e.NewPartsOrModels=z and v.DescendantAdded:Connect(function(G)if G:IsA("\080\086\073\110\115\116\097\110\099\101")then if G:IsA("\066\097\115\101\080\097\114\116")then local f=(Selection.PartIndex[G]or 0)+1 Selection.PartIndex[G]=f Selection.Parts=Support.Keys(Selection.PartIndex)if f==1 then Selection.PartsAdded:Fire({G})end elseif G:IsA("\077\111\100\101\108")then local f=(Selection.ModelIndex[G]or 0)+1 Selection.ModelIndex[G]=f Selection.Models=Support.Keys(Selection.ModelIndex)end end end)e.RemovingPartsOrModels=z and v.DescendantRemoving:Connect(function(G)if Selection.PartIndex[G]then local f=(Selection.PartIndex[G]or 0)-1 Selection.PartIndex[G]=f>0 and f or nil if f==0 then Selection.Parts=Support.Keys(Selection.PartIndex)Selection.PartsRemoved:Fire({G})end elseif Selection.ModelIndex[G]then local f=(Selection.ModelIndex[G]or 0)-1 Selection.ModelIndex[G]=f>0 and f or nil if f==0 then Selection.Models=Support.Keys(Selection.ModelIndex)end end end)end Selection.Items=Support.Keys(Selection.ItemIndex)if v and#z>0 then TrackSelectionChange(j)end local Y={}for G,f in pairs(r)do local v=(Selection.PartIndex[f]or 0)+1 Selection.PartIndex[f]=v if v==1 then table.insert(Y,f)end end local o=0 for G,f in ipairs(b)do local v=(Selection.ModelIndex[f]or 0)+1 Selection.ModelIndex[f]=v if v==1 then o+=1 end end if#Y>0 then Selection.Parts=Support.Keys(Selection.PartIndex)Selection.PartsAdded:Fire(Y)end if o>0 then Selection.Models=Support.Keys(Selection.ModelIndex)end if#z>0 then Selection.ItemsAdded:Fire(z)Selection.Changed:Fire()end end function Selection.Remove(f,v)local e={}for G,f in pairs(f)do if Selection.IsSelected(f)then table.insert(e,f)end end local z=Selection.Items local j={}local r={}for f,v in pairs(e)do Selection.ItemIndex[v]=nil RemoveSelectionBoxes(v)Selection.Maid[v]=nil G(v,j,r)end Selection.Items=Support.Keys(Selection.ItemIndex)if v and#e>0 then TrackSelectionChange(z)end local b={}for G,f in pairs(j)do local v=(Selection.PartIndex[f]or 0)-1 Selection.PartIndex[f]=v>0 and v or nil if v==0 then table.insert(b,f)end end local Y=0 for G,f in ipairs(r)do local v=(Selection.ModelIndex[f]or 0)-1 Selection.ModelIndex[f]=v>0 and v or nil if v==0 then Y+=1 end end if#b>0 then Selection.Parts=Support.Keys(Selection.PartIndex)Selection.PartsRemoved:Fire(b)end if Y>0 then Selection.Models=Support.Keys(Selection.ModelIndex)end if#e>0 then Selection.ItemsRemoved:Fire(e)Selection.Changed:Fire()end end function Selection.Clear(G)Selection.Remove(Selection.Items,G)Selection.Cleared:Fire()end function Selection.Replace(G,f)local v=Selection.Items local e={}for G,f in ipairs(G)do if not Selection.ItemIndex[f]then table.insert(e,f)end end local z={}local j=Support.FlipTable(G)for G,f in ipairs(Selection.Items)do if not j[f]then table.insert(z,f)end end if#z>0 then Selection.Remove(z,false)end if#e>0 then Selection.Add(e,false)end if f then TrackSelectionChange(v)end end local function f(G)return G:IsA("\077\111\100\101\108")or G:IsA("\066\097\115\101\080\097\114\116")end local function v(G)if not G then return nil end if f(G)then return G elseif G then return G:FindFirstChildWhichIsA("\066\097\115\101\080\097\114\116")or G:FindFirstChildWhichIsA("\077\111\100\101\108")or G:FindFirstChildWhichIsA("\066\097\115\101\080\097\114\116",true)or G:FindFirstChildWhichIsA("\077\111\100\101\108",true)end end function Selection.SetFocus(G)local f=v(G)if Selection.Focus==f then return end Selection.Focus=f Selection.FocusChanged:Fire(f)end function FocusOnLastSelectedPart()if#Selection.Items==0 then Selection.SetFocus(nil)else Selection.SetFocus(Selection.Items[#Selection.Items])end end

local function CollectPartsAndModels(Item, PartTable, ModelTable)

	-- Collect item if it's a part
	if Item:IsA('BasePart') then
		table.insert(PartTable, Item)

	else

		-- Collect item if it's a model
		if Item:IsA('Model') then
			table.insert(ModelTable, Item)
		end

		-- Collect parts & models within item
		local Descendants = Item:GetDescendants()
		for _, Descendant in ipairs(Descendants) do
			if Descendant:IsA('BasePart') then
				table.insert(PartTable, Descendant)
			elseif Descendant:IsA('Model') then
				table.insert(ModelTable, Descendant)
			end
		end
	end
end

function Selection.Add(Items, RegisterHistory)
	-- Adds the given items to the selection

	-- Get core API
	local Core = GetCore();

	-- Go through and validate each given item
	local SelectableItems = {};
	for _, Item in pairs(Items) do

		-- Make sure each item is valid and not already selected
		if Item.Parent and (not Selection.ItemIndex[Item]) then
			table.insert(SelectableItems, Item);
		end;

	end;

	local OldSelection = Selection.Items;

	-- Track parts and models in new selection
	local Parts = {}
	local Models = {}

	-- Go through the valid new selection items
	for _, Item in pairs(SelectableItems) do

		-- Add each valid item to the selection
		Selection.ItemIndex[Item] = true;
		CreateSelectionBoxes(Item)

		-- Create maid for cleaning up item listeners
		local ItemMaid = Maid.new()
		Selection.Maid[Item] = ItemMaid

		-- Deselect items that are destroyed
		ItemMaid.RemovalListener = Item.AncestryChanged:Connect(function (Object, Parent)
			if Parent == nil then
				Selection.Remove({ Item })
			end
		end)

		-- Find parts and models within item
		CollectPartsAndModels(Item, Parts, Models)

		-- Listen for new parts or models in groups
		local IsGroup = not Item:IsA 'BasePart' or nil
		ItemMaid.NewPartsOrModels = IsGroup and Item.DescendantAdded:Connect(function (Descendant)
			if Descendant:IsA('PVInstance') then
				if Descendant:IsA('BasePart') then
					local NewRefCount = (Selection.PartIndex[Descendant] or 0) + 1
					Selection.PartIndex[Descendant] = NewRefCount
					Selection.Parts = Support.Keys(Selection.PartIndex)
					if NewRefCount == 1 then
						Selection.PartsAdded:Fire({ Descendant })
					end
				elseif Descendant:IsA('Model') then
					local NewRefCount = (Selection.ModelIndex[Descendant] or 0) + 1
					Selection.ModelIndex[Descendant] = NewRefCount
					Selection.Models = Support.Keys(Selection.ModelIndex)
				end
			end
		end)
		ItemMaid.RemovingPartsOrModels = IsGroup and Item.DescendantRemoving:Connect(function (Descendant)
			if Selection.PartIndex[Descendant] then
				local NewRefCount = (Selection.PartIndex[Descendant] or 0) - 1
				Selection.PartIndex[Descendant] = (NewRefCount > 0) and NewRefCount or nil
				if NewRefCount == 0 then
					Selection.Parts = Support.Keys(Selection.PartIndex)
					Selection.PartsRemoved:Fire { Descendant }
				end
			elseif Selection.ModelIndex[Descendant] then
				local NewRefCount = (Selection.ModelIndex[Descendant] or 0) - 1
				Selection.ModelIndex[Descendant] = (NewRefCount > 0) and NewRefCount or nil
				if NewRefCount == 0 then
					Selection.Models = Support.Keys(Selection.ModelIndex)
				end
			end
		end)

	end

	-- Update selected item list
	Selection.Items = Support.Keys(Selection.ItemIndex);

	-- Create a history record for this selection change, if requested
	if RegisterHistory and #SelectableItems > 0 then
		TrackSelectionChange(OldSelection);
	end;

	-- Register references to new parts
	local NewParts = {}
	for _, Part in pairs(Parts) do
		local NewRefCount = (Selection.PartIndex[Part] or 0) + 1
		Selection.PartIndex[Part] = NewRefCount
		if NewRefCount == 1 then
			table.insert(NewParts, Part)
		end
	end

	-- Register references to new models
	local NewModelCount = 0
	for _, Model in ipairs(Models) do
		local NewRefCount = (Selection.ModelIndex[Model] or 0) + 1
		Selection.ModelIndex[Model] = NewRefCount
		if NewRefCount == 1 then
			NewModelCount += 1
		end
	end

	-- Update parts list
	if #NewParts > 0 then
		Selection.Parts = Support.Keys(Selection.PartIndex)
		Selection.PartsAdded:Fire(NewParts)
	end

	-- Update models list
	if NewModelCount > 0 then
		Selection.Models = Support.Keys(Selection.ModelIndex)
	end

	-- Fire relevant events
	if #SelectableItems > 0 then
		Selection.ItemsAdded:Fire(SelectableItems)
		Selection.Changed:Fire()
	end

end;

function Selection.Remove(Items, RegisterHistory)
	-- Removes the given items from the selection

	-- Go through and validate each given item
	local DeselectableItems = {};
	for _, Item in pairs(Items) do

		-- Make sure each item is actually selected
		if Selection.IsSelected(Item) then
			table.insert(DeselectableItems, Item);
		end;

	end;

	local OldSelection = Selection.Items;

	-- Track parts and models in removing selection
	local Parts = {}
	local Models = {}

	-- Go through the valid deselectable items
	for _, Item in pairs(DeselectableItems) do

		-- Remove item from selection
		Selection.ItemIndex[Item] = nil;
		RemoveSelectionBoxes(Item)

		-- Stop tracking item's parts
		Selection.Maid[Item] = nil

		-- Find parts and models associated with item
		CollectPartsAndModels(Item, Parts, Models)

	end;

	-- Update selected item list
	Selection.Items = Support.Keys(Selection.ItemIndex);

	-- Create a history record for this selection change, if requested
	if RegisterHistory and #DeselectableItems > 0 then
		TrackSelectionChange(OldSelection);
	end;

	-- Clear references to removing parts
	local RemovingParts = {}
	for _, Part in pairs(Parts) do
		local NewRefCount = (Selection.PartIndex[Part] or 0) - 1
		Selection.PartIndex[Part] = (NewRefCount > 0) and NewRefCount or nil
		if NewRefCount == 0 then
			table.insert(RemovingParts, Part)
		end
	end

	-- Clear references to removing models
	local RemovingModelCount = 0
	for _, Model in ipairs(Models) do
		local NewRefCount = (Selection.ModelIndex[Model] or 0) - 1
		Selection.ModelIndex[Model] = (NewRefCount > 0) and NewRefCount or nil
		if NewRefCount == 0 then
			RemovingModelCount += 1
		end
	end

	-- Update parts list
	if #RemovingParts > 0 then
		Selection.Parts = Support.Keys(Selection.PartIndex)
		Selection.PartsRemoved:Fire(RemovingParts)
	end

	-- Update models list
	if RemovingModelCount > 0 then
		Selection.Models = Support.Keys(Selection.ModelIndex)
	end

	-- Fire relevant events
	if #DeselectableItems > 0 then
		Selection.ItemsRemoved:Fire(DeselectableItems)
		Selection.Changed:Fire()
	end

end;

function Selection.Clear(RegisterHistory)
	-- Clears all items from selection

	-- Remove all selected items
	Selection.Remove(Selection.Items, RegisterHistory);

	-- Fire relevant events
	Selection.Cleared:Fire();

end;

function Selection.Replace(Items, RegisterHistory)
	-- Replaces the current selection with the given new items

	-- Save old selection reference for history
	local OldSelection = Selection.Items;

	-- Find new items
	local NewItems = {}
	for _, Item in ipairs(Items) do
		if not Selection.ItemIndex[Item] then
			table.insert(NewItems, Item)
		end
	end

	-- Find removing items
	local RemovingItems = {}
	local NewItemIndex = Support.FlipTable(Items)
	for _, Item in ipairs(Selection.Items) do
		if not NewItemIndex[Item] then
			table.insert(RemovingItems, Item)
		end
	end

	-- Update selection
	if #RemovingItems > 0 then
		Selection.Remove(RemovingItems, false)
	end
	if #NewItems > 0 then
		Selection.Add(NewItems, false)
	end

	-- Create a history record for this selection change, if requested
	if RegisterHistory then
		TrackSelectionChange(OldSelection);
	end;

end;

local function IsVisible(Item)
	return Item:IsA 'Model' or Item:IsA 'BasePart'
end

local function GetVisibleFocus(Item)
	-- Returns a visible focus representing the item

	-- Return nil if no focus
	if not Item then
		return nil
	end

	-- Return focus if it's visible
	if IsVisible(Item) then
		return Item

	-- Return first visible item within focus if not visible itself
	elseif Item then
		return Item:FindFirstChildWhichIsA('BasePart') or
			Item:FindFirstChildWhichIsA('Model') or
			Item:FindFirstChildWhichIsA('BasePart', true) or
			Item:FindFirstChildWhichIsA('Model', true)
	end
end

function Selection.SetFocus(Item)
	-- Selects `Item` as the focused selection item

	-- Ensure focus has changed
	local Focus = GetVisibleFocus(Item)
	if Selection.Focus == Focus then
		return
	end

	-- Set new focus item
	Selection.Focus = Focus

	-- Fire relevant events
	Selection.FocusChanged:Fire(Focus)

end

function FocusOnLastSelectedPart()
	-- Sets the last part of the selection as the focus

	-- If selection is empty, clear the focus
	if #Selection.Items == 0 then
		Selection.SetFocus(nil);

	-- Otherwise, focus on the last part in the selection
	else
		Selection.SetFocus(Selection.Items[#Selection.Items]);
	end;

end;
