Files

1098 lines
36 KiB
Lua

-- Wood and Seeds Gather: planter timer.
-- Every planter gets its own bar. Planting, Un'Goro Soil and watering are spotted by the seed,
-- soil or water leaving your bags right after you point at (or open) a planter or plant.
-- Each bar counts down its stage and chimes when the next step is due.
-- Lua 5.0 / client 1.12: no '#', no '%' operator, no string methods with ':'.
local ADDON = WoodAndSeedsGather
local Print = ADDON.Print
local SOUND = "Interface\\AddOns\\WoodAndSeedsGather\\sounds\\chime.wav"
local PLANTER = "Simple Wooden Planter"
local SOIL = "Un'Goro Soil"
local WATER = "Refreshing Spring Water"
local REMIND = 120 -- seconds between reminders while a step is due
local SOON = 60 -- bars due this soon share the chime of one that's due now
local POINT_WINDOW = 20 -- seconds an item may leave your bags after you pointed at a plant
local LOOT_WINDOW = 10 -- the same for picking a ripe plant
local CATCH_DELAY = 2 -- a plant you point at moves its bar on this much later, so your bags go first
local RELOAD_GAP = 20 -- planters saved longer ago than this at login were removed by the game
local RIPE_KEEP = 1800 -- a ready-to-pick bar goes away by itself after 30 minutes
local THIN_AFTER = 6 -- with more bars than this they get thinner
local TIMER_DEFAULTS = {
timer = true, timerSound = true, timerRepeat = true, timerLock = false,
timerMinutes = 9, -- minutes per stage, from Octo's gardening guide
}
local LABELS = {
pumpkin = "Pumpkin", berry = "Mountain Berry", melon = "Watermelon", grape = "Grape",
yam = "Yam", carrot = "Carrot", cabbage = "Cabbage", mushroom = "Mushroom",
}
local PLANTER_ICON = "Interface\\Icons\\INV_Misc_Herb_07"
local SOIL_ICON = "Interface\\Icons\\INV_Misc_Dust_02"
local WATER_ICON = "Interface\\Icons\\INV_Drink_07"
-- Each crop's stage objects, from Octo's database, in order:
-- 1 growing, 2 needs soil, 3 growing, 4 needs water, 5 growing, 6 needs water, 7 ripe.
local SPROUT = "Little sproutling. Looks healthy."
local SPROUT_SOIL = "Little sproutling. It yearns for fertile soil!"
local CHAINS = {
pumpkin = { SPROUT, SPROUT_SOIL, "Little pumpkin. Watch it grow!", "Cute pumpkin looks thirsty!",
"Pumpkin is getting bigger!", "Medium pumpkin. Water it!", "Ripe, juicy pumpkin. Ready to pick!" },
berry = { "Small berry shrub. Looks promising.", "Small berry shrub. Needs fertile soil.",
"Berry bush growing. Patience...", "Berry bush growing. Water it!", "Berry bush is thriving!",
"Berry bush needs water!", "Bush full of berries. Time to harvest!" },
melon = { "Little sproutling. Nice and healthy!", "Little sproutling needs fertile soil!",
"Small watermelon. Growing steadily.", "Small watermelon. Water it well!", "Medium watermelon. Getting bigger!",
"Medium watermelon. Needs more water!", "Big, juicy watermelon ready to harvest!" },
mushroom = { "Little mushrooms. Looking cute.", "Germinating slowly. Mushrooms need fertile soil.",
"Mushrooms are sprouting. Patience...", "Small mushrooms need some water.", "Mushrooms are germinating!",
"Mushrooms are growing! Water them!", "Delicious, chunky mushrooms ready to harvest." },
grape = { SPROUT, SPROUT_SOIL, "Small grape vine. Watch it grow!", "Young grape vine looks thirsty!",
"Grape vine is getting bigger!", "Maturing grape vine. Water it!", "Ripe Northwind grapes. Ready to pick!" },
yam = { SPROUT, SPROUT_SOIL, "Small yam. Watch it grow!", "Young yam looks thirsty!",
"Yam is getting bigger!", "Medium yam. Water it!", "Ripe Wildhammer yam. Ready to pick!" },
carrot = { SPROUT, SPROUT_SOIL, "Small carrot. Watch it grow!", "Young carrot looks thirsty!",
"Carrot is getting bigger!", "Medium carrot. Water it!", "Ripe Sandswept carrot. Ready to pick!" },
cabbage = { SPROUT, SPROUT_SOIL, "Small cabbage. Watch it grow!", "Young cabbage looks thirsty!",
"Cabbage is getting bigger!", "Medium cabbage. Water it!", "Ripe cabbage. Ready to pick!" },
}
-- name you see when pointing at it -> { k = stage 1-7 (0 = empty planter),
-- crop = key (nil for a stage several crops share), crops = every crop it can be }
local GARDEN = { [PLANTER] = { k = 0, crops = {} } }
for crop, chain in pairs(CHAINS) do
for k, name in ipairs(chain) do
local g = GARDEN[name]
if not g then
g = { k = k, crop = crop, crops = {} }
GARDEN[name] = g
elseif g.crop ~= crop then
g.crop = nil
end
g.crops[crop] = true
end
end
-- One entry per planter, saved in DB.planters so a /reload keeps them.
-- phase 1 = waiting for soil, 2 = waiting for water, 3 = waiting for the last water, 4 = ripe.
-- due = when the next step is due (time() seconds).
local DB
local planters = {}
local TRACK = {} -- item name -> crop key, or "soil" / "water"
local SEED_OF, ICON_OF = {}, {}
local counts -- item name -> how many are in the bags
local itemIcons = {}
local needs = {} -- plants you pointed at lately that wanted something: { name, info, seen, used }
local pending = {} -- plant name -> when to check whether its bar is behind
local lastTip
local nextRemind
local nextId = 0
-- /trees timer debug: a chat line for everything the timer notices, to find out why it missed a step
local STAGE_WORD = { [0] = "empty planter", "growing", "needs soil", "growing", "needs water", "growing",
"needs water", "ripe" }
local NEXT_WORD = { "soil", "water", "last water", "pick" }
local function Dbg(text)
if DB and DB.timerDebug then
DEFAULT_CHAT_FRAME:AddMessage(string.format("|cff7fbfffWSG %.1f|r %s", math.mod(GetTime(), 1000), text))
end
end
local function Now() return time() end
local function StageSeconds() return (DB.timerMinutes or 9) * 60 end
local function Clock(sec)
if sec < 0 then sec = 0 end
local m = math.floor(sec / 60)
return string.format("%d:%02d", m, sec - m * 60)
end
local function Label(p)
local text = LABELS[p.crop] or "Planter"
if p.test then text = "Test: " .. text end
return text
end
local function CropIcon(p)
return ICON_OF[p.crop] or PLANTER_ICON
end
local NEED_SHORT = { "Soil", "Water", "Water" }
local NEED_TEXT = { "add Un'Goro Soil", "time to water", "water once more" }
local STEP_NAME = { "Un'Goro Soil", "Refreshing Spring Water", "Refreshing Spring Water, one last time" }
local function NeedIcon(phase)
if phase == 1 then return itemIcons[SOIL] or SOIL_ICON end
return itemIcons[WATER] or WATER_ICON
end
-- "Pumpkin x4: add Un'Goro Soil, Watermelon: time to water" for a list of bars
local function NeedText(list)
local groups, order = {}, {}
for _, p in ipairs(list) do
local key = Label(p) .. p.phase
local g = groups[key]
if not g then
g = { label = Label(p), phase = p.phase, n = 0 }
groups[key] = g
table.insert(order, g)
end
g.n = g.n + 1
end
local text = ""
for i, g in ipairs(order) do
if i > 3 then
text = text .. ", ..."
break
end
if i > 1 then text = text .. ", " end
text = text .. g.label
if g.n > 1 then text = text .. " x" .. g.n end
text = text .. ": " .. NEED_TEXT[g.phase]
end
return text
end
-- alert: big text in the middle of the screen, a chime and (the first time) a chat line --------
local alert = CreateFrame("Frame", nil, UIParent)
alert:SetFrameStrata("HIGH")
alert:SetWidth(800)
alert:SetHeight(40)
alert:SetPoint("TOP", UIParent, "TOP", 0, -240)
local alertText = alert:CreateFontString(nil, "OVERLAY")
alertText:SetFont("Fonts\\FRIZQT__.TTF", 24, "OUTLINE")
alertText:SetPoint("CENTER", alert, "CENTER", 0, 0)
alertText:SetTextColor(1, 0.85, 0.3)
alert:Hide()
local alertUntil = 0
alert:SetScript("OnUpdate", function()
local left = alertUntil - GetTime()
if left <= 0 then
this:Hide()
elseif left < 1.5 then
this:SetAlpha(left / 1.5)
else
this:SetAlpha(1)
end
end)
local function Alert(text, chat)
alertText:SetText(text)
alertUntil = GetTime() + 5
alert:SetAlpha(1)
alert:Show()
if DB.timerSound then PlaySoundFile(SOUND) end
if chat then Print(text) end
end
-- planters ---------------------------------------------------------------------------------
local Draw -- defined with the bars below
local function NewPlanter(phase, crop)
nextId = nextId + 1
local p = { id = nextId, crop = crop or "?", phase = phase, zone = GetRealZoneText(), started = Now() }
p.due = p.started + StageSeconds()
if phase >= 4 then
p.phase = 4
p.due = p.started
end
table.insert(planters, p)
return p
end
-- the planter got its next step, or with phase: jumped on to that phase
local function Advance(p, phase)
p.phase = phase or (p.phase + 1)
p.started = Now()
p.due = p.started + StageSeconds()
p.alerted = nil
if p.phase >= 4 then
p.phase = 4
p.due = p.started
end
end
-- the step was undone (a click by mistake): it's due again
local function Back(p)
if p.phase <= 1 then return end
p.phase = p.phase - 1
p.started = Now() - StageSeconds()
p.due = Now()
p.alerted = true
end
local function Remove(p)
for i, x in ipairs(planters) do
if x == p then
table.remove(planters, i)
return
end
end
end
-- you did a bar's step by hand (a left-click): it moves on, or goes once it's picked
local function Done(p)
if p.phase >= 4 then
Remove(p)
else
Advance(p)
end
end
-- could this bar be that plant?
local function Matches(p, info)
return not p.test and (p.crop == "?" or info.crops[p.crop] == true)
end
local function Planted(crop, d)
for i = 1, d do
local p = NewPlanter(1, crop)
Dbg("new " .. Label(p) .. " bar #" .. p.id .. ", next: soil")
end
end
-- d planters got the step that ends this phase (soil for 1, water for 2 and 3)
local function Acted(phase, info, d)
local now = Now()
for i = 1, d do
local best, bestScore
for _, p in ipairs(planters) do
-- a bar waiting for this step, or one still due a step before it (that step was missed)
if Matches(p, info) and (p.phase == phase or (p.phase < phase and now >= p.due)) then
local score = p.due
if p.phase < phase then score = score + 100000000 end
if p.crop == "?" then score = score + 10000000 end
if not best or score < bestScore then best, bestScore = p, score end
end
end
if best then
Advance(best, phase + 1)
Dbg(Label(best) .. " bar #" .. best.id .. " moved on, next: " .. NEXT_WORD[best.phase])
else
-- the planting was missed (planted before the addon was on, say): start from this step
local p = NewPlanter(phase + 1, info.crop)
Dbg("no bar was waiting for this, so a new " .. Label(p) .. " bar #" .. p.id .. " started, next: "
.. NEXT_WORD[p.phase])
end
end
end
-- you picked a ripe plant: its bar goes, even if the timer was behind
local function Picked(info)
local best
for _, p in ipairs(planters) do
if Matches(p, info) and p.phase >= 2 then
if not best or p.phase > best.phase or (p.phase == best.phase and p.due < best.due) then best = p end
end
end
if best then
Remove(best)
Dbg("picked: " .. Label(best) .. " bar #" .. best.id .. " removed")
else
Dbg("picked, but no bar of that crop was far enough on to remove")
end
end
-- a plant's stage (1-7) -> the phase its bar should be in
local function PhaseOf(k)
if k >= 7 then return 4 end
return math.floor((k + 1) / 2)
end
-- You pointed at a plant, a moment ago. If its bar is behind, catch it up:
-- - it asks for soil or water while its bar still counts down: the stage was quicker than the
-- timer, so the bar shows it as due now (no chime, you're there)
-- - it's further on than every bar of its crop: a step was missed, so the bar that's been
-- waiting longest jumps to the plant's stage
local function CatchUp(info, name)
local k = info.k
if not k or k < 1 then return end
local phase = PhaseOf(k)
local asking = k < 7 and math.mod(k, 2) == 0
local now = Now()
local already, same, behind
for _, p in ipairs(planters) do
if Matches(p, info) then
if p.phase == phase then
-- a bar already shows this stage: the plant is most likely that one
if not asking or now >= p.due then
already = already or p
elseif not same or p.due < same.due then
same = p
end
elseif p.phase < phase and now >= p.due then
if not behind or p.phase > behind.phase or (p.phase == behind.phase and p.due < behind.due) then
behind = p
end
end
end
end
if already then
if behind then
Dbg("pointing at " .. name .. ": bar #" .. already.id .. " already shows that, so bar #" .. behind.id
.. " stays behind")
end
return
end
local p = same or behind
if not p then return end
if p ~= same then Advance(p, phase) end
if asking then
p.due = now
p.alerted = true
end
Dbg("pointing at " .. name .. ": " .. Label(p) .. " bar #" .. p.id .. " caught up, next: " .. NEXT_WORD[p.phase]
.. (asking and " (due now)" or ""))
end
-- what you point at -------------------------------------------------------------------------
local quietUntil = 0 -- just after a step the plant you did may still show its old name for a moment
local function PointingAt(name, src)
local info = GARDEN[name]
local t = GetTime()
Dbg("pointing at (" .. src .. "): " .. name .. " - " .. STAGE_WORD[info.k])
for i = table.getn(needs), 1, -1 do
if t - needs[i].seen > POINT_WINDOW then table.remove(needs, i) end
end
-- a planter, or a plant asking for soil, water or picking: remember it for a while, so the
-- item leaving your bags still counts after the plant has turned into its next stage
if math.mod(info.k, 2) == 0 or info.k == 7 then
local last = needs[table.getn(needs)]
if last and last.name == name and not last.used then
last.seen = t
else
table.insert(needs, { name = name, info = info, seen = t })
end
end
if t >= quietUntil then pending[name] = t + CATCH_DELAY end
end
-- still pointing at the same plant
local function Seen(name)
local last = needs[table.getn(needs)]
if last and last.name == name and not last.used then last.seen = GetTime() end
end
local skippedTip -- for the debug line: a plant's tooltip the check below turned down
local function PollTooltip()
local name
if GameTooltip:IsVisible() and not UnitExists("mouseover") then
-- world objects use a one-line tooltip owned by UIParent; items in your bags don't
local owned = true
if GameTooltip.IsOwned then owned = GameTooltip:IsOwned(UIParent) end
local text = GameTooltipTextLeft1 and GameTooltipTextLeft1:GetText()
if owned or GameTooltip:NumLines() <= 3 then
name = text
skippedTip = nil
elseif text and GARDEN[text] and text ~= skippedTip then
skippedTip = text
Dbg("tooltip shows " .. text .. " but it was skipped (" .. GameTooltip:NumLines() .. " lines)")
end
end
if name and GARDEN[name] then
if name ~= lastTip then PointingAt(name, "tooltip") else Seen(name) end
end
lastTip = name
end
local function CheckPending()
local t = GetTime()
for name, at in pairs(pending) do
if t >= at then
pending[name] = nil
CatchUp(GARDEN[name], name)
end
end
end
-- which plant stage an item goes with
local function Fits(kind, k)
if kind == "soil" then return k == 2 end
if kind == "water" then return k == 4 or k == 6 end
if kind == "ripe" then return k == 7 end
return k == 0 -- a seed goes in an empty planter
end
-- the newest plant you pointed at lately that wanted this
local function TakeNeed(kind, window)
local t = GetTime()
for i = table.getn(needs), 1, -1 do
local n = needs[i]
if not n.used and t - n.seen <= window and Fits(kind, n.info.k) then
n.used = true
return n
end
end
end
-- for the debug lines: the plants you pointed at lately, newest first
local function NeedsText()
local t = GetTime()
local s = ""
for i = table.getn(needs), 1, -1 do
local n = needs[i]
s = s .. string.format(" [%s - %s, %ds ago%s]", n.name, STAGE_WORD[n.info.k], math.floor(t - n.seen),
n.used and ", used" or "")
end
if s == "" then s = " none" end
return s
end
local ITEM_WORD = { soil = "soil", water = "water", ripe = "picking" }
-- bags ---------------------------------------------------------------------------------------
local BUSY = { "MerchantFrame", "BankFrame", "MailFrame", "TradeFrame", "AuctionFrame", "TradeSkillFrame", "CraftFrame" }
local function Busy()
for _, name in ipairs(BUSY) do
local f = getglobal(name)
if f and f:IsVisible() then return true end
end
return false
end
local function ScanBags()
local c = {}
for bag = 0, 4 do
for slot = 1, GetContainerNumSlots(bag) do
local link = GetContainerItemLink(bag, slot)
if link then
local _, _, name = string.find(link, "%[(.-)%]")
if name and TRACK[name] then
local tex, n = GetContainerItemInfo(bag, slot)
c[name] = (c[name] or 0) + (n or 1)
if tex then itemIcons[name] = tex end
end
end
end
end
return c
end
local function ItemUsed(kind, d)
local word = ITEM_WORD[kind] or "planting"
local n = TakeNeed(kind, POINT_WINDOW)
if not n then
Dbg("NOT counted: no plant wanting " .. word .. " pointed at in the last " .. POINT_WINDOW
.. " s. Lately:" .. NeedsText())
return
end
Dbg(string.format("counted as %s for %s, pointed at %.1f s before", word, n.name, GetTime() - n.seen))
local info = n.info
if kind == "soil" then
Acted(1, info, d)
elseif kind == "water" then
Acted(info.k / 2, info, d)
else
Planted(kind, d)
end
-- still pointing at a plant on the next check counts as pointing at it anew
lastTip = nil
quietUntil = GetTime() + 3
end
local function BagsChanged()
local new = ScanBags()
if counts then
local busy = Busy()
for name, kind in pairs(TRACK) do
local before, after = counts[name] or 0, new[name] or 0
if before ~= after then
Dbg("bags: " .. name .. " " .. before .. " -> " .. after
.. (busy and " (a vendor, bank, mail or trade window is open: not counted)" or ""))
if before > after and not busy then ItemUsed(kind, before - after) end
end
end
end
counts = new
end
-- the bars ---------------------------------------------------------------------------------
local BAR_W, BAR_H, THIN_H = 230, 20, 14
local anchor = CreateFrame("Frame", "WoodAndSeedsGatherTimer", UIParent)
anchor:SetWidth(BAR_W)
anchor:SetHeight(BAR_H)
anchor:SetMovable(true)
if anchor.SetClampedToScreen then anchor:SetClampedToScreen(true) end
anchor:SetPoint("TOP", UIParent, "TOP", 0, -150)
local bars = {}
local menu, menuPlanter
local function PlacePanel()
anchor:ClearAllPoints()
local p = DB.timerPos
if p then
anchor:SetPoint(p[1], UIParent, p[2], p[3], p[4])
else
anchor:SetPoint("TOP", UIParent, "TOP", 0, -150)
end
end
local function BarTooltip()
local p = this.planter
if not p then return end
GameTooltip:SetOwner(this, "ANCHOR_BOTTOM")
GameTooltip:AddLine(Label(p))
if SEED_OF[p.crop] then GameTooltip:AddLine(SEED_OF[p.crop], 1, 1, 1) end
local left = p.due - Now()
if p.phase >= 4 then
GameTooltip:AddLine("Ready to pick", 0.4, 1, 0.4)
elseif left > 0 then
GameTooltip:AddLine("Next: " .. STEP_NAME[p.phase] .. " in " .. Clock(left), 1, 0.82, 0)
else
GameTooltip:AddLine("Now: " .. STEP_NAME[p.phase], 1, 0.82, 0)
end
GameTooltip:AddLine("Planted in " .. (p.zone or "?"), 0.85, 0.85, 0.85)
GameTooltip:AddLine("Each stage takes " .. (DB.timerMinutes or 9) .. " minutes. Plants don't spoil if you're late.", 0.6, 0.6, 0.6)
if p.phase >= 4 then
GameTooltip:AddLine("Left-click: picked, remove the bar", 0.5, 0.8, 1)
else
GameTooltip:AddLine("Left-click: I've done this step", 0.5, 0.8, 1)
end
GameTooltip:AddLine("Right-click: options", 0.5, 0.8, 1)
if not DB.timerLock then GameTooltip:AddLine("Drag to move", 0.5, 0.8, 1) end
GameTooltip:Show()
end
local function CreateBar()
local f = CreateFrame("Button", nil, anchor)
f:SetWidth(BAR_W)
f:RegisterForClicks("LeftButtonUp", "RightButtonUp")
f:RegisterForDrag("LeftButton")
local icon = f:CreateTexture(nil, "ARTWORK")
icon:SetPoint("LEFT", f, "LEFT", 0, 0)
icon:SetTexCoord(0.08, 0.92, 0.08, 0.92)
f.icon = icon
local sb = CreateFrame("StatusBar", nil, f)
sb:SetStatusBarTexture("Interface\\TargetingFrame\\UI-StatusBar")
sb:SetMinMaxValues(0, 1)
local bg = sb:CreateTexture(nil, "BACKGROUND")
bg:SetAllPoints(sb)
bg:SetTexture(0, 0, 0, 0.55)
f.sb = sb
local left = sb:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
left:SetPoint("LEFT", sb, "LEFT", 4, 0)
left:SetJustifyH("LEFT")
f.left = left
local right = sb:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
right:SetPoint("RIGHT", sb, "RIGHT", -4, 0)
right:SetJustifyH("RIGHT")
f.right = right
-- the item that's due, just right of the bar
local need = f:CreateTexture(nil, "OVERLAY")
need:SetPoint("LEFT", f, "RIGHT", 3, 0)
need:SetTexCoord(0.08, 0.92, 0.08, 0.92)
f.need = need
f:SetScript("OnMouseDown", function()
this.dragged = nil
this.downX, this.downY = GetCursorPosition()
end)
f:SetScript("OnClick", function()
local p = this.planter
if not p then return end
if arg1 == "RightButton" then
menuPlanter = p
ToggleDropDownMenu(1, nil, menu, "cursor")
return
end
-- a drag ends in a click too: only count it if the mouse stayed put
if this.dragged then return end
local x, y = GetCursorPosition()
if this.downX and math.abs(x - this.downX) + math.abs(y - this.downY) > 6 then return end
Done(p)
GameTooltip:Hide()
Draw()
end)
f:SetScript("OnDragStart", function()
this.dragged = true
if not DB.timerLock then anchor:StartMoving() end
end)
f:SetScript("OnDragStop", function()
anchor:StopMovingOrSizing()
-- no GetPoint here: right after a move it can crash the 1.12 client (error #132)
local x, y = anchor:GetCenter()
if not x then return end
anchor:ClearAllPoints()
anchor:SetPoint("CENTER", UIParent, "BOTTOMLEFT", x, y)
DB.timerPos = { "CENTER", "BOTTOMLEFT", x, y }
end)
f:SetScript("OnEnter", BarTooltip)
f:SetScript("OnLeave", function() GameTooltip:Hide() end)
return f
end
-- size and place bar i; thinner bars when there are lots of them
local function Layout(f, i, h)
if f.h == h and f.i == i then return end
f.h, f.i = h, i
local gap = 3
if h < BAR_H then gap = 2 end
f:SetHeight(h)
f:ClearAllPoints()
f:SetPoint("TOP", anchor, "TOP", 0, -(i - 1) * (h + gap))
f.icon:SetWidth(h)
f.icon:SetHeight(h)
f.need:SetWidth(h)
f.need:SetHeight(h)
f.sb:ClearAllPoints()
f.sb:SetPoint("TOPLEFT", f, "TOPLEFT", h + 2, 0)
f.sb:SetPoint("BOTTOMRIGHT", f, "BOTTOMRIGHT", 0, 0)
end
local function DrawBar(f, p)
local now = Now()
f.planter = p
f.icon:SetTexture(CropIcon(p))
f.left:SetText(Label(p))
f.need:Hide()
if p.phase >= 4 then
f.sb:SetStatusBarColor(0.35, 0.8, 0.35)
f.sb:SetValue(1)
f.right:SetText("Ready to pick!")
elseif now >= p.due then
-- due: gold and gently pulsing, with the item it needs beside it
local glow = 0.65 + 0.35 * math.abs(math.sin(GetTime() * 2.5))
f.sb:SetStatusBarColor(glow, glow * 0.75, 0.1)
f.sb:SetValue(1)
f.right:SetText(NEED_SHORT[p.phase] .. " now!")
f.need:SetTexture(NeedIcon(p.phase))
f.need:Show()
else
local total = StageSeconds()
f.sb:SetStatusBarColor(0.25, 0.6, 0.25)
f.sb:SetValue(1 - (p.due - now) / total)
f.right:SetText(NEED_SHORT[p.phase] .. " in " .. Clock(p.due - now))
end
end
-- the bar that's due soonest goes at the top
local order = {}
local function Sooner(a, b)
if a.due ~= b.due then return a.due < b.due end
return (a.id or 0) < (b.id or 0)
end
Draw = function()
local shown = 0
if DB.timer then
-- table.remove, not order[i] = nil: in Lua 5.0 that leaves table.getn at the old size
for i = table.getn(order), 1, -1 do table.remove(order) end
for _, p in ipairs(planters) do table.insert(order, p) end
table.sort(order, Sooner)
local h = BAR_H
if table.getn(order) > THIN_AFTER then h = THIN_H end
for i, p in ipairs(order) do
shown = i
local f = bars[i]
if not f then
f = CreateBar()
bars[i] = f
end
Layout(f, i, h)
DrawBar(f, p)
f:Show()
end
end
for i = shown + 1, table.getn(bars) do
bars[i]:Hide()
bars[i].planter = nil
end
end
-- right-click menu on a bar
local function MenuButton(text, func, checked)
UIDropDownMenu_AddButton({ text = text, func = func, checked = checked })
end
local function BarMenuInit()
local p = menuPlanter
if not p then return end
UIDropDownMenu_AddButton({ text = Label(p), isTitle = 1 })
if p.phase < 4 then
MenuButton("I did it (" .. string.lower(NEED_SHORT[p.phase]) .. ")", function() Done(p); Draw() end)
MenuButton("Start this stage's timer again", function()
p.started = Now()
p.due = p.started + StageSeconds()
p.alerted = nil
Draw()
end)
else
MenuButton("I picked it", function() Remove(p); Draw() end)
end
if p.phase > 1 then
MenuButton("Back one step", function() Back(p); Draw() end)
end
MenuButton("Remove this bar", function() Remove(p); Draw() end)
MenuButton("Chime", function() DB.timerSound = not DB.timerSound end, DB.timerSound and 1 or nil)
MenuButton("Remind every 2 minutes", function() DB.timerRepeat = not DB.timerRepeat end, DB.timerRepeat and 1 or nil)
MenuButton("Lock the bars", function() DB.timerLock = not DB.timerLock end, DB.timerLock and 1 or nil)
end
-- once a second: alerts, reminders and tidying ---------------------------------------------
local function Tick()
local now = Now()
DB.plantersSeen = now
for i = table.getn(planters), 1, -1 do
local p = planters[i]
if (p.phase >= 4 and now - p.due > RIPE_KEEP) or (p.test and p.alerted and now - p.due > 30) then
table.remove(planters, i)
end
end
local fresh = false
for _, p in ipairs(planters) do
if p.phase < 4 and not p.alerted and now >= p.due then
fresh = true
break
end
end
if fresh then
-- one chime for every bar that's due now or within the next minute
local list = {}
for _, p in ipairs(planters) do
if p.phase < 4 and not p.alerted and p.due - now <= SOON then
p.alerted = true
table.insert(list, p)
end
end
Alert(NeedText(list) .. "!", true)
nextRemind = now + REMIND
return
end
-- reminders: one for all the bars still waiting
local list = {}
for _, p in ipairs(planters) do
if p.phase < 4 and now >= p.due and not p.test then table.insert(list, p) end
end
if not list[1] then
nextRemind = nil
elseif not nextRemind then
nextRemind = now + REMIND
elseif now >= nextRemind then
nextRemind = now + REMIND
if DB.timerRepeat then Alert(NeedText(list), false) end
end
end
-- settings, menu and slash command ----------------------------------------------------------
local function Test()
for i = 1, 2 do
local p = NewPlanter(1, "berry")
p.test = true
p.started = Now() - StageSeconds() + 8
p.due = Now() + 8
end
Draw()
Print("two test bars added: they chime together in 8 seconds.")
end
local function ClearAll()
for i = table.getn(planters), 1, -1 do table.remove(planters, i) end
end
local function OnOff(v)
if v then return "|cff40ff40on|r" end
return "|cffff5050off|r"
end
local function TimerHelp()
Print("planter timer " .. OnOff(DB.timer) .. ", chime " .. OnOff(DB.timerSound) .. ", reminders "
.. OnOff(DB.timerRepeat) .. ", bars locked " .. OnOff(DB.timerLock) .. ", " .. DB.timerMinutes
.. " min stages. Each planter gets its own bar.")
Print("/trees timer on | off - turn the planter timer on or off")
Print("/trees timer test - show two test bars that chime in 8 seconds")
Print("/trees timer sound | remind | lock - chime, reminders every 2 minutes, lock the bars")
Print("/trees timer start <seed> [count] - start bars by hand, like /trees timer start berry 4")
Print("/trees timer minutes <n> - how long each stage takes")
Print("/trees timer clear | reset - remove all bars, or move them back to the top middle")
Print("/trees timer debug - a chat line for everything the timer notices (now " .. OnOff(DB.timerDebug) .. ")")
Print("Left-click a bar when you've done its step, right-click it for more.")
end
-- for the debug switch: every bar and what it's waiting for
local function ListBars()
if not planters[1] then
Dbg("no bars")
return
end
local now = Now()
for _, p in ipairs(planters) do
local state
if p.phase >= 4 then
state = "ripe"
elseif now >= p.due then
state = NEXT_WORD[p.phase] .. " due now"
else
state = NEXT_WORD[p.phase] .. " in " .. Clock(p.due - now)
end
Dbg("bar #" .. p.id .. " " .. Label(p) .. ": " .. state)
end
end
local function TimerSlash(msg)
local _, _, cmd, rest = string.find(msg or "", "^%s*(%S*)%s*(.-)%s*$")
cmd = cmd or ""
if cmd == "on" then
DB.timer = true
elseif cmd == "off" then
DB.timer = false
elseif cmd == "sound" or cmd == "chime" then
DB.timerSound = not DB.timerSound
if DB.timerSound then PlaySoundFile(SOUND) end
elseif cmd == "remind" then
DB.timerRepeat = not DB.timerRepeat
elseif cmd == "lock" then
DB.timerLock = not DB.timerLock
elseif cmd == "test" then
DB.timer = true
Test()
return
elseif cmd == "debug" then
DB.timerDebug = not DB.timerDebug
if DB.timerDebug then
Print("debug lines " .. OnOff(true) .. ". Do your planters as usual, then send a screenshot of this chat. "
.. "/trees timer debug again turns them off.")
ListBars()
else
Print("debug lines " .. OnOff(false) .. ".")
end
return
elseif cmd == "clear" then
ClearAll()
elseif cmd == "reset" then
DB.timerPos = nil
PlacePanel()
elseif cmd == "minutes" then
local v = tonumber(rest)
if not v or v < 1 or v > 60 then
Print("use a number from 1 to 60")
return
end
DB.timerMinutes = v
elseif cmd == "start" then
local _, _, key, num = string.find(rest or "", "^(%a+)%s*(%d*)")
if not key or not LABELS[key] then
Print("seeds: pumpkin, berry, melon, grape, yam, carrot, cabbage, mushroom")
return
end
ADDON.TimerStart(key, tonumber(num) or 1)
else
TimerHelp()
return
end
Draw()
TimerHelp()
end
-- extra lines for the Seeds box's right-click menu
local function TimerMenu(AddToggle)
-- the game builds the menu once at login, before this file's settings are loaded: skip that one
if not DB then return end
UIDropDownMenu_AddButton({ text = "Planter timer", isTitle = 1 })
AddToggle("Planter timer", function() return DB.timer end, function(v) DB.timer = v; Draw() end)
AddToggle("Chime when soil or water is due", function() return DB.timerSound end, function(v) DB.timerSound = v end)
AddToggle("Remind every 2 minutes", function() return DB.timerRepeat end, function(v) DB.timerRepeat = v end)
AddToggle("Lock the timer bars", function() return DB.timerLock end, function(v) DB.timerLock = v end)
UIDropDownMenu_AddButton({ text = "Show a test timer", func = function() DB.timer = true; Test() end })
end
ADDON.TimerSlash = TimerSlash
ADDON.TimerMenu = TimerMenu
-- for the settings window's buttons
ADDON.TimerTest = function()
if not DB then return end
DB.timer = true
Test()
end
ADDON.TimerClear = function()
if not DB then return end
ClearAll()
Draw()
end
ADDON.TimerReset = function()
if not DB then return end
DB.timerPos = nil
PlacePanel()
end
ADDON.TimerRedraw = function()
if DB then Draw() end
end
-- start bars by hand (the settings window's Start button and /trees timer start)
ADDON.TimerLabels = LABELS
ADDON.TimerStart = function(key, n)
if not DB or not LABELS[key] then return end
n = n or 1
DB.timer = true
Planted(key, n)
Draw()
Print("started " .. n .. " " .. LABELS[key] .. " bar(s): Un'Goro Soil is due in "
.. (DB.timerMinutes or 9) .. " minutes.")
end
-- events --------------------------------------------------------------------------------------
-- Up to 1.3.0 one bar could hold several planters: give each planter its own bar.
local function OneEach(list)
local out = {}
for _, b in ipairs(list) do
if b.n then
local keys = {}
for key, c in pairs(b.crops or {}) do
for i = 1, c do table.insert(keys, key) end
end
for i = 1, b.n - (b.picked or 0) do
local p = { crop = keys[i] or "?", phase = b.phase, started = b.started, due = b.due,
zone = b.zone, alerted = b.alerted, test = b.test }
if i <= (b.done or 0) and b.phase < 4 then
-- this one already got the step
p.phase = b.phase + 1
p.started = b.lastDone or b.started
p.due = p.started + StageSeconds()
p.alerted = nil
if p.phase >= 4 then p.due = p.started end
end
table.insert(out, p)
end
else
table.insert(out, b)
end
end
return out
end
local function Setup()
if type(WoodAndSeedsGatherDB) ~= "table" then WoodAndSeedsGatherDB = {} end
DB = WoodAndSeedsGatherDB
for k, v in pairs(TIMER_DEFAULTS) do
if DB[k] == nil then DB[k] = v end
end
DB.timerGroup = nil -- planters no longer share a bar
for _, t in ipairs(ADDON.TYPES) do
if t.seed then
TRACK[t.seed] = t.key
SEED_OF[t.key] = t.seed
ICON_OF[t.key] = t.icon
end
end
TRACK[SOIL] = "soil"
TRACK[WATER] = "water"
if type(DB.planters) ~= "table" then DB.planters = {} end
DB.planters = OneEach(DB.planters)
planters = DB.planters
for i = table.getn(planters), 1, -1 do
local p = planters[i]
if p.test then
table.remove(planters, i)
else
p.away, p.awaySince = nil, nil -- 1.3.0 stopped bars when you left the zone
if p.id and p.id > nextId then nextId = p.id end
end
end
for _, p in ipairs(planters) do
if not p.id then
nextId = nextId + 1
p.id = nextId
end
end
-- a /reload keeps the bars; after a logout or disconnect the game has removed the planters
local real = table.getn(planters)
if real > 0 and Now() - (DB.plantersSeen or 0) > RELOAD_GAP then
Print("the game removed your " .. real .. " planter(s) when you logged out or disconnected.")
ClearAll()
end
menu = CreateFrame("Frame", "WoodAndSeedsGatherTimerMenu", UIParent, "UIDropDownMenuTemplate")
UIDropDownMenu_Initialize(menu, BarMenuInit, "MENU")
PlacePanel()
end
local ev = CreateFrame("Frame")
ev:RegisterEvent("PLAYER_LOGIN")
ev:RegisterEvent("PLAYER_LOGOUT")
ev:RegisterEvent("PLAYER_ENTERING_WORLD")
ev:RegisterEvent("BAG_UPDATE")
ev:RegisterEvent("GOSSIP_SHOW")
ev:RegisterEvent("QUEST_GREETING")
ev:RegisterEvent("QUEST_DETAIL")
ev:RegisterEvent("QUEST_PROGRESS")
ev:RegisterEvent("QUEST_COMPLETE")
ev:RegisterEvent("LOOT_OPENED")
local bagsDirty, cursorNoted = false, nil
ev:SetScript("OnEvent", function()
if event == "PLAYER_LOGIN" then
Setup()
return
end
if not DB then return end
if event == "PLAYER_LOGOUT" then
DB.plantersSeen = Now()
elseif event == "BAG_UPDATE" then
bagsDirty = true
elseif event == "PLAYER_ENTERING_WORLD" then
counts = ScanBags()
elseif event == "LOOT_OPENED" then
if not DB.timer then return end
local n = TakeNeed("ripe", LOOT_WINDOW)
if n then
Dbg("loot window: counted as picking " .. n.name)
lastTip = nil
Picked(n.info)
elseif needs[1] then
Dbg("loot window: no ripe plant pointed at in the last " .. LOOT_WINDOW .. " s. Lately:" .. NeedsText())
end
else
-- a gossip or quest window opened: is it a planter or plant?
local name = UnitName("npc")
Dbg("window " .. event .. ": " .. (name or "no name"))
if DB.timer and name and GARDEN[name] then PointingAt(name, "window") end
end
end)
local elapsed, second = 0, 0
ev:SetScript("OnUpdate", function()
if not DB then return end
elapsed = elapsed + arg1
if elapsed < 0.1 then return end
second = second + elapsed
elapsed = 0
if not DB.timer then
if bars[1] and bars[1]:IsVisible() then Draw() end
return
end
PollTooltip()
if bagsDirty then
if CursorHasItem() then
if not cursorNoted then
cursorNoted = true
Dbg("bags changed, but an item is on your cursor: waiting until it's put down")
end
else
bagsDirty, cursorNoted = false, nil
BagsChanged()
end
end
if next(pending) then CheckPending() end
if second >= 1 then
second = 0
Tick()
end
if planters[1] or (bars[1] and bars[1]:IsVisible()) then Draw() end
end)